hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
79f241413151fb6fff5a98fe4196226821d4592f
10,359
// // JXNetworkManager.swift // ShoppingGo // // Created by 杜进新 on 2017/6/12. // Copyright © 2017年 杜进新. All rights reserved. // import UIKit import AFNetworking public class JXNetworkManager: NSObject { //AFNetworking manager public var afmanager = AFHTTPSessionManager() //request 缓存 public var requestCache = [String:JXBaseRequest]() //网络状态 public var networkStatus : AFNetworkReachabilityStatus = .reachableViaWiFi //单例 public static let manager = JXNetworkManager() public override init() { super.init() //返回数据格式AFHTTPResponseSerializer(http) AFJSONResponseSerializer(json) AFXMLDocumentResponseSerializer ... afmanager.responseSerializer = AFHTTPResponseSerializer.init() afmanager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html","application/json","text/json","image/jpeg") as? Set<String> afmanager.operationQueue.maxConcurrentOperationCount = 5 //请求参数格式AFHTTPRequestSerializer(http) AFJSONRequestSerializer(json) AFPropertyListRequestSerializer (plist) afmanager.requestSerializer = AFHTTPRequestSerializer.init() afmanager.requestSerializer.timeoutInterval = 10 //set header //afmanager.requestSerializer.setValue("3.0.1", forHTTPHeaderField: "version") afmanager.reachabilityManager = AFNetworkReachabilityManager.shared() //很大概率,切换网络时,监听不到,不能实时修改状态 afmanager.reachabilityManager.setReachabilityStatusChange { (status:AFNetworkReachabilityStatus) in print("网络状态变化 == \(status.rawValue)") self.networkStatus = AFNetworkReachabilityStatus(rawValue: status.rawValue)! } afmanager.reachabilityManager.startMonitoring() } public func buildRequest(_ request:JXBaseRequest) { print("网络状态 = ",AFNetworkReachabilityManager.shared().isReachable) //afmanager.reachabilityManager.startMonitoring() ///网络判断 if networkStatus == .unknown || networkStatus == .notReachable { print("网络不可用") // let error = NSError.init(domain: "网络连接断开", code: JXNetworkError.kRequestErrorNotConnectedToInternet.rawValue, userInfo: nil) // request.requestFailure(error: error) // return } ///获取URL guard let url = buildUrl(request: request) else { let error = NSError.init(domain: "URL构建失败", code: JXNetworkError.kRequestUrlInitFailed.rawValue, userInfo: nil) request.requestFailure(error: error) return } if let customUrlRequest = request.buildCustomUrlRequest() { request.sessionTask = afmanager.dataTask(with: customUrlRequest, uploadProgress: nil, downloadProgress: nil, completionHandler: { (response, responseData, error) in // self.handleTask(task: nil, data: responseData, error: error) }) }else{ switch request.method { case .get: request.sessionTask = afmanager.get(url, parameters: request.param, progress: nil, success: { (task:URLSessionDataTask, responseData:Any?) in self.handleTask(task: task, data: responseData, error: nil) }, failure: { (task:URLSessionDataTask?, error:Error) in self.handleTask(task: task, data: nil, error: error) }) case .post: if let constructBlock = request.customConstruct(), constructBlock != nil{ request.sessionTask = afmanager.post(url, parameters: request.param, constructingBodyWith: constructBlock, progress: nil, success: { (task:URLSessionDataTask, responseData:Any?) in self.handleTask(task: task, data: responseData, error: nil) }, failure: { (task:URLSessionDataTask?, error:Error) in self.handleTask(task: task, data: nil, error: error) }) }else{ request.sessionTask = afmanager.post(url, parameters: request.param, progress: nil, success: { (task:URLSessionDataTask, responseData:Any?) in self.handleTask(task: task, data: responseData) }, failure: { (task:URLSessionDataTask?, error:Error) in self.handleTask(task: task, error: error) }) } case .delete: request.sessionTask = afmanager.delete(url, parameters: request.param, success: { (task:URLSessionDataTask, responseData:Any?) in self.handleTask(task: task, data: responseData) }, failure: { (task:URLSessionDataTask?, error:Error) in self.handleTask(task: task, error: error) }) case .put: request.sessionTask = afmanager.put(url, parameters: request.param, success: { (task:URLSessionDataTask, responseData:Any?) in self.handleTask(task: task, data: responseData) }, failure: { (task:URLSessionDataTask?, error:Error) in self.handleTask(task: task, error: error) }) case .head: request.sessionTask = afmanager.head(url, parameters: request.param, success: { (task:URLSessionDataTask) in self.handleTask(task: task, data: nil) }, failure: { (task:URLSessionDataTask?, error:Error) in self.handleTask(task: task, error: error) }) default: assert(request.method == .unknow, "请求类型未知") break } } addRequest(request: request) } func download(_ request: JXBaseRequest) { guard let urlStr = request.requestUrl, let url = URL(string: urlStr) else { fatalError("Bad UrlStr") } let urlRequest = URLRequest.init(url: url) request.urlRequest = urlRequest guard let destination = request.destination else { fatalError("destination block can not be nil") } request.sessionTask = afmanager.downloadTask(with: urlRequest, progress: request.progress, destination: destination, completionHandler: request.download) // request.sessionTask = afmanager.downloadTask(with: urlRequest, progress: { (progress) in // print(progress.totalUnitCount,progress.completedUnitCount) // }, destination: destination) { (urlResponse, url, error) in // print(urlResponse,url,error) // } request.sessionTask?.resume() addRequest(request: request) } } //MARK: request add remove resume cancel extension JXNetworkManager { /// 缓存request /// /// - Parameter request: 已经包装好含有URL,param的request public func addRequest(request:JXBaseRequest) { guard let task = request.sessionTask else { return } let key = requestHashKey(task: task) requestCache[key] = request } /// 删除缓存中request /// /// - Parameter request: 已经包装好含有URL,param的request public func removeRequest(_ request:JXBaseRequest) { guard let task = request.sessionTask else { return } let key = requestHashKey(task: task) requestCache.removeValue(forKey: key) } /// 取消request /// /// - Parameter request: 已经包装好含有URL,param的request public func cancelRequest(_ request:JXBaseRequest) { guard (request.sessionTask as? URLSessionDataTask) != nil else { return } request.sessionTask?.cancel() removeRequest(request) } /// 取消所有request public func cancelRequests(keepCurrent request:JXBaseRequest? = nil) { for (_,r) in requestCache { if let current = request, current == r{ //保留当前请求 } else { cancelRequest(r) } } } /// 重发request /// /// - Parameter request: 已经包装好含有URL,param的request public func resumeRequest(_ request:JXBaseRequest) { buildRequest(request) } /// 重发所有缓冲中的request /// /// - Parameter request: 已经包装好含有URL,param的request public func resumeRequests(except request:JXBaseRequest) { for (_,value) in requestCache { let r = value as JXBaseRequest if r == request { //不作处理 } else { removeRequest(r) resumeRequest(r) } } } } extension JXNetworkManager{ /// 对请求任务hash处理 /// /// - Parameter task: 当前请求task /// - Returns: hash后的字符串 public func requestHashKey(task:URLSessionTask) -> String { return String(format: "%lu", task.hash) } } extension JXNetworkManager { public func buildUrl(request:JXBaseRequest) -> String? { guard let url = request.requestUrl else { fatalError("request URL can not be nil") } if url.hasPrefix("http") == true{ return url } guard let baseUrl = request.baseUrl() else { fatalError("please set baseUrl in your custom request class") } let wholeUrl = baseUrl + url let encodingUrl = wholeUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) return encodingUrl } } //MARK: 结果处理 response handle extension JXNetworkManager { public func handleTask(task:URLSessionDataTask?, data:Any? = nil, error:Error? = nil) { /// guard let task = task else { return} // let key = requestHashKey(task: task) guard let request = requestCache[key] else { return} if checkResult(request: request) == true && error == nil{ request.requestSuccess(responseData: data!) } else { request.requestFailure(error: error!) } requestCache.removeValue(forKey: key) } public func checkResult(request:JXBaseRequest) -> Bool { let result = request.statusCodeValidate() return result } } extension JXNetworkManager { }
38.366667
200
0.600251
5d29993dc489f85d59a8877e8fcc84e6b7c93baa
2,348
// // base_app_iosUITests.swift // base-app-iosUITests // // Created by Roberto Frontado on 2/11/16. // Copyright © 2016 Roberto Frontado. All rights reserved. // import XCTest @testable import base_app_ios class base_app_iosUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. let app = XCUIApplication() sleep(1) app.childrenMatchingType(.Window).elementBoundByIndex(0).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.tap() let userNavigationBar = app.navigationBars["User"] userNavigationBar.buttons["Users"].tap() sleep(1) app.navigationBars["Users"].buttons["Menu"].tap() sleep(1) let tablesQuery = app.tables tablesQuery.cells["User"].tap() sleep(1) userNavigationBar.buttons["Menu"].tap() sleep(1) tablesQuery.staticTexts["Find user"].tap() sleep(1) let usernameTextField = app.textFields["Username"] usernameTextField.tap() usernameTextField.typeText("valid") app.buttons["Find user"].tap() sleep(1) } }
37.870968
344
0.661414
6174abe76b6ab2db51ea056abc6c7eeab486bb3a
1,394
/** * Copyright (c) 2016 Razeware 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 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
38.722222
135
0.763271
338bf8c6cfa1eb3da09629d98b1558c731501df4
175
// // JobType.swift // // // Created by zunda on 2022/03/22. // import Foundation extension Sweet { public enum JobType: String { case tweets case users } }
10.9375
35
0.617143
bf8c96a46626f137a64807df00e624290f407f16
168
// // main.swift // swiftpath // // Created by user160046 on 3/22/20. // Copyright © 2020 path. All rights reserved. // import Foundation print("Hello, World!")
12.923077
47
0.64881
d5664392c73da211f8b96feb246cb48b129f5f9f
3,117
// Copyright (c) 2017 Luc Dion // 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 PinLayout class MethodCell: UITableViewCell { static let reuseIdentifier = "MethodCell" private let iconImageView = UIImageView(image: UIImage(named: "method")) private let nameLabel = UILabel() private let descriptionLabel = UILabel() private let padding: CGFloat = 10 override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none separatorInset = .zero contentView.addSubview(iconImageView) nameLabel.font = UIFont.boldSystemFont(ofSize: 14) nameLabel.lineBreakMode = .byTruncatingTail contentView.addSubview(nameLabel) descriptionLabel.font = UIFont.systemFont(ofSize: 12) descriptionLabel.numberOfLines = 0 contentView.addSubview(descriptionLabel) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func configure(method: Method) { nameLabel.text = method.name descriptionLabel.text = method.description } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { iconImageView.pin.top().left().size(30).margin(padding) nameLabel.pin.after(of: iconImageView, aligned: .center).right().marginHorizontal(padding).sizeToFit(.width) descriptionLabel.pin.below(of: [iconImageView, nameLabel]).horizontally().margin(padding).sizeToFit(.width) } override func sizeThatFits(_ size: CGSize) -> CGSize { // 1) Set the contentView's width to the specified size parameter contentView.pin.width(size.width) // 2) Layout the contentView's controls layout() // 3) Returns a size that contains all controls return CGSize(width: contentView.frame.width, height: descriptionLabel.frame.maxY + padding) } }
39.455696
116
0.69522
1dca13f9751295d2cdf06a856842f91d5885438d
805
// // CMPreworkUITestsLaunchTests.swift // CMPreworkUITests // // Created by Caroline Mitchem on 2/2/22. // import XCTest class CMPreworkUITestsLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
24.393939
88
0.675776
eff7781385e83b86b3ac4666361765c210dbc23a
5,493
import Foundation public class VvoProvider: AbstractEfaProvider { static let API_BASE = "http://efa.vvo-online.de:8080/dvb/" static let STOPFINDER_ENDPOINT = "XSLT_STOPFINDER_REQUEST" static let COORD_ENDPOINT = "XSLT_COORD_REQUEST" static let DESKTOP_TRIP_ENDPOINT = "https://www.vvo-online.de/de/fahrplan/fahrplanauskunft/fahrten" static let DESKTOP_DEPARTURES_ENDPOINT = "https://www.vvo-online.de/de/fahrplan/aktuelle-abfahrten-ankuenfte/abfahrten" public init() { super.init(networkId: .VVO, apiBase: VvoProvider.API_BASE, departureMonitorEndpoint: nil, tripEndpoint: nil, stopFinderEndpoint: VvoProvider.STOPFINDER_ENDPOINT, coordEndpoint: VvoProvider.COORD_ENDPOINT, tripStopTimesEndpoint: nil, desktopTripEndpoint: VvoProvider.DESKTOP_TRIP_ENDPOINT, desktopDeparturesEndpoint: VvoProvider.DESKTOP_DEPARTURES_ENDPOINT) } override func parseLine(id: String?, network: String?, mot: String?, symbol: String?, name: String?, longName: String?, trainType: String?, trainNum: String?, trainName: String?) -> Line { if mot == "0" { if trainName == "Twoje Linie Kolejowe", let symbol = symbol { return Line(id: id, network: network, product: .highSpeedTrain, label: "TLK" + symbol) } else if trainName == "Regionalbahn" && trainNum == nil { return Line(id: id, network: network, product: .regionalTrain, label: nil) } else if longName == "Ostdeutsche Eisenbahn GmbH" { return Line(id: id, network: network, product: .regionalTrain, label: "OE") } else if longName == "Meridian" { return Line(id: id, network: network, product: .regionalTrain, label: "M") } else if longName == "trilex" { return Line(id: id, network: network, product: .regionalTrain, label: "TLX") } else if trainName == "Trilex" && trainNum == nil { return Line(id: id, network: network, product: .regionalTrain, label: "TLX") } else if symbol == "U 28" { // Nationalparkbahn return Line(id: id, network: network, product: .regionalTrain, label: "U28") } else if symbol == "SB 71" { // Städtebahn Sachsen return Line(id: id, network: network, product: .regionalTrain, label: "SB71") } else if symbol == "RB 71" { return Line(id: id, network: network, product: .regionalTrain, label: "RB71") } else if trainName == "Fernbus" && trainNum == nil { return Line(id: id, network: network, product: .regionalTrain, label: "Fernbus") } } return super.parseLine(id: id, network: network, mot: mot, symbol: symbol, name: name, longName: longName, trainType: trainType, trainNum: trainNum, trainName: trainName) } override func queryTripsParameters(builder: UrlBuilder, from: Location, via: Location?, to: Location, date: Date, departure: Bool, products: [Product]?, optimize: Optimize?, walkSpeed: WalkSpeed?, accessibility: Accessibility?, options: [Option]?, desktop: Bool) { if desktop { builder.addParameter(key: "originid", value: locationValue(location: from)) if let via = via { builder.addParameter(key: "viaid", value: locationValue(location: via)) } builder.addParameter(key: "destinationid", value: locationValue(location: to)) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd.MM.yyyy" dateFormatter.timeZone = timeZone dateFormatter.locale = Locale(identifier: "de_DE") let timeFormatter = DateFormatter() timeFormatter.dateFormat = "HH:mm" timeFormatter.timeZone = timeZone timeFormatter.locale = Locale(identifier: "de_DE") builder.addParameter(key: "date", value: dateFormatter.string(from: date)) builder.addParameter(key: "time", value: timeFormatter.string(from: date)) builder.addParameter(key: "arrival", value: !departure) } else { super.queryTripsParameters(builder: builder, from: from, via: via, to: to, date: date, departure: departure, products: products, optimize: optimize, walkSpeed: walkSpeed, accessibility: accessibility, options: options, desktop: desktop) } } override func queryDeparturesParameters(builder: UrlBuilder, stationId: String, departures: Bool, time: Date?, maxDepartures: Int, equivs: Bool, desktop: Bool) { if desktop { builder.addParameter(key: "stopid", value: stationId) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd.MM.yyyy" dateFormatter.timeZone = timeZone dateFormatter.locale = Locale(identifier: "de_DE") let timeFormatter = DateFormatter() timeFormatter.dateFormat = "HH:mm" timeFormatter.timeZone = timeZone timeFormatter.locale = Locale(identifier: "de_DE") builder.addParameter(key: "date", value: dateFormatter.string(from: time ?? Date())) builder.addParameter(key: "time", value: timeFormatter.string(from: time ?? Date())) } else { super.queryDeparturesParameters(builder: builder, stationId: stationId, departures: departures, time: time, maxDepartures: maxDepartures, equivs: equivs, desktop: desktop) } } }
64.623529
364
0.647005
752c4bd8413110745c17f9ca33f009fa075f8e01
3,670
// // LoginServiceSpec.swift // Rocket.ChatTests // // Created by Matheus Cardoso on 10/23/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import XCTest import RealmSwift import SwiftyJSON @testable import Rocket_Chat extension LoginService { static func testInstance() -> LoginService { let loginService = LoginService() loginService.service = "github" loginService.scope = "user" loginService.serverUrl = "https://github.com" loginService.tokenPath = "/login/oauth/access_token" loginService.authorizePath = "/login/oauth/authorize" loginService.clientId = "client-id" return loginService } } class LoginServiceSpec: XCTestCase, RealmTestCase { let testJSON = JSON(parseJSON: """ { \"mergeUsers\" : false, \"clientId\" : \"NhT7feA98YvKj6v6p\", \"scope\" : \"openid\", \"custom\" : true, \"authorizePath\" : \"/oauth/authorize\", \"serverURL\" : \"https://open.rocket.chat\", \"service\" : \"openrocketchat\", \"loginStyle\" : \"popup\", \"tokenSentVia\" : \"header\", \"buttonColor\" : \"#13679A\", \"buttonLabelText\" : \"Open\", \"buttonLabelColor\" : \"#FFFFFF\", \"tokenPath\" : \"/oauth/token\", \"usernameField\" : \"\" } """) func testFind() throws { let realm = testRealm() let github = LoginService() github.identifier = "githubid" github.service = "github" let google = LoginService() google.identifier = "googleid" google.service = "google" try realm.write { realm.add(github) realm.add(google) } XCTAssertEqual(LoginService.find(service: "github", realm: realm), github, "Finds LoginService correctly") } func testMap() { let loginService = LoginService() loginService.map(testJSON, realm: nil) XCTAssertEqual(loginService.mergeUsers, false) XCTAssertEqual(loginService.clientId, "NhT7feA98YvKj6v6p") XCTAssertEqual(loginService.scope, "openid") XCTAssertEqual(loginService.custom, true) XCTAssertEqual(loginService.authorizePath, "/oauth/authorize") XCTAssertEqual(loginService.serverUrl, "https://open.rocket.chat") XCTAssertEqual(loginService.service, "openrocketchat") XCTAssertEqual(loginService.loginStyle, "popup") XCTAssertEqual(loginService.tokenSentVia, "header") XCTAssertEqual(loginService.buttonColor, "#13679A") XCTAssertEqual(loginService.buttonLabelText, "Open") XCTAssertEqual(loginService.buttonLabelColor, "#FFFFFF") XCTAssertEqual(loginService.tokenPath, "/oauth/token") XCTAssertEqual(loginService.usernameField, "") } func testAuthorizeUrl() { let service = LoginService() service.serverUrl = "https://open.rocket.chat/" service.authorizePath = "authorize_path" XCTAssertEqual(service.authorizeUrl, "https://open.rocket.chat/authorize_path") service.authorizePath = nil XCTAssertNil(service.authorizeUrl, "https://open.rocket.chat/authorize_path") } func testAccessTokenUrl() { let service = LoginService() service.serverUrl = "https://open.rocket.chat/" service.tokenPath = "token_path" XCTAssertEqual(service.accessTokenUrl, "https://open.rocket.chat/token_path") service.tokenPath = nil XCTAssertNil(service.accessTokenUrl, "https://open.rocket.chat/token_path") } }
33.063063
114
0.625613
e83727d104cd416d0ab6f8ea8d9adf0d9d1d2f62
1,293
// // ExtensionInstallationViewModel.swift // CodeEdit // // Created by Pavel Kasila on 8.04.22. // import Foundation import Combine import ExtensionsStore final class ExtensionInstallationViewModel: ObservableObject { var plugin: Plugin init(plugin: Plugin) { self.plugin = plugin } @Published var release: PluginRelease? @Published var releases = [PluginRelease]() // Tells if all records have been loaded. (Used to hide/show activity spinner) var listFull = false // Tracks last page loaded. Used to load next page (current + 1) var currentPage = 1 // Limit of records per page. (Only if backend supports, it usually does) let perPage = 10 private var cancellable: AnyCancellable? func fetch() { cancellable = ExtensionsStoreAPI.pluginReleases(id: plugin.id, page: currentPage) .tryMap { $0.items } .catch { _ in Just(self.releases) } .sink { [weak self] in self?.currentPage += 1 self?.releases.append(contentsOf: $0) // If count of data received is less than perPage value then it is last page. if $0.count < self?.perPage ?? 10 { self?.listFull = true } } } }
28.108696
93
0.614849
cc8b02f848c4a3dea7ebee1644b6da1c91d4f2bb
22,402
// RUN: %target-swift-frontend -use-native-super-method -sdk %S/Inputs -I %S/Inputs -enable-source-import -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | FileCheck %s // RUN: %target-swift-frontend -use-native-super-method -sdk %S/Inputs -I %S/Inputs -enable-source-import -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify // REQUIRES: objc_interop import Foundation import gizmo class Foo: Proto { // Not objc or dynamic, so only a vtable entry init(native: Int) {} func nativeMethod() {} var nativeProp: Int = 0 subscript(native native: Int) -> Int { get { return native } set {} } // @objc, so it has an ObjC entry point but can also be dispatched // by vtable @objc init(objc: Int) {} @objc func objcMethod() {} @objc var objcProp: Int = 0 @objc subscript(objc objc: AnyObject) -> Int { get { return 0 } set {} } // dynamic, so it has only an ObjC entry point dynamic init(dynamic: Int) {} dynamic func dynamicMethod() {} dynamic var dynamicProp: Int = 0 dynamic subscript(dynamic dynamic: Int) -> Int { get { return dynamic } set {} } func overriddenByDynamic() {} @NSManaged var managedProp: Int } protocol Proto { func nativeMethod() var nativeProp: Int { get set } subscript(native native: Int) -> Int { get set } func objcMethod() var objcProp: Int { get set } subscript(objc objc: AnyObject) -> Int { get set } func dynamicMethod() var dynamicProp: Int { get set } subscript(dynamic dynamic: Int) -> Int { get set } } // ObjC entry points for @objc and dynamic entry points // normal and @objc initializing ctors can be statically dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo10objcMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog8objcPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos8objcPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // TODO: dynamic initializing ctor must be objc dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TTDFC7dynamic3Fooc // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Fooc // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign : // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT7dynamicSi_Si // Protocol witnesses use best appropriate dispatch // Native witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_12nativeMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // @objc witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_10objcMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // Dynamic witnesses use objc dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_13dynamicMethod // CHECK: function_ref @_TTDFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foo13dynamicMethod // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign : // Superclass dispatch class Subclass: Foo { // Native and objc methods can directly reference super members override init(native: Int) { super.init(native: native) } // CHECK-LABEL: sil hidden @_TFC7dynamic8SubclassC // CHECK: function_ref @_TFC7dynamic8Subclassc override func nativeMethod() { super.nativeMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass12nativeMethod // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.nativeMethod!1 override var nativeProp: Int { get { return super.nativeProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg10nativePropSi // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.nativeProp!getter.1 set { super.nativeProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss10nativePropSi // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.nativeProp!setter.1 } override subscript(native native: Int) -> Int { get { return super[native: native] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT6nativeSi_Si // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.subscript!getter.1 set { super[native: native] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT6nativeSi_Si // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.subscript!setter.1 } override init(objc: Int) { super.init(objc: objc) } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.init!initializer.1 override func objcMethod() { super.objcMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass10objcMethod // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.objcMethod!1 override var objcProp: Int { get { return super.objcProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg8objcPropSi // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.objcProp!getter.1 set { super.objcProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss8objcPropSi // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.objcProp!setter.1 } override subscript(objc objc: AnyObject) -> Int { get { return super[objc: objc] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT4objcPs9AnyObject__Si // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.subscript!getter.1 set { super[objc: objc] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT4objcPs9AnyObject__Si // CHECK: super_method {{%[0-9]+}} : $Subclass, #Foo.subscript!setter.1 } // Dynamic methods are super-dispatched by objc_msgSend override init(dynamic: Int) { super.init(dynamic: dynamic) } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign : override func dynamicMethod() { super.dynamicMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass13dynamicMethod // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign : override var dynamicProp: Int { get { return super.dynamicProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign : set { super.dynamicProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign : } override subscript(dynamic dynamic: Int) -> Int { get { return super[dynamic: dynamic] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign : set { super[dynamic: dynamic] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign : } dynamic override func overriddenByDynamic() {} } // CHECK-LABEL: sil hidden @_TF7dynamic20nativeMethodDispatchFT_T_ : $@convention(thin) () -> () func nativeMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(native: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic18objcMethodDispatchFT_T_ : $@convention(thin) () -> () func objcMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(objc: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[objc: 0 as NSNumber] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[objc: 0 as NSNumber] = y } // CHECK-LABEL: sil hidden @_TF7dynamic21dynamicMethodDispatchFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic15managedDispatchFCS_3FooT_ func managedDispatch(c: Foo) { // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic21foreignMethodDispatchFT_T_ func foreignMethodDispatch() { // CHECK: function_ref @_TFCSo9GuisemeauC let g = Guisemeau() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign g.frob() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign let x = g.count // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign g.count = x // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign let y: AnyObject! = g[0] // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign g[0] = y // CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign _ = g.description } extension Gizmo { // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5Gizmoc // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign convenience init(convenienceInExtension: Int) { self.init(bellsOn: convenienceInExtension) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassFactory x: Int) { self.init(stuff: x) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassExactFactory x: Int) { self.init(exactlyStuff: x) } @objc func foreignObjCExtension() { } dynamic func foreignDynamicExtension() { } } // CHECK-LABEL: sil hidden @_TF7dynamic24foreignExtensionDispatchFCSo5GizmoT_ func foreignExtensionDispatch(g: Gizmo) { // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : Gizmo g.foreignObjCExtension() // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign g.foreignDynamicExtension() } // CHECK-LABEL: sil hidden @_TF7dynamic33nativeMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func nativeMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(native: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic31objcMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func objcMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(objc: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[objc: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[objc: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic34dynamicMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic28managedDispatchFromOtherFileFCS_13FromOtherFileT_ func managedDispatchFromOtherFile(c: FromOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic23dynamicExtensionMethodsFCS_13ObjCOtherFileT_ func dynamicExtensionMethods(obj: ObjCOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign obj.extensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign _ = obj.extensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = obj.dynamicType.extensionClassProp // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign obj.dynExtensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign _ = obj.dynExtensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = obj.dynamicType.dynExtensionClassProp } public class Base { dynamic var x: Bool { return false } } public class Sub : Base { // CHECK-LABEL: sil hidden @_TFC7dynamic3Subg1xSb : $@convention(method) (@guaranteed Sub) -> Bool { // CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error ErrorType) // CHECK: = partial_apply [[AUTOCLOSURE]](%0) // CHECK: return {{%.*}} : $Bool // CHECK: } // CHECK-LABEL: sil shared [transparent] @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error ErrorType) { // CHECK: [[SUPER:%.*]] = super_method [volatile] %0 : $Sub, #Base.x!getter.1.foreign : Base -> () -> Bool , $@convention(objc_method) (Base) -> ObjCBool // CHECK: = apply [[SUPER]]({{%.*}}) // CHECK: return {{%.*}} : $Bool // CHECK: } override var x: Bool { return false || super.x } } // Vtable contains entries for native and @objc methods, but not dynamic ones // CHECK-LABEL: sil_vtable Foo { // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.nativeMethod!1: _TFC7dynamic3Foo12nativeMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.getter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.setter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.objcMethod!1: _TFC7dynamic3Foo10objcMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.getter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.setter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-NOT: dynamic.Foo.init (dynamic.Foo.Type)(dynamic : Swift.Int) -> dynamic.Foo // CHECK-NOT: dynamic.Foo.dynamicMethod // CHECK-NOT: dynamic.Foo.subscript.getter (dynamic : Swift.Int) -> Swift.Int // CHECK-NOT: dynamic.Foo.subscript.setter (dynamic : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TFC7dynamic3Foo19overriddenByDynamic // CHECK-LABEL: #Foo.nativeProp!getter.1: _TFC7dynamic3Foog10nativePropSi // dynamic.Foo.nativeProp.getter : Swift.Int // CHECK-LABEL: #Foo.nativeProp!setter.1: _TFC7dynamic3Foos10nativePropSi // dynamic.Foo.nativeProp.setter : Swift.Int // CHECK-LABEL: #Foo.objcProp!getter.1: _TFC7dynamic3Foog8objcPropSi // dynamic.Foo.objcProp.getter : Swift.Int // CHECK-LABEL: #Foo.objcProp!setter.1: _TFC7dynamic3Foos8objcPropSi // dynamic.Foo.objcProp.setter : Swift.Int // CHECK-NOT: dynamic.Foo.dynamicProp.getter // CHECK-NOT: dynamic.Foo.dynamicProp.setter // Vtable uses a dynamic thunk for dynamic overrides // CHECK-LABEL: sil_vtable Subclass { // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TTDFC7dynamic8Subclass19overriddenByDynamic
48.176344
180
0.703866
6285eb3942ec1215a3d7bcf60ffa0a43730118b9
405
// // ContainerController.swift // SKTextInputsManager // // Created by Sergey Kostyan on 22.08.2018. // import UIKit open class ContainerControllerFactory { func controller(for view: UIView) -> ContainerControlling { guard let scroll = view as? UIScrollView else { return ViewController(view: view) } return ScrollController(scroll: scroll) } }
20.25
63
0.65679
ef4a3ca76cac8ce68bae05da6b5e244c4d94c893
367
// // EvidationBoldRule.swift // EvidationMarkdown // // Created by Gilbert Lo on 12/10/19. // Copyright © 2019 Evidation Health, Inc. All rights reserved. // import Markdown class EvidationBoldRule: BoldRule { override init() { super.init() expression = NSRegularExpression.expressionWithPattern("(\\*{2})(.+?)(\\*{2})(?!\\*|\\_)") } }
21.588235
98
0.629428
21d0f21893ee1b1d422ff3d257148153ccb62a8e
809
// // GeohashTests.swift // GPSTests // // Created by Michael Neas on 5/28/20. // Copyright © 2020 Path Check Inc. All rights reserved. // import XCTest class GeohashTests: XCTestCase { func testGeoHash() { let location = TestMAURLocation(latitude: 42.360084, longitude: -71.058905, date: Date()) let hashes = [ "d", "dr", "drt", "drt2", "drt2z", "drt2zp", "drt2zp2", "drt2zp2m", "drt2zp2mr" ] for index in 0..<hashes.count { XCTAssertEqual(Geohash.encode(latitude: location.latitude.doubleValue, longitude: location.longitude.doubleValue, length: index + 1), hashes[index]) } } func testGeohashSpec() { XCTAssertEqual("sr6de7ee", Geohash.encode(latitude: 41.24060321, longitude: 14.91328448, length: 8)) } }
23.114286
154
0.63288
5bf9115cd8bc68833c2d9c0483938b9ef00a8035
2,336
// // SceneDelegate.swift // WiseBookLife // // Created by 서보경 on 2020/06/21. // Copyright © 2020 서보경. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.259259
147
0.712757
abe944a06dbaea2d5836078b7d57a91bd3fc018a
7,403
// // LiveViewController.swift // XMGTV // // Created by apple on 16/11/9. // Copyright © 2016年 coderwhy. All rights reserved. // import UIKit import Kingfisher fileprivate let kChatToolViewHeight : CGFloat = 44.0 class LYCRoomViewController: UIViewController , LYCEmitterProtocol { // MARK: 控件属性 @IBOutlet weak var bgImageView: UIImageView! fileprivate var timer : Timer? fileprivate lazy var chatToolsView : LYCChatToolView = LYCChatToolView.loadNibAble() fileprivate lazy var chatContainerView : LYCChatContainerView = LYCChatContainerView.loadNibAble() fileprivate lazy var giftView : LYCGifView = { let rect = CGRect(x: 0, y: kScreenHeight, width: kScreenWidth, height: 280) let gifView = LYCGifView(frame:rect) gifView.deleage = self return gifView }() fileprivate lazy var chatScoket : YCSocket = { let chatSocket = YCSocket(addr: "192.168.0.108", port: 8788) if chatSocket.connectServer() { chatSocket.startReadMsg() } chatSocket.delegate = self; return chatSocket; }() // MARK: 系统回调函数 override func viewDidLoad() { super.viewDidLoad() setupUI() addObserver() chatScoket.sendJoinRoom() } deinit { chatScoket.sendLeaveRoom() print(" room deinit" ) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setNavigationBarHidden(false, animated: animated) } } // MARK:- 设置UI界面内容 extension LYCRoomViewController { fileprivate func setupUI() { setupChatContainerView() setupBlurView() setupBottomView() setupGifView() } //设置聊天框 private func setupChatContainerView(){ chatContainerView.frame = CGRect(x: 0, y: self.view.frame.height - 200 - 44 , width: kScreenWidth, height: 200) chatContainerView.backgroundColor = UIColor.clear view.addSubview(chatContainerView); } // 设置毛玻璃 private func setupBlurView() { let blur = UIBlurEffect(style: .dark) let blurView = UIVisualEffectView(effect: blur) blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = bgImageView.bounds bgImageView.addSubview(blurView) } // 设置顶部聊天框 private func setupBottomView() { chatToolsView.frame = CGRect(x: 0, y: view.bounds.height, width: view.bounds.width , height:kChatToolViewHeight ) chatToolsView.autoresizingMask = [.flexibleTopMargin,.flexibleWidth] chatToolsView.delegate = self view.addSubview(chatToolsView) } // 设置礼物界面 private func setupGifView(){ LYCGifViewModel.shareInstance.loadGifData(finishCallBack: { self.view.addSubview(self.giftView) self.view.bringSubview(toFront: self.giftView) }) } } extension LYCRoomViewController { fileprivate func addObserver() { NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillChangeFrame (_:)) , name: .UIKeyboardWillChangeFrame, object: nil) } } // MARK:- 事件监听 extension LYCRoomViewController { @IBAction func exitBtnClick() { timer?.invalidate() timer = nil chatScoket.sendLeaveRoom() _ = navigationController?.popViewController(animated: true) } @IBAction func bottomMenuClick(_ sender: UIButton) { switch sender.tag { case 0: chatToolsView.chatTextFiled.becomeFirstResponder() case 1: print("点击了分享") case 2: let gifViewY = kScreenHeight - giftView.frame.height UIView.animate(withDuration: 0.5, animations: { self.giftView.frame.origin.y = gifViewY }) case 3: print("点击了更多") case 4: sender.isSelected = !sender.isSelected sender.isSelected ? addEmitter(point: CGPoint(x: sender.center.x, y: UIScreen.main.bounds.size.height - sender.center.y)) : stopEmitter() default: fatalError("未处理按钮") } } // @objc fileprivate func emotionButtonClick(_ sender : UIButton){ sender.isSelected = !sender.isSelected print("…………………………") } @objc fileprivate func keyBoardWillChangeFrame (_ notify : Notification){ chatToolsView.sendButton.isEnabled = true let userInfo = notify.userInfo as! Dictionary<String, Any> let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double let value = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue let keyBoardFrame = value.cgRectValue let chatToolY = keyBoardFrame.minY - kChatToolViewHeight UIView.animate(withDuration: duration) { self.chatToolsView.frame.origin.y = chatToolY self.chatContainerView.frame.origin.y = chatToolY - self.chatContainerView.frame.height } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.chatToolsView.chatTextFiled.resignFirstResponder() UIView.animate(withDuration: 0.5) { self.chatToolsView.frame.origin.y = kScreenHeight self.giftView.frame.origin.y = kScreenHeight } } } //MARK:-LYCChatToolViewDelegate 聊天框代理 extension LYCRoomViewController : LYCChatToolViewDelegate{ func chatToolView(_ chatToolView: LYCChatToolView, message: String) { chatScoket.sendTextMessage(textMsg: message) } } //MARK:-LYCGifView 发送礼物回调 extension LYCRoomViewController : LYCGifViewDelegate{ func gitView(_ gifView: LYCGifView, collectionView: UICollectionView, didSelectRowAtIndex indexPath: IndexPath, gifModel: LYCGifModel) { chatScoket.sendGif(gifName: gifModel.subject, gifUrl: gifModel.img, gifNum: "1") self.giftView.frame.origin.y = kScreenHeight } } //MARK:- YCSocketDelegate socket消息代理 extension LYCRoomViewController : YCSocketDelegate{ func socket(_ socket: YCSocket, joinRoom userInfo: UserInfo) { let attrSting = LYCMAttributStingExtension.userJoinLeaveRoom(userName: userInfo.name, isJoinRoom: true) chatContainerView.addAttributeStringReloadData(attrSting: attrSting) } func socket(_ socket: YCSocket, leaveRoom userInfo: UserInfo) { let attrSting = LYCMAttributStingExtension.userJoinLeaveRoom(userName: userInfo.name, isJoinRoom: false) chatContainerView.addAttributeStringReloadData(attrSting: attrSting) } func socket(_ socket: YCSocket, chatMsg: TextMessage) { let attrSting = LYCMAttributStingExtension.userSendMsg(userName: chatMsg.user.name, chatMsg: chatMsg.text) chatContainerView.addAttributeStringReloadData(attrSting: attrSting) } func socket(_ socket: YCSocket, sendGif gif: GiftMessage) { let attrSting = LYCMAttributStingExtension.sendGif(userName: gif.user.name, gifUrl: gif.giftUrl, gifName: gif.giftname) chatContainerView.addAttributeStringReloadData(attrSting: attrSting) } }
34.432558
151
0.670134
201a565213432eac1051678172711f48efb20173
712
// // Cat4490175.swift // WorklightTest // // Created by Luis Cuevas on 20/06/17. // Copyright © 2017 Deloitte. All rights reserved. // import Foundation import ObjectMapper public class Cat4490175: Mappable{ public var L2CategoryInfo: L2CategoryInfo? public var CHILDPRODUCTS_COUNT: String? public var NAME: String? public var ID: String? public var CHILDCATEGORY_COUNT: Float? required public init?(map: Map){ } public func mapping(map: Map){ L2CategoryInfo <- map["L2CategoryInfo"] CHILDPRODUCTS_COUNT <- map["CHILDPRODUCTS_COUNT"] NAME <- map["NAME"] ID <- map["ID"] CHILDCATEGORY_COUNT <- map["CHILDCATEGORY_COUNT"] } }
24.551724
57
0.66573
233154987035d604f7d7e3c5cbe564f4cc68f207
1,137
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "Provide", products: [ .library( name: "provide", targets: ["provide"]), ], dependencies: [ .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.7.3"), // .package(url: "https://github.com/tristanhimmelman/AlamofireObjectMapper.git", from: "5.0.0"), .package(url: "https://github.com/tristanhimmelman/ObjectMapper.git", from: "3.4.1"), .package(url: "https://github.com/kthomas/JWTDecode.swift.git", from: "2.1.4"), .package(url: "https://github.com/kthomas/UICKeyChainStore.git", from: "2.1.4"), ], targets: [ .target( name: "provide", dependencies: [ "Alamofire", // "AlamofireObjectMapper", "ObjectMapper", "JWTDecode.swift", "UICKeyChainStore", ], path: "Sources"), .testTarget( name: "provide-swiftTests", dependencies: ["provide"], path: "Tests"), ] )
30.72973
104
0.525945
db4750d5c86c732c5d8e41dc4a0afc71ad99a8ef
5,529
// Copyright 2019 Bryant Luk // // 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 NIO internal struct BNSConnectionInternalState<StateSettable: BNSInternalStateSettable>: BNSInternalStateTransitionable, CustomStringConvertible, CustomDebugStringConvertible where StateSettable.State == BNSConnectionState { internal var state: BNSInternalState = .setup // swiftlint:disable multiline_arguments @inlinable internal func assertStart(file: StaticString = #file, line: UInt = #line) { assert({ () -> Bool in switch self.state { case .setup: return true case .preparing, .ready, .failed, .cancelled: return false } }(), "start() called from an invalid state: \(self.state)", file: file, line: line) } @inlinable internal func assertDeinit(file: StaticString = #file, line: UInt = #line) { assert({ () -> Bool in switch self.state { case .cancelled, .setup: return true case .preparing, .ready, .failed: return false } }(), "deinit in an invalid state: \(self.state)", file: file, line: line) } // swiftlint:enable multiline_arguments // swiftlint:disable function_body_length cyclomatic_complexity internal mutating func transition(to newState: BNSInternalState, on connection: StateSettable) { connection.eventLoop.assertInEventLoop() switch state { case .setup: switch newState { case .setup: preconditionFailure("Invalid transition from \(self.state) to \(newState)") case .preparing, .ready, .failed, .cancelled: break } case .preparing: switch newState { case .setup, .preparing: preconditionFailure("Invalid transition from \(self.state) to \(newState)") case .ready, .failed, .cancelled: break } case .ready: switch newState { case .setup, .preparing, .ready: preconditionFailure("Invalid transition from \(self.state) to \(newState)") case .failed, .cancelled: break } case .failed: switch newState { case .setup: preconditionFailure("Invalid transition from \(self.state) to \(newState)") case .preparing, .ready: // Could have failed before the connection was ready, so do not perform transition. return case .failed, .cancelled: break } case .cancelled: switch newState { case .setup, .cancelled: preconditionFailure("Invalid transition from \(self.state) to \(newState)") case .preparing, .ready: // Could have cancelled after starting but before the connection was ready, // so do not perform transition. return case let .failed(error): switch error { case let connectionError as BNSConnectionError: switch connectionError { case .connectionReset: return case .idleTimeout: return case .connectionUpgraded: assertionFailure("Invalid transition from \(self.state) to \(newState)") case .invalidState: assertionFailure("Invalid transition from \(self.state) to \(newState)") } case is IOError: return default: assertionFailure("Invalid transition from \(self.state) to \(newState)") } return } } self.state = newState let updateHandler = connection.eventLoopProtectedStateUpdateHandler connection.withQueueIfPossible { let connectionState: BNSConnectionState switch newState { case .setup: connectionState = BNSConnectionState.setup case .preparing: connectionState = BNSConnectionState.preparing case .ready: connectionState = BNSConnectionState.ready case let .failed(error): connectionState = BNSConnectionState.failed(error) case .cancelled: connectionState = BNSConnectionState.cancelled } connection.state = connectionState updateHandler?(connectionState) } } // swiftlint:enable function_body_length cyclomatic_complexity var description: String { return "\(self.state)" } var debugDescription: String { return "BNSConnectionInternalState(\(self.state))" } }
36.615894
116
0.573702
def98eb83f232a0d1dd2a43c9de8ba7f7b212413
9,645
// // Recipe.swift // // Created by Wilson Ding on 3/4/17 // Copyright (c) . All rights reserved. // import Foundation import SwiftyJSON public final class Recipe { // MARK: Declaration for string constants to be used to decode and also serialize. private struct SerializationKeys { static let collection = "Collection" static let poster = "Poster" static let adTags = "AdTags" static let yieldNumber = "YieldNumber" static let isBookmark = "IsBookmark" static let bookmarkSiteLogo = "BookmarkSiteLogo" static let isPrivate = "IsPrivate" static let starRating = "StarRating" static let creationDate = "CreationDate" static let imageURL = "ImageURL" static let ingredients = "Ingredients" static let totalMinutes = "TotalMinutes" static let recipeID = "RecipeID" static let notesCount = "NotesCount" static let category = "Category" static let isSponsored = "IsSponsored" static let subcategory = "Subcategory" static let nutritionInfo = "NutritionInfo" static let verifiedByClass = "VerifiedByClass" static let cuisine = "Cuisine" static let verifiedDateTime = "VerifiedDateTime" static let webURL = "WebURL" static let reviewCount = "ReviewCount" static let medalCount = "MedalCount" static let maxImageSquare = "MaxImageSquare" static let title = "Title" static let favoriteCount = "FavoriteCount" static let primaryIngredient = "PrimaryIngredient" static let yieldUnit = "YieldUnit" static let menuCount = "MenuCount" static let description = "Description" static let lastModified = "LastModified" static let allCategoriesText = "AllCategoriesText" static let imageSquares = "ImageSquares" static let instructions = "Instructions" static let photoUrl = "PhotoUrl" static let activeMinutes = "ActiveMinutes" static let adminBoost = "AdminBoost" } // MARK: Properties public var collection: String? public var poster: RecipePoster? public var adTags: String? public var yieldNumber: Int? public var isBookmark: Bool? = false public var bookmarkSiteLogo: String? public var isPrivate: Bool? = false public var starRating: Float? public var creationDate: String? public var imageURL: String? public var ingredients: [Ingredients]? public var totalMinutes: Int? public var recipeID: Int? public var notesCount: Int? public var category: String? public var isSponsored: Bool? = false public var subcategory: String? public var nutritionInfo: NutritionInfo? public var verifiedByClass: String? public var cuisine: String? public var verifiedDateTime: String? public var webURL: String? public var reviewCount: Int? public var medalCount: Int? public var maxImageSquare: Int? public var title: String? public var favoriteCount: Int? public var primaryIngredient: String? public var yieldUnit: String? public var menuCount: Int? public var description: String? public var lastModified: String? public var allCategoriesText: String? public var imageSquares: [Int]? public var instructions: String? public var photoUrl: String? public var activeMinutes: Int? public var adminBoost: Int? init() { } // MARK: SwiftyJSON Initializers /// Initiates the instance based on the object. /// /// - parameter object: The object of either Dictionary or Array kind that was passed. /// - returns: An initialized instance of the class. public convenience init(object: Any) { self.init(json: JSON(object)) } /// Initiates the instance based on the JSON that was passed. /// /// - parameter json: JSON object from SwiftyJSON. public required init(json: JSON) { collection = json[SerializationKeys.collection].string poster = RecipePoster(json: json[SerializationKeys.poster]) adTags = json[SerializationKeys.adTags].string yieldNumber = json[SerializationKeys.yieldNumber].int isBookmark = json[SerializationKeys.isBookmark].boolValue bookmarkSiteLogo = json[SerializationKeys.bookmarkSiteLogo].string isPrivate = json[SerializationKeys.isPrivate].boolValue starRating = json[SerializationKeys.starRating].float creationDate = json[SerializationKeys.creationDate].string imageURL = json[SerializationKeys.imageURL].string if let items = json[SerializationKeys.ingredients].array { ingredients = items.map { Ingredients(json: $0) } } totalMinutes = json[SerializationKeys.totalMinutes].int recipeID = json[SerializationKeys.recipeID].int notesCount = json[SerializationKeys.notesCount].int category = json[SerializationKeys.category].string isSponsored = json[SerializationKeys.isSponsored].boolValue subcategory = json[SerializationKeys.subcategory].string nutritionInfo = NutritionInfo(json: json[SerializationKeys.nutritionInfo]) verifiedByClass = json[SerializationKeys.verifiedByClass].string cuisine = json[SerializationKeys.cuisine].string verifiedDateTime = json[SerializationKeys.verifiedDateTime].string webURL = json[SerializationKeys.webURL].string reviewCount = json[SerializationKeys.reviewCount].int medalCount = json[SerializationKeys.medalCount].int maxImageSquare = json[SerializationKeys.maxImageSquare].int title = json[SerializationKeys.title].string favoriteCount = json[SerializationKeys.favoriteCount].int primaryIngredient = json[SerializationKeys.primaryIngredient].string yieldUnit = json[SerializationKeys.yieldUnit].string menuCount = json[SerializationKeys.menuCount].int description = json[SerializationKeys.description].string lastModified = json[SerializationKeys.lastModified].string allCategoriesText = json[SerializationKeys.allCategoriesText].string if let items = json[SerializationKeys.imageSquares].array { imageSquares = items.map { $0.intValue } } instructions = json[SerializationKeys.instructions].string photoUrl = json[SerializationKeys.photoUrl].string activeMinutes = json[SerializationKeys.activeMinutes].int adminBoost = json[SerializationKeys.adminBoost].int } /// Generates description of the object in the form of a NSDictionary. /// /// - returns: A Key value pair containing all valid values in the object. public func dictionaryRepresentation() -> [String: Any] { var dictionary: [String: Any] = [:] if let value = collection { dictionary[SerializationKeys.collection] = value } if let value = poster { dictionary[SerializationKeys.poster] = value.dictionaryRepresentation() } if let value = adTags { dictionary[SerializationKeys.adTags] = value } if let value = yieldNumber { dictionary[SerializationKeys.yieldNumber] = value } dictionary[SerializationKeys.isBookmark] = isBookmark if let value = bookmarkSiteLogo { dictionary[SerializationKeys.bookmarkSiteLogo] = value } dictionary[SerializationKeys.isPrivate] = isPrivate if let value = starRating { dictionary[SerializationKeys.starRating] = value } if let value = creationDate { dictionary[SerializationKeys.creationDate] = value } if let value = imageURL { dictionary[SerializationKeys.imageURL] = value } if let value = ingredients { dictionary[SerializationKeys.ingredients] = value.map { $0.dictionaryRepresentation() } } if let value = totalMinutes { dictionary[SerializationKeys.totalMinutes] = value } if let value = recipeID { dictionary[SerializationKeys.recipeID] = value } if let value = notesCount { dictionary[SerializationKeys.notesCount] = value } if let value = category { dictionary[SerializationKeys.category] = value } dictionary[SerializationKeys.isSponsored] = isSponsored if let value = subcategory { dictionary[SerializationKeys.subcategory] = value } if let value = nutritionInfo { dictionary[SerializationKeys.nutritionInfo] = value.dictionaryRepresentation() } if let value = verifiedByClass { dictionary[SerializationKeys.verifiedByClass] = value } if let value = cuisine { dictionary[SerializationKeys.cuisine] = value } if let value = verifiedDateTime { dictionary[SerializationKeys.verifiedDateTime] = value } if let value = webURL { dictionary[SerializationKeys.webURL] = value } if let value = reviewCount { dictionary[SerializationKeys.reviewCount] = value } if let value = medalCount { dictionary[SerializationKeys.medalCount] = value } if let value = maxImageSquare { dictionary[SerializationKeys.maxImageSquare] = value } if let value = title { dictionary[SerializationKeys.title] = value } if let value = favoriteCount { dictionary[SerializationKeys.favoriteCount] = value } if let value = primaryIngredient { dictionary[SerializationKeys.primaryIngredient] = value } if let value = yieldUnit { dictionary[SerializationKeys.yieldUnit] = value } if let value = menuCount { dictionary[SerializationKeys.menuCount] = value } if let value = description { dictionary[SerializationKeys.description] = value } if let value = lastModified { dictionary[SerializationKeys.lastModified] = value } if let value = allCategoriesText { dictionary[SerializationKeys.allCategoriesText] = value } if let value = imageSquares { dictionary[SerializationKeys.imageSquares] = value } if let value = instructions { dictionary[SerializationKeys.instructions] = value } if let value = photoUrl { dictionary[SerializationKeys.photoUrl] = value } if let value = activeMinutes { dictionary[SerializationKeys.activeMinutes] = value } if let value = adminBoost { dictionary[SerializationKeys.adminBoost] = value } return dictionary } }
48.712121
122
0.748782
b94236cd4999340e59077e8fa797de9e71a9795d
916
// // Copyright (c) 2020 Arpit Lokwani // // 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 //------------------------------------------------------------------------------------------------------------------------------------------------- extension Error { //--------------------------------------------------------------------------------------------------------------------------------------------- func code() -> Int { return (self as NSError).code } }
39.826087
147
0.504367
8f537969e8a641773ac06a4825b5330a97bb73cd
3,885
// // SSKRSetup.swift // Gordian Guardian // // Created by Wolf McNally on 12/16/20. // import SwiftUI import WolfSwiftUI struct SSKRSetup: View { let seed: Seed @Binding var isPresented: Bool @StateObject private var model: SSKRModel init(seed: Seed, isPresented: Binding<Bool>) { self.seed = seed self._isPresented = isPresented self._model = StateObject(wrappedValue: SSKRModel()) } var body: some View { NavigationView { VStack { ModelObjectIdentity(model: .constant(seed)) .frame(height: 100) .padding() Form { Section() { Stepper("Number of Groups: \(model.numberOfGroups)", value: $model.numberOfGroups.animation(), in: model.groupsRange) .accessibility(label: Text("Number of Groups")) .accessibility(value: Text(String(describing: model.numberOfGroups))) if model.groups.count > 1 { Stepper("Group Threshold: \(model.groupThreshold)", value: $model.groupThreshold.animation(), in: model.groupThresholdRange) .accessibility(label: Text("Group Threshold")) .accessibility(value: Text(String(describing: model.groupThreshold))) Text(model.note) .font(.caption) } } .font(.callout) ForEach(model.groups.indices, id: \.self) { index in GroupView(index: index, count: model.groups.count, group: model.groups[index]) } .font(.callout) NavigationLink( destination: LazyView(SSKRDisplay(seed: seed, model: model, isPresented: $isPresented)), label: { Button { } label: { Text("Next") .bold() .frame(maxWidth: .infinity) } }) .accessibility(label: Text("Next")) } } .frame(maxWidth: 500) .navigationTitle("SSKR Export") .navigationBarItems(leading: CancelButton($isPresented)) } .copyConfirmation() .navigationViewStyle(StackNavigationViewStyle()) } struct GroupView: View { let index: Int let count: Int @ObservedObject var group: SSKRModelGroup var body: some View { Section(header: Text(count > 1 ? "Group \(index + 1)" : "")) { Stepper("Number of Shares: \(group.count)", value: $group.count.animation(), in: group.countRange) .accessibility(label: Text("Group \(index + 1): Number of Shares")) .accessibility(value: Text(String(describing: group.count))) if group.count > 1 { Stepper("Threshold: \(group.threshold)", value: $group.threshold.animation(), in: group.thresholdRange) .accessibility(label: Text("Group \(index + 1): Threshold")) .accessibility(value: Text(String(describing: group.threshold))) if group.count > 1 { Text(group.note) .font(.caption) } } } } } } #if DEBUG import WolfLorem struct SSKRSetup_Previews: PreviewProvider { static let seed = Lorem.seed() static var previews: some View { SSKRSetup(seed: seed, isPresented: .constant(true)) .darkMode() } } #endif
37.355769
152
0.493951
cc5c4f2eaf057e143f0f232bdc0bb021db3fc458
18,999
// // WebimActions.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 11.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Class that is responsible for history storage when it is set to memory mode. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ class WebimActions { // MARK: - Constants enum ContentType: String { case multipartBody = "multipart/form-data; boundary=" // + boundary string case urlEncoded = "application/x-www-form-urlencoded" } enum Event: String { case initialization = "init" } enum Parameter: String { case actionn = "action" case applicationVersion = "app-version" case authorizationToken = "auth-token" case beforeTimestamp = "before-ts" case buttonId = "button-id" case chatMode = "chat-mode" case clientSideID = "client-side-id" case data = "data" case deleteDraft = "del-message-draft" case departmentKey = "department-key" case deviceID = "device-id" case deviceToken = "push-token" case draft = "message-draft" case event = "event" case firstQuestion = "first-question" case forceOnline = "force-online" case hintQuestion = "hint_question" case location = "location" case message = "message" case operatorID = "operator_id" case pageID = "page-id" case platform = "platform" case providedAuthenticationToken = "provided_auth_token" case quote = "quote" case rating = "rate" case respondImmediately = "respond-immediately" case requestMessageId = "request-message-id" case visitSessionID = "visit-session-id" case since = "since" case timestamp = "ts" case title = "title" case visitor = "visitor" case visitorExt = "visitor-ext" case visitorTyping = "typing" case prechat = "prechat-key-independent-fields" case customFields = "custom_fields" } enum Platform: String { case ios = "ios" } enum ServerPathSuffix: String { case doAction = "/l/v/m/action" case getDelta = "/l/v/m/delta" case downloadFile = "/l/v/m/download" case getHistory = "/l/v/m/history" case uploadFile = "/l/v/m/upload" } enum MultipartBody: String { case name = "webim_upload_file" } private enum ChatMode: String { case online = "online" } private enum Action: String { case closeChat = "chat.close" case rateOperator = "chat.operator_rate_select" case respondSentryCall = "chat.action_request.call_sentry_action_request" case sendMessage = "chat.message" case deleteMessage = "chat.delete_message" case setDeviceToken = "set_push_token" case setPrechat = "chat.set_prechat_fields" case setVisitorTyping = "chat.visitor_typing" case startChat = "chat.start" case chatRead = "chat.read_by_visitor" case widgetUpdate = "widget.update" case keyboardResponse = "chat.keyboard_response" } // MARK: - Properties private let baseURL: String private let actionRequestLoop: ActionRequestLoop // MARK: - Initialization init(baseURL: String, actionRequestLoop: ActionRequestLoop) { self.baseURL = baseURL self.actionRequestLoop = actionRequestLoop } // MARK: - Methods func send(message: String, clientSideID: String, dataJSONString: String?, isHintQuestion: Bool?, dataMessageCompletionHandler: DataMessageCompletionHandler? = nil, editMessageCompletionHandler: EditMessageCompletionHandler? = nil) { var dataToPost = [Parameter.actionn.rawValue: Action.sendMessage.rawValue, Parameter.clientSideID.rawValue: clientSideID, Parameter.message.rawValue: message] as [String: Any] if let isHintQuestion = isHintQuestion { dataToPost[Parameter.hintQuestion.rawValue] = isHintQuestion ? "1" : "0" // True / false. } if let dataJSONString = dataJSONString { dataToPost[Parameter.data.rawValue] = dataJSONString } let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, messageID: clientSideID, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString, dataMessageCompletionHandler: dataMessageCompletionHandler, editMessageCompletionHandler: editMessageCompletionHandler)) } func send(file: Data, filename: String, mimeType: String, clientSideID: String, completionHandler: SendFileCompletionHandler?) { let dataToPost = [Parameter.chatMode.rawValue: ChatMode.online.rawValue, Parameter.clientSideID.rawValue: clientSideID] as [String: Any] let urlString = baseURL + ServerPathSuffix.uploadFile.rawValue let boundaryString = NSUUID().uuidString actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, messageID: clientSideID, filename: filename, mimeType: mimeType, fileData: file, boundaryString: boundaryString, contentType: (ContentType.multipartBody.rawValue + boundaryString), baseURLString: urlString, sendFileCompletionHandler: completionHandler)) } func replay(message: String, clientSideID: String, quotedMessageID: String) { let dataToPost = [Parameter.actionn.rawValue: Action.sendMessage.rawValue, Parameter.clientSideID.rawValue: clientSideID, Parameter.message.rawValue: message, Parameter.quote.rawValue: getQuotedMessage(repliedMessageId: quotedMessageID)] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, messageID: clientSideID, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } private func getQuotedMessage(repliedMessageId: String) -> String { return "{\"ref\":{\"msgId\":\"\(repliedMessageId)\",\"msgChannelSideId\":null,\"chatId\":null}}"; } func delete(clientSideID: String, completionHandler: DeleteMessageCompletionHandler?) { let dataToPost = [Parameter.actionn.rawValue: Action.deleteMessage.rawValue, Parameter.clientSideID.rawValue: clientSideID] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, messageID: clientSideID, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString, deleteMessageCompletionHandler: completionHandler)) } func startChat(withClientSideID clientSideID: String, firstQuestion: String? = nil, departmentKey: String? = nil, customFields: String? = nil) { var dataToPost = [Parameter.actionn.rawValue: Action.startChat.rawValue, Parameter.forceOnline.rawValue: "1", // true Parameter.clientSideID.rawValue: clientSideID] as [String: Any] if let firstQuestion = firstQuestion { dataToPost[Parameter.firstQuestion.rawValue] = firstQuestion } if let departmentKey = departmentKey { dataToPost[Parameter.departmentKey.rawValue] = departmentKey } if let custom_fields = customFields { dataToPost[Parameter.customFields.rawValue] = custom_fields } let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func closeChat() { let dataToPost = [Parameter.actionn.rawValue: Action.closeChat.rawValue] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func set(visitorTyping: Bool, draft: String?, deleteDraft: Bool) { var dataToPost = [Parameter.actionn.rawValue: Action.setVisitorTyping.rawValue, Parameter.deleteDraft.rawValue: deleteDraft ? "1" : "0", // true / false Parameter.visitorTyping.rawValue: visitorTyping ? "1" : "0"] as [String: Any] // true / false if let draft = draft { dataToPost[Parameter.draft.rawValue] = draft } let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func set(prechatFields: String) { let dataToPost = [Parameter.actionn.rawValue: Action.setPrechat.rawValue, Parameter.prechat.rawValue: prechatFields] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func requestHistory(since: String?, completion: @escaping (_ data: Data?) throws -> ()) { var dataToPost = [String: Any]() if let since = since { dataToPost[Parameter.since.rawValue] = since } let urlString = baseURL + ServerPathSuffix.getHistory.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, historyRequestCompletionHandler: completion)) } func requestHistory(beforeMessageTimestamp: Int64, completion: @escaping (_ data: Data?) throws -> ()) { let dataToPost = [Parameter.beforeTimestamp.rawValue: String(beforeMessageTimestamp)] as [String: Any] let urlString = baseURL + ServerPathSuffix.getHistory.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .get, primaryData: dataToPost, baseURLString: urlString, historyRequestCompletionHandler: completion)) } func rateOperatorWith(id: String?, rating: Int, completionHandler: RateOperatorCompletionHandler?) { var dataToPost = [Parameter.actionn.rawValue: Action.rateOperator.rawValue, Parameter.rating.rawValue: String(rating)] as [String: Any] if let id = id { dataToPost[Parameter.operatorID.rawValue] = id } let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString, rateOperatorCompletionHandler: completionHandler)) } func respondSentryCall(id: String) { let dataToPost = [Parameter.actionn.rawValue: Action.respondSentryCall.rawValue, Parameter.clientSideID.rawValue: id] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func update(deviceToken: String) { let dataToPost = [Parameter.actionn.rawValue: Action.setDeviceToken.rawValue, Parameter.deviceToken.rawValue: deviceToken] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func setChatRead() { let dataToPost = [Parameter.actionn.rawValue: Action.chatRead.rawValue] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func updateWidgetStatusWith(data: String) { let dataToPost = [Parameter.actionn.rawValue: Action.widgetUpdate.rawValue, Parameter.data.rawValue: data] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString)) } func sendKeyboardRequest(buttonId: String, messageId: String, completionHandler: SendKeyboardRequestCompletionHandler?) { let dataToPost = [Parameter.actionn.rawValue: Action.keyboardResponse.rawValue, Parameter.buttonId.rawValue: buttonId, Parameter.requestMessageId.rawValue: messageId] as [String: Any] let urlString = baseURL + ServerPathSuffix.doAction.rawValue actionRequestLoop.enqueue(request: WebimRequest(httpMethod: .post, primaryData: dataToPost, messageID: messageId, contentType: ContentType.urlEncoded.rawValue, baseURLString: urlString, keyboardResponseCompletionHandler: completionHandler)) } }
48.590793
123
0.539239
f5845f551ea36f766077a95d8c271db998cf0233
2,020
// // HttpApi.swift // Moco360 // // Created by Mark G on 3/18/20. // Copyright © 2020 Mobiclix. All rights reserved. // import Foundation import Promises import Alamofire // MARK: - Protocol public typealias RequestHandler = () -> Promise<Data> public protocol ApiService { func request( method: HttpMethod, baseUrl: String?, endPoint: String, token: String?, params: HttpParametable? ) -> Promise<ApiResponse> func upload( method: HttpMethod, baseUrl: String?, endPoint: String, token: String?, params: FormDataParametable ) -> Promise<ApiResponse> func download( method: HttpMethod, baseUrl: String?, endPoint: String, token: String?, params: HttpParametable ) -> Promise<URL> } public extension ApiService { func request( method: HttpMethod, baseUrl: String? = nil, endPoint: String, token: String? = nil, params: HttpParametable? = nil ) -> Promise<ApiResponse> { request( method: method, baseUrl: baseUrl, endPoint: endPoint, token: token, params: params ) } func upload( method: HttpMethod, baseUrl: String? = nil, endPoint: String, token: String? = nil, params: FormDataParametable ) -> Promise<ApiResponse> { upload( method: method, baseUrl: baseUrl, endPoint: endPoint, token: token, params: params ) } func download( method: HttpMethod, baseUrl: String? = nil, endPoint: String, token: String? = nil, params: HttpParametable ) -> Promise<URL> { download( method: method, baseUrl: baseUrl, endPoint: endPoint, token: token, params: params ) } }
21.956522
53
0.531683
f804d3216ffeb8a9003f63c40f7db18f340351af
2,394
// // Example // man.li // // Created by man.li on 11/11/2018. // Copyright © 2020 man.li. All rights reserved. // import Foundation import UIKit class NetworkDetailCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentTextView: CustomTextView! @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var titleView: UIView! @IBOutlet weak var topLine: UIView! @IBOutlet weak var middleLine: UIView! @IBOutlet weak var bottomLine: UIView! @IBOutlet weak var editView: UIView! @IBOutlet weak var titleViewBottomSpaceToMiddleLine: NSLayoutConstraint! //-12.5 var tapEditViewCallback:((NetworkDetailModel?) -> Void)? var detailModel: NetworkDetailModel? { didSet { titleLabel.text = detailModel?.title contentTextView.text = detailModel?.content //图片 if detailModel?.image == nil { imgView.isHidden = true } else { imgView.isHidden = false imgView.image = detailModel?.image } //自动隐藏内容 if detailModel?.blankContent == "..." { middleLine.isHidden = true imgView.isHidden = true titleViewBottomSpaceToMiddleLine.constant = -12.5 + 2 } else { middleLine.isHidden = false if detailModel?.image != nil { imgView.isHidden = false } titleViewBottomSpaceToMiddleLine.constant = 0 } //底部分割线 if detailModel?.isLast == true { bottomLine.isHidden = false } else { bottomLine.isHidden = true } } } //MARK: - awakeFromNib override func awakeFromNib() { super.awakeFromNib() editView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(tapEditView))) contentTextView.textContainer.lineFragmentPadding = 0 contentTextView.textContainerInset = .zero } //MARK: - target action //编辑 @objc func tapEditView() { if let tapEditViewCallback = tapEditViewCallback { tapEditViewCallback(detailModel) } } }
28.5
112
0.562657
cc6e09eb8bd8fd6c79a6f6d1ac9d2c67774d677e
600
// RUN: %target-swift-frontend -emit-sil -verify %s // rdar://problem/29716016 - Check that we properly enforce DI on `let` // variables and class properties. protocol P { } extension P { mutating func foo() {} var bar: Int { get { return 0 } set {} } } class ImmutableP { let field: P // expected-note* {{}} init(field: P) { self.field = field self.field.foo() // expected-error{{}} self.field.bar = 4 // expected-error{{}} } } func immutableP(field: P) { let x: P // expected-note* {{}} x = field x.foo() // expected-error{{}} x.bar = 4 // expected-error{{}} }
20
71
0.6
1aba7ca57abd5826e282f66c9d8421ae34c73f01
27,189
// // UPnPEventSubscriptionManager.swift // // Copyright (c) 2015 David Robles // // 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 import AFNetworking import GCDWebServer protocol UPnPEventSubscriber: class { func handleEvent(_ eventSubscriptionManager: UPnPEventSubscriptionManager, eventXML: Data) func subscriptionDidFail(_ eventSubscriptionManager: UPnPEventSubscriptionManager) } class UPnPEventSubscriptionManager { // Subclasses NSObject in order to filter collections of this class using NSPredicate class Subscription: NSObject { fileprivate(set) var subscriptionID: String fileprivate(set) var expiration: Date weak var subscriber: UPnPEventSubscriber? let eventURLString: String fileprivate unowned let _manager: UPnPEventSubscriptionManager fileprivate var _renewDate: Date { return expiration.addingTimeInterval(-30) // attempt renewal 30 seconds before expiration } fileprivate var _renewWarningTimer: Timer? fileprivate var _expirationTimer: Timer? init(subscriptionID: String, expiration: Date, subscriber: UPnPEventSubscriber, eventURLString: String, manager: UPnPEventSubscriptionManager) { self.subscriptionID = subscriptionID self.expiration = expiration self.subscriber = subscriber self.eventURLString = eventURLString _manager = manager super.init() updateTimers() } func invalidate() { _renewWarningTimer?.invalidate() _expirationTimer?.invalidate() } func update(_ subscriptionID: String, expiration: Date) { self.invalidate() self.subscriptionID = subscriptionID self.expiration = expiration updateTimers() } fileprivate func updateTimers() { let renewDate = _renewDate let expiration = self.expiration DispatchQueue.main.async(execute: { () -> Void in self._renewWarningTimer = Timer.scheduledTimerWithTimeInterval(renewDate.timeIntervalSinceNow, repeats: false, closure: { [weak self] () -> Void in if let strongSelf = self { strongSelf._manager.subscriptionNeedsRenewal(strongSelf) } }) self._expirationTimer = Timer.scheduledTimerWithTimeInterval(expiration.timeIntervalSinceNow, repeats: false, closure: { [weak self] () -> Void in if let strongSelf = self { strongSelf._manager.subscriptionDidExpire(strongSelf) } }) }) } } // internal static let sharedInstance = UPnPEventSubscriptionManager() // private /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue fileprivate var _subscriptions = [String: Subscription]() /* [eventURLString: Subscription] */ fileprivate let _concurrentSubscriptionQueue = DispatchQueue(label: "com.upnatom.upnp-event-subscription-manager.subscription-queue", attributes: DispatchQueue.Attributes.concurrent) /// Must be accessed within the subscription manager's concurrent queue fileprivate var _httpServer: GCDWebServer! // TODO: Should ideally be a constant, non-optional, see Github issue #10 fileprivate let _httpServerPort: UInt = 52808 fileprivate let _subscribeSessionManager = AFHTTPSessionManager() fileprivate let _renewSubscriptionSessionManager = AFHTTPSessionManager() fileprivate let _unsubscribeSessionManager = AFHTTPSessionManager() fileprivate let _defaultSubscriptionTimeout: Int = 1800 fileprivate let _eventCallBackPath = "/Event/\(UUID().dashlessUUIDString)" init() { _subscribeSessionManager.requestSerializer = UPnPEventSubscribeRequestSerializer() _subscribeSessionManager.responseSerializer = UPnPEventSubscribeResponseSerializer() _renewSubscriptionSessionManager.requestSerializer = UPnPEventRenewSubscriptionRequestSerializer() _renewSubscriptionSessionManager.responseSerializer = UPnPEventRenewSubscriptionResponseSerializer() _unsubscribeSessionManager.requestSerializer = UPnPEventUnsubscribeRequestSerializer() _unsubscribeSessionManager.responseSerializer = UPnPEventUnsubscribeResponseSerializer() #if os(iOS) NotificationCenter.default.addObserver(self, selector: #selector(UIApplicationDelegate.applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(UIApplicationDelegate.applicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) #endif /// GCDWebServer must be initialized on the main thread. In order to guarantee this, it's initialization is dispatched on the main queue. To prevent critical sections from accessing it before it is initialized, the dispatch is synchronized within a dispatch barrier to the subscription manager's critical section queue. _concurrentSubscriptionQueue.async(flags: .barrier, execute: { () -> Void in DispatchQueue.main.sync(execute: { () -> Void in self._httpServer = GCDWebServer() GCDWebServer.setLogLevel(Int32(3)) self._httpServer.addHandler(forMethod: "NOTIFY", path: self._eventCallBackPath, request: GCDWebServerDataRequest.self) { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in if let dataRequest = request as? GCDWebServerDataRequest, let headers = dataRequest.headers as? [String: AnyObject], let sid = headers["SID"] as? String { let data = dataRequest.data LogVerbose("NOTIFY request: Final body with size: \(data.count)\nAll headers: \(headers)") self.handleIncomingEvent(subscriptionID: sid, eventData: data) } return GCDWebServerResponse() } }) }) } /// Subscribers should hold on to a weak reference of the subscription object returned. It's ok to call subscribe for a subscription that already exists, the subscription will simply be looked up and returned. func subscribe(_ subscriber: UPnPEventSubscriber, eventURL: URL, completion: ((_ result: Result<AnyObject>) -> Void)? = nil) { let failureClosure = { (error: NSError) -> Void in if let completion = completion { completion(.failure(error as NSError)) } } let eventURLString = eventURL.absoluteString // check if subscription for event URL already exists subscriptions { [unowned self] (subscriptions: [String: Subscription]) -> Void in if let subscription = subscriptions[eventURLString] { if let completion = completion { completion(Result.success(subscription)) } return } self.eventCallBackURL({ [unowned self] (eventCallBackURL: URL?) -> Void in guard let eventCallBackURL: URL = eventCallBackURL else { failureClosure(createError("Event call back URL could not be created") as NSError) return } LogInfo("event callback url: \(eventCallBackURL)") let parameters = UPnPEventSubscribeRequestSerializer.Parameters(callBack: eventCallBackURL, timeout: self._defaultSubscriptionTimeout) let _ = self._subscribeSessionManager.SUBSCRIBE(eventURL.absoluteString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in guard let response: UPnPEventSubscribeResponseSerializer.Response = responseObject as? UPnPEventSubscribeResponseSerializer.Response else { failureClosure(createError("Failure serializing event subscribe response") as NSError) return } let now = Date() let expiration = now.addingTimeInterval(TimeInterval(response.timeout)) let subscription = Subscription(subscriptionID: response.subscriptionID, expiration: expiration, subscriber: subscriber, eventURLString: eventURL.absoluteString, manager: self) LogInfo("Successfully subscribed with timeout: \(response.timeout/60) mins: \(subscription)") self.add(subscription: subscription, completion: { () -> Void in if let completion = completion { completion(Result.success(subscription)) } }) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in LogError("Failed to subscribe to event URL: \(eventURL.absoluteString)\nerror: \(error)") failureClosure(error as NSError) }) }) } } func unsubscribe(_ subscription: AnyObject, completion: ((_ result: EmptyResult) -> Void)? = nil) { guard let subscription: Subscription = subscription as? Subscription else { if let completion = completion { completion(.failure(createError("Failure using subscription object passed in"))) } return } // remove local version of subscription immediately to prevent any race conditions self.remove(subscription: subscription, completion: { [unowned self] () -> Void in let parameters = UPnPEventUnsubscribeRequestSerializer.Parameters(subscriptionID: subscription.subscriptionID) let _ = self._unsubscribeSessionManager.UNSUBSCRIBE(subscription.eventURLString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in LogInfo("Successfully unsubscribed: \(subscription)") if let completion = completion { completion(.success) } }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in LogError("Failed to unsubscribe: \(subscription)\nerror: \(error)") if let completion = completion { completion(.failure(error as NSError)) } }) }) } fileprivate func handleIncomingEvent(subscriptionID: String, eventData: Data) { subscriptions { (subscriptions: [String: Subscription]) -> Void in if let subscription: Subscription = (Array(subscriptions.values) as NSArray).firstUsingPredicate(NSPredicate(format: "subscriptionID = %@", subscriptionID)) { DispatchQueue.main.async(execute: { () -> Void in subscription.subscriber?.handleEvent(self, eventXML: eventData) return }) } } } @objc fileprivate func applicationDidEnterBackground(_ notification: Notification) { // GCDWebServer handles stopping and restarting itself as appropriate during application life cycle events. Invalidating the timers is all that's necessary here :) subscriptions { (subscriptions: [String: Subscription]) -> Void in DispatchQueue.main.async(execute: { () -> Void in // invalidate all timers before being backgrounded as the will be trashed upon foregrounding anyways for (_, subscription) in subscriptions { subscription.invalidate() } }) } } @objc fileprivate func applicationWillEnterForeground(_ notification: Notification) { subscriptions { [unowned self] (subscriptions: [String: Subscription]) -> Void in // unsubscribe and re-subscribe for all event subscriptions for (_, subscription) in subscriptions { self.unsubscribe(subscription, completion: { (result) -> Void in self.resubscribe(subscription, completion: { if let error = $0.error as NSError?, let errorDescription = error.localizedDescriptionOrNil { LogError("\(errorDescription)") } }) }) } } } fileprivate func add(subscription: Subscription, completion: (() -> Void)? = nil) { self._concurrentSubscriptionQueue.async(flags: .barrier, execute: { () -> Void in self._subscriptions[subscription.eventURLString] = subscription self.startStopHTTPServerIfNeeded(self._subscriptions.count) if let completion = completion { DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: { () -> Void in completion() }) } }) } fileprivate func remove(subscription: Subscription, completion: (() -> Void)? = nil) { self._concurrentSubscriptionQueue.async(flags: .barrier, execute: { () -> Void in self._subscriptions.removeValue(forKey: subscription.eventURLString)?.invalidate() self.startStopHTTPServerIfNeeded(self._subscriptions.count) if let completion = completion { DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: { () -> Void in completion() }) } }) } fileprivate func eventCallBackURL(_ closure: @escaping (_ eventCallBackURL: URL?) -> Void) { // only reading subscriptions, so distpach_async is appropriate to allow for concurrent reads self._concurrentSubscriptionQueue.async(execute: { () -> Void in // needs to be running in order to get server url for the subscription message let httpServer = self._httpServer var serverURL: URL? = httpServer?.serverURL // most likely nil if the http server is stopped if serverURL == nil && !(httpServer?.isRunning)! { // Start http server if self.startHTTPServer() { // Grab server url serverURL = httpServer?.serverURL // Stop http server if it's not needed further self.startStopHTTPServerIfNeeded(self._subscriptions.count) } else { LogError("Error starting HTTP server") } } DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: { () -> Void in serverURL != nil ? closure(URL(string: self._eventCallBackPath, relativeTo: serverURL)!) : closure(nil) }) }) } /// Safe to call from any queue and closure is called on callback queue fileprivate func subscriptions(_ closure: @escaping (_ subscriptions: [String: Subscription]) -> Void) { // only reading subscriptions, so distpach_async is appropriate to allow for concurrent reads self._concurrentSubscriptionQueue.async(execute: { () -> Void in let subscriptions = self._subscriptions DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: { () -> Void in closure(subscriptions) }) }) } /// Must be called with the most up to date knowledge of the subscription count so should be called withing the subscription queue. // TODO: consider putting entire method inside a dispatch_barrier_async to subscription queue fileprivate func startStopHTTPServerIfNeeded(_ subscriptionCount: Int) { let httpServer = self._httpServer if subscriptionCount == 0 && (httpServer?.isRunning)! { if !stopHTTPServer() { LogError("Error stopping HTTP server") } } else if subscriptionCount > 0 && !(httpServer?.isRunning)! { if !startHTTPServer() { LogError("Error starting HTTP server") } } } fileprivate func renewSubscription(_ subscription: Subscription, completion: ((_ result: Result<AnyObject>) -> Void)? = nil) { guard subscription.subscriber != nil else { if let completion = completion { completion(.failure(createError("Subscriber doesn't exist anymore"))) } return } let parameters = UPnPEventRenewSubscriptionRequestSerializer.Parameters(subscriptionID: subscription.subscriptionID, timeout: _defaultSubscriptionTimeout) let _ = _renewSubscriptionSessionManager.SUBSCRIBE(subscription.eventURLString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in guard let response: UPnPEventRenewSubscriptionResponseSerializer.Response = responseObject as? UPnPEventRenewSubscriptionResponseSerializer.Response else { if let completion = completion { completion(.failure(createError("Failure serializing event subscribe response"))) } return } let now = Date() let expiration = now.addingTimeInterval(TimeInterval(response.timeout)) subscription.update(response.subscriptionID, expiration: expiration) LogInfo("Successfully renewed subscription with timeout: \(response.timeout/60) mins: \(subscription)") // read just in case it was removed self.add(subscription: subscription, completion: { () -> Void in if let completion = completion { completion(Result.success(subscription)) } }) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in LogError("Failed to renew subscription: \(subscription)\nerror: \(error)") if let completion = completion { completion(.failure(error as NSError)) } }) } fileprivate func resubscribe(_ subscription: Subscription, completion: ((_ result: Result<AnyObject>) -> Void)? = nil) { // remove, just in case resubscription fails remove(subscription: subscription) let failureClosure = { (error: NSError) -> Void in subscription.subscriber?.subscriptionDidFail(self) if let completion = completion { completion(.failure(error as NSError)) } } // re-subscribe only if subscriber still exists guard subscription.subscriber != nil else { failureClosure(createError("Subscriber doesn't exist anymore") as NSError) return } self.eventCallBackURL({ [unowned self] (eventCallBackURL: URL?) -> Void in guard let eventCallBackURL: URL = eventCallBackURL else { failureClosure(createError("Event call back URL could not be created") as NSError) return } let parameters = UPnPEventSubscribeRequestSerializer.Parameters(callBack: eventCallBackURL, timeout: self._defaultSubscriptionTimeout) let _ = self._subscribeSessionManager.SUBSCRIBE(subscription.eventURLString, parameters: parameters, success: { (task: URLSessionDataTask, responseObject: Any?) -> Void in guard let response: UPnPEventSubscribeResponseSerializer.Response = responseObject as? UPnPEventSubscribeResponseSerializer.Response else { failureClosure(createError("Failure serializing event subscribe response") as NSError) return } let now = Date() let expiration = now.addingTimeInterval(TimeInterval(response.timeout)) subscription.update(response.subscriptionID, expiration: expiration) LogInfo("Successfully re-subscribed with timeout: \(response.timeout/60) mins: \(subscription)") self.add(subscription: subscription, completion: { () -> Void in if let completion = completion { completion(Result.success(subscription)) } }) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in LogError("Failed to re-subscribe: \(subscription)\nerror: \(error)") failureClosure(error as NSError) }) }) } fileprivate func subscriptionNeedsRenewal(_ subscription: Subscription) { renewSubscription(subscription) } fileprivate func subscriptionDidExpire(_ subscription: Subscription) { resubscribe(subscription, completion: { if let error = $0.error as NSError?, let errorDescription = error.localizedDescriptionOrNil { LogError("\(errorDescription)") } }) } fileprivate func startHTTPServer() -> Bool { if _httpServer.safeToStart { return _httpServer.start(withPort: _httpServerPort, bonjourName: nil) } return false } fileprivate func stopHTTPServer() -> Bool { if _httpServer.safeToStop { _httpServer.stop() return true } return false } } internal func ==(lhs: UPnPEventSubscriptionManager.Subscription, rhs: UPnPEventSubscriptionManager.Subscription) -> Bool { return lhs.subscriptionID == rhs.subscriptionID } extension UPnPEventSubscriptionManager.Subscription: ExtendedPrintable { #if os(iOS) var className: String { return "Subscription" } #elseif os(OSX) // NSObject.className actually exists on OSX! Who knew. override var className: String { return "Subscription" } #endif override var description: String { var properties = PropertyPrinter() properties.add("subscriptionID", property: subscriptionID) properties.add("expiration", property: expiration) properties.add("eventURLString", property: eventURLString) return properties.description } } extension AFHTTPSessionManager { func SUBSCRIBE(_ URLString: String, parameters: AnyObject, success: ((_ task: URLSessionDataTask, _ responseObject: AnyObject?) -> Void)?, failure: ((_ task: URLSessionDataTask?, _ error: NSError) -> Void)?) -> URLSessionDataTask? { let dataTask = self.dataTask("SUBSCRIBE", URLString: URLString, parameters: parameters, success: success, failure: failure) dataTask?.resume() return dataTask } func UNSUBSCRIBE(_ URLString: String, parameters: AnyObject, success: ((_ task: URLSessionDataTask, _ responseObject: AnyObject?) -> Void)?, failure: ((_ task: URLSessionDataTask?, _ error: NSError) -> Void)?) -> URLSessionDataTask? { let dataTask = self.dataTask("UNSUBSCRIBE", URLString: URLString, parameters: parameters, success: success, failure: failure) dataTask?.resume() return dataTask } fileprivate func dataTask(_ method: String, URLString: String, parameters: AnyObject, success: ((_ task: URLSessionDataTask, _ responseObject: AnyObject?) -> Void)?, failure: ((_ task: URLSessionDataTask?, _ error: NSError) -> Void)?) -> URLSessionDataTask? { let request: URLRequest! var serializationError: NSError? request = self.requestSerializer.request(withMethod: method, urlString: URL(string: URLString, relativeTo: self.baseURL)!.absoluteString, parameters: parameters, error: &serializationError) as URLRequest! if let serializationError = serializationError { if let failure = failure { (self.completionQueue != nil ? self.completionQueue! : DispatchQueue.main).async(execute: { () -> Void in failure(nil, serializationError) }) } return nil } var dataTask: URLSessionDataTask! dataTask = self.dataTask(with: request, completionHandler: { (response: URLResponse, responseObject: Any?, error: Error?) -> Void in if let error = error { if let failure = failure { failure(dataTask, error as NSError) } } else { if let success = success { success(dataTask, responseObject as AnyObject) } } }) return dataTask } } extension GCDWebServer { var safeToStart: Bool { // prevents a crash where although the http server reports running is false, attempting to start while GCDWebServer->_source4 is not null causes abort() to be called which kills the app. GCDWebServer.serverURL == nil is equivalent to GCDWebServer->_source4 == NULL. return !isRunning && serverURL == nil } var safeToStop: Bool { // prevents a crash where http server must actually be running to stop it or abort() is called which kills the app. return isRunning } }
49.979779
327
0.622494
e430c4444bdeeba7cfe4346449d2ae14095579fb
996
// // IntroView.swift // SendbirdExample // // Created by Ernest Hong on 2022/01/18. // import SwiftUI struct IntroView: View { @StateObject var viewModel = IntroViewModel() var body: some View { NavigationView { if let user = viewModel.user { GroupChannelListView(viewModel: .init(user: user)) } else { loginView } } } private var loginView: some View { VStack { Text("Welcome to Sendbird Chat 👋") TextField("Input UserId", text: $viewModel.userId) .multilineTextAlignment(.center) Spacer() Button("Login") { viewModel.login() } .disabled(viewModel.isLoginButtonDisabled) } .padding() .navigationTitle(Text("Sendbird")) } } struct IntroView_Previews: PreviewProvider { static var previews: some View { IntroView() } }
22.133333
66
0.535141
1a6524b23dbb2762fcd20777ec58b7c3cd9f54c0
2,540
// // LoginViewController.swift // recipe.ios // // Created by Shaun Sargent on 3/10/18. // Copyright © 2018 My Family Cooks. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var userNameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! let tokenService = TokenService() let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func logInButtonClick(_ sender: Any) { if let validationError = self.IsValid(){ self.showSimpleAlert(title: "Error", message: validationError) }else{ if let userName = self.userNameTextField.text, let password = self.passwordTextField.text{ // show a spinner. self.showSpinner(activityIndicator: self.spinner) // make a call to the http endpoint. self.tokenService.getToken(userName: userName, password: password, completed: { (success, errorMessage, tokenResponse) in if(success){ // I assume we need to save this token in userDefaults? // where to go from here?? // segue to next Viewcontroller? //self.showSimpleAlert(title: "Token Received", message: tokenResponse!.token) // the user is loggedIn, so self.performSegue(withIdentifier: "loggedIn", sender: self) } else { self.showSimpleAlert(title: "Error", message: errorMessage) } self.stopSpinner(activityIndicatory: self.spinner) }) } } } func IsValid() -> String?{ guard self.userNameTextField.text != nil else { return "Enter user name." } guard self.passwordTextField.text != nil else { return "Enter password." } return nil } }
32.987013
137
0.538976
3904d0ddd56cc8f9371f2d07446d914cad45c32e
1,802
// // ViewController.swift // PreloadURLCache // // Created by [email protected] on 04/27/2021. // Copyright (c) 2021 [email protected]. All rights reserved. // import UIKit import PreloadURLCache import WebKit class ViewController: UIViewController { lazy var preloadUrls = [ // "https://v.qq.com/" "https://www.baidu.com/" ].compactMap { URL(string: $0) } lazy var preloadURLCache = PreloadURLCache(config: { (mk) in mk.isUsingURLProtocol(true) }).then { $0.delegate = self } override func viewDidLoad() { super.viewDidLoad() } @IBAction func preload(_ sender: Any) { URLProtocol.wk_registerScheme("http") URLProtocol.wk_registerScheme("https") preloadURLCache.preloadByWebView(urls: preloadUrls) { (webView, javascriptBridge) in // javascriptBridge.zy_registerLuckySpinHandler(webView, [jsParameterKey_roomId : "roomId"]) } } @IBAction func openWebView(_ sender: Any) { guard let url = preloadUrls.randomElement() else { return } debugPrint(url) let detailViewController = DetailViewController(url: url) show(detailViewController, sender: nil) } } extension ViewController: PreloadURLCacheDelegate { func preloadDidStartLoad(_ preloadURLCache: PreloadURLCache) { debugPrint("开始") } func preloadDidFinishLoad(_ preloadURLCache: PreloadURLCache, webview: WKWebView, remain: UInt) { debugPrint("finish") } func preloadDidFailLoad(_ preloadURLCache: PreloadURLCache) { debugPrint("fail") } func preloadDidAllDone(_ preloadURLCache: PreloadURLCache) { debugPrint("allDone") } }
25.380282
104
0.635405
03babfcba7ddf57773869e5e43f9a54559d5f3a8
6,736
// // // // import UIKit public protocol UIKeyboardInput : NSObjectProtocol { func keyboardInputShouldDelete(_ textView: UITextView) -> Bool } extension UITextView : UIKeyboardInput {} extension UITextView { open var selectedParagraphRange: NSRange { return paragraphRangeForRange(selectedRange) } open var visibleRange: NSRange? { if let start = closestPosition(to: contentOffset) { if let end = characterRange(at: CGPoint(x: contentOffset.x + bounds.maxX, y: contentOffset.y + bounds.maxY))?.end { return NSMakeRange(offset(from: beginningOfDocument, to: start), offset(from: start, to: end)) } } return nil } open var rangeOfPrecedingWord: NSRange? { return rangeOfPrecedingWordWithAcceptableCharacters("@#$&\\-") } open var precedingWord: String? { guard let range = rangeOfPrecedingWord else { return nil } guard text.range.contains(range) else { return nil } return substring(with: range) } open var precedingCharacter: String { return precedingCharacters(1) } open var procedingCharacter: String { return procedingCharacters(1) } open var locationOfNextNonWhitespaceCharacter: Int { guard let expr = try? NSRegularExpression(pattern: "\\S", options: []) else { return NSNotFound } guard let match = expr.firstMatch(in: text, options: [], range: NSMakeRange(selectedRange.location, text.length - selectedRange.location)) else { return NSNotFound } return match.range.location } open var nextNonWhitespaceCharacter: String? { return locationOfNextNonWhitespaceCharacter != NSNotFound ? text.substring(with: NSMakeRange(locationOfNextNonWhitespaceCharacter, 1)) : nil } // MARK: - ** Protocol Methods ** // MARK: - Public Methods open func substring(with range: NSRange) -> String { return text.substring(with: range) } open func paragraphRangeForRange(_ range: NSRange) -> NSRange { return text.paragraphRange(for: range) } @available(iOS 4.0, *) open func enumerateSubstrings(in range: Range<String.Index>, options opts: String.EnumerationOptions, body: @escaping (String?, Range<String.Index>, Range<String.Index>, inout Bool) -> Void) { text.enumerateSubstrings(in: range, options: opts, body) } // MARK: - open func boundingRectForCharacterRange(_ range: NSRange) -> CGRect { var glyphRange = NSRange() layoutManager.characterRange(forGlyphRange: range, actualGlyphRange: &glyphRange) return layoutManager.boundingRect(forGlyphRange: range, in: textContainer) } // MARK: - open func invalidateCharacterDisplayAndLayout() { invalidateCharacterDisplayAndLayoutForCharacterRange(text.range) } open func invalidateCharacterDisplayAndLayoutForCharacterRange(_ range: NSRange) { let range = text.range.contains(range) ? range : text.range layoutManager.invalidateDisplay(forCharacterRange: range) layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil) } open func undo() { undoManager?.undo() } open func redo() { undoManager?.redo() } open func rangeOfPrecedingWordWithAcceptableCharacters(_ characters: String) -> NSRange? { guard let expr = try? NSRegularExpression(pattern: "[\\w\(characters)]+$", options: []) else { return nil } let paragraphRange = paragraphRangeForRange(selectedRange) let searchRange = NSMakeRange(paragraphRange.location, selectedRange.location - paragraphRange.location) guard let match = expr.firstMatch(in: text, options: [.withTransparentBounds], range: searchRange) else { return nil } return match.range } open func precedingCharacters(_ length: Int) -> String { if text.length < length { return "" } return selectedRange.location > length ? text.substring(with: NSMakeRange(selectedRange.location - length, length)) : text.substring(with: NSMakeRange(0, length - selectedRange.location)) } open func procedingCharacters(_ length: Int) -> String { if text.length < selectedRange.location + length { return "" } return selectedRange.location + length <= text.length ? text.substring(with: NSMakeRange(selectedRange.location, length)) : text.substring(with: NSMakeRange(selectedRange.location, text.length - selectedRange.location)) } open func precedingCharactersContainString(_ string: String) -> Bool { guard let expr = try? NSRegularExpression(pattern: string + "$", options: []) else { return false } let paragraphRange = paragraphRangeForRange(selectedRange) let searchRange = NSMakeRange(paragraphRange.location, selectedRange.location - paragraphRange.location) if let _ = expr.firstMatch(in: text, options: [.withTransparentBounds], range: searchRange) { return true } return false } open func precedingCharactersContainString(_ string: String, range: inout NSRange) -> Bool { guard let expr = try? NSRegularExpression(pattern: string + "$", options: []) else { return false } let paragraphRange = paragraphRangeForRange(selectedRange) let searchRange = NSMakeRange(paragraphRange.location, selectedRange.location - paragraphRange.location) if let match = expr.firstMatch(in: text, options: [.withTransparentBounds], range: searchRange) { range = match.range return true } return false } open func procedingCharactersContainString(_ string: String) -> Bool { guard let expr = try? NSRegularExpression(pattern: "^" + string, options: []) else { return false } let searchRange = NSMakeRange(selectedRange.location, text.length - selectedRange.location) if let _ = expr.firstMatch(in: text, options: [.withTransparentBounds], range: searchRange) { return true } return false } open func procedingCharactersContainString(_ string: String, range: inout NSRange) -> Bool { guard let expr = try? NSRegularExpression(pattern: "^" + string, options: []) else { return false } let searchRange = NSMakeRange(selectedRange.location, text.length - selectedRange.location) if let match = expr.firstMatch(in: text, options: [.withTransparentBounds], range: searchRange) { range = match.range return true } return false } }
40.824242
196
0.667904
1cfbbfe8cfd2926ff30ceca8b6e7412e1332c0a2
1,732
// // CLDMultiResult.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation @objcMembers open class CLDMultiResult: CLDBaseResult { // MARK: - Getters open var url: String? { return getParam(.url) as? String } open var secureUrl: String? { return getParam(.secureUrl) as? String } open var publicId: String? { return getParam(.publicId) as? String } open var version: String? { guard let version = getParam(.version) else { return nil } return String(describing: version) } }
33.960784
82
0.691109
8f974582565b0312ef761b00fd897565048ef87e
2,355
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import UIKit final class FeedLightDataSource: XCCollectionViewDataSource { let height = CGFloat(Int.random(in: 100...500)) let color: UIColor = { switch Int.random(in: 0...2) { case 0: return .red case 1: return .green case 2: return .yellow default: return .black } }() override init(collectionView: UICollectionView) { super.init(collectionView: collectionView) } override func numberOfSections(in collectionView: UICollectionView) -> Int { 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(for: indexPath.with(globalSection)) as FeedColorViewCell cell.configure(height: height, color: color) return cell } override func collectionView(_ collectionView: UICollectionView, headerAttributesForSectionAt section: Int) -> (enabled: Bool, size: CGSize?) { (false, nil) } override func collectionView(_ collectionView: UICollectionView, footerAttributesForSectionAt section: Int) -> (enabled: Bool, size: CGSize?) { (false, nil) } override func collectionView(_ collectionView: UICollectionView, viewForHeaderInSectionAt indexPath: IndexPath) -> UICollectionReusableView? { let indexPath = indexPath.with(globalSection) let headerView = collectionView.dequeueReusableSupplementaryView(.header, for: indexPath) as FeedTextHeaderFooterViewCell headerView.configure(title: "S: \(indexPath.section)") return headerView } override func collectionView(_ collectionView: UICollectionView, viewForFooterInSectionAt indexPath: IndexPath) -> UICollectionReusableView? { let indexPath = indexPath.with(globalSection) let footerView = collectionView.dequeueReusableSupplementaryView(.footer, for: indexPath) as FeedTextHeaderFooterViewCell footerView.configure(title: "FOOTER!") return footerView } }
36.796875
147
0.687473
21e339b338189e19304a5b85190f67ad018f3bd5
2,881
// // EZA2DArray+Arithmetic.swift // EZAccelerate // import Foundation import Accelerate extension EZA2DArray { static func +(lhs: EZA2DArray, rhs: EZA2DArray) -> EZA2DArray { var rst = EZA2DArray(row: lhs.row, column: lhs.column) vDSP_vaddD(lhs.content, 1, rhs.content, 1, &rst.content, 1, vDSP_Length(lhs.row*lhs.column)) return rst } static func -(lhs: EZA2DArray, rhs: EZA2DArray) -> EZA2DArray { var rst = EZA2DArray(row: lhs.row, column: lhs.column) vDSP_vsubD(rhs.content, 1, lhs.content, 1, &rst.content, 1, vDSP_Length(lhs.row*lhs.column)) return rst } static func pointWiseProduct(lhs: EZA2DArray, rhs: EZA2DArray) -> EZA2DArray { var rst = EZA2DArray(row: lhs.row, column: lhs.column) vDSP_vmulD(lhs.content, 1, rhs.content, 1, &rst.content, 1, vDSP_Length(lhs.row*lhs.column)) return rst } static func *(lhs: EZA2DArray, rhs: Double) -> EZA2DArray { var rst = EZA2DArray(row: lhs.row, column: lhs.column) var oprand = rhs vDSP_vsmulD(lhs.content, 1, &oprand, &rst.content, 1, vDSP_Length(lhs.row*lhs.column)) return rst } static func *(lhs: Double, rhs: EZA2DArray) -> EZA2DArray { var rst = EZA2DArray(row: rhs.row, column: rhs.column) var oprand = lhs vDSP_vsmulD(rhs.content, 1, &oprand, &rst.content, 1, vDSP_Length(rhs.row*rhs.column)) return rst } static func *(lhs: EZA2DArray, rhs: EZA2DArray) -> EZA2DArray { var rst = EZA2DArray(row: lhs.row, column: rhs.column) if !lhs.transposed { if !rhs.transposed { cblas_dgemm(CBLAS_ORDER(UInt32(102)), CBLAS_TRANSPOSE(UInt32(111)), CBLAS_TRANSPOSE(UInt32(111)), Int32(lhs.row), Int32(rhs.column), Int32(lhs.column), 1, lhs.content, Int32(lhs.row), rhs.content, Int32(rhs.row), 1, &rst.content, Int32(rst.row)) } else { cblas_dgemm(CBLAS_ORDER(UInt32(102)), CBLAS_TRANSPOSE(UInt32(111)), CBLAS_TRANSPOSE(UInt32(112)), Int32(lhs.row), Int32(rhs.column), Int32(lhs.column), 1, lhs.content, Int32(lhs.row), rhs.content, Int32(rhs.column), 1, &rst.content, Int32(rst.row)) } } else { if !rhs.transposed { cblas_dgemm(CBLAS_ORDER(UInt32(102)), CBLAS_TRANSPOSE(UInt32(112)), CBLAS_TRANSPOSE(UInt32(111)), Int32(lhs.row), Int32(rhs.column), Int32(lhs.column), 1, lhs.content, Int32(lhs.column), rhs.content, Int32(rhs.row), 1, &rst.content, Int32(rst.row)) } else { cblas_dgemm(CBLAS_ORDER(UInt32(102)), CBLAS_TRANSPOSE(UInt32(112)), CBLAS_TRANSPOSE(UInt32(112)), Int32(lhs.row), Int32(rhs.column), Int32(lhs.column), 1, lhs.content, Int32(lhs.column), rhs.content, Int32(rhs.column), 1, &rst.content, Int32(rst.row)) } } return rst } }
48.016667
267
0.634502
2fd3f8134ce59c02117e0ab0c0ff75599e06cd7d
374
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // /// API Category Plugin public protocol APICategoryPlugin: Plugin, APICategoryBehavior { } /// API Category Plugin public extension APICategoryPlugin { /// The category type for API var categoryType: CategoryType { return .api } }
19.684211
66
0.697861
50acfc40515646662c7c62759f8c4d4d7f4e625d
1,346
// // Dismissable.swift // Fastlee // // Created by Lukasz Szarkowicz on 31/08/2020. // Copyright © 2020 Mobilee. All rights reserved. // import UIKit public protocol Dismissable { func dismiss(animated: Bool, completion: (() -> Void)?) } extension UIViewController: Dismissable {} extension Coordinator: Dismissable { public func dismiss(animated: Bool, completion: (() -> Void)? = nil) { // Safe guard -- dismiss should happend just in case presentedViewController or presentingViewController exists. if presentableViewController().presentedViewController != nil { // It's case when any VC is presented in current context. DispatchQueue.main.async { self.presentableViewController().dismiss(animated: animated, completion: completion) } } else if presentableViewController().presentingViewController != nil { // It's case when this coordinator is presented by other VC. DispatchQueue.main.async { self.presentableViewController().dismiss(animated: animated, completion: { [weak self] in guard let `self` = self else { return } completion?() self.end() }) } } } }
32.047619
120
0.598811
280e544041472c87ed3d1026a213239f4d1e5bac
413
import XCTest import Umbrella import UmbrellaAnswers import Answers final class AnswersProviderTests: XCTestCase { func testAnswersProvider() { let provider = AnswersProvider() XCTAssertTrue(provider.cls === Answers.self) XCTAssertNil(provider.instance) XCTAssertEqual(provider.selector, #selector(Answers.logCustomEvent(withName:customAttributes:))) XCTAssertTrue(provider.responds) } }
27.533333
100
0.784504
71f3e91b3c700992cbc127fd81c8fa14e220bc92
258
// // StreamEntitlementLoadedProtocol.swift // F1A-TV // // Created by Noah Fetz on 12.03.21. // import Foundation protocol StreamEntitlementLoadedProtocol { func didLoadStreamEntitlement(playerId: String, streamEntitlement: StreamEntitlementDto) }
19.846154
92
0.775194
fe7ce422ef83f221e95a549044b297ef65787ce6
3,895
/// Copyright (c) 2019 Razeware 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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 extension AsyncOperation { enum State: String { case ready, executing, finished fileprivate var keyPath: String { return "is\(rawValue.capitalized)" } } } class AsyncOperation: Operation { // Create state management var state = State.ready { willSet { willChangeValue(forKey: newValue.keyPath) willChangeValue(forKey: state.keyPath) } didSet { didChangeValue(forKey: oldValue.keyPath) didChangeValue(forKey: state.keyPath) } } // Override properties override var isReady: Bool { return super.isReady && state == .ready } override var isExecuting: Bool { return state == .executing } override var isFinished: Bool { return state == .finished } override var isAsynchronous: Bool { return true } // Override start override func start() { main() state = .executing } } /*: AsyncSumOperation simply adds two numbers together asynchronously and assigns the result. It sleeps for two seconds just so that you can see the random ordering of the operation. Nothing guarantees that an operation will complete in the order it was added. - important: Notice that `self.state` is being set to `.finished`. What would happen if you left this line out? */ class AsyncSumOperation: AsyncOperation { let rhs: Int let lhs: Int var result: Int? init(lhs: Int, rhs: Int) { self.lhs = lhs self.rhs = rhs super.init() } override func main() { DispatchQueue.global().async { Thread.sleep(forTimeInterval: 2) self.result = self.lhs + self.rhs self.state = .finished } } } //: Now that you've got an `AsyncOperation` base class and a `AsyncSumOperation` subclass, run it through a small test. let queue = OperationQueue() let pairs = [(2, 3), (5, 3), (1, 7), (12, 34), (99, 99)] pairs.forEach { pair in let op = AsyncSumOperation(lhs: pair.0, rhs: pair.1) op.completionBlock = { guard let result = op.result else { return } print("\(pair.0) + \(pair.1) = \(result)") } queue.addOperation(op) } //: This prevents the playground from finishing prematurely. Never do this on a main UI thread! queue.waitUntilAllOperationsAreFinished()
31.92623
137
0.709371
c1a9d7841162b40356017c98c5b397b015e068b6
483
// // String+HMAC.swift // TUSKit // // Created by Mark Robert Masterson on 10/25/20. // import Foundation import CommonCrypto internal extension String { func hmac(key: String) -> String { var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key, key.count, self, self.count, &digest) let data = Data(bytes: digest) return data.map { String(format: "%02hhx", $0) }.joined() } }
23
90
0.650104
62995322a5c37e54df7449112cf191970a17edc6
4,644
// // UBURLRequest+BodyMultipart.swift // UBFoundation // // Created by Joseph El Mallah on 23.03.19. // import Foundation /// A multipart body public struct UBURLRequestBodyMultipart: URLRequestBodyConvertible { /// The encoding to use for strings public var encoding: String.Encoding /// The parameters to send public var parameters: [Parameter] /// The payloads to send public var payloads: [Payload] /// The boundary to be used for segmentation public let boundary: String /// Initializes a multipart request body /// /// - Parameters: /// - parameters: The parameters describing the data /// - payloads: The payloads containing the data /// - encoding: The encoding to use for strings public init(parameters: [Parameter] = [], payloads: [Payload] = [], encoding: String.Encoding = .utf8) { self.parameters = parameters self.payloads = payloads self.encoding = encoding boundary = "Boundary-\(UUID().uuidString)" } /// :nodoc: public func httpRequestBody() throws -> UBURLRequestBody { guard parameters.isEmpty == false || payloads.isEmpty == false else { throw UBInternalNetworkingError.couldNotEncodeBody } var data: Data = Data() guard let boundaryPrefix = "--\(boundary)\r\n".data(using: encoding) else { throw UBInternalNetworkingError.couldNotEncodeBody } for parameter in parameters { guard let header = "Content-Disposition: form-data; name=\"\(parameter.name)\"\r\n\r\n".data(using: encoding), let value = "\(parameter.value)\r\n".data(using: encoding) else { throw UBInternalNetworkingError.couldNotEncodeBody } data.append(boundaryPrefix) data.append(header) data.append(value) } for payload in payloads { guard let header = "Content-Disposition: form-data; name=\"\(payload.name)\"; filename=\"\(payload.fileName)\"\r\n".data(using: encoding), let contentType = "Content-Type: \(payload.mimeType.stringValue)\r\n\r\n".data(using: encoding), let ending = "\r\n".data(using: encoding) else { throw UBInternalNetworkingError.couldNotEncodeBody } data.append(boundaryPrefix) data.append(header) data.append(contentType) data.append(payload.data) data.append(ending) } let endingString = "--" + boundary + "--\r\n" guard let ending = endingString.data(using: encoding) else { throw UBInternalNetworkingError.couldNotEncodeBody } data.append(ending) return UBURLRequestBody(data: data, mimeType: .multipartFormData(boundary: boundary)) } } // MARK: - Parts public extension UBURLRequestBodyMultipart { /// Multipart parameter struct Parameter { /// Name let name: String /// Value let value: String /// Initializes a multipart parameter /// /// - Parameters: /// - name: Name of the parameter /// - value: Value of the parameter public init(name: String, value: String) { self.name = name self.value = value } } /// Multipart payload struct Payload { /// Name let name: String /// File name let fileName: String /// Data let data: Data /// MIME type let mimeType: UBMIMEType /// Initializes a multipart payload /// /// - Parameters: /// - name: The name of payload /// - fileName: The file name of payload /// - data: The data of payload /// - mimeType: The MIME type of the data public init(name: String, fileName: String, data: Data, mimeType: UBMIMEType) { self.name = name self.fileName = fileName self.data = data self.mimeType = mimeType } /// Initializes a multipart payload /// /// - Parameters: /// - name: The name of payload /// - fileName: The file name of payload /// - body: A request body convertible object to serve as a payload /// - Throws: Errors in case the data could not be extracted from the body public init(name: String, fileName: String, body: URLRequestBodyConvertible) throws { let b = try body.httpRequestBody() self.init(name: name, fileName: fileName, data: b.data, mimeType: b.mimeType) } } }
34.147059
296
0.592593
d9ba3df818793475106d8160033bda8d5540aa9c
198
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing { var a{{().}class case c,()
24.75
87
0.732323
fcfbbc26a03b02fa191f06b0f48467f28ec62881
2,004
/// Copyright (c) 2019 Razeware 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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 SwiftUI struct User { var imageName: String var name: String var likedBooks: [Book] init(name: String, imageName: String, likedBooks: [Book] = []) { self.name = name self.imageName = imageName self.likedBooks = likedBooks } } extension User { static let exampleUser = User(name: "Ray", imageName: "Ray") }
43.565217
83
0.742515
628ffdd3c6339a8893cb4da4a348cdc0d771185c
16,438
// // xtra_prime.swift // pons // // Created by Dan Kogai on 2/9/16. // Copyright © 2016 Dan Kogai. All rights reserved. // public extension POUtil { public class Prime : SequenceType { public init(){} } } public extension POUtil.Prime { /// stream of primes public func generate()->AnyGenerator<BigInt> { var currPrime = BigInt(0) return AnyGenerator { if let nextPrime = currPrime.nextPrime { currPrime = nextPrime return currPrime } return nil } } } // // Primarity Test // public extension POUInt { /// `true` if `self` passes the [Miller-Rabin] test on `base`. `false` otherwise. /// /// [Miller-Rabin]: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test public func millerRabinTest(base:Int)->Bool { if self < 2 { return false } if self & 1 == 0 { return self == 2 } var d = self - 1 while d & 1 == 0 { d >>= 1 } var t = d var y = Self.powmod(Self(base), t, mod:self) //var y = Self.powmod(Self(base), t, self) // print("\(__FILE__):\(__LINE__): base=\(base),\nself=\(self),\ny=\(y)\nt=\(t)") while t != self-1 && y != 1 && y != self-1 { // y = (y * y) % self y = Self.mulmod(y, y, mod:self) t <<= 1 } // print("\(__FILE__):\(__LINE__): base=\(base),self=\(self),y=\(y),t=\(t)") return y == self-1 || t & 1 == 1 } /// [Lucas–Lehmer primality test] on `self`. /// /// [Lucas–Lehmer primality test]: https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test /// /// - returns: `true` if `self` is a Mersenne prime, `false` if not. Or `nil` if self is not even a Mersenne number. public var isMersennePrime:Bool? { let p = Self(min(self.msbAt + 1, Self.precision - 1)) // mersenne number = number of bits // print("\(__FILE__):\(__LINE__): p = \(p), self = \(self)") guard self == Self(1)<<p - 1 else { return nil // self is not 2**n - 1 } guard p.isPrime else { // if n is composite, so is Mn return false } var s:BigUInt = 4 let d = self.asBigUInt! let n = p.asBigUInt! for _ in 0..<(p-2) { // s = (s * s - 2) % d // BigUInt is used to avoid overflow at s * s let s2 = s * s s = (s2 & d) + (s2 >> n) if d <= s { s -= d } s -= 2 // print(i, s.toString(16)) } return s == 0 } public func jacobiSymbol(i:Int)->Int { var m = self var j = 1 var n = Self(i.abs) if (m <= 0 || m % 2 == 0) { return 0 } if (i < 0 && m % 4 == 3) { j = -j } while (n != 0) { while (n % 2 == 0) { n >>= 1 if (m % 8 == 3 || m % 8 == 5 ) { j = -j } } (m, n) = (n, m) if (n % 4 == 3 && m % 4 == 3) { j = -j } n %= m } return (m == 1) ? j : 0 } /// `true` if `self` is [Lucas pseudoprime]. `false` otherwise. /// /// [Lucas pseudoprime]: https://en.wikipedia.org/wiki/Lucas_pseudoprime public var isLucasProbablePrime:Bool { // make sure self is not a perfect square let r = Self.sqrt(self) if r*r == self { return false } let d:Int = { var d = 1 for i in 2...256 { // 256 is arbitrary d = (i & 1 == 0 ? 1 : -1) * (2 * i + 1) if self.jacobiSymbol(d) == -1 { return d } } fatalError("no such d found that self.jacobiSymbol(d) == -1") }() let p = 1 var q = BigInt(1 - d) / 4 // print("p = \(p), q = \(q)") var n = (self.asBigInt! + 1) / 2 // print("n = \(n)") var (u, v) = (BigInt(0), BigInt(2)) var (u2, v2) = (BigInt(1), p.asBigInt!) var q2 = 2*q let (bs, bd) = (self.asBigInt!, d.asBigInt!) while 0 < n { // u2 = (u2 * v2) % bs u2 *= v2 u2 %= bs // v2 = (v2 * v2 - q2) % bs v2 *= v2 v2 -= q2 v2 %= bs if n & 1 == 1 { let t = u // u = u2 * v + u * v2 u *= v2 u += u2 * v u += u & 1 == 0 ? 0 : bs // u = (u / 2) % bs u /= 2 u %= bs // v = (v2 * v) + (u2 * t * bd) v *= v2 v += u2 * t * bd v += v & 1 == 0 ? 0 : bs // v = (v / 2) % bs v /= 2 v %= bs } // q = (q * q) % bs q *= q q %= bs // q2 = q + q q2 = q << 1 // print(u, v) n >>= 1 } return u == 0 } /// true if `self` is prime according to the BPSW primarity test /// /// https://en.wikipedia.org/wiki/Baillie–PSW_primality_test public var isPrime:Bool { if self < 2 { return false } if self & 1 == 0 { return self == 2 } if self % 3 == 0 { return self == 3 } if self % 5 == 0 { return self == 5 } if self % 7 == 0 { return self == 7 } return self.millerRabinTest(2) && self.isLucasProbablePrime } public var nextPrime:Self? { if self < 2 { return 2 } var (u, o):(Self, Bool) (u, o) = Self.addWithOverflow(self, self & 1 == 0 ? 1 : 2) if o { return nil } while !u.isPrime { (u, o) = Self.addWithOverflow(u, 2) if o { return nil } } return u } public var prevPrime:Self? { if self <= 2 { return nil } if self == 3 { return 2 } var u = self - (self & 1 == 0 ? 1 : 2) while !u.isPrime { u = u - 2 } return u } } // // Prime Factorization // public extension POUtil.Prime { // cf. // http://en.wikipedia.org/wiki/Shanks'_square_forms_factorization // https://github.com/danaj/Math-Prime-Util/blob/master/factor.c public static let squfofMultipliers:[UIntMax] = [ 1, 3, 5, 7, 11, 3*5, 3*7, 3*11, 5*7, 5*11, 7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11 ] } public extension UIntMax { // faster but prone to overflow public static func squfof_one(n:UIntMax, _ k:UIntMax)->UIntMax { // print("n=\(n),k=\(k)") if n < 2 { return 1 } if n & 1 == 0 { return 2 } let rn = UIntMax.sqrt(n) if rn * rn == n { return rn } let kn = IntMax(k) &* IntMax(n) let rkn = IntMax.sqrt(kn) var p0 = rkn var q0 = IntMax(1) var q1 = kn &- p0*p0 var b0, b1, p1, q2 : IntMax for i in 0..<IntMax.sqrt(2 * rkn) { // print("Stage 1: p0=\(p0), q0=\(q0), q1=\(q1)") b1 = (rkn &+ p0) / q1 p1 = b1 &* q1 &- p0 q2 = q0 &+ b1 &* (p0 - p1) if i & 1 == 1 { let rq = IntMax.sqrt(q1) if rq * rq == q1 { // square root found; the algorithm cannot fail now. b0 = (rkn &- p0) / rq p0 = b0 &* rq &+ p0 q0 = rq q1 = (kn &- p0*p0) / q0 while true { // print("Stage 2: p0=\(p0), q0=\(q0), q1=\(q1)") b1 = (rkn &+ p0) / q1 p1 = b1 &* q1 &- p0 q2 = q0 &+ b1 &* (p0 - p1) if p0 == p1 { return UIntMax.gcd(n, UIntMax(p1)) } p0 = p1; q0 = q1; q1 = q2; } } } p0 = p1; q0 = q1; q1 = q2 } return 1 } } public extension BigUInt { // slower but never overflows public static func squfof_one(n:BigUInt, _ k:BigUInt)->BigUInt { // print("n=\(n),k=\(k)") if n < 2 { return 1 } if n & 1 == 0 { return 2 } let rn = BigUInt.sqrt(n) if rn * rn == n { return rn } let kn = k.asBigInt! * n.asBigInt! let rkn = BigInt.sqrt(kn) var p0 = rkn var q0 = BigInt(1) var q1 = kn - p0*p0 var b0, b1, p1, q2 : BigInt for i in 0..<(BigInt.sqrt(2 * rkn)) { // print("Stage 1: p0=\(p0), q0=\(q0), q1=\(q1)") b1 = (rkn + p0) / q1 p1 = b1 * q1 - p0 q2 = q0 + b1 * (p0 - p1) if i & 1 == 1 { let rq = BigInt.sqrt(q1) if rq * rq == q1 { // square root found; the algorithm cannot fail now. b0 = (rkn - p0) / rq p0 = b0 * rq + p0 q0 = rq q1 = (kn - p0*p0) / q0 while true { // print("Stage 2: p0=\(p0), q0=\(q0), q1=\(q1)") b1 = (rkn + p0) / q1 p1 = b1 * q1 - p0 q2 = q0 + b1 * (p0 - p1) if p0 == p1 { return BigUInt.gcd(n.asBigUInt!, p1.asUnsigned!) } p0 = p1; q0 = q1; q1 = q2; } } } p0 = p1; q0 = q1; q1 = q2 } return 1 } } public extension POUInt { /// Try to factor `n` by [SQUFOF] = Shanks' Square Forms Factorization /// /// [SQUFOF]: http://en.wikipedia.org/wiki/Shanks'_square_forms_factorization public static func squfof(n:Self, verbose:Bool = false)->Self { // if verbose { print("ks=\(ks)") } let threshold = IntMax.max.asUnsigned!.asBigUInt! for k in POUtil.Prime.squfofMultipliers { let bn = n.asBigUInt! let bk = k.asBigUInt! var g:Self = 0 if threshold < bn * bk { g = Self(BigUInt.squfof_one(bn, bk)) if verbose { print("BigUInt.squof(\(n),\(k)) == \(g)") } } else { g = Self(UIntMax.squfof_one(n.toUIntMax(), k.toUIntMax())) if verbose { print("UIntMax.squof(\(n),\(k)) == \(g)") } } if g != 1 { return g } } return 1 } /// Try to factor `n` by [Pollard's rho] algorithm /// /// [Pollard's rho]: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm /// /// - parameter n: the number to factor /// - parameter l: the number of iterations /// - parameter c: seed public static func pollardsRho(n:Self, _ l:Self, _ c:Self, verbose:Bool=false)->Self { var (x, y, j) = (Self(2), Self(2), Self(2)) for i in 1...l { x = mulmod(x, x, mod:n) x += c let d = Self.gcd(x < y ? y - x : x - y, n); if (d != 1) { if verbose { print("pollardsRho(\(n), \(l), \(c)): i=\(i), d=\(d)") } return d == n ? 1 : d } if (i % j == 0) { y = x j += j } } if verbose { print("pollardsRho(\(n), \(l), \(c)): giving up") } return 1 } /// factor `n` and return prime factors of it in array. /// /// axiom: `self.primeFactors.reduce(1,combine:*) == self` for any `self` /// /// It should succeed for all `u <= UInt.max` but may fail for larger numbers. /// In which case `1` is prepended to the result so the axiom still holds. /// /// If `verbose` is `true`, it shows the diagnostics /// public static func factor(n:Self, verbose v:Bool=false)->[Self] { if n < 2 || n.isPrime { return [n] } var k = n var ps = [Self]() var p = Self(2) while p < 2048 { while k % p == 0 { ps.append(p); k /= p } if k == 1 { return ps } p = p.nextPrime! } if k.isPrime { return ps + [k] } var d = Self.pollardsRho(k, 2048, 3, verbose:v) if d == 1 { d = Self.squfof(k, verbose:v) } ps += d != 1 ? factor(d, verbose:v) + factor(k/d, verbose:v) : [1, k] ps.sortInPlace(<) return ps } /// factor `self` and return prime factors of it in array. /// /// axiom: `self.primeFactors.reduce(1,combine:*) == self` for any `self` /// /// It should succeed for all `u <= UInt.max` but may fail for larger numbers. /// In which case `1` is prepended to the result so the axiom still holds. public var primeFactors:[Self] { return Self.factor(self) } } public extension POInt { public var isPrime:Bool { return self < 2 ? false : self.abs.asUnsigned!.isPrime } // appears to be the same as POUInt version but addWithOveerflow is internally different public var nextPrime:Self? { if self < 2 { return 2 } var (u, o):(Self, Bool) (u, o) = Self.addWithOverflow(self, self & 1 == 0 ? 1 : 2) if o { return nil } while !u.isPrime { (u, o) = Self.addWithOverflow(u, 2) if o { return nil } } return u } public var prevPrime:Self? { return self <= 2 ? nil : Self(self.abs.asUnsigned!.prevPrime!) } /// the prime factors of `self` /// /// axiom: `self.primeFactors.reduce(1,combine:*) == self` for any `self` /// /// It may fail if `self` contains factors beyond `Int.max`. /// In which case `1` is prepended to the result. /// /// For negative `self`, `-1` is prepended so the axiom still holds. public var primeFactors:[Self] { let factors = self.abs.asUnsigned!.primeFactors.map{ Self($0) } return self.isSignMinus ? [-1] + factors : factors } } public extension BigUInt { /// ### [A014233] /// /// Smallest odd number for which Miller-Rabin primality test /// on bases <= n-th prime does not reveal compositeness. /// /// [A014233]: https://oeis.org/A014233 public static let A014233:[BigUInt] = [ 2047, // p0 = 2 1373653, // p1 = 3 25326001, // p2 = 5 3215031751, // p3 = 7 2152302898747, // p4 = 11 3474749660383, // p5 = 13 341550071728321, // p6 = 17 341550071728321, // p7 = 19 3825123056546413051, // p8 = 23 3825123056546413051, // p9 = 29 3825123056546413051, // p10 = 31 "318665857834031151167461", // p11 = 37 "3317044064679887385961981" // p12 = 41 ] /// - returns: (Bool, surely:Bool) /// /// *surely* means if the primarity test is surely prime or surely composite. /// When composite it is always `true`. When prime it is `true` up to /// `3317044064679887385961981`, the last number in A014233 as of this writing. /// /// If `self` is a [Mersenne number], it check is if it is a Mersenne prime. /// In which case it is surely a prime or a composite. /// /// [Mersenne number]: https://en.wikipedia.org/wiki/Mersenne_prime public var isSurelyPrime:(Bool, surely:Bool) { if self < 2 { return (false, true) } if let self64 = self.asUInt64 { return (self64.isPrime, true) } if let mp = self.isMersennePrime { return (mp, true) } if BigUInt.A014233.last! <= self { let isPrime = self.isPrime return (isPrime, !isPrime) } if self & 1 == 0 { return (self == 2, true) } if self % 3 == 0 { return (self == 3, true) } if self % 5 == 0 { return (self == 5, true) } if self % 7 == 0 { return (self == 7, true) } var p = 2 for i in 0..<BigUInt.A014233.count { if self.millerRabinTest(p) == false { return (false, true) } if self < BigUInt.A014233[i] { return (true, true) } p = p.nextPrime! } // should not reach here let isPrime = self.isLucasProbablePrime return (isPrime, !isPrime) } }
35.812636
120
0.449386
3aa23d5b2023407cba2155938f538319acb43fa1
3,230
// -*- swift -*- //===----------------------------------------------------------------------===// // Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb // Do Not Edit Directly! //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // FIXME: the test is too slow when the standard library is not optimized. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest var SliceTests = TestSuite("Collection") let prefix: [Int] = [-9999, -9998, -9997, -9996, -9995] let suffix: [Int] = [] func makeCollection(elements: [OpaqueValue<Int>]) -> Slice<DefaultedRangeReplaceableCollection<OpaqueValue<Int>>> { var baseElements = prefix.map(OpaqueValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(OpaqueValue.init)) let base = DefaultedRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfEquatable(elements: [MinimalEquatableValue]) -> Slice<DefaultedRangeReplaceableCollection<MinimalEquatableValue>> { var baseElements = prefix.map(MinimalEquatableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init)) let base = DefaultedRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } func makeCollectionOfComparable(elements: [MinimalComparableValue]) -> Slice<DefaultedRangeReplaceableCollection<MinimalComparableValue>> { var baseElements = prefix.map(MinimalComparableValue.init) baseElements.append(contentsOf: elements) baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init)) let base = DefaultedRangeReplaceableCollection(elements: baseElements) let startIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count)) let endIndex = base.index( base.startIndex, offsetBy: numericCast(prefix.count + elements.count)) return Slice(base: base, bounds: startIndex..<endIndex) } var resiliencyChecks = CollectionMisuseResiliencyChecks.all resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap SliceTests.addRangeReplaceableSliceTests( "Slice_Of_DefaultedRangeReplaceableCollection_WithPrefixAndSuffix.swift.", makeCollection: makeCollection, wrapValue: identity, extractValue: identity, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: identityEq, extractValueFromEquatable: identityEq, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: 6 ) runAllTests()
38
86
0.752941
61618cc8f97691242899d9b49ffc8779c1c614e8
451
// // AppDelegate.swift // Swift-TableView-Example // // Created by Bilal ARSLAN on 11/10/14. // Copyright (c) 2014 Bilal ARSLAN. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } }
21.47619
145
0.727273
f7d85b90b6d579a745b3925be9517038d9315f57
2,174
// // AppDelegate.swift // CustomCell // // Created by KoKang Chu on 2017/8/26. // Copyright © 2017年 KoKang Chu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.255319
285
0.75529
893c0103fda2091de24bcff2fafa015b368cf751
2,172
// // AppDelegate.swift // CI-CD // // Created by Douglas Frari on 30/08/18. // Copyright © 2018 CESAR School. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.212766
285
0.754604
01f5ba887a38929f4e4d04e64e5938588896ec50
4,106
// Copyright 2015-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialAppBar import MaterialComponents.MaterialAppBar_Theming import MaterialComponents.MaterialContainerScheme // This example shows a bug when using an MDCFlexibleHeaderView in a UITableViewController. // When you scroll downwards until the header is down to its minimum size, try selecting // a cell in the UITableView, and you will see the header shift slightly downwards as a response // to the UITableView manipulation (addition of a cell animated). class AppBarWithUITableViewController: UITableViewController { let appBarViewController = MDCAppBarViewController() var numberOfRows = 50 @objc var containerScheme: MDCContainerScheming = MDCContainerScheme() deinit { // Required for pre-iOS 11 devices because we've enabled observesTrackingScrollViewScrollEvents. appBarViewController.headerView.trackingScrollView = nil } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(style: UITableView.Style) { super.init(style: style) commonInit() } func commonInit() { // Behavioral flags. appBarViewController.inferTopSafeAreaInsetFromViewController = true appBarViewController.headerView.minMaxHeightIncludesSafeArea = false self.addChild(appBarViewController) } override func viewDidLoad() { super.viewDidLoad() // Allows us to avoid forwarding events, but means we can't enable shift behaviors. appBarViewController.headerView.observesTrackingScrollViewScrollEvents = true view.addSubview(appBarViewController.view) appBarViewController.didMove(toParent: self) appBarViewController.applyPrimaryTheme(withScheme: containerScheme) self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") let headerView = appBarViewController.headerView headerView.trackingScrollView = self.tableView headerView.maximumHeight = 300 headerView.minimumHeight = 100 } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: animated) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfRows } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "Cell #\(indexPath.item)" return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) tableView.beginUpdates() tableView.insertRows(at: [IndexPath(item: indexPath.item + 1, section: 0)], with: .automatic) numberOfRows += 1 tableView.endUpdates() } } extension AppBarWithUITableViewController { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["App Bar", "AppBar+UITableViewController"], "primaryDemo": false, "presentable": false, ] } @objc func catalogShouldHideNavigation() -> Bool { return true } }
33.382114
100
0.754262
01167776113efbefb515cbbd54a9299f36e33a3d
296
// // InlineObject13.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct InlineObject13: Codable { /** Message to send */ public var message: String public init(message: String) { self.message = message } }
14.8
39
0.662162
4aa7cc941910e01ebd9b5029bce83891884e3185
1,070
// // ChildController6.swift // CFStreamingVideo // // Created by chenfeng on 2019/8/28. // Copyright © 2019 chenfeng. All rights reserved. // import UIKit class ChildController6: CFBaseController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. view.backgroundColor = ThemeYellowColor let titleStr = UILabel.init(frame: CGRect(x: 50, y: 50, width: 100, height: 100)) titleStr.font = UIFont.boldSystemFont(ofSize: 20) titleStr.textAlignment = .center titleStr.text = "电影" titleStr.textColor = UIColor.darkText view.addSubview(titleStr) } /* // 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.destination. // Pass the selected object to the new view controller. } */ }
26.097561
106
0.64486
edb39098d58ad7a6f8d7f128365c53f24de9e69a
445
// // HybridClipboardParams.swift // JGHybrid // // Created by 李保君 on 2017/12/11. // import UIKit import JGHybrid class HybridClipboardParams: HybridBaseParams { var content:String = "" //解析数据对象 override class func convert(_ dic: [String: AnyObject]) -> HybridClipboardParams { let obj:HybridClipboardParams = HybridClipboardParams.init() obj.content = dic["content"] as? String ?? "" return obj } }
22.25
86
0.669663
56cf8a277047f2cb54d87207ed0a8a318579f9cd
10,060
// // SAInboxDetailViewController.swift // SAInboxViewController // // Created by Taiki Suzuki on 2015/08/15. // Copyright (c) 2015年 Taiki Suzuki. All rights reserved. // import UIKit @objc public protocol SAInboxDetailViewControllerDelegate: NSObjectProtocol { @objc optional func inboxDetailViewControllerShouldChangeStatusBarColor(_ viewController: SAInboxDetailViewController, isScrollingDirectionUp: Bool) } open class SAInboxDetailViewController: SAInboxViewController { //MARK: Static Properties private struct Const { static let cellIdentifier = "Cell"; static let standardValue = UIScreen.main.bounds.height * 0.2 } //MARK: Instatnce Properties private lazy var headerPanGesture: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(SAInboxDetailViewController.handleHeaderPanGesture(_:))) }() private lazy var swipePanGesture: UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: #selector(SAInboxDetailViewController.handleSwipePanGesture(_:))) }() private var stopScrolling = false private var defaultHeaderPosition: CGPoint = .zero private var defaultTableViewPosition: CGPoint = .zero var thumbImage: UIImage? private(set) var endHeaderPosition: CGPoint = .zero private(set) var endTableViewPosition: CGPoint = .zero open weak var delegate: SAInboxDetailViewControllerDelegate? let alphaView = UIView() //MARK: Initialize Methods public init() { super.init(nibName: nil, bundle: nil) } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } //MARK: - Life Cycle override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = self tableView.backgroundColor = .clear tableView.backgroundView?.backgroundColor = .clear view.backgroundColor = .white automaticallyAdjustsScrollViewInsets = false headerView.addGestureRecognizer(headerPanGesture) view.addGestureRecognizer(swipePanGesture) shouldHideHeaderView = false } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) view.insertSubview(SAInboxAnimatedTransitioningController.shared.transitioningContainerView, belowSubview: tableView) setupAlphaView() view.bringSubview(toFront: headerView) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() defaultHeaderPosition = headerView.frame.origin defaultTableViewPosition = tableView.frame.origin } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Private Methods func setupAlphaView() { alphaView.frame = view.bounds alphaView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) alphaView.alpha = 0 view.insertSubview(alphaView, belowSubview: tableView) } func calculateRudderBanding(_ distance: CGFloat, constant: CGFloat, dimension: CGFloat) -> CGFloat { return (1 - (1 / ((distance * constant / dimension) + 1))) * dimension } //MARK: - Internal Methods func resetContentOffset(isLower: Bool) { if isLower { tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentSize.height - tableView.bounds.size.height), animated: false) return } tableView.setContentOffset(CGPoint.zero, animated: false) } func handleSwipePanGesture(_ gesture: UIPanGestureRecognizer) { let translation = gesture.translation(in: view) let velocity = gesture.velocity(in: view) switch gesture.state { case .began: SAInboxAnimatedTransitioningController.shared.transitioningType = .swipePop case .changed: let position = max(0, translation.x) let rudderBanding = calculateRudderBanding(position, constant: 0.55, dimension: view.frame.size.width) let headerPosition = max(defaultHeaderPosition.x, defaultHeaderPosition.x + rudderBanding) headerView.frame.origin.x = headerPosition let tableViewPosition = max(defaultTableViewPosition.x, defaultTableViewPosition.x + rudderBanding) tableView.frame.origin.x = tableViewPosition alphaView.alpha = 1 - min(rudderBanding / view.frame.size.width, 1) case .cancelled, .ended: if velocity.x > 0 { endHeaderPosition = headerView.frame.origin endTableViewPosition = tableView.frame.origin navigationController?.popViewController(animated: true) } else { UIView.animate(withDuration: 0.25, animations: { self.headerView.frame.origin = self.defaultHeaderPosition self.tableView.frame.origin = self.defaultTableViewPosition }) } case .failed, .possible: break } } func handleHeaderPanGesture(_ gesture: UIPanGestureRecognizer) { let translation = gesture.translation(in: view) let velocity = gesture.velocity(in: view) switch gesture.state { case .began: SAInboxAnimatedTransitioningController.shared.transitioningType = .headerPop case .changed: let position = max(0, translation.y) let rudderBanding = calculateRudderBanding(position, constant: 0.55, dimension: view.frame.size.height) let headerPosition = max(defaultHeaderPosition.y, defaultHeaderPosition.y + rudderBanding) headerView.frame.origin.y = headerPosition let tableViewPosition = max(defaultTableViewPosition.y, defaultTableViewPosition.y + rudderBanding) tableView.frame.origin.y = tableViewPosition SAInboxAnimatedTransitioningController.shared.transitioningContainerView.upperMoveToValue(rudderBanding) alphaView.alpha = 1 - min(1, (rudderBanding / 180)) case .cancelled, .ended: if velocity.y > 0 { endHeaderPosition = headerView.frame.origin endTableViewPosition = tableView.frame.origin navigationController?.popViewController(animated: true) } else { UIView.animate(withDuration: 0.25, animations: { self.headerView.frame.origin = self.defaultHeaderPosition self.tableView.frame.origin = self.defaultTableViewPosition SAInboxAnimatedTransitioningController.shared.transitioningContainerView.upperMoveToValue(0) self.alphaView.alpha = 1 }) } case .failed, .possible: break } } //MARK: - UITableViewDelegate Methods open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let yOffset = scrollView.contentOffset.y let value = yOffset - (scrollView.contentSize.height - scrollView.bounds.size.height) let standardValue = Const.standardValue if value > standardValue || yOffset < -standardValue { endHeaderPosition = headerView.frame.origin endTableViewPosition = tableView.frame.origin navigationController?.popViewController(animated: true) stopScrolling = true } else { stopScrolling = false } } open override func scrollViewDidScroll(_ scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView) let yOffset = scrollView.contentOffset.y if yOffset < 0 { scrollView.scrollIndicatorInsets.top = -yOffset } else if yOffset > scrollView.contentSize.height - scrollView.bounds.size.height { scrollView.scrollIndicatorInsets.bottom = yOffset - (scrollView.contentSize.height - scrollView.bounds.size.height) } else { scrollView.scrollIndicatorInsets = UIEdgeInsets.zero } if stopScrolling { scrollView.setContentOffset(scrollView.contentOffset, animated: false) return } let standardValue = Const.standardValue let transitioningController = SAInboxAnimatedTransitioningController.shared let value = yOffset - (scrollView.contentSize.height - scrollView.bounds.size.height) let transitioningContainerView = transitioningController.transitioningContainerView if value >= 0 { transitioningContainerView.lowerMoveToValue(value) transitioningController.transitioningType = .bottomPop alphaView.alpha = 1 - min(max(0 ,value / (standardValue * 2)), 1) return } else { transitioningContainerView.lowerMoveToValue(0) alphaView.alpha = 0 } if yOffset <= 0 { transitioningContainerView.upperMoveToValue(-yOffset) headerView.frame.origin.y = -yOffset transitioningController.transitioningType = .topPop alphaView.alpha = 1 - min(max(0 ,-yOffset / (standardValue * 2)), 1) } else { transitioningContainerView.upperMoveToValue(0) alphaView.alpha = 0 headerView.frame.origin.y = 0 } } }
40.894309
152
0.632406
db41140f221e4e12a919a6b995b7347eb2f2882e
501
// // RegionalBloc.swift // ABC-CODE // // Created by Kudzai Mhou on 2019/03/13. // Copyright © 2019 Kudzai Mhou. All rights reserved. // import Foundation struct RegionalBloc: Codable { let acronym: String? let name: String? let otherAcronyms: [String]? let otherNames: [String]? enum CodingKeys: String, CodingKey { case acronym = "acronym" case name = "name" case otherAcronyms = "otherAcronyms" case otherNames = "otherNames" } }
20.875
54
0.632735
082a102399430fed7f12f7090ecd3a2439ac33b6
844
// // GetUsersRequest.swift // Networking Demo App // // Created by Mohamed Eldoheiri on 7/30/21. // import Foundation import AdyenNetworking internal struct GetUsersErrorResponse: Decodable, Error { internal struct Data: Decodable { let message: String? } internal let data: Data? } internal struct GetUsersRequest: Request { typealias ResponseType = GetUsersResponse typealias ErrorResponseType = GetUsersErrorResponse let method: HTTPMethod = .get var path: String { "users/\(userId ?? "")" } let queryParameters: [URLQueryItem] = [] var userId: String? = nil var counter: UInt = 0 let headers: [String : String] = [:] private enum CodingKeys: CodingKey {} } internal struct GetUsersResponse: Response { let data: [UserModel] }
19.627907
57
0.654028
9c6192e497848c5bd959bdcdbb0a253afb7a1295
4,001
import ARHeadsetKit extension GameInterface { func updateResources() { Self.interfaceScale = gameRenderer.interfaceScale if buttons == nil { buttons = .init() } else if gameRenderer.interfaceScaleChanged { buttons.resetSize() } adjustInterface() var selectedButton: CachedParagraph? let renderer = gameRenderer.renderer if let interactionRay = renderer.interactionRay, let traceResult = buttons.trace(ray: interactionRay) { selectedButton = traceResult.elementID } if let selectedButton = selectedButton { buttons[selectedButton].isHighlighted = true if renderer.shortTappingScreen { executeAction(for: selectedButton) } } interfaceRenderer.render(elements: buttons.elements) if let selectedButton = selectedButton { buttons[selectedButton].isHighlighted = false } } func executeAction(for button: CachedParagraph) { var cubes: [Cube] { get { cubeRenderer.cubes } set { cubeRenderer.cubes = newValue } } switch button { case .resetButton: reactionParams = nil cubePicker.cubeIndex = nil cubes.removeAll(keepingCapacity: true) for _ in 0..<10 { cubes.append(cubeRenderer.makeNewCube()) } case .extendButton: for i in 0..<10 where cubes[i].velocity != nil { let pos = simd_float3(repeating: .infinity) cubes[i].location = pos cubes[i] = cubeRenderer.makeNewCube() } default: break } } func adjustInterface() { let cameraTransform = gameRenderer.cameraToWorldTransform let cameraDirection4 = -cameraTransform.columns.2 let cameraDirection = simd_make_float3(cameraDirection4) var rotation = simd_quatf(from: [0, 1, 0], to: cameraDirection) var axis = rotation.axis if rotation.angle == 0 { axis = [0, 1, 0] } func adjustButton(_ button: CachedParagraph, angleDegrees: Float) { let angleRadians = degreesToRadians(angleDegrees) rotation = simd_quatf(angle: angleRadians, axis: axis) let backwardDirection = rotation.act([0, 1, 0]) let upDirection = cross(backwardDirection, axis) let orientation = ARInterfaceElement.createOrientation( forwardDirection: -backwardDirection, orthogonalUpDirection: upDirection ) var position = gameRenderer.interfaceCenter let depth = type(of: renderer).interfaceDepth position += backwardDirection * depth buttons[button].setProperties(position: position, orientation: orientation) } let separationDegrees = 10 * Self.interfaceScale let extendAngleDegrees = 135 + separationDegrees adjustButton(.resetButton, angleDegrees: 135) adjustButton(.extendButton, angleDegrees: extendAngleDegrees) if let position = reactionParams?.location { buttons[.reactionLabel].hidden = false var forwardDirection = gameRenderer.interfaceCenter forwardDirection -= position if length(forwardDirection) == 0 { forwardDirection = [0, 0, 1] } else { forwardDirection = normalize(forwardDirection) } } else { buttons[.reactionLabel].hidden = true } } }
32.008
75
0.546113
8754b6acc010692500194fba1bc454a56a1e70d4
1,063
/* * The following code is auto generated using webidl2swift */ import JavaScriptKit public struct AssignedNodesOptions: ExpressibleByDictionaryLiteral, JSBridgedType { public enum Key: String, Hashable { case flatten } private let dictionary: [String: JSValue] public init(uniqueKeysWithValues elements: [(Key, ConvertibleToJSValue)]) { dictionary = Dictionary(uniqueKeysWithValues: elements.map { ($0.0.rawValue, $0.1.jsValue()) }) } public init(dictionaryLiteral elements: (Key, ConvertibleToJSValue)...) { dictionary = Dictionary(uniqueKeysWithValues: elements.map { ($0.0.rawValue, $0.1.jsValue()) }) } subscript(_ key: Key) -> JSValue? { dictionary[key.rawValue] } public init?(from value: JSValue) { if let dictionary: [String: JSValue] = value.fromJSValue() { self.dictionary = dictionary } return nil } public var value: JSValue { jsValue() } public func jsValue() -> JSValue { return dictionary.jsValue() } }
26.575
103
0.652869
f4cd8db7cdbf926fe709a90d55805d51c7a416e4
362
// // Double.swift // Clark // // Created by Vladislav Zagorodnyuk on 9/13/17. // Copyright © 2017 Clark. All rights reserved. // extension Double { /// Rounds the double to decimal places value func rounded(toPlaces places:Int) -> Double { let divisor = pow(10.0, Double(places)) return (self * divisor).rounded() / divisor } }
22.625
51
0.635359
71460f05b75049cb95e5e70f452da02b0295fdde
1,238
// // State.swift // Home // // Created by Johan Torell on 2021-02-24. // import Foundation import ReSwift import FolksamCommon enum Actions { struct SetUser: Action { var user: ParentUser? } struct SetPolicies: Action { let policies: [Policy] } struct SetLoading: Action {} struct SetUserAndPolicies: Action { let user: ParentUser? let policies: [Policy] } } enum LoadState { case loading case ready } public struct HomeState { var user: ParentUser? var policies: [Policy]? var loadstate: LoadState = .loading } public protocol HasHomeState { var home: HomeState { get } } public func homeReducer(action: Action, state: HomeState?) -> HomeState { var state = state ?? HomeState() switch action { case let action as Actions.SetUser: state.user = action.user case let action as Actions.SetPolicies: state.policies = action.policies case _ as Actions.SetLoading: state.loadstate = .loading case let action as Actions.SetUserAndPolicies: state.loadstate = .ready state.user = action.user state.policies = action.policies default: break } return state }
19.967742
73
0.64378
e40079cf8b3d4b797b3a8df91ecbbf587a0954fa
3,935
// // ViewController.swift // TagListViewDemo // // Created by Dongyuan Liu on 2015-05-09. // Copyright (c) 2015 Ela. All rights reserved. // import UIKit import Foundation let html = """ <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head> \n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n<title></title>\n<meta name=\"Generator\" content=\"Cocoa HTML Writer\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px \'Times New Roman\'; color: #000000; -webkit-text-stroke: #000000}\nspan.s1 {font-family: \'TimesNewRomanPS-BoldMT\'; font-weight: bold; font-style: normal; font-size: 12.00px; font-kerning: none}\nspan.s2 {font-family: \'.SFUI-Regular\'; font-weight: normal; font-style: normal; font-size: 14.00px; -webkit-text-stroke: 0px #000000}\nspan.s3 {font-family: \'.SFUI-Regular\'; font-weight: normal; font-style: normal; font-size: 14.00px; color: #000000; -webkit-text-stroke: 0px #000000}\n</style>\n</head>\n<body>\n<p class=\"p1\"> <span class=\"s1\">This text is bold</span><span class=\"s2\"> <a href=\"https://www.youtube.com/watch?v=o8KGtruDxPQ\"> <span class=\"s3\">YouTube</span></a> <span class=\"Apple-converted-space\">&nbsp;</span></span></p>\n</body>\n</html>\n """ class ViewController: UIViewController { @IBOutlet weak var tagListView: TagListView! @IBOutlet weak var biggerTagListView: TagListView! @IBOutlet weak var biggestTagListView: TagListView! override func viewDidLoad() { super.viewDidLoad() let title1 = NSMutableAttributedString(string: "体の特徴(困りごと) | ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .regular), NSAttributedString.Key.foregroundColor: UIColor.lightGray]) let description1 = NSAttributedString(string: "高身長さん, 低身長さん, 肩幅広いさん, 大胸さん, 肩幅広め, 二の腕太め, おしり大きめ, ふともも太め, ふくらはぎ太め, 下腹ぽっこり, 足が甲高, 足が幅広", attributes:[NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.darkGray]) title1.append(description1) let attributedTag1 = TagView(title: title1) attributedTag1.titleLineBreakMode = .byTruncatingTail attributedTag1.paddingX = 12 attributedTag1.paddingY = 8 let title2 = NSMutableAttributedString(string: "Athul George | ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .regular), NSAttributedString.Key.foregroundColor: UIColor.lightGray as Any]) guard let description2 = try? NSAttributedString(data: Data(html.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else { return } title2.append(description2) let attributedTag2 = TagView(title: title2) attributedTag2.paddingX = 12 attributedTag2.paddingY = 8 biggestTagListView.addTagViews([attributedTag1]) biggestTagListView.backgroundColor = UIColor.red } } // 体の特徴(困りごと) | 高身長さん, 低身長さん, 肩幅広いさん, 大胸さん, 肩幅広め, 二の腕太め, おしり大きめ, ふともも太め, ふくらはぎ太め, 下腹ぽっこり, 足が甲高, 足が幅広
48.580247
141
0.573571
d66558e5f95965a93b79f9b77ab390521a41dfaa
5,246
// // TrendingRespostriesTableCellView.swift // MobileExercise // // Created by Jawad Ali on 24/09/2020. // Copyright © 2020 Jawad Ali. All rights reserved. // import UIKit class TrendingRespostriesTableCellView: UITableViewCell, DequeueInitializable { // MARK: Views private lazy var avatarImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private lazy var authorNameLabel: UILabel = UILabelFactory.createUILabel(with: UIColor.universalColor5, font: UIFont.systemFont(ofSize: FontSize.medium.rawValue), alignment: .left, text:" " ) private lazy var respositoryNameLabel: UILabel = UILabelFactory.createUILabel(with: UIColor.universalColor3, font: UIFont.boldSystemFont(ofSize: FontSize.large.rawValue), alignment: .left, text:" " ) private lazy var DescriptionLabel: UILabel = UILabelFactory.createUILabel(with: UIColor.universalColor5, font: UIFont.systemFont(ofSize: FontSize.small.rawValue), alignment: .left, numberOfLines: 0, text: " ") private lazy var languageLabel: UILabel = UILabelFactory.createUILabel(with: UIColor.universalColor3, font: UIFont.systemFont(ofSize: FontSize.medium.rawValue), alignment: .left) private lazy var langaugeColorView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private lazy var starsLabel: UILabel = UILabelFactory.createUILabel(with: UIColor.universalColor3, font: UIFont.systemFont(ofSize: FontSize.medium.rawValue), alignment: .left) private lazy var verticalStack: UIStackView = UIStackViewFactory.createStackView(with: .vertical, alignment: .fill, distribution: .fill, spacing: 10, arrangedSubviews: [authorNameLabel, respositoryNameLabel, DescriptionLabel, languageStarStack]) private lazy var languageStarStack: UIStackView = UIStackViewFactory.createStackView(with: .horizontal, alignment: .center, distribution: .fill, spacing: 10, arrangedSubviews:[langaugeColorView, languageLabel, starsLabel,UIView()] ) private lazy var seperator: UIView = { let view = UIView() view.backgroundColor = .universalColor4 view.translatesAutoresizingMaskIntoConstraints = false return view }() //MARK:- Properties private var viewModel: TrendingRespostriesTableCellViewModelType? // MARK: Initialization override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } required public init?(coder: NSCoder) { super.init(coder: coder) commonInit() } private func commonInit() { selectionStyle = .none setupViews() setupConstraints() } // MARK: Configurations func configure(with viewModel:TrendingRespostriesTableCellViewModelType) { self.viewModel = viewModel binding() } override func draw(_ rect: CGRect) { super.draw(rect) avatarImageView.layer.cornerRadius = avatarImageView.bounds.midY langaugeColorView.layer.cornerRadius = langaugeColorView.bounds.midY } func loadImage() { if let url = viewModel?.getAvatarURL() { AppAsyncImage().loadImage(for: url, in: avatarImageView) } } } // MARK: View setup private extension TrendingRespostriesTableCellView { func setupViews() { subscribeToShimmerView([self,avatarImageView,authorNameLabel,verticalStack,respositoryNameLabel,DescriptionLabel,languageStarStack]) contentView.addSubview(avatarImageView) contentView.addSubview(verticalStack) contentView.addSubview(seperator) } func setupConstraints() { avatarImageView .alignEdgesWithSuperview([.top,.left],constant:10) .height(constant: 50) .width(constant: 50) langaugeColorView .height(constant: 10) .width(constant: 10) languageStarStack .setCustomSpacing(30, after: languageLabel) verticalStack .toRightOf(avatarImageView, constant:10) .alignEdgesWithSuperview([.top, .right, .bottom], constant:15) seperator .alignEdgesWithSuperview([.left, .right], constant:10) .height(constant: 1) .alignEdgeWithSuperview(.bottom, constant: 1) } } //MARK:- View Binding private extension TrendingRespostriesTableCellView { func binding() { authorNameLabel.text = viewModel?.getAuthorName() respositoryNameLabel.text = viewModel?.getRespostryName() starsLabel.text = viewModel?.getStars() languageLabel.text = viewModel?.getLanguage() langaugeColorView.backgroundColor = UIColor(hexString: viewModel?.getLanguageColor() ?? "") DescriptionLabel.text = viewModel?.getDescription() } }
36.430556
249
0.6809
e58068e733e6ca694f2f7a1e314fa4974d9998d5
787
// // Scale.swift // ForceTouchPlayer // // Created by Danilo Campana Fuchs on 21/10/20. // Copyright © 2020 Danilo Campana Fuchs. All rights reserved. // import Foundation let cMajorScale = Song( name: "C Major Scale", defaultTempo: 144.0, rawNotes: [ (NOTE_C1, 1), (NOTE_D1, 1), (NOTE_E1, 1), (NOTE_F1, 1), (NOTE_G1, 1), (NOTE_A1, 1), (NOTE_B1, 1), (NOTE_C2, 1), (NOTE_D2, 1), (NOTE_E2, 1), (NOTE_F2, 1), (NOTE_G2, 1), (NOTE_F2, 1), (NOTE_E2, 1), (NOTE_D2, 1), (NOTE_C2, 1), (NOTE_B1, 1), (NOTE_A1, 1), (NOTE_G1, 1), (NOTE_F1, 1), (NOTE_E1, 1), (NOTE_D1, 1), (NOTE_C1, 1), ] )
18.738095
63
0.465057
bfc1e3fd17a1eaf4040fd6e6476449ec5ca6da5e
2,724
// // JVRemotableViewController.swift // Pods // // Created by Jorge Villalobos Beato on 12/19/16. // // import UIKit import LGRefreshView public enum RemoteError:Error{ case unimplemented } public protocol JVRemotableViewController { var useRefreshControl:Bool {get set} func reloadData() func fetchRemoteData(_ completion:@escaping (_ result:JVResult<Any>) -> Void) } public extension JVRemotableViewController where Self: UIViewController { public func internalFetchRemoteData(_ showHUD:Bool) { JVBaseUtils.executeBlockOnMainThread({ () -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = true }) if showHUD { JVUserInterfaceUtils.showProgressHUD() } self.fetchRemoteData { (result:JVResult<Any>) in if let error = result.error() { //self.refreshView?.endRefreshing() if showHUD { JVUserInterfaceUtils.changeProgressHUDIntoError(NSError.error(withText: result.description)) JVUserInterfaceUtils.hideProgressHUD() } else { JVUserInterfaceUtils.showErrorHUD(NSError.error(withText: result.description)) } JVBaseUtils.executeBlockOnMainThread({ () -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) } else { JVBaseUtils.executeBlockOnMainThread({ () -> Void in self.reloadData() if showHUD { JVUserInterfaceUtils.hideProgressHUD() } //self.refreshView?.endRefreshing() JVBaseUtils.executeBlockOnMainThread({ () -> Void in UIApplication.shared.isNetworkActivityIndicatorVisible = false }) }) } } } public func fetchRemoteDataFromRefresh() { self.internalFetchRemoteData(false) } open func customViewDidLoad(_ mainView:UIView) { self.internalFetchRemoteData(true) if self.useRefreshControl { if let theScrollView = mainView as? UIScrollView { //self.refreshView = theScrollView.addRefreshView(.yellow, refreshBlock: { (refreshView) in self.internalFetchRemoteData(false) refreshView?.endRefreshing() }) } } } public func customViewWillDisappear(_ animated: Bool) { JVUserInterfaceUtils.hideProgressHUD() } }
31.674419
112
0.574156
89c30a8cf8b73ee8cf16936c177201cb82a48ad4
132
//Some text. import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
13.2
55
0.765152
61e7f3326443740b09fc6263cf8a4bb6d8eed6b5
1,571
// Foundation/URLSession/libcurlHelpers - URLSession & libcurl // // 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- /// /// These are libcurl helpers for the URLSession API code. /// - SeeAlso: https://curl.haxx.se/libcurl/c/ /// - SeeAlso: URLSession.swift /// // ----------------------------------------------------------------------------- @_implementationOnly import CoreFoundation import CFURLSessionInterface //TODO: Move things in this file? internal func initializeLibcurl() { try! CFURLSessionInit().asError() } internal extension String { /// Create a string by a buffer of UTF 8 code points that is not zero /// terminated. init?(utf8Buffer: UnsafeBufferPointer<UInt8>) { var bufferIterator = utf8Buffer.makeIterator() var codec = UTF8() var result: String = "" iter: repeat { switch codec.decode(&bufferIterator) { case .scalarValue(let scalar): result.append(String(describing: scalar)) case .error: return nil case .emptyInput: break iter } } while true self.init(stringLiteral: result) } }
30.803922
80
0.586251
ef308043905436b69daa147e38a0c2e36ea671ab
1,036
import UIKit import Foundation import DynamicColor public class Colors { public static let cyan = UIColor(hex: 0x1FD5BE) public static let pink = UIColor(hex: 0xFE018A) public static let blue = UIColor(hex: 0x039add) public static let magenta = UIColor(hex: 0xff01d3) public static let orange = UIColor(hex: 0xfcab53) public static let yellow = UIColor(hex: 0xf0c954) public static let mandy = UIColor(hex: 0xed4959) public static let mediumAquamarine = UIColor(hex: 0x50d2c2) public static let purple = UIColor(hex: 0xbf5fff) public static let green = UIColor(hex: 0x2ecc71) public static let lightGray = UIColor(hex: 0xc6d2d6) public static let accents = [ blue, orange, magenta, yellow, mandy, mediumAquamarine, purple, green, ] public static func accentFor<H: Hashable>(_ object: H) -> UIColor { let hash = abs(object.hashValue) return accents[hash % accents.count] } }
28
71
0.653475
abd0f68dbd71e7536dc0cb5d153b4cfc0395df08
5,375
/* Copyright 2021 natinusala Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import Dispatch import Backtrace import RippleCore import CRippleUI extension App where Target == AppTarget { /// Main entry point for an app. /// /// Use the `@main` attribute on the app to mark it as the main /// entry point of your executable target. Calling this /// method directly is not supported. public static func main() { // Enable backtraces for Linux and Windows Backtrace.install() let engine = Engine(running: Self.init()) engine.target.run() } } public extension App { typealias Target = AppTarget /// Overrides the default `Never` target to provide our own instead. static func makeTarget(of app: Self) -> AppTarget { do { return try AppTarget() } catch { Logger.error("Cannot initialize app: \(error.qualifiedName)") exit(-1) } } } /// The target of a Ripple app. public class AppTarget: TargetNode, FrameTarget, Context { public let type: TargetType = .app public var children = [TargetNode]() public var parent: TargetNode? /// Has the user requested that the app exits? var exitRequested = false var canvas: Canvas? let platform: Platform /// Creates a new app target. init() throws { // Init platform guard let platform = try createPlatform() else { throw AppError.noPlatformFound } self.platform = platform // Register ourselves as running context sharedContext = self } public func insert(child: inout TargetNode, at position: UInt?) { // Only allow one child container for now if !self.children.isEmpty { fatalError("App targets can only have one container") } // Ensure the target node is a container if child.type != .container { fatalError("App targets can only contain containers, tried to insert a \(child.type): \(child)") } // Add the child self.children = [child] child.parent = self } public func remove(child: TargetNode) { fatalError("Removing containers from an app target is not implemented yet") } /// Must the app exit on next frame? var mustExit: Bool { // TODO: handle SIGINT to exit gracefully return exitRequested } /// Runs the app until it exits. func run() { while !self.mustExit { let beginFrameTime = Date() // Poll events self.platform.poll() // Run one frame self.frame() // Consume all messages in main queue drainMainQueue() // Sleep for however much time is needed let frameTime = 0.016666666 // TODO: make it an env variable if frameTime > 0 { let endFrameTime = Date() let currentFrameTime = beginFrameTime.distance(to: endFrameTime) var sleepAmount: TimeInterval = 0 // Only sleep if the frame took less time to render // than desired frame time if currentFrameTime < frameTime { sleepAmount = frameTime - currentFrameTime } if sleepAmount > 0 { Thread.sleep(forTimeInterval: sleepAmount) } } } Logger.info("Exiting...") } /// Runs the app for one frame. func frame() { for container in self.children { (container as? FrameTarget)?.frame() } } func exit() { self.exitRequested = true } } /// Errors that can occur when the app is initialized. enum AppError: Error { case noPlatformFound } /// Runs everything in the main queue. func drainMainQueue() { // XXX: Dispatch does not expose a way to drain the main queue // without parking the main thread, so we need to use obscure // CoreFoundation / Cocoa functions. // See https://github.com/apple/swift-corelibs-libdispatch/blob/macosforge/trac/ticket/38.md _dispatch_main_queue_callback_4CF(nil) } /// Represents the currently running app. Used to get global /// objects as well as manipulate the app. protocol Context { /// Currently running platform. var platform: Platform { get } /// The canvas used by views to draw themselves. /// Set by the `Container` implementation when it gets created. var canvas: Canvas? { get set } /// Exits the app on next frame. func exit() } /// Returns the `Context` instance of the currently running app. func getContext() -> Context { return sharedContext } /// Currently running app as `Context`. var sharedContext: Context!
28.590426
108
0.620279
5d6488ef423be9591c44ce1e2ab078c3793a17da
11,315
import Core import Venice extension XML : DecodingMedia { public static var mediaType: MediaType { return .xml } public init(from readable: Readable, deadline: Deadline) throws { self = try XMLParser.parse(readable, deadline: deadline) } public func keyCount() -> Int? { return 1 } public func allKeys<Key>(keyedBy: Key.Type) -> [Key] where Key : CodingKey { return Key(stringValue: root.name).map({ [$0] }) ?? [] } public func contains<Key>(_ key: Key) -> Bool where Key : CodingKey { return root.name == key.stringValue } public func keyedContainer() throws -> DecodingMedia { return self } public func unkeyedContainer() throws -> DecodingMedia { throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) } public func singleValueContainer() throws -> DecodingMedia { throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) } public func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia { return XMLMap.single(root) // change this (wrap root) } public func decodeIfPresent( _ type: DecodingMedia.Type, forKey key: CodingKey ) throws -> DecodingMedia? { guard root.name == key.stringValue else { return nil } return XMLMap.single(root) // change this (wrap root) } public func decodeNil() -> Bool { return false } public func decode(_ type: Bool.Type) throws -> Bool { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Int.Type) throws -> Int { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Int8.Type) throws -> Int8 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Int16.Type) throws -> Int16 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Int32.Type) throws -> Int32 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Int64.Type) throws -> Int64 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: UInt.Type) throws -> UInt { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: UInt8.Type) throws -> UInt8 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: UInt16.Type) throws -> UInt16 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: UInt32.Type) throws -> UInt32 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: UInt64.Type) throws -> UInt64 { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Float.Type) throws -> Float { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: Double.Type) throws -> Double { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } public func decode(_ type: String.Type) throws -> String { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } } enum XMLMap { case single(XML.Element) case multiple([XML.Element]) } extension XMLMap : DecodingMedia { static var mediaType: MediaType { return .xml } init(from readable: Readable, deadline: Deadline) throws { let xml = try XML(from: readable, deadline: deadline) self = .single(xml.root) } public func keyCount() -> Int? { switch self { case let .single(element): return Set(element.elements.map({ $0.name })).count case let .multiple(elements): return elements.count } } public func allKeys<Key>(keyedBy: Key.Type) -> [Key] where Key : CodingKey { switch self { case let .single(element): return Set(element.elements.map({ $0.name })).flatMap({ Key(stringValue: $0) }) case let .multiple(elements): return elements.indices.flatMap({ Key(intValue: $0) }) } } public func contains<Key>(_ key: Key) -> Bool where Key : CodingKey { switch self { case let .single(element): return !element.elements(named: key.stringValue).isEmpty case let .multiple(elements): return elements.indices.contains(key.intValue ?? -1) } } public func keyedContainer() throws -> DecodingMedia { switch self { case .single: return self default: throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) } } public func unkeyedContainer() throws -> DecodingMedia { switch self { case .multiple: return self default: throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) } } public func singleValueContainer() throws -> DecodingMedia { switch self { case .single: return self default: throw DecodingError.typeMismatch(DecodingMedia.self, DecodingError.Context()) } } func decode(_ type: DecodingMedia.Type, forKey key: CodingKey) throws -> DecodingMedia { switch self { case let .single(element): let elements = element.elements(named: key.stringValue) guard elements.count == 1, let element = elements.first else { return XMLMap.multiple(elements) } return XMLMap.single(element) case let .multiple(elements): guard let index = key.intValue else { throw DecodingError.keyNotFound(key, DecodingError.Context()) } guard elements.indices.contains(index) else { throw DecodingError.keyNotFound(key, DecodingError.Context()) } return XMLMap.single(elements[index]) } } public func decodeIfPresent( _ type: DecodingMedia.Type, forKey key: CodingKey ) throws -> DecodingMedia? { switch self { case let .single(element): let elements = element.elements(named: key.stringValue) guard elements.count == 1, let element = elements.first else { return XMLMap.multiple(elements) } return XMLMap.single(element) case let .multiple(elements): guard let index = key.intValue else { throw DecodingError.keyNotFound(key, DecodingError.Context()) } guard elements.indices.contains(index) else { throw DecodingError.keyNotFound(key, DecodingError.Context()) } return XMLMap.single(elements[index]) } } public func decodeNil() -> Bool { return false } public func decode(_ type: Bool.Type) throws -> Bool { guard let bool = try Bool(contents(forType: type)) else { throw DecodingError.typeMismatch(Bool.self, DecodingError.Context()) } return bool } public func decode(_ type: Int.Type) throws -> Int { guard let int = try Int(contents(forType: type)) else { throw DecodingError.typeMismatch(Int.self, DecodingError.Context()) } return int } public func decode(_ type: Int8.Type) throws -> Int8 { guard let int8 = try Int8(contents(forType: type)) else { throw DecodingError.typeMismatch(Int8.self, DecodingError.Context()) } return int8 } public func decode(_ type: Int16.Type) throws -> Int16 { guard let int16 = try Int16(contents(forType: type)) else { throw DecodingError.typeMismatch(Int16.self, DecodingError.Context()) } return int16 } public func decode(_ type: Int32.Type) throws -> Int32 { guard let int32 = try Int32(contents(forType: type)) else { throw DecodingError.typeMismatch(Int32.self, DecodingError.Context()) } return int32 } public func decode(_ type: Int64.Type) throws -> Int64 { guard let int64 = try Int64(contents(forType: type)) else { throw DecodingError.typeMismatch(Int64.self, DecodingError.Context()) } return int64 } public func decode(_ type: UInt.Type) throws -> UInt { guard let uint = try UInt(contents(forType: type)) else { throw DecodingError.typeMismatch(UInt.self, DecodingError.Context()) } return uint } public func decode(_ type: UInt8.Type) throws -> UInt8 { guard let uint8 = try UInt8(contents(forType: type)) else { throw DecodingError.typeMismatch(UInt8.self, DecodingError.Context()) } return uint8 } public func decode(_ type: UInt16.Type) throws -> UInt16 { guard let uint16 = try UInt16(contents(forType: type)) else { throw DecodingError.typeMismatch(UInt16.self, DecodingError.Context()) } return uint16 } public func decode(_ type: UInt32.Type) throws -> UInt32 { guard let uint32 = try UInt32(contents(forType: type)) else { throw DecodingError.typeMismatch(UInt32.self, DecodingError.Context()) } return uint32 } public func decode(_ type: UInt64.Type) throws -> UInt64 { guard let uint64 = try UInt64(contents(forType: type)) else { throw DecodingError.typeMismatch(UInt64.self, DecodingError.Context()) } return uint64 } public func decode(_ type: Float.Type) throws -> Float { guard let float = try Float(contents(forType: type)) else { throw DecodingError.typeMismatch(Float.self, DecodingError.Context()) } return float } public func decode(_ type: Double.Type) throws -> Double { guard let double = try Double(contents(forType: type)) else { throw DecodingError.typeMismatch(Double.self, DecodingError.Context()) } return double } public func decode(_ type: String.Type) throws -> String { return try contents(forType: type) } private func contents(forType: Any.Type) throws -> String { guard case let .single(element) = self else { throw DecodingError.typeMismatch(forType, DecodingError.Context()) } return element.contents } }
32.144886
99
0.597879
269c7b97f7478240a98b904825e002a7076a541f
11,582
// // UnitSimulationMainBodyCell.swift // DereGuide // // Created by zzk on 2017/5/16. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit protocol UnitSimulationMainBodyCellDelegate: class { func startCalculate(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func startSimulate(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func cancelSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func startAfkModeSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) func cancelAfkModeSimulating(_ unitSimulationMainBodyCell: UnitSimulationMainBodyCell) } class UnitSimulationMainBodyCell: UITableViewCell { var calculationButton: UIButton! var calculationGrid: GridLabel! var simulationButton: UIButton! var cancelButton: UIButton! var simulationGrid: GridLabel! var simulatingIndicator: UIActivityIndicatorView! var cancelButtonWidthConstraint: Constraint! var cancelButtonLeftConstraint: Constraint! let afkModeButton = WideButton() let afkModeCancelButton = WideButton() let afkModeIndicator = UIActivityIndicatorView(style: .white) let afkModeGrid = GridLabel(rows: 2, columns: 3) var afkModeCancelButtonLeftConstraint: Constraint! var afkModeCancelButtonWidthConstraint: Constraint! // var scoreDistributionButton: UIButton! // // var scoreDetailButton: UIButton! // // var supportSkillDetailButton: UIButton! weak var delegate: UnitSimulationMainBodyCellDelegate? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) calculationButton = WideButton() calculationButton.setTitle(NSLocalizedString("一般计算", comment: "队伍详情页面"), for: .normal) calculationButton.backgroundColor = .dance calculationButton.addTarget(self, action: #selector(startCalculate), for: .touchUpInside) contentView.addSubview(calculationButton) calculationButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(10) } calculationGrid = GridLabel.init(rows: 2, columns: 4) contentView.addSubview(calculationGrid) calculationGrid.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(calculationButton.snp.bottom).offset(10) } simulationButton = WideButton() simulationButton.setTitle(NSLocalizedString("模拟计算", comment: "队伍详情页面"), for: .normal) simulationButton.backgroundColor = .vocal simulationButton.addTarget(self, action: #selector(startSimulate), for: .touchUpInside) contentView.addSubview(simulationButton) simulationButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(calculationGrid.snp.bottom).offset(10) } simulatingIndicator = UIActivityIndicatorView(style: .white) simulationButton.addSubview(simulatingIndicator) simulatingIndicator.snp.makeConstraints { (make) in make.right.equalTo(simulationButton.titleLabel!.snp.left) make.centerY.equalTo(simulationButton) } cancelButton = WideButton() cancelButton.setTitle(NSLocalizedString("取消", comment: ""), for: .normal) cancelButton.backgroundColor = .vocal cancelButton.addTarget(self, action: #selector(cancelSimulating), for: .touchUpInside) contentView.addSubview(cancelButton) cancelButton.snp.makeConstraints { (make) in make.right.equalTo(-10) make.top.equalTo(simulationButton) self.cancelButtonWidthConstraint = make.width.equalTo(0).constraint self.cancelButtonLeftConstraint = make.left.equalTo(simulationButton.snp.right).constraint make.width.equalTo(calculationGrid.snp.width).dividedBy(4).priority(900) make.left.equalTo(simulationButton.snp.right).offset(1).priority(900) } cancelButton.titleLabel?.adjustsFontSizeToFitWidth = true cancelButton.titleLabel?.baselineAdjustment = .alignCenters simulationGrid = GridLabel.init(rows: 2, columns: 4) contentView.addSubview(simulationGrid) simulationGrid.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(simulationButton.snp.bottom).offset(10) } contentView.addSubview(afkModeButton) afkModeButton.setTitle(NSLocalizedString("模拟挂机模式", comment: ""), for: .normal) afkModeButton.backgroundColor = .passion afkModeButton.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(simulationGrid.snp.bottom).offset(10) } afkModeButton.addTarget(self, action: #selector(startAfkModeSimulating), for: .touchUpInside) contentView.addSubview(afkModeGrid) afkModeGrid.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-10) make.top.equalTo(afkModeButton.snp.bottom).offset(10) make.bottom.equalTo(-10) } afkModeButton.addSubview(afkModeIndicator) afkModeIndicator.snp.makeConstraints { (make) in make.right.equalTo(afkModeButton.titleLabel!.snp.left) make.centerY.equalTo(afkModeButton) } afkModeCancelButton.setTitle(NSLocalizedString("取消", comment: ""), for: .normal) afkModeCancelButton.backgroundColor = .passion afkModeCancelButton.addTarget(self, action: #selector(cancelAfkModeSimulating), for: .touchUpInside) contentView.addSubview(afkModeCancelButton) afkModeCancelButton.snp.makeConstraints { (make) in make.right.equalTo(-10) make.top.equalTo(afkModeButton) self.afkModeCancelButtonWidthConstraint = make.width.equalTo(0).constraint self.afkModeCancelButtonLeftConstraint = make.left.equalTo(afkModeButton.snp.right).constraint make.width.equalTo(afkModeGrid.snp.width).dividedBy(4).priority(900) make.left.equalTo(afkModeButton.snp.right).offset(1).priority(900) } afkModeCancelButton.titleLabel?.adjustsFontSizeToFitWidth = true afkModeCancelButton.titleLabel?.baselineAdjustment = .alignCenters prepareGridViewFields() selectionStyle = .none } private func prepareGridViewFields() { var calculationString = [[String]]() calculationString.append([NSLocalizedString("表现值", comment: "队伍详情页面"), NSLocalizedString("极限分数", comment: "队伍详情页面") + "1", NSLocalizedString("极限分数", comment: "队伍详情页面") + "2", NSLocalizedString("平均分数", comment: "队伍详情页面")]) calculationString.append(["", "", "", ""]) calculationGrid.setContents(calculationString) var simulationStrings = [[String]]() simulationStrings.append(["1%", "5%", "20%", "50%"]) simulationStrings.append(["", "", "", ""]) simulationGrid.setContents(simulationStrings) var afkModeStrings = [[String]]() afkModeStrings.append([NSLocalizedString("存活率%", comment: ""), NSLocalizedString("S Rank率%", comment: ""), NSLocalizedString("最高得分", comment: "")]) afkModeStrings.append(["", "", "", ""]) afkModeGrid.setContents(afkModeStrings) } func resetCalculationButton() { calculationButton.setTitle(NSLocalizedString("一般计算", comment: ""), for: .normal) calculationButton.isUserInteractionEnabled = true } func stopSimulationAnimating() { simulationButton.isUserInteractionEnabled = true UIView.animate(withDuration: 0.25) { self.cancelButtonWidthConstraint.activate() self.cancelButtonLeftConstraint.activate() self.layoutIfNeeded() } simulatingIndicator.stopAnimating() simulationButton.setTitle(NSLocalizedString("模拟计算", comment: ""), for: .normal) } func startSimulationAnimating() { simulatingIndicator.startAnimating() UIView.animate(withDuration: 0.25) { self.cancelButtonLeftConstraint.deactivate() self.cancelButtonWidthConstraint.deactivate() self.layoutIfNeeded() } simulationButton.isUserInteractionEnabled = false } func startAfkModeSimulationAnimating() { afkModeIndicator.startAnimating() UIView.animate(withDuration: 0.25) { self.afkModeCancelButtonLeftConstraint.deactivate() self.afkModeCancelButtonWidthConstraint.deactivate() self.layoutIfNeeded() } afkModeButton.isUserInteractionEnabled = false } func stopAfkModeSimulationAnimating() { afkModeButton.isUserInteractionEnabled = true UIView.animate(withDuration: 0.25) { self.afkModeCancelButtonLeftConstraint.activate() self.afkModeCancelButtonWidthConstraint.activate() self.layoutIfNeeded() } afkModeIndicator.stopAnimating() afkModeButton.setTitle(NSLocalizedString("模拟挂机模式", comment: ""), for: .normal) } func setupCalculationResult(value1: Int, value2: Int, value3: Int, value4: Int) { calculationGrid[1, 0].text = String(value1) calculationGrid[1, 1].text = String(value2) calculationGrid[1, 2].text = String(value3) calculationGrid[1, 3].text = String(value4) } func setupSimulationResult(value1: Int, value2: Int, value3: Int, value4: Int) { simulationGrid[1, 0].text = String(value1) simulationGrid[1, 1].text = String(value2) simulationGrid[1, 2].text = String(value3) simulationGrid[1, 3].text = String(value4) } func setupAfkModeResult(value1: String, value2: String, value3: String) { afkModeGrid[1, 0].text = value1 afkModeGrid[1, 1].text = value2 afkModeGrid[1, 2].text = value3 } func setupAppeal(_ appeal: Int) { calculationGrid[1, 0].text = String(appeal) } func clearCalculationGrid() { calculationGrid[1, 2].text = "" calculationGrid[1, 1].text = "" calculationGrid[1, 0].text = "" calculationGrid[1, 3].text = "" } func clearSimulationGrid() { simulationGrid[1, 0].text = "" simulationGrid[1, 1].text = "" simulationGrid[1, 2].text = "" simulationGrid[1, 3].text = "" } func clearAfkModeGrid() { afkModeGrid[1, 0].text = "" afkModeGrid[1, 1].text = "" afkModeGrid[1, 2].text = "" } @objc func startCalculate() { delegate?.startCalculate(self) } @objc func startSimulate() { delegate?.startSimulate(self) } @objc func cancelSimulating() { delegate?.cancelSimulating(self) } @objc private func startAfkModeSimulating() { delegate?.startAfkModeSimulating(self) } @objc private func cancelAfkModeSimulating() { delegate?.cancelAfkModeSimulating(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
38.735786
229
0.659817
1a8bc640eec3cc0564482ddd109e49ea7170fd91
4,117
// // Created by Raimundas Sakalauskas on 7/23/19. // Copyright (c) 2018 Particle. All rights reserved. // import UIKit class Gen3SetupControlPanelManageWifiViewController: Gen3SetupNetworkListViewController { override class var nibName: String { return "Gen3SetupNetworkListNoActivityIndicatorView" } internal var networks:[Gen3SetupKnownWifiNetworkInfo]? internal var callback: ((Gen3SetupKnownWifiNetworkInfo) -> ())! func setup(didSelectNetwork: @escaping (Gen3SetupKnownWifiNetworkInfo) -> ()) { self.callback = didSelectNetwork } override func viewDidLoad() { super.viewDidLoad() self.viewsToFade = [self.networksTableView, self.titleLabel] } override func setStyle() { super.setStyle() } override var customTitle: String { return Gen3SetupStrings.ControlPanel.ManageWifi.Title } override func setContent() { titleLabel.text = Gen3SetupStrings.ControlPanel.ManageWifi.Text } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.stopScanning() } func setNetworks(networks: [Gen3SetupKnownWifiNetworkInfo]) { var networks = networks networks.sort { info, info2 in return info.ssid.localizedCaseInsensitiveCompare(info2.ssid) == .orderedAscending } self.networks = networks } override func resume(animated: Bool) { super.resume(animated: true) self.networksTableView.reloadData() self.networksTableView.isUserInteractionEnabled = true self.isBusy = false } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return networks?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:Gen3SetupCell! = nil let network = networks![indexPath.row] cell = tableView.dequeueReusableCell(withIdentifier: "Gen3SetupWifiNetworkCell") as! Gen3SetupCell cell.cellTitleLabel.text = network.ssid cell.cellTitleLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.LargeSize, color: ParticleStyle.PrimaryTextColor) let cellHighlight = UIView() cellHighlight.backgroundColor = ParticleStyle.CellHighlightColor cell.selectedBackgroundView = cellHighlight cell.preservesSuperviewLayoutMargins = false cell.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) NSLog("networks![indexPath.row].security = \(networks![indexPath.row].security)") if networks![indexPath.row].credentialsType == .noCredentials { cell.cellSecondaryAccessoryImageView.image = nil } else { cell.cellSecondaryAccessoryImageView.image = UIImage.init(named: "Gen3SetupWifiProtectedIcon") } cell.cellAccessoryImageView.isHidden = true cell.cellSecondaryAccessoryImageView.isHidden = (cell.cellSecondaryAccessoryImageView.image == nil) cell.accessoryView = nil cell.accessoryType = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let alert = UIAlertController(title: Gen3SetupStrings.ControlPanel.Prompt.DeleteWifiTitle, message: Gen3SetupStrings.ControlPanel.Prompt.DeleteWifiText.replacingOccurrences(of: "{{wifiSSID}}", with: self.networks![indexPath.row].ssid), preferredStyle: .alert) alert.addAction(UIAlertAction(title: Gen3SetupStrings.ControlPanel.Action.DeleteWifi, style: .default) { action in tableView.isUserInteractionEnabled = false self.isBusy = true self.fade(animated: true) self.callback(self.networks![indexPath.row]) }) alert.addAction(UIAlertAction(title: Gen3SetupStrings.ControlPanel.Action.DontDeleteWifi, style: .cancel) { action in }) self.present(alert, animated: true) } }
34.889831
267
0.698567
0e11957fa19e249baa0b5ecf016abced29636644
325
// // MOPhoto.swift // FlickrAndCoreData // // Created by nate.taylor_macbook on 22/11/2019. // Copyright © 2019 natetaylor. All rights reserved. // import UIKit import CoreData @objc(MOPhoto) class MOPhoto: NSManagedObject { @NSManaged var id: Int16 @NSManaged var text: String @NSManaged var data: Data }
18.055556
53
0.707692
eb9c786eb66ee7dc53d5deae4b0a27bc42ffbec9
400
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // -----------------------------Protoclo------------------------------- // class ProtocolTest { var property : String init(property:String){ self.property = property } } var test = ProtocolTest(property: "protocol") println(test.property) test.property = "hello"
15.384615
75
0.5525
fefebc2f67dd55b35df33cbbbd037b3e6eb99d15
5,953
// // 🦠 Corona-Warn-App // import AVFoundation import Foundation import UIKit class ExposureSubmissionQRScannerViewModel: NSObject, AVCaptureMetadataOutputObjectsDelegate { // MARK: - Init init( onSuccess: @escaping (CoronaTestQRCodeInformation) -> Void, onError: @escaping (QRScannerError, _ reactivateScanning: @escaping () -> Void) -> Void ) { self.onSuccess = onSuccess self.onError = onError self.captureSession = AVCaptureSession() self.captureDevice = AVCaptureDevice.default(for: .video) super.init() setupCaptureSession() #if DEBUG if isUITesting { onSuccess(CoronaTestQRCodeInformation.pcr("guid")) } #endif } // MARK: - Protocol AVCaptureMetadataOutputObjectsDelegate func metadataOutput( _: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from _: AVCaptureConnection ) { didScan(metadataObjects: metadataObjects) } // MARK: - Internal let onError: (QRScannerError, _ reactivateScanning: @escaping () -> Void) -> Void let captureSession: AVCaptureSession var isScanningActivated: Bool { captureSession.isRunning } /// get current torchMode by device state var torchMode: TorchMode { guard let device = captureDevice, device.hasTorch else { return .notAvailable } switch device.torchMode { case .off: return .lightOff case .on: return .lightOn case .auto: return .notAvailable @unknown default: return .notAvailable } } func activateScanning() { captureSession.startRunning() } func deactivateScanning() { captureSession.stopRunning() } func setupCaptureSession() { /// this special case is need to avoid system alert while UI tests are running #if DEBUG if isUITesting { activateScanning() return } #endif guard let currentCaptureDevice = captureDevice, let caputureDeviceInput = try? AVCaptureDeviceInput(device: currentCaptureDevice) else { onError(.cameraPermissionDenied) { Log.error("Failed to setup AVCaptureDeviceInput", log: .ui) } return } let metadataOutput = AVCaptureMetadataOutput() captureSession.addInput(caputureDeviceInput) captureSession.addOutput(metadataOutput) metadataOutput.metadataObjectTypes = [.qr] metadataOutput.setMetadataObjectsDelegate(self, queue: .main) } func startCaptureSession() { switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: Log.info("AVCaptureDevice.authorized - enable qr code scanner") activateScanning() case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { [weak self] isAllowed in guard isAllowed else { self?.onError(.cameraPermissionDenied) { Log.error("camera requestAccess denied - stop here we can't go on", log: .ui) } return } self?.activateScanning() } default: onError(.cameraPermissionDenied) { Log.info(".cameraPermissionDenied - stop here we can't go on", log: .ui) } } } func stopCaptureSession() { deactivateScanning() } /// toggle torchMode between on / off after finish call optional completion handler func toggleFlash(completion: (() -> Void)? = nil ) { guard let device = captureDevice, device.hasTorch else { return } defer { device.unlockForConfiguration() completion?() } do { try device.lockForConfiguration() if device.torchMode == .on { device.torchMode = .off } else { try device.setTorchModeOn(level: 1.0) } } catch { Log.error(error.localizedDescription, log: .api) } } func didScan(metadataObjects: [MetadataObject]) { guard isScanningActivated else { Log.info("Scanning not stopped from previous run") return } deactivateScanning() if let code = metadataObjects.first(where: { $0 is MetadataMachineReadableCodeObject }) as? MetadataMachineReadableCodeObject, let stringValue = code.stringValue { guard let coronaTestQRCodeInformation = coronaTestQRCodeInformation(from: stringValue) else { onError(.codeNotFound) { [weak self] in self?.activateScanning() } return } onSuccess(coronaTestQRCodeInformation) } } /// Filters the input string and extracts a guid. /// - the input needs to start with https://localhost/? /// - the input must not be longer than 150 chars and cannot be empty /// - the guid contains only the following characters: a-f, A-F, 0-9,- /// - the guid is a well formatted string (6-8-4-4-4-12) with length 43 /// (6 chars encode a random number, 32 chars for the uuid, 5 chars are separators) func coronaTestQRCodeInformation(from input: String) -> CoronaTestQRCodeInformation? { // general checks for both PCR and Rapid tests guard !input.isEmpty, let urlComponents = URLComponents(string: input), !urlComponents.path.contains(" "), urlComponents.scheme?.lowercased() == "https" else { return nil } // specific checks based on test type if urlComponents.host?.lowercased() == "localhost" { return pcrTestInformation(from: input, urlComponents: urlComponents) } else if let route = Route(input), case .rapidAntigen(let testInformationResult) = route, case let .success(testInformation) = testInformationResult { return testInformation } else { return nil } } // MARK: - Private private let onSuccess: (CoronaTestQRCodeInformation) -> Void private let captureDevice: AVCaptureDevice? private func pcrTestInformation(from guidURL: String, urlComponents: URLComponents) -> CoronaTestQRCodeInformation? { guard guidURL.count <= 150, urlComponents.path.components(separatedBy: "/").count == 2, // one / will separate into two components let candidate = urlComponents.query, candidate.count == 43, let matchings = candidate.range( of: #"^[0-9A-Fa-f]{6}-[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$"#, options: .regularExpression ) else { return nil } return matchings.isEmpty ? nil : .pcr(candidate) } }
27.560185
165
0.712246
fb52e161a31f1dc4446f658e369c34e0c02a458e
1,375
// // MGRequestSender.swift // mgbaseproject // // Created by Magical Water on 2018/1/30. // Copyright © 2018年 Magical Water. All rights reserved. // import Foundation /* 一般呼叫 api(非跳頁, 或者須完全自行處理的) */ public class MGRequestSender: MGRequestCallback { /* 一般呼叫 api 都會有統一回傳的接口 為了分辨誰是誰, 我們得給每次的 request 加上一個編號 通常request 只有幾種分類, 未免每次都重新定義, 這邊直接定義幾種 */ public static let REQUEST_DEFAUT = -1 public static let REQUEST_LOAD_MORE = -2 public static let REQUEST_LOAD_TOP = -3 public static let REQUEST_REFRESH = -4 weak var delegate: MGRequestSenderDelegate? //儲存所有的 request private var requests: [Int:MGUrlRequest] = [:] /**************************供外部呼叫 以下********************************/ //發送 REQUEST, 默認 code 是 REQUEST_DEFAUT public func send(_ request: MGUrlRequest, requestCode: Int = REQUEST_DEFAUT) { MGRequestConnect.shared.getData(request, requestCode: requestCode, callback: self) } /**************************供外部呼叫 結束********************************/ public func response(_ request: MGUrlRequest, requestCode: Int, success: Bool) { delegate?.response(request, success: success, requestCode: requestCode) } } //處理 MGRequestSender 的回傳 protocol MGRequestSenderDelegate: class { func response(_ request: MGUrlRequest, success: Bool, requestCode: Int) }
23.706897
90
0.640727
f440547b81cbc8c62faba19a26c60fda8f2ebd9d
4,825
// // CBCentralManager+BluePipe.swift // CBCentralManager+BluePipe // // Created by zhiou on 2021/8/23. // import CoreBluetooth import UIKit public enum ScanStrategy { case take(n: Int) case untilTimeout } public typealias BPScanFilter = (BPDiscovery) -> Bool public typealias BPScanBlock = (BPDiscovery) -> Void public typealias BPScanCompletionHandler = (BPError?) -> Void public typealias BPWillStartScanBlock = () -> Void public typealias BPDidStopScanBlock = () -> Void public typealias BPFindBlock = (Result<BPDiscovery, BPError>) -> Void extension BluePipeWrapper where Base: CBCentralManager { public func just(_ strategy: ScanStrategy) -> Self { var mutatingSelf = self mutatingSelf.scanStrategy = strategy return self } public func timeout(_ timeout: Int) -> Self { var mutatingSelf = self mutatingSelf.timeout = timeout return self } public func filter(_ filter: @escaping BPScanFilter) -> Self { var mutatingSelf = self mutatingSelf.filter = filter return self } public func willStartScan(_ block: @escaping BPWillStartScanBlock) -> Self { var mutatingSelf = self mutatingSelf.willStartScan = block return self } public func didStopScan(_ block: @escaping BPDidStopScanBlock) -> Self { var mutatingSelf = self mutatingSelf.didStopScan = block return self } public func scan(_ scanBlock: @escaping BPScanBlock, completionHandler: BPScanCompletionHandler? = nil) { var mutatingSelf = self let scanner = BP.centralManager.scanner scanner.discoverClosure = { discovery in scanBlock(discovery) if let count = mutatingSelf.count { mutatingSelf.count = count + 1 if case .take(let n) = mutatingSelf.scanStrategy, n == count { scanner.stop() } } } if let filter = mutatingSelf.filter { scanner.filterClosure = filter } scanner.didStop = { error in completionHandler?(error) } if let timeout = self.timeout { let ti = TimeInterval(timeout) scanner.startWith(duration: ti) } else { scanner.start() } mutatingSelf.scanner = scanner } public func find(_ displayName: String, block: @escaping BPFindBlock) { let predicate = NSPredicate(format: "SELF MATCHES %@", displayName) self.filter { discovery in return predicate.evaluate(with: discovery.displayName) } .scan { discovery in block(Result.success(discovery)) } completionHandler: { error in if let error = error { block(Result.failure(error)) } } } } private var scanStrategyKey: Void? private var timeoutKey: Void? private var countKey: Void? private var scannerKey: Void? private var filterKey: Void? private var willStartScanKey: Void? private var didStopScanKey: Void? extension BluePipeWrapper where Base: CBCentralManager { var scanStrategy: ScanStrategy? { get { return objc_getAssociatedObject(base, &scanStrategyKey) as? ScanStrategy} set { objc_setAssociatedObject(base, &scanStrategyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } var timeout: Int? { get { return objc_getAssociatedObject(base, &timeoutKey) as? Int} set { objc_setAssociatedObject(base, &timeoutKey, newValue, .OBJC_ASSOCIATION_ASSIGN)} } var count: Int? { get { return objc_getAssociatedObject(base, &countKey) as? Int} set { objc_setAssociatedObject(base, &countKey, newValue, .OBJC_ASSOCIATION_ASSIGN)} } var scanner: BPScanner? { get { return objc_getAssociatedObject(base, &scannerKey) as? BPScanner} set { objc_setAssociatedObject(base, &scannerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } var filter: BPScanFilter? { get { return objc_getAssociatedObject(base, &filterKey) as? BPScanFilter} set { objc_setAssociatedObject(base, &filterKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } var willStartScan: BPWillStartScanBlock? { get { return objc_getAssociatedObject(base, &willStartScanKey) as? BPWillStartScanBlock} set { objc_setAssociatedObject(base, &willStartScanKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } var didStopScan: BPDidStopScanBlock? { get { return objc_getAssociatedObject(base, &didStopScanKey) as? BPDidStopScanBlock} set { objc_setAssociatedObject(base, &didStopScanKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)} } }
33.506944
110
0.654922
d722040db58d9a1e43cfd54f8397ea389b7abf4a
7,327
// // ViewController.swift // UUChatTableViewSwift // // Created by XcodeYang on 8/13/15. // Copyright © 2015 XcodeYang. All rights reserved. // import UIKit private let leftCellId = "UUChatLeftMessageCell" private let rightCellId = "UUChatRightMessageCell" class ChatTableViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var chatTableView: UITableView! var inputBackView: UUInputView! var dataArray: [AnyObject]! var inputViewConstraint: NSLayoutConstraint? = nil override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardFrameChanged:"), name: UIKeyboardWillChangeFrameNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } //TODO: This method seems like would fix the problem of cells layout when Orientation changed. override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { //chatTableView.reloadData() self.view.endEditing(true) } override func viewDidLoad() { super.viewDidLoad() self.dataArray = UUChatModel.creatRandomArray(count: 10) initBaseViews() chatTableView.registerClass(UUChatLeftMessageCell.classForKeyedArchiver(), forCellReuseIdentifier: leftCellId) chatTableView.registerClass(UUChatRightMessageCell.classForKeyedArchiver(), forCellReuseIdentifier: rightCellId) chatTableView.estimatedRowHeight = 100 } func initBaseViews() { self.title = "UUChat - Swift2" navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Stop, target: self, action: Selector("backAction")) navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: .Search, target: self, action: nil) inputBackView = UUInputView() self.view.addSubview(inputBackView) //TODO: I don't know how to get constraint from snapkit's methods. //It doesn't works. why.why.why... //https://github.com/SnapKit/SnapKit/tree/feature/protocol-api#1-references //inputViewConstraint = make.bottom.equalTo(view).constraint // temporary method inputViewConstraint = NSLayoutConstraint( item: inputBackView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0 ) inputBackView.snp_makeConstraints { (make) -> Void in make.leading.trailing.equalTo(self.view) } view.addConstraint(inputViewConstraint!) inputBackView.sendMessage( imageBlock: { [weak self](image:UIImage, textView:UITextView) -> Void in self!.dataArray.append(UUChatModel.creatMessageFromMeByImage(image)) self!.chatTableView.reloadData() self!.chatTableView.scrollToBottom(animation: true) }, textBlock: { [weak self](text:String, textView:UITextView) -> Void in self!.dataArray.append(UUChatModel.creatMessageFromMeByText(text)) self!.chatTableView.reloadData() self!.chatTableView.scrollToBottom(animation: true) }, voiceBlock: { [weak self](voice:NSData, textView:UITextView) -> Void in }) chatTableView = UITableView.init(frame: CGRectZero, style: .Plain) chatTableView.dataSource = self chatTableView.delegate = self chatTableView.separatorStyle = UITableViewCellSeparatorStyle.None chatTableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive chatTableView.estimatedRowHeight = 60 self.view.addSubview(chatTableView) chatTableView.snp_makeConstraints { (make) -> Void in make.top.leading.trailing.equalTo(self.view) make.bottom.equalTo(inputBackView.snp_top) } chatTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0) } // private method func backAction(){ if navigationController?.viewControllers.count>1 { self.navigationController?.popViewControllerAnimated(true) } else { self.dismissViewControllerAnimated(true, completion: nil) } } @objc func keyboardFrameChanged(notification: NSNotification) { let dict = NSDictionary(dictionary: notification.userInfo!) let keyboardValue = dict.objectForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue let bottomDistance = mainScreenSize().height - keyboardValue.CGRectValue().origin.y let duration = Double(dict.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as! NSNumber) UIView.animateWithDuration(duration, animations: { self.inputViewConstraint!.constant = -bottomDistance self.view.layoutIfNeeded() }, completion: { (value: Bool) in self.chatTableView.scrollToBottom(animation: true) }) } private func mainScreenSize() -> CGSize { return UIScreen.mainScreen().bounds.size } // tableview delegate & dataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let model = dataArray[indexPath.row] as! UUChatModel if model.from == .Me { let cell:UUChatRightMessageCell = tableView.dequeueReusableCellWithIdentifier(rightCellId) as! UUChatRightMessageCell cell.configUIWithModel(model) return cell } else { let cell:UUChatLeftMessageCell = tableView.dequeueReusableCellWithIdentifier(leftCellId) as! UUChatLeftMessageCell cell.configUIWithModel(model) return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.view.endEditing(true) } // action @IBAction func sendImage(btn:UIButton) { self.view.endEditing(true) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) let libraryAction = UIAlertAction(title: "本地相册", style: .Default) { (action:UIAlertAction) -> Void in } let takePhotoAction = UIAlertAction(title: "拍照", style: .Default) { (action:UIAlertAction) -> Void in } let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) alert.addAction(cancelAction) alert.addAction(libraryAction) alert.addAction(takePhotoAction) self.presentViewController(alert, animated: true, completion: nil) } }
38.563158
165
0.660025
ff9b95e587c6306894250fccf4157a0b69e995f2
863
// // Bundle+Extensions.swift // GitTime // // Created by Kanz on 09/11/2019. // Copyright © 2019 KanzDevelop. All rights reserved. // import Foundation extension Bundle { class func resource<T>(name: String?, extensionType: String?) -> T? where T: Decodable { guard let resourceName = name, !resourceName.isEmpty, let extensionType = extensionType, !extensionType.isEmpty else { return nil } guard let url = Bundle.main.url(forResource: resourceName, withExtension: extensionType) else { return nil } do { let data = try Data(contentsOf: url) let decoder = JSONDecoder() let resource = try decoder.decode(T.self, from: data) return resource } catch { log.error(error.localizedDescription) return nil } } }
29.758621
116
0.611819
46858b93a57ccdfee010ca099b5c7738364a3b04
11,219
// // DisplayView.swift // Aerial // // Created by Guillaume Louel on 09/05/2019. // Copyright © 2019 John Coates. All rights reserved. // import Foundation import Cocoa class DisplayPreview: NSObject { var screen: Screen var previewRect: CGRect init(screen: Screen, previewRect: CGRect) { self.screen = screen self.previewRect = previewRect } } extension NSImage { func flipped(flipHorizontally: Bool = false, flipVertically: Bool = false) -> NSImage { let flippedImage = NSImage(size: size) flippedImage.lockFocus() NSGraphicsContext.current?.imageInterpolation = .high let transform = NSAffineTransform() transform.translateX(by: flipHorizontally ? size.width : 0, yBy: flipVertically ? size.height : 0) transform.scaleX(by: flipHorizontally ? -1 : 1, yBy: flipVertically ? -1 : 1) transform.concat() draw(at: .zero, from: NSRect(origin: .zero, size: size), operation: .sourceOver, fraction: 1) flippedImage.unlockFocus() return flippedImage } } class DisplayView: NSView { // We store our computed previews here var displayPreviews = [DisplayPreview]() // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { super.init(coder: coder) } // MARK: - Drawing //swiftlint:disable:next cyclomatic_complexity override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) let preferences = Preferences.sharedInstance // We need to handle dark mode var backgroundColor = NSColor.init(white: 0.9, alpha: 1.0) var borderColor = NSColor.init(white: 0.8, alpha: 1.0) //let screenColor = NSColor.init(red: 0.38, green: 0.60, blue: 0.85, alpha: 1.0) let screenBorderColor = NSColor.black let timeManagement = TimeManagement.sharedInstance if DarkMode.isEnabled() { backgroundColor = NSColor.init(white: 0.2, alpha: 1.0) borderColor = NSColor.init(white: 0.6, alpha: 1.0) } // Draw background with a 1pt border borderColor.setFill() __NSRectFill(dirtyRect) let path = NSBezierPath(rect: dirtyRect.insetBy(dx: 1, dy: 1)) backgroundColor.setFill() path.fill() let displayDetection = DisplayDetection.sharedInstance displayPreviews = [DisplayPreview]() // Empty the array in case we redraw // In order to draw the screen we need to know the total size of all // the displays together let globalRect = displayDetection.getGlobalScreenRect() var minX: CGFloat, minY: CGFloat, maxX: CGFloat, maxY: CGFloat, scaleFactor: CGFloat if (frame.width / frame.height) > (globalRect.width / globalRect.height) { // We fill vertically then maxY = frame.height - 60 minY = 30 scaleFactor = globalRect.height / maxY maxX = globalRect.width / scaleFactor minX = (frame.width - maxX)/2 } else { // We fill horizontally maxX = frame.width - 60 minX = 30 scaleFactor = globalRect.width / maxX maxY = globalRect.height / scaleFactor minY = (frame.height - maxY)/2 } // In spanned mode, we start by a faint full view of the span if preferences.newViewingMode == Preferences.NewViewingMode.spanned.rawValue { let activeRect = displayDetection.getZeroedActiveSpannedRect() debugLog("spanned active rect \(activeRect)") let activeSRect = NSRect(x: minX + (activeRect.origin.x/scaleFactor), y: minY + (activeRect.origin.y/scaleFactor), width: activeRect.width/scaleFactor, height: activeRect.height/scaleFactor) let bundle = Bundle(for: PreferencesWindowController.self) if let imagePath = bundle.path(forResource: "screen0", ofType: "jpg") { let image = NSImage(contentsOfFile: imagePath) image!.draw(in: activeSRect, from: calcScreenshotRect(src: activeSRect), operation: NSCompositingOperation.copy, fraction: 0.1) } else { errorLog("\(#file) screenshot is missing!!!") } } var idx = 0 var shouldFlip = true // Now we draw each individual screen for screen in displayDetection.screens { let sRect = NSRect(x: minX + (screen.zeroedOrigin.x/scaleFactor), y: minY + (screen.zeroedOrigin.y/scaleFactor), width: screen.bottomLeftFrame.width/scaleFactor, height: screen.bottomLeftFrame.height/scaleFactor) let sPath = NSBezierPath(rect: sRect) screenBorderColor.setFill() sPath.fill() let sInRect = sRect.insetBy(dx: 1, dy: 1) func rawValue(for mode: Preferences.NewViewingMode) -> Int { return mode.rawValue } let viewMode = preferences.newViewingMode if viewMode == rawValue(for: .independent) || viewMode == rawValue(for: .cloned) || viewMode == rawValue(for: .mirrored) { if displayDetection.isScreenActive(id: screen.id) { let bundle = Bundle(for: PreferencesWindowController.self) if let imagePath = bundle.path(forResource: "screen"+String(idx), ofType: "jpg") { var image = NSImage(contentsOfFile: imagePath) if preferences.newViewingMode == Preferences.NewViewingMode.mirrored.rawValue && shouldFlip { image = image?.flipped(flipHorizontally: true, flipVertically: false) } shouldFlip = !shouldFlip image!.draw(in: sInRect, from: calcScreenshotRect(src: sInRect), operation: NSCompositingOperation.copy, fraction: 1.0) } else { errorLog("\(#file) screenshot is missing!!!") } // Show difference images in independant mode to simulate if preferences.newViewingMode == Preferences.NewViewingMode.independent.rawValue { if idx < 2 { idx += 1 } else { idx = 0 } } } else { // If the screen is innactive we fill it with a near black color let sInPath = NSBezierPath(rect: sInRect) let grey = NSColor(white: 0.1, alpha: 1.0) grey.setFill() sInPath.fill() } } else { // Spanned mode if displayDetection.isScreenActive(id: screen.id) { // Calculate which portion of the image to display let activeRect = displayDetection.getZeroedActiveSpannedRect() let activeSRect = NSRect(x: minX + (activeRect.origin.x/scaleFactor), y: minY + (activeRect.origin.y/scaleFactor), width: activeRect.width/scaleFactor, height: activeRect.height/scaleFactor) let ssRect = calcScreenshotRect(src: activeSRect) let xFactor = ssRect.width / activeSRect.width let yFactor = ssRect.height / activeSRect.height // ... let sFRect = CGRect(x: (sInRect.origin.x - activeSRect.origin.x) * xFactor + ssRect.origin.x, y: (sInRect.origin.y - activeSRect.origin.y) * yFactor + ssRect.origin.y, width: sInRect.width*xFactor, height: sInRect.height*yFactor) let bundle = Bundle(for: PreferencesWindowController.self) if let imagePath = bundle.path(forResource: "screen0", ofType: "jpg") { let image = NSImage(contentsOfFile: imagePath) //image!.draw(in: sInRect) image!.draw(in: sInRect, from: sFRect, operation: NSCompositingOperation.copy, fraction: 1.0) } else { errorLog("\(#file) screenshot is missing!!!") } } } // We preserve those calculations to handle our clicking logic displayPreviews.append(DisplayPreview(screen: screen, previewRect: sInRect)) // We put a white bar on the main screen if screen.isMain { let mainRect = CGRect(x: sRect.origin.x, y: sRect.origin.y + sRect.height-8, width: sRect.width, height: 8) let sMainPath = NSBezierPath(rect: mainRect) NSColor.black.setFill() sMainPath.fill() let sMainInPath = NSBezierPath(rect: mainRect.insetBy(dx: 1, dy: 1)) NSColor.white.setFill() sMainInPath.fill() } } } // Helper to keep aspect ratio of screenshots to be displayed func calcScreenshotRect(src: CGRect) -> CGRect { var minX: CGFloat, minY: CGFloat, maxX: CGFloat, maxY: CGFloat, scaleFactor: CGFloat let imgw: CGFloat = 720 let imgh: CGFloat = 400 if (imgw/imgh) < (src.width/src.height) { minX = 0 maxX = imgw scaleFactor = src.width / maxX maxY = src.height / scaleFactor minY = (imgh - maxY)/2 } else { minY = 0 maxY = imgh scaleFactor = src.height / maxY maxX = src.width / scaleFactor minX = (imgw - maxX)/2 } return CGRect(x: minX, y: minY, width: maxX, height: maxY) } // MARK: - Clicking override func mouseDown(with event: NSEvent) { let displayDetection = DisplayDetection.sharedInstance let preferences = Preferences.sharedInstance // Grab relative location of the click in view let point = convert(event.locationInWindow, from: nil) // If in selection mode, toggle the screen & redraw if preferences.newDisplayMode == Preferences.NewDisplayMode.selection.rawValue { for displayPreview in displayPreviews { if displayPreview.previewRect.contains(point) { if displayDetection.isScreenActive(id: displayPreview.screen.id) { displayDetection.unselectScreen(id: displayPreview.screen.id) } else { displayDetection.selectScreen(id: displayPreview.screen.id) } debugLog("Clicked on \(displayPreview.screen.id)") self.needsDisplay = true } } } } }
41.86194
143
0.55923
f46d546df1b6cbd3935e638b9b9dbf1e92c2c525
279
// // Inbox.swift // SingletonEvil // // Created by Christian Menschel on 07.09.18. // Copyright © 2018 sd. All rights reserved. // import Foundation struct Inbox { let user: User var messsages = [Message]() init(user: User) { self.user = user } }
14.684211
46
0.609319
0987dd4bac59d9af793880f579a3317e4136cb95
2,673
import ComposableArchitecture import SwiftUI private let readMe = """ This screen demonstrates how the `Reducer` struct can be extended to enhance reducers with extra \ functionality. In it we introduce a stricter interface for constructing reducers that takes state and action as \ its only two arguments, and returns a new function that takes the environment as its only \ argument and returns an effect: ``` (inout State, Action) -> (Environment) -> Effect<Action, Never> ``` This form of reducer is useful if you want to be very strict in not allowing the reducer to have \ access to the environment when it is computing state changes, and only allowing access to the \ environment when computing effects. Tapping "Roll die" below with update die state to a random side using the environment. It uses \ the strict interface and so it cannot synchronously evaluate its environment to update state. \ Instead, it introduces a new action to feed the random number back into the system. """ extension Reducer { static func strict( _ reducer: @escaping (inout State, Action) -> (Environment) -> Effect<Action, Never> ) -> Reducer { Self { state, action, environment in reducer(&state, action)(environment) } } } struct DieRollState: Equatable { var dieSide = 1 } enum DieRollAction { case rollDie case dieRolled(side: Int) } struct DieRollEnvironment { var rollDie: () -> Int } let dieRollReducer = Reducer<DieRollState, DieRollAction, DieRollEnvironment>.strict { state, action in switch action { case .rollDie: return { environment in Effect(value: .dieRolled(side: environment.rollDie())) } case let .dieRolled(side): state.dieSide = side return { _ in .none } } } struct DieRollView: View { let store: Store<DieRollState, DieRollAction> var body: some View { WithViewStore(self.store) { viewStore in Form { Section(header: Text(template: readMe, .caption)) { HStack { Button("Roll die") { viewStore.send(.rollDie) } Spacer() Text("\(viewStore.dieSide)") .font(Font.body.monospacedDigit()) } .buttonStyle(BorderlessButtonStyle()) } } .navigationBarTitle("Strict reducers") } } } struct DieRollView_Previews: PreviewProvider { static var previews: some View { NavigationView { DieRollView( store: Store( initialState: DieRollState(), reducer: dieRollReducer, environment: DieRollEnvironment( rollDie: { .random(in: 1...6) } ) ) ) } } }
27
100
0.664048
1159b7e31bdd3a64e59f29e981a0b8c9f91420ae
11,306
// // SelectVehicleViewController.swift // VehicleID // import UIKit import GPUIKit import EdmundsAPI public protocol SelectVehicleDelegate: class { func vehicleSelected(vehicle: Vehicle) } public class SelectVehicleViewController: ATViewController, UIPickerViewDataSource, UIPickerViewDelegate, GetMakesDelegate, GetModelsDelegate, GetStylesDelegate { @IBOutlet weak var yearPickerView: UIPickerView! @IBOutlet weak var makePickerView: UIPickerView! @IBOutlet weak var modelPickerView: UIPickerView! @IBOutlet weak var stylePickerView: UIPickerView! @IBOutlet weak var yearLabel: UILabel! @IBOutlet weak var makeLabel: UILabel! @IBOutlet weak var modelLabel: UILabel! @IBOutlet weak var styleLabel: UILabel! @IBOutlet weak var doneButton: UIBarButtonItem! @IBAction func cancel(sender: AnyObject) { goBack() } @IBAction func done(sender: AnyObject) { if inputIsComplete() { let newVehicle = Vehicle(year: selectedYear!.value, make: selectedMake!.value, model: selectedModel!.value) if let style = selectedStyle { newVehicle.style = style.value } if newVehicle == self.vehicle { newVehicle.vin = self.vehicle?.vin } delegate?.vehicleSelected(newVehicle) } goBack() } private var years = [String]() private var makes: [String]? { didSet { if makes == nil || makes!.isEmpty { selectedMake = nil models = nil } makePickerView.reloadAllComponents() } } private var models: [String]? { didSet { if models == nil || models!.isEmpty { selectedModel = nil styles = nil } modelPickerView.reloadAllComponents() } } private var styles: [VehicleStyle]? { didSet { if styles == nil || styles!.isEmpty { selectedStyle = nil } stylePickerView.reloadAllComponents() } } var vehicle: Vehicle? public weak var delegate: SelectVehicleDelegate? private let getMakesSvc = GetMakes() private let getModelsSvc = GetModels() private let getStylesSvc = GetStyles() // MARK: - Selections var selectedYear: (value: NSNumber, validated: Bool)? { didSet { yearLabel.text = "\(selectedYear!.value)" updateDoneButtonEnabled() } } var selectedMake: (value: String, validated: Bool)? { didSet { if selectedMake == nil { models = nil } makeLabel.text = selectedMake?.value updateDoneButtonEnabled() } } var selectedModel: (value: String, validated: Bool)? { didSet { if selectedModel == nil { styles = nil } modelLabel.text = selectedModel?.value updateDoneButtonEnabled() } } var selectedStyle: (value: VehicleStyle, validated: Bool)? { didSet { styleLabel.text = selectedStyle?.value.style updateDoneButtonEnabled() } } private func populateMakes(year: NSNumber) { getMakesSvc.makeRequest(year) if let make = selectedMake?.value { selectedMake = (make, false) } } private func populateModels(year: NSNumber, make: String) { getModelsSvc.makeRequest(year, make: make) if let model = selectedModel?.value { selectedModel = (model, false) } } private func populateStyles(year: NSNumber, make: String, model: String) { getStylesSvc.makeRequest(year, make: make, model: model) if let style = selectedStyle?.value { selectedStyle = (style, false) } } private func inputIsComplete() -> Bool { return selectedYear != nil && selectedMake != nil && selectedModel != nil } private func inputIsValid() -> Bool { return inputIsComplete() && selectedYear!.validated && selectedMake!.validated && selectedModel!.validated && (selectedStyle?.validated ?? true) } public override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = UIRectEdge.None yearPickerView.delegate = self yearPickerView.dataSource = self makePickerView.delegate = self makePickerView.dataSource = self modelPickerView.delegate = self modelPickerView.dataSource = self stylePickerView.delegate = self stylePickerView.dataSource = self getMakesSvc.delegate = self getModelsSvc.delegate = self getStylesSvc.delegate = self years = (1970...(NSCalendar.getCurrentYear()+1)).map() { return "\($0)"} if let preselectedVehicle = vehicle { self.selectedYear = (preselectedVehicle.year, true) self.selectedMake = (preselectedVehicle.make, true) self.selectedModel = (preselectedVehicle.model, true) if let preselectedStyle = preselectedVehicle.style { self.selectedStyle = (preselectedStyle, true) } yearPickerView.selectRow(preselectedVehicle.year as Int - 1970, inComponent: 0, animated: true) populateMakes(preselectedVehicle.year) populateModels(selectedYear!.value, make: selectedMake!.value) populateStyles(selectedYear!.value, make: selectedMake!.value, model: selectedModel!.value) } else { yearPickerView.selectRow(years.count-2, inComponent: 0, animated: true) } updateDoneButtonEnabled() } public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { if pickerView === yearPickerView { return 1 } else if pickerView === makePickerView { return 1 } else if pickerView === modelPickerView { return 1 } else if pickerView === stylePickerView { return 1 } return 1 } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView === yearPickerView { return years.count } else if pickerView === makePickerView { return makes?.count ?? 0 } else if pickerView === modelPickerView { return models?.count ?? 0 } else if pickerView === stylePickerView { return styles?.count ?? 0 } return 1 } public func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { let pickerLabel = UILabel() var titleString = "" if pickerView === yearPickerView { titleString = years[row] } else if pickerView === makePickerView { titleString = makes?[row] ?? "" } else if pickerView === modelPickerView { titleString = models?[row] ?? "" } else if pickerView === stylePickerView { titleString = styles?[row].style ?? "" } let title = NSAttributedString(string: titleString, attributes: [NSFontAttributeName:UIFont(name: "Helvetica", size: 18.0)!, NSForegroundColorAttributeName:UIColor.whiteColor()]) pickerLabel.attributedText = title return pickerLabel } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { doneButton?.enabled = false if pickerView === yearPickerView { if row >= years.count { return } selectedYear = (Int(years[row])!, true) populateMakes(selectedYear!.value) } else if pickerView === makePickerView { if let makes = self.makes { if row >= makes.count { return } selectedMake = (makes[row], true) populateModels(selectedYear!.value, make: selectedMake!.value) } } else if pickerView === modelPickerView { if let models = self.models { if row >= models.count { return } selectedModel = (models[row], true) populateStyles(selectedYear!.value, make: selectedMake!.value, model: selectedModel!.value) } } else if pickerView === stylePickerView { if let styles = self.styles { if row >= styles.count { return } selectedStyle = (styles[row], true) } } updateDoneButtonEnabled() } // MARK: - Get Makes public func onSuccess(makes: [String]) { self.makes = makes // Did we have a selected make already? if let make = selectedMake?.value { // Yes. Is that make still valid, ie is it in the new set of makes? if let index = makes.indexOf(make) { // It is still valid. Select it and set it as validated. makePickerView.selectRow(index, inComponent: 0, animated: true) selectedMake!.validated = true pickerView(makePickerView, didSelectRow: index, inComponent: 0) } else { makePickerView.selectRow(0, inComponent: 0, animated: true) selectedMake = nil } } } public func onFail(reason: String) { showErrorAlert("Failed to retrieve vehicle makes.") makes = nil } // MARK: - Get Models public func gotModels(models: [String]) { self.models = models if let model = selectedModel?.value { if let index = models.indexOf(model) { modelPickerView.selectRow(index, inComponent: 0, animated: true) selectedModel!.validated = true pickerView(modelPickerView, didSelectRow: index, inComponent: 0) } else { modelPickerView.selectRow(0, inComponent: 0, animated: true) selectedModel = nil } } } public func getModelsFailed(reason: String) { showErrorAlert("Failed to retrieve vehicle models.") models = nil } // MARK: - GetStylesDelegate public func gotStyles(styles: [VehicleStyle]) { self.styles = styles if let style = selectedStyle?.value { if let index = styles.indexOf(style) { stylePickerView.selectRow(index, inComponent: 0, animated: true) selectedStyle!.validated = true } else { selectedStyle = nil } } } public func getStylesFailed(reason: String) { showErrorAlert("Failed to retrieve style info") styles = nil } // MARK: - Utilities private func updateDoneButtonEnabled() { doneButton?.enabled = inputIsValid() } }
32.866279
186
0.574031
89f5db691a73f7fed23ede3cbf688f72b4acdf71
2,298
// // FeedbackView.swift // Myra // // Created by Amir Shayegh on 2018-11-16. // Copyright © 2018 Government of British Columbia. All rights reserved. // import UIKit class FeedbackView: CustomModal { let whiteScreenTag = 201 let visibleAlpha: CGFloat = 1 let invisibleAlpha: CGFloat = 0 let whiteScreenAlpha: CGFloat = 0.9 var viewWidth: CGFloat = 390 var viewHeight: CGFloat = 400 var parent: UIViewController? @IBOutlet weak var sectionNameHeight: NSLayoutConstraint! @IBOutlet weak var sectionNameHeader: UILabel! @IBOutlet weak var sectionNameField: UITextField! @IBOutlet weak var anonHeader: UILabel! @IBOutlet weak var anonSwitch: UISwitch! @IBOutlet weak var feedbackHeader: UILabel! @IBOutlet weak var feedbackField: UITextView! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var viewTitle: UILabel! @IBOutlet weak var anonInfo: UILabel! @IBOutlet weak var divider: UIView! @IBAction func sendAction(_ sender: Any) { guard let feedback = feedbackField.text, let section = sectionNameField.text else {return} let element = FeedbackElement(feedback: feedback, section: section, anonymous: anonSwitch.isOn) Feedback.send(feedback: element) { (success) in self.remove() Feedback.initializeButton() } } @IBAction func cancelAction(_ sender: UIButton) { self.removeWhiteScreen() remove() Feedback.initializeButton() } func initialize() { Feedback.removeButton() style() setSmartSizingWith(horizontalPadding: 200, verticalPadding: 100) present() } func style() { styleDivider(divider: divider) viewTitle.font = Fonts.getPrimaryBold(size: 22) viewTitle.textColor = Colors.active.blue styleFieldHeader(label: anonInfo) styleContainer(view: self) styleInputField(field: sectionNameField, header: sectionNameHeader, height: sectionNameHeight) styleTextviewInputField(field: feedbackField, header: feedbackHeader) styleFillButton(button: sendButton) styleHollowButton(button: cancelButton) styleFieldHeader(label: anonHeader) } }
32.366197
103
0.68886
f5ef7e3fd87dcb2c3fff15d4b2b0f817414bb559
990
//===--- RangeAssignment.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 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 // //===----------------------------------------------------------------------===// import TestsUtils public let benchmarks = BenchmarkInfo( name: "RangeAssignment", runFunction: run_RangeAssignment, tags: [.validation, .api]) @inline(never) public func run_RangeAssignment(_ scale: Int) { let range: Range = 100..<200 var vector = [Double](repeating: 0.0 , count: 5000) let alfa = 1.0 let n = 500*scale for _ in 1...n { vector[range] = ArraySlice(vector[range].map { $0 + alfa }) } check(vector[100] == Double(n)) }
30
80
0.59899
fedb31df12f447a6dd759335144df4aad51ae46c
1,135
// Copyright 2020 Tokamak contributors // // 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. // // Created by Max Desiatov on 07/12/2018. // import TokamakStaticHTML import XCTest final class ReconcilerTests: XCTestCase { struct Model { let text: Text } private struct OptionalBody: View { var model: Model? var body: some View { if let text = model?.text { VStack { text Spacer() } } } } func testOptional() { let renderer = StaticHTMLRenderer(OptionalBody(model: Model(text: Text("text")))) XCTAssertEqual(renderer.html.count, 2777) } }
24.673913
85
0.682819
2291fc553f62623bccb17857de598457e6c9a41e
2,433
// // Persistence.swift // Shared // // Created by Mitch on 2/14/22. // import CoreData struct PersistenceController { static let shared = PersistenceController() static var preview: PersistenceController = { let result = PersistenceController(inMemory: true) let viewContext = result.container.viewContext for _ in 0..<1 { let newItem = Account(context: viewContext) newItem.address = "address" newItem.name = "Wallet name" } do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } return result }() let container: NSPersistentContainer init(inMemory: Bool = false) { container = NSPersistentContainer(name: "PassiveWallet") if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) } }
41.237288
199
0.63173
22fc178ce02b2bf814420880a292651bf01453db
1,522
// // SingleFlipView.swift // SwiftUIFlipClock // // Created by Luan Nguyen on 27/12/2020. // import SwiftUI struct SingleFlipView: View { init(text: String, type: FlipType) { self.text = text self.type = type } var body: some View { Text(text) .font(.system(size: 40)) .fontWeight(.heavy) .foregroundColor(.textColor) .fixedSize() .padding(type.padding, -20) .frame(width: 15, height: 20, alignment: type.alignment) .padding(type.paddingEdges, 10) .clipped() .background(Color.flipBackground) .cornerRadius(4) .padding(type.padding, -4.5) .clipped() } enum FlipType { case top case bottom var padding: Edge.Set { switch self { case .top: return .bottom case .bottom: return .top } } var paddingEdges: Edge.Set { switch self { case .top: return [.top, .leading, .trailing] case .bottom: return [.bottom, .leading, .trailing] } } var alignment: Alignment { switch self { case .top: return .bottom case .bottom: return .top } } } // MARK: - Private private let text: String private let type: FlipType }
21.742857
68
0.471091
f53467ee4c49fd99f3ed4cca2c6a17fe9cac263d
3,157
// // Utilities.swift // BinaryTest // // Created by Jonathan Wight on 6/25/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import XCTest //func XCTAssertEqual<T: Equatable>(@autoclosure expression1: () -> T, @autoclosure _ expression2: () -> T, @autoclosure _ expression3: () -> T, message: String = "", file: String = __FILE__, line: UInt = __LINE__) { // XCTAssertEqual(expression1, expression2, message, file: file, line: line) // XCTAssertEqual(expression2, expression3, message, file: file, line: line) // XCTAssertEqual(expression3, expression1, message, file: file, line: line) //} import SwiftUtilities func XCTAssertThrows(closure: () throws -> Void) { do { try closure() XCTAssert(false) } catch { return } } func bits(bits: Int) -> Int { return bits * 8 } func buildBinary(length: Int, @noescape closure: (UnsafeMutableBufferPointer <UInt8>) -> Void) -> [UInt8] { var data = [UInt8](count: Int(ceil(Double(length) / 8)), repeatedValue: 0) data.withUnsafeMutableBufferPointer() { (inout buffer: UnsafeMutableBufferPointer <UInt8>) -> Void in closure(buffer) } return data } func byteArrayToBinary(bytes: Array <UInt8>) throws -> String { return try bytes.map({ try binary($0, width: 8, prefix: false) }).joinWithSeparator("") } struct BitString { var string: String init(count: Int) { string = String(count: count, repeatedValue: Character("0")) } mutating func bitSet(start: Int, length: Int, newValue: UIntMax) throws { let newValue = try binary(newValue, width: length, prefix: false) let start = string.startIndex.advancedBy(start) let end = start.advancedBy(length) string.replaceRange(Range(start: start, end: end), with: newValue) } }
37.583333
216
0.702566
509dc8495bb9309afe38ec69dcd0006c977a2daa
2,886
// Copyright 2015-present 650 Industries. All rights reserved. class DevMenuAppInstance: NSObject, RCTBridgeDelegate { static private var CloseEventName = "closeDevMenu" private let manager: DevMenuManager var bridge: RCTBridge? init(manager: DevMenuManager) { self.manager = manager super.init() self.bridge = DevMenuRCTBridge.init(delegate: self, launchOptions: nil) fixChromeDevTools() } init(manager: DevMenuManager, bridge: RCTBridge) { self.manager = manager super.init() self.bridge = bridge fixChromeDevTools() } private func fixChromeDevTools() { // Hermes inspector will use latest executed script for Chrome DevTools Protocol. // It will be EXDevMenuApp.ios.js in our case. // To let Hermes aware target bundle, we try to reload here as a workaround solution. // See https://github.com/facebook/react-native/blob/ec614c16b331bf3f793fda5780fa273d181a8492/ReactCommon/hermes/inspector/Inspector.cpp#L291 if let appBridge = manager.delegate?.appBridge?(forDevMenuManager: manager) as? RCTBridge { appBridge.requestReload() } } /** Sends an event to JS triggering the animation that collapses the dev menu. */ public func sendCloseEvent() { bridge?.enqueueJSCall("RCTDeviceEventEmitter.emit", args: [DevMenuAppInstance.CloseEventName]) } // MARK: RCTBridgeDelegate func sourceURL(for bridge: RCTBridge!) -> URL! { #if DEBUG if let packagerHost = jsPackagerHost() { return RCTBundleURLProvider.jsBundleURL(forBundleRoot: "index", packagerHost: packagerHost, enableDev: true, enableMinification: false) } #endif return jsSourceUrl() } func extraModules(for bridge: RCTBridge!) -> [RCTBridgeModule]! { var modules: [RCTBridgeModule] = [DevMenuInternalModule(manager: manager)] modules.append(contentsOf: DevMenuVendoredModulesUtils.vendoredModules()) modules.append(MockedRNCSafeAreaProvider.init()) modules.append(DevMenuLoadingView.init()) return modules } func bridge(_ bridge: RCTBridge!, didNotFindModule moduleName: String!) -> Bool { return moduleName == "DevMenu" } // MARK: private private func jsSourceUrl() -> URL? { return DevMenuUtils.resourcesBundle()?.url(forResource: "EXDevMenuApp.ios", withExtension: "js") } private func jsPackagerHost() -> String? { // Return `nil` if resource doesn't exist in the bundle. guard let packagerHostPath = DevMenuUtils.resourcesBundle()?.path(forResource: "dev-menu-packager-host", ofType: nil) else { return nil } // Return `nil` if the content is not a valid URL. guard let content = try? String(contentsOfFile: packagerHostPath, encoding: String.Encoding.utf8).trimmingCharacters(in: CharacterSet.newlines), let url = URL(string: content) else { return nil } return url.absoluteString } }
33.172414
148
0.719681
2051dd2976bca47a81b0d07f8fa2d9d7265c1b0f
2,180
// // AppDelegate.swift // LOLChamps // // Created by hyeoktae kwon on 31/05/2019. // Copyright © 2019 hyeoktae kwon. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.382979
285
0.755505
481c916e002b4d294ebcd6fe09e9720a150cb858
6,095
// // BroadcastViewController.swift // iBeacon Demo // // Created by Darktt on 15/01/31. // Copyright (c) 2015年 Darktt. All rights reserved. // import UIKit import CoreLocation import CoreBluetooth class BroadcastViewController: UIViewController { // fileprivate var broadcasting: Bool = false // // fileprivate var beacon: CLBeaconRegion? // fileprivate var peripheralManager: CBPeripheralManager? // // @IBOutlet weak var statusLabel: UILabel! // @IBOutlet weak var triggerButton: UIButton! // // override func viewDidAppear(_ animated: Bool) // { // super.viewDidAppear(animated) // // self.setNeedsStatusBarAppearanceUpdate() // } // // override func viewDidLoad() // { // super.viewDidLoad() // // self.view.backgroundColor = UIColor.iOS7WhiteColor() // // let UUID: UUID = iBeaconConfiguration.uuid // // let major: CLBeaconMajorValue = CLBeaconMajorValue(arc4random() % 100 + 1) // let minor: CLBeaconMinorValue = CLBeaconMinorValue(arc4random() % 2 + 1) // // self.beacon = CLBeaconRegion(proximityUUID: UUID, major: major, minor: minor, identifier: "tw.darktt.beaconDemo") // // self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil) // } // // deinit // { // self.beacon = nil // self.peripheralManager = nil // } // // override func didReceiveMemoryWarning() // { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } //} // //// MARK: - Status Bar - // //extension BroadcastViewController //{ // override var preferredStatusBarStyle: UIStatusBarStyle // { // if self.broadcasting { // return .lightContent // } // // return .default // } // // override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation // { // return .fade // } // // override var prefersStatusBarHidden: Bool // { // return false // } //} // ////MARK: - Actions - // //extension BroadcastViewController //{ // @IBAction fileprivate func broadcastBeacon(sender: UIButton) -> Void // { // let state: CBManagerState = self.peripheralManager!.state // // if (state == .poweredOff && !self.broadcasting) { // let OKAction: UIAlertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) // // let alert: UIAlertController = UIAlertController(title: "Bluetooth OFF", message: "Please power on your Bluetooth!", preferredStyle: .alert) // alert.addAction(OKAction) // // self.present(alert, animated: true, completion: nil) // // return // } // // let titleFromStatus: (Void) -> String = { // let title: String = (self.broadcasting) ? "Start" : "Stop" // // return title + " Broadcast" // } // // let buttonTitleColor: UIColor = (self.broadcasting) ? UIColor.iOS7BlueColor() : UIColor.iOS7WhiteColor() // // sender.setTitle(titleFromStatus(), for: UIControlState.normal) // sender.setTitleColor(buttonTitleColor, for: UIControlState.normal) // // let labelTextFromStatus: (Void) -> String = { // let text: String = (self.broadcasting) ? "Not Broadcast" : "Broadcasting..." // // return text // } // // self.statusLabel.text = labelTextFromStatus() // // let animations: () -> Void = { // let backgroundColor: UIColor = (self.broadcasting) ? UIColor.iOS7WhiteColor() : UIColor.iOS7BlueColor() // // self.view.backgroundColor = backgroundColor // // self.broadcasting = !self.broadcasting // self.setNeedsStatusBarAppearanceUpdate() // } // // let completion: (Bool) -> Void = { // finish in // self.advertising(start: self.broadcasting) // } // // UIView.animate(withDuration: 0.25, animations: animations, completion: completion) // } // // // MARK: - Broadcast Beacon // // func advertising(start: Bool) -> Void // { // if self.peripheralManager == nil { // return // } // // if (!start) { // self.peripheralManager!.stopAdvertising() // // return // } // // let state: CBManagerState = self.peripheralManager!.state // // if (state == .poweredOn) { // let UUID:UUID = (self.beacon?.proximityUUID)! // let serviceUUIDs: Array<CBUUID> = [CBUUID(nsuuid: UUID)] // // // Why NSMutableDictionary can not convert to Dictionary<String, Any> 😂 // var peripheralData: Dictionary<String, Any> = self.beacon!.peripheralData(withMeasuredPower: 1) as NSDictionary as! Dictionary<String, Any> // peripheralData[CBAdvertisementDataLocalNameKey] = "iBeacon Demo" // peripheralData[CBAdvertisementDataServiceUUIDsKey] = serviceUUIDs // // self.peripheralManager!.startAdvertising(peripheralData) // } // } //} // //// MARK: - CBPeripheralManager Delegate - // //extension BroadcastViewController: CBPeripheralManagerDelegate //{ // func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) // { // let state: CBManagerState = peripheralManager!.state // // if state == .poweredOff { // self.statusLabel.text = "Bluetooth Off" // // if self.broadcasting { // self.broadcastBeacon(sender: self.triggerButton) // } // } // // if state == .unsupported { // self.statusLabel.text = "Unsupported Beacon" // } // // if state == .poweredOn { // self.statusLabel.text = "Not Broadcast" // } }
31.744792
154
0.568007
648eb49abeccbd31755c7278e5009ace83e0fd35
5,845
// Copyright 2018 Alex Deem // // 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 XCTest import ScreamEssentials public class UnorderedCollectionUpdatesTestsDifferentType: XCTestCase { class StringWrapper: Equatable { let string: String init(_ string: String) { self.string = string } static func == (lhs: UnorderedCollectionUpdatesTestsDifferentType.StringWrapper, rhs: UnorderedCollectionUpdatesTestsDifferentType.StringWrapper) -> Bool { return lhs.string == rhs.string } } func testEmptyToEmpty() { let a: [String] = [] let b: [StringWrapper] = [] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, []) } func testEmptyToNotEmpty() { let a: [String] = [] let b: [StringWrapper] = [StringWrapper("a"), StringWrapper("b")] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, [StringWrapper("a"), StringWrapper("b")]) XCTAssertEqual(updates.remove, []) } func testNotEmptyToEmpty() { let a: [String] = ["a", "b"] let b: [StringWrapper] = [] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, ["a", "b"]) } func testNoChange() { let a: [String] = ["a", "b"] let b: [StringWrapper] = [StringWrapper("a"), StringWrapper("b")] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, []) } func testAdd1Remove0() { let a: [String] = ["a", "b"] let b: [StringWrapper] = [StringWrapper("a"), StringWrapper("c"), StringWrapper("b")] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, [StringWrapper("c")]) XCTAssertEqual(updates.remove, []) } func testAdd0Remove1() { let a: [String] = ["a", "b"] let b: [StringWrapper] = [StringWrapper("a")] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, ["b"]) } func testAdd1Remove1() { let a: [String] = ["a", "b"] let b: [StringWrapper] = [StringWrapper("a"), StringWrapper("c")] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, [StringWrapper("c")]) XCTAssertEqual(updates.remove, ["b"]) } func testDistinctSets() { let a: [String] = ["a", "b"] let b: [StringWrapper] = [StringWrapper("x"), StringWrapper("y")] let updates = UnorderedCollectionUpdates(old: a, new: b, comparator: { $0 == $1.string }) XCTAssertEqual(updates.add, b) XCTAssertEqual(updates.remove, a) } } public class UnorderedCollectionUpdatesTestsSameType: XCTestCase { func testEmptyToEmpty() { let a: [String] = [] let b: [String] = [] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, []) } func testEmptyToNotEmpty() { let a: [String] = [] let b: [String] = ["a", "b"] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, ["a", "b"]) XCTAssertEqual(updates.remove, []) } func testNotEmptyToEmpty() { let a: [String] = ["a", "b"] let b: [String] = [] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, ["a", "b"]) } func testNoChange() { let a: [String] = ["a", "b"] let b: [String] = ["a", "b"] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, []) } func testAdd1Remove0() { let a: [String] = ["a", "b"] let b: [String] = ["a", "c", "b"] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, ["c"]) XCTAssertEqual(updates.remove, []) } func testAdd0Remove1() { let a: [String] = ["a", "b"] let b: [String] = ["a"] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, []) XCTAssertEqual(updates.remove, ["b"]) } func testAdd1Remove1() { let a: [String] = ["a", "b"] let b: [String] = ["a", "c"] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, ["c"]) XCTAssertEqual(updates.remove, ["b"]) } func testDistinctSets() { let a: [String] = ["a", "b"] let b: [String] = ["x", "y"] let updates = UnorderedCollectionUpdates(old: a, new: b) XCTAssertEqual(updates.add, b) XCTAssertEqual(updates.remove, a) } }
35.424242
163
0.592472
4b46de6c5f4cde56ce5297106e4f22a6ab74af7f
387
// // ViewController.swift // AlExtensions // // Created by sonifex on 02/07/2019. // Copyright (c) 2019 sonifex. All rights reserved. // import UIKit import AlExtensions class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } }
16.826087
52
0.677003
eb9d9ad5d5dd420a19f1bf578024529e5869718d
359
// // ContentView.swift // RxNavyExample // // Created by lyzkov on 11/06/2020. // Copyright © 2020 lyzkov. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, World!") } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
16.318182
49
0.640669
1ef67a50a5af50cd5dad44b051d3e622385227a2
354
// // ViewController.swift // GitExample2 // // Created by Diego Estrella III on 2/8/19. // Copyright © 2019 Diego Estrella III. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("Working on Git") print("OMG another change") } }
16.857143
61
0.649718
d7029c6ffea0963fefbe6d37070991cb093232ad
167
func factorial(n: Int) -> Int { if n <= 1 { return n} return n * factorial(n: n - 1) } let number = 4 print("\(number)! is equal to \(factorial(n: number))")
20.875
55
0.57485
f405e0dcbf239f5a7c45fcdd44aeb1efd5a5556a
1,499
// // Card.swift // Challenge // // Created by Mikhail Strizhenov on 12.05.2020. // Copyright © 2020 Mikhail Strizhenov. All rights reserved. // import UIKit class Card: UIButton { static var image: UIImage! var isMatch = false var isChosen = false override init(frame: CGRect) { super.init(frame: frame) setupButton() } required init?(coder: NSCoder) { super.init(coder: coder) setupButton() } func setupButton() { clipsToBounds = true setTitleColor(.white, for: .normal) setBackgroundImage(Card.image, for: .normal) backgroundColor = .gray titleLabel?.font = UIFont(name: "AvenirNext-DemiBoldItalic", size: 18) layer.cornerRadius = 10 } static func loadImage() { let renderRect = CGRect(origin: .zero, size: CGSize(width: 90, height: 150)) let renderer = UIGraphicsImageRenderer(size: renderRect.size) let rendImage = renderer.image { ctx in ctx.cgContext.translateBy(x: 45, y: 75) let rotations = 16 let amount = Double.pi / Double(rotations) for _ in 0..<rotations { ctx.cgContext.rotate(by: CGFloat(amount)) ctx.cgContext.addRect(CGRect(x: 22.5, y: 37.5, width: 45, height: 75)) } ctx.cgContext.setStrokeColor(UIColor.black.cgColor) ctx.cgContext.strokePath() } Card.image = rendImage } }
27.254545
86
0.592395
399fc8588fe7f2ee586fdfd8f092791efbe9795f
15,578
// // Hibizcus.swift // // Created by Muthu Nedumaran on 15/2/21. // import Foundation import SwiftUI struct Hibizcus { struct UIString { static let TestStringPlaceHolder = "Type the string you want to test" static let DragAndDropTwoFontFiles = "Drag font files and drop them here.\nYou can drop up to two font files,\none at a time." static let DragAndDropOneFontFile = "Drag a font file and drop it here." static let DragAndDropGridItemOrTwoFontFiles = "Drag a cluster or word item and drop it here\nOR\ndrag font files and drop them here.\nYou can drop up to two font files,\none at a time." } enum Position { case None, Prefix, Base, BaseEx, Nukta, Matra, Sign, Joiner } enum ShapingEngine { case CoreText, Harfbuzz } enum ShapingTableAction { case System, Subtituting, Positioning } struct Key { static let SVString = "sv.string" // The test string in StringViewer static let TVString = "tv.string" // The test string in TraceViewer static let WVString = "wv.string" static let SelectedLanguages = "selected.languages" } static let FontScale: Float = 10.66666666666666667 struct Shaper { static let CoreText = "CoreText" static let Harfbuzz = "Harfbuzz" static let None = "None" static let DefaultLanguageName = "Default" static let DefaultLanguageCode = "dflt" static let DefaultLanguage = Language(langName: DefaultLanguageName, langId: DefaultLanguageCode, selected: true) } struct FontColor { static let MainFontColor = NSColor.systemGreen.withAlphaComponent(0.6).cgColor static let CompareFontColor = NSColor.systemRed.withAlphaComponent(0.6).cgColor static let MainFontUIColor = Color(NSColor.systemGreen) static let CompareFontUIColor = Color(NSColor.systemRed) } // The color array used to draw glyphs static let colorAlpha:CGFloat = 0.70 static let colorArray = [ NSColor.systemRed.withAlphaComponent(colorAlpha).cgColor, NSColor.systemBlue.withAlphaComponent(colorAlpha).cgColor, NSColor.systemBrown.withAlphaComponent(colorAlpha).cgColor, NSColor.systemGreen.withAlphaComponent(colorAlpha).cgColor, NSColor.systemOrange.withAlphaComponent(colorAlpha).cgColor, NSColor.systemPink.withAlphaComponent(colorAlpha).cgColor, NSColor.systemPurple.withAlphaComponent(colorAlpha).cgColor, NSColor.systemTeal.withAlphaComponent(colorAlpha).cgColor, NSColor.systemYellow.withAlphaComponent(colorAlpha).cgColor ] static let AnchorColor = NSColor.textColor.withAlphaComponent(0.5).cgColor } func defaultLanguage(forScript: String) -> String { // This sould be configured in an external file switch forScript.lowercased() { case "balinese" : return "Balinese" case "batak" : return "Batak" case "bengali" : return "Bengali" case "buginese" : return "Buginese" case "devanagari" : return "Hindi" case "grantha" : return "Sanskrit" case "gujarati" : return "Gujarati" case "gurmukhi" : return "Punjabi" case "javanese" : return "Javanese" case "kannada" : return "Kannada" case "khmer" : return "Khmer" case "lao" : return "Lao" case "malayalam" : return "Malayalam" case "meeteimayek" : return "Meetei" case "myanmar" : return "Myanmar" case "odia" : return "Odia" case "rejang" : return "Rejang" case "sinhala" : return "Sinhala" case "sundanese" : return "Sundanese" case "tamil" : return "Tamil" case "telugu" : return "Telugu" case "thaana" : return "Divehi" case "thai" : return "Thai" case "tirhuta" : return "Maithili" default: return "" } } // Clipboard functions func copyTextToClipboard(textToCopy: String) { NSPasteboard.general.clearContents() if !NSPasteboard.general.setString(textToCopy, forType: NSPasteboard.PasteboardType.string) { print("Error setting string in pasteboard") } else { postNotification(title: "Hibizcus", message: "'\(textToCopy)' copied to clipboard") } } // User Notifications import UserNotifications func requestNotificationPermission() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge, .provisional]) { granted, error in if error != nil { print ("Request notifications permission Error"); } if granted { print ("Notifications allowed"); } else { print ("Notifications denied"); } } } func postNotification(title: String, message: String) { let notificationCenter = UNUserNotificationCenter.current() notificationCenter.getNotificationSettings { (settings) in if settings.authorizationStatus == .authorized { // Create the notification content let content = UNMutableNotificationContent() content.title = title content.body = message content.badge = false // Time interval for the banner to appear. Can't be 0? let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false) // Create the request let uuidString = UUID().uuidString let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger) // Schedule the request with the system. notificationCenter.add(request, withCompletionHandler: { (error) in if error != nil { // Something went wrong print("Something went wrong: \(error!.localizedDescription)") } }) } else { print("Notifications not allowed. Request for permission") requestNotificationPermission() } } } // Custom extensions public extension Color { #if os(macOS) static let background = Color(NSColor.windowBackgroundColor) static let secondaryBackground = Color(NSColor.underPageBackgroundColor) static let tertiaryBackground = Color(NSColor.controlBackgroundColor) #else static let background = Color(UIColor.systemBackground) static let secondaryBackground = Color(UIColor.secondarySystemBackground) static let tertiaryBackground = Color(UIColor.tertiarySystemBackground) #endif } extension String { func hexString() -> String { var hexText:String = "" if self.count == 0 { return " " } for c in self.unicodeScalars { if hexText.lengthOfBytes(using: .utf8) > 0 { hexText = hexText + ", " } hexText = hexText + String(format:"%04X",c.value) } return hexText } // Truncate String // https://gist.github.com/budidino/8585eecd55fd4284afaaef762450f98e enum TruncationPosition { case head case middle case tail } func truncated(limit: Int, position: TruncationPosition = .tail, leader: String = "…") -> String { guard self.count > limit else { return self } switch position { case .head: return leader + self.suffix(limit) case .middle: let headCharactersCount = Int(ceil(Float(limit - leader.count) / 2.0)) let tailCharactersCount = Int(floor(Float(limit - leader.count) / 2.0)) return "\(self.prefix(headCharactersCount))\(leader)\(self.suffix(tailCharactersCount))" case .tail: return self.prefix(limit) + leader } } /* func countOfSpacingLetters() -> Int { var c = 0 for u in self.unicodeScalars { if !"ஂ்".unicodeScalars.contains(u) { //print ("\(u) - is a mark") c += 1 } } return c } */ } // From: // https://stackoverflow.com/questions/50006899/dictionary-extension-that-swaps-keys-values-swift-4-1 extension Dictionary where Value : Hashable { func swapKeyValues() -> [Value : Key] { assert(Set(self.values).count == self.keys.count, "Values must be unique") var newDict = [Value : Key]() for (key, value) in self { newDict[value] = key } return newDict } } // NSView extension NSView { func drawLine(inContext:CGContext, fromPoint:CGPoint, toPoint:CGPoint, lineWidth:CGFloat, lineColor:CGColor) { inContext.setLineWidth(lineWidth) inContext.setStrokeColor(lineColor) inContext.move(to: fromPoint) inContext.addLine(to: toPoint) inContext.strokePath() } func drawMetricLinesForFont(forFont:CTFont, inContext: CGContext, baseLine:CGFloat, lineColor:CGColor, labelXPos: LabelPosition, drawUnderlinePos: Bool) { let nsFont = forFont as NSFont // slData.font! as NSFont //let yOffset = /*slData.yOffset > 0 ? slData.yOffset : */getYOffsetFor(font: slData.font! as NSFont) // Baseline drawMetricLine(atY: baseLine, inContext: inContext, label:"base", lx:labelXPos, ly:1, color: lineColor) // Ascender drawMetricLine(atY: baseLine+nsFont.ascender, inContext: inContext, label:"asc", lx:labelXPos, ly:1, color: lineColor) // Descender drawMetricLine(atY: baseLine+nsFont.descender, inContext: inContext, label:"dec", lx:labelXPos, ly:0, color: lineColor) // xHeight drawMetricLine(atY: baseLine+nsFont.xHeight, inContext: inContext, label:"x", lx:labelXPos, ly:1, color: lineColor) // CapHeight drawMetricLine(atY: baseLine+nsFont.capHeight, inContext: inContext, label:"cap", lx:labelXPos, ly:1, color: lineColor) // Underline if drawUnderlinePos { drawMetricLine(atY: baseLine+nsFont.underlinePosition, inContext: inContext, label:"ul", lx:labelXPos, ly:0, color: lineColor) } } func drawMetricLine(atY:CGFloat, inContext:CGContext, label:String, lx:LabelPosition, ly:Int, color:CGColor) { // Draw the line drawLine(inContext: inContext, fromPoint: CGPoint(x:0, y:atY), toPoint: CGPoint(x:bounds.size.width, y:atY), lineWidth: 0.5, lineColor: color) // CGColor(gray: 0.8, alpha: 0.8)) // Label attributes let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = lx == .left ? .left : .right let attributes: [NSAttributedString.Key : Any] = [ .paragraphStyle: paragraphStyle, .font: NSFont.init(name: "Monaco", size: 10)!, .foregroundColor: NSColor.init(cgColor:color)!// NSColor.white ] let labelSize = label.size(withAttributes: attributes) let padding:CGFloat = 3.0 let xpos = lx == .left ? padding : self.bounds.width - labelSize.width - padding let ypos = ly == 1 ? atY : atY - labelSize.height // Daww the label // TODO: Position the labels based on lx and ly label.draw(at: CGPoint(x: xpos, y: ypos), withAttributes: attributes) // there is no promise that the text matrix will be identity before calling the next draw // see this post: https://stackoverflow.com/questions/53047093/swift-text-draw-method-messes-up-cgcontext inContext.textMatrix = .identity } func drawRoundedRect(rect: CGRect, inContext context: CGContext?, radius: CGFloat, borderColor: CGColor, fillColor: CGColor, strokeWidth:CGFloat=1.0) { let path = CGMutablePath() path.move( to: CGPoint(x: rect.midX, y:rect.minY )) path.addArc( tangent1End: CGPoint(x: rect.maxX, y: rect.minY ), tangent2End: CGPoint(x: rect.maxX, y: rect.maxY), radius: radius) path.addArc( tangent1End: CGPoint(x: rect.maxX, y: rect.maxY ), tangent2End: CGPoint(x: rect.minX, y: rect.maxY), radius: radius) path.addArc( tangent1End: CGPoint(x: rect.minX, y: rect.maxY ), tangent2End: CGPoint(x: rect.minX, y: rect.minY), radius: radius) path.addArc( tangent1End: CGPoint(x: rect.minX, y: rect.minY ), tangent2End: CGPoint(x: rect.maxX, y: rect.minY), radius: radius) path.closeSubpath() context?.setLineWidth(strokeWidth) context?.setFillColor(fillColor) context?.setStrokeColor(borderColor) context?.addPath(path) context?.drawPath(using: .fillStroke) } } extension Data { // A hexadecimal string representation of the bytes. // Taken from https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift/52600783#52600783 // On 2021-03-23 func hexEncodedString() -> String { let hexDigits = Array("0123456789abcdef".utf16) var hexChars = [UTF16.CodeUnit]() hexChars.reserveCapacity(count * 2) for byte in self { let (index1, index2) = Int(byte).quotientAndRemainder(dividingBy: 16) hexChars.append(hexDigits[index1]) hexChars.append(hexDigits[index2]) } return String(utf16CodeUnits: hexChars, count: hexChars.count) } } extension String { // A data representation of the hexadecimal bytes in this string. // Taken from https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift/52600783#52600783 func hexDecodedData() -> Data { // Get the UTF8 characters of this string let chars = Array(utf8) // Keep the bytes in an UInt8 array and later convert it to Data var bytes = [UInt8]() bytes.reserveCapacity(count / 2) // It is a lot faster to use a lookup map instead of strtoul let map: [UInt8] = [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 01234567 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 89:;<=>? 0x00, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, // @ABCDEFG 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // HIJKLMNO ] // Grab two characters at a time, map them and turn it into a byte for i in stride(from: 0, to: count, by: 2) { let index1 = Int(chars[i] & 0x1F ^ 0x10) let index2 = Int(chars[i + 1] & 0x1F ^ 0x10) bytes.append(map[index1] << 4 | map[index2]) } return Data(bytes) } } extension URL { public var queryParameters: [String: String]? { guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else { return nil } return queryItems.reduce(into: [String: String]()) { (result, item) in result[item.name] = item.value } } }
37.002375
197
0.609513
095427311af7abf2a63760bf79d02cbb8fcefc6f
2,531
import Vapor import HTTP import Auth import Turnstile final class UserController: ResourceRepresentable { let drop:Droplet public init(droplet: Droplet) { self.drop = droplet } func index(request: Request) throws -> ResponseRepresentable { return try User.all().makeNode().converted(to: JSON.self) } func create(request: Request) throws -> ResponseRepresentable { var user = try User(with: request) guard user.password == request.data["confirm"]?.string else { throw Abort.custom(status: .badRequest, message: "Non matching passwords") } guard try User.query().filter("name", user.name).first() == nil else { throw Abort.custom(status: .badRequest, message: "User already exists") } try user.save() return Response(redirect: "users/") } func show(request: Request, user: User) throws -> ResponseRepresentable { return user } func delete(request: Request, user: User) throws -> ResponseRepresentable { try user.delete() return JSON([:]) } func login(request: Request) throws -> ResponseRepresentable { guard let username = request.data["username"]?.string, let password = request.data["password"]?.string else { throw Abort.custom(status: .badRequest, message: "Incomplete credentials") } let pair = UsernamePassword(username: username, password: password) try request.auth.login(pair) return Response(redirect: "users") } func makeResource() -> Resource<User> { return Resource( index: index, store: create, show: show, destroy: delete ) } } extension User { public convenience init(with request:Request) throws { guard let name = request.data["username"]?.string, let email = request.data["email"], let password = request.data["password"]?.string else { throw Abort.custom(status: .badRequest, message: "Input not conform") } try self.init(name:name, email:email.validated(), password:password) } } extension Request { func user() throws -> User { guard let user = try auth.user() as? User else { throw Abort.custom(status: .badRequest, message: "Wrong user type") } return user } }
28.761364
117
0.585934
69cfba8a679c1db578f53f72789f0546b04b3ddf
107
// // File.swift // // // Created by Joey Smalen on 04/11/2020. // public struct Response: Codable {}
11.888889
41
0.607477
ed48f0874b1a7c5aa04d567001d9485220e112bd
3,938
// // AlpsManager.swift // Alps // // Created by Rafal Kowalski on 04/10/2016 // Copyright © 2018 Matchmore SA. All rights reserved. // import CoreLocation import Foundation import UIKit public typealias OnMatchClosure = (_ matches: [Match], _ device: Device) -> Void public protocol MatchDelegate: class { var onMatch: OnMatchClosure? { get } } public class AlpsManager: MatchMonitorDelegate, ContextManagerDelegate, RemoteNotificationManagerDelegate { public var delegates = MulticastDelegate<MatchDelegate>() let apiKey: String let worldId: String var baseURL: String { set { AlpsAPI.basePath = newValue } get { return AlpsAPI.basePath } } lazy var contextManager = ContextManager(id: worldId, delegate: self, locationManager: locationManager) lazy var matchMonitor = MatchMonitor(delegate: self) lazy var remoteNotificationManager = RemoteNotificationManager(delegate: self) lazy var publications = PublicationStore(id: worldId) lazy var subscriptions = SubscriptionStore(id: worldId) lazy var mobileDevices: MobileDeviceStore = { let mobileDevices = MobileDeviceStore(id: worldId) mobileDevices.delegates += publications mobileDevices.delegates += subscriptions return mobileDevices }() lazy var pinDevices: PinDeviceStore = { let pinDevices = PinDeviceStore(id: worldId) pinDevices.delegates += publications pinDevices.delegates += subscriptions return pinDevices }() lazy var locationUpdateManager = LocationUpdateManager() private let locationManager: CLLocationManager internal init(apiKey: String, baseURL: String? = nil, customLocationManager: CLLocationManager?) { self.apiKey = apiKey self.worldId = apiKey.getWorldIdFromToken() if let customLocationManager = customLocationManager { self.locationManager = customLocationManager } else { self.locationManager = CLLocationManager() self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestAlwaysAuthorization() self.locationManager.requestWhenInUseAuthorization() } self.setupAPI() if let baseURL = baseURL { self.baseURL = baseURL } } private func setupAPI() { let device = UIDevice.current let headers = [ "api-key": self.apiKey, "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json", "user-agent": "\(device.systemName) \(device.systemVersion)" ] AlpsAPI.customHeaders = headers } // MARK: - Match Monitor Delegate func didFind(matches: [Match], for device: Device) { delegates.invoke { $0.onMatch?(matches, device) } } // MARK: - Context Manager Delegate func didUpdateLocation(location: CLLocation) { mobileDevices.findAll { (result) in result.forEach { guard let deviceId = $0.id else { return } self.locationUpdateManager.tryToSend(location: Location(location: location), for: deviceId) } } } // MARK: - Remote Notification Manager Delegate func didReceiveMatchUpdateForDeviceId(deviceId: String) { matchMonitor.refreshMatchesFor(deviceId: deviceId) } func didReceiveDeviceTokenUpdate(deviceToken: String) { mobileDevices.findAll { (result) in result.forEach { guard let deviceId = $0.id else { return } let deviceUpdate = DeviceUpdate() deviceUpdate.deviceToken = deviceToken DeviceAPI.updateDevice(deviceId: deviceId, device: deviceUpdate, completion: { (_, _) in }) } } } }
33.092437
107
0.643474