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
18464093fecbd4bf8cf3b2d99a498bddee272552
1,091
// // MovieDetailBuilderTests.swift // Careem-Test-ImdbTests // // Created by Ali Akhtar on 22/05/2019. // Copyright © 2019 Ali Akhtar. All rights reserved. // import XCTest @testable import Careem_Test_Imdb class MovieDetailBuilderTests: XCTestCase { var builder: MovieDetailBuilder! var view: MovieDetailViewController! override func setUp() { builder = MovieDetailBuilderImpl() let upcomingMovies = try! JSONDecoder().decode(UpcomingMovies.self, from: upcomingMovieSuccessStub) view = builder.build(withMovie: upcomingMovies.results?.first) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testBuilderBuildViewModelProperly() { //Given //When //Then XCTAssertTrue(view.viewModel != nil) } func testBuilderBuildViewControllerProperly() { //Given //When //Then XCTAssertTrue(view != nil) } }
22.265306
111
0.631531
56fb88c18040c7a656459c4a7fbe3cd285625c60
2,892
// // AppDelegate.swift // Parse Chat // // Created by Tony Zhang on 10/14/18. // Copyright © 2018 Tony. All rights reserved. // import UIKit import Parse @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. Parse.initialize(with: ParseClientConfiguration(block: { (configuration: ParseMutableClientConfiguration) in configuration.applicationId = "CodePath-Parse" configuration.server = "http://45.79.67.127:1337/parse" })) if let currentUser = PFUser.current() { print("Welcome back \(currentUser.username!) 😀") // TODO: Load Chat view controller and set as root view controller let storyboard = UIStoryboard(name: "Main", bundle: nil) let chatViewController = storyboard.instantiateViewController(withIdentifier: "ChatViewController") window?.rootViewController = chatViewController } 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:. } }
48.2
285
0.728562
e0a5fb736a5541a0ed813d36f0e3a55a15c6ba58
3,880
// // AlertController.swift // ZOOVIE // // Created by SFS on 26/05/20. // Copyright © 2020 Zoovie. All rights reserved. // import Foundation import UIKit enum AlertAction:String { case Ok case nCancel case Cancel case Delete case Yes case No var title:String { switch self { case .nCancel: return "Cancel" default: return self.rawValue } } var style: UIAlertAction.Style { switch self { case .Cancel: return .cancel case .Delete: return .destructive default: return .default } } } enum AlertInputType:Int { case normal case email case password } typealias AlertHandler = (_ action:AlertAction) -> Void extension UIAlertController { class func showAlert(withTitle title: String?, message: String?) { showAlert(title: title, message: message, preferredStyle: .cancel, sender: nil, actions: .Ok, handler: nil) } class func showAlert(title:String?, message:String?, preferredStyle: UIAlertAction.Style, sender: AnyObject?, target:UIViewController? = UIApplication.topViewController(), actions:AlertAction..., handler:AlertHandler?) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for arg in actions { let action = UIAlertAction(title: arg.title, style: arg.style, handler: { (action) in handler?(arg) }) alertController.addAction(action) } if let presenter = alertController.popoverPresentationController { presenter.sourceView = target?.view; presenter.permittedArrowDirections = .any presenter.sourceRect = sender?.bounds ?? .zero } target?.present(alertController, animated: true, completion: nil) } class func showInputAlert(title:String?, message:String?, inputPlaceholders:[String]?, preferredStyle: UIAlertAction.Style, sender: AnyObject?, target:UIViewController?, actions:AlertAction..., handler:AlertHandler?) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for placeholder in inputPlaceholders ?? [] { alertController.addTextField(configurationHandler: { (txtField) in txtField.placeholder = placeholder }) } for arg in actions { let action = UIAlertAction(title: arg.title, style: arg.style, handler: { (action) in handler?(arg) }) alertController.addAction(action) } if let presenter = alertController.popoverPresentationController { presenter.sourceView = target?.view presenter.permittedArrowDirections = .any presenter.sourceRect = sender?.bounds ?? .zero } target?.present(alertController, animated: true, completion: nil) } } extension UIApplication { class func topViewController(_ controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let navController = controller as? UINavigationController { return topViewController(navController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return topViewController(selected) } } if let presented = controller?.presentedViewController { return topViewController(presented) } // if let slide = controller as? SlideMenuController { // return topViewController(slide.mainViewController) // } return controller } }
34.336283
224
0.632216
0aaca56fb8496ff6833a418c803ab4d7f92542c1
454
//: [Previous](@previous) import Foundation import Combine // scan(_:_:) | Apple Developer Documentation // https://developer.apple.com/documentation/combine/publisher/scan(_:_:) // ReactiveX - Scan operator // http://reactivex.io/documentation/operators/scan.html let range = (0...5) let cancellable = range.publisher .scan(0, { return $0 + $1 }) .sink(receiveValue: { print("\($0)", terminator: " ") }) // 0 1 3 6 10 15 //: [Next](@next)
22.7
73
0.660793
670fc6e367e0bfbbbf2570549b8713be73b5a824
289
// // BitcoinPriceIndex.swift // CoinDeskProvider // // Created by Vladimir Abramichev on 22/07/2018. // Copyright © 2018 Vladimir Abramichev. All rights reserved. // import Foundation struct Time : Codable { let updated : String let updatedISO : String let updateduk : String? }
18.0625
62
0.723183
e841e3f5cd262aa65f7a4f6393b7559da2a89abe
2,318
import Foundation /// An action that archives the built products. /// /// It's initialized with the `.archiveAction` static method. public struct ArchiveAction: Equatable, Codable { /// Indicates the build configuration to run the archive with. public let configuration: ConfigurationName /// If set to true, Xcode will reveal the Organizer on completion. public let revealArchiveInOrganizer: Bool /// Set if you want to override Xcode's default archive name. public let customArchiveName: String? /// A list of actions that are executed before starting the archive process. public let preActions: [ExecutionAction] /// A list of actions that are executed after the archive process. public let postActions: [ExecutionAction] init( configuration: ConfigurationName, revealArchiveInOrganizer: Bool = true, customArchiveName: String? = nil, preActions: [ExecutionAction] = [], postActions: [ExecutionAction] = [] ) { self.configuration = configuration self.revealArchiveInOrganizer = revealArchiveInOrganizer self.customArchiveName = customArchiveName self.preActions = preActions self.postActions = postActions } /// Initialize a `ArchiveAction` /// - Parameters: /// - configuration: Indicates the build configuration to run the archive with. /// - revealArchiveInOrganizer: If set to true, Xcode will reveal the Organizer on completion. /// - customArchiveName: Set if you want to override Xcode's default archive name. /// - preActions: A list of actions that are executed before starting the archive process. /// - postActions: A list of actions that are executed after the archive process. public static func archiveAction( configuration: ConfigurationName, revealArchiveInOrganizer: Bool = true, customArchiveName: String? = nil, preActions: [ExecutionAction] = [], postActions: [ExecutionAction] = [] ) -> ArchiveAction { ArchiveAction( configuration: configuration, revealArchiveInOrganizer: revealArchiveInOrganizer, customArchiveName: customArchiveName, preActions: preActions, postActions: postActions ) } }
42.145455
100
0.687662
212bfac7024d1100b51e2122e9bb165a9ec267bf
12,047
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension CloudTrail { /// Returns all public keys whose private keys were used to sign the digest files within the specified time range. The public key is needed to validate digest files that were signed with its corresponding private key. CloudTrail uses different private/public key pairs per region. Each digest file is signed with a private key unique to its region. Therefore, when you validate a digest file from a particular region, you must look in the same region for its corresponding public key. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPublicKeysPaginator<Result>( _ input: ListPublicKeysRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPublicKeysResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPublicKeys, tokenKey: \ListPublicKeysResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPublicKeysPaginator( _ input: ListPublicKeysRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPublicKeysResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPublicKeys, tokenKey: \ListPublicKeysResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the tags for the trail in the current region. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTagsPaginator<Result>( _ input: ListTagsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTagsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTags, tokenKey: \ListTagsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTagsPaginator( _ input: ListTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTagsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTags, tokenKey: \ListTagsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists trails that are in the current account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listTrailsPaginator<Result>( _ input: ListTrailsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListTrailsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listTrails, tokenKey: \ListTrailsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listTrailsPaginator( _ input: ListTrailsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListTrailsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listTrails, tokenKey: \ListTrailsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Looks up management events or CloudTrail Insights events that are captured by CloudTrail. You can look up events that occurred in a region within the last 90 days. Lookup supports the following attributes for management events: AWS access key Event ID Event name Event source Read only Resource name Resource type User name Lookup supports the following attributes for Insights events: Event ID Event name Event source All attributes are optional. The default number of results returned is 50, with a maximum of 50 possible. The response includes a token that you can use to get the next page of results. The rate of lookup requests is limited to two per second, per account, per region. If this limit is exceeded, a throttling error occurs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func lookupEventsPaginator<Result>( _ input: LookupEventsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, LookupEventsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: lookupEvents, tokenKey: \LookupEventsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func lookupEventsPaginator( _ input: LookupEventsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (LookupEventsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: lookupEvents, tokenKey: \LookupEventsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension CloudTrail.ListPublicKeysRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CloudTrail.ListPublicKeysRequest { return .init( endTime: self.endTime, nextToken: token, startTime: self.startTime ) } } extension CloudTrail.ListTagsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CloudTrail.ListTagsRequest { return .init( nextToken: token, resourceIdList: self.resourceIdList ) } } extension CloudTrail.ListTrailsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CloudTrail.ListTrailsRequest { return .init( nextToken: token ) } } extension CloudTrail.LookupEventsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CloudTrail.LookupEventsRequest { return .init( endTime: self.endTime, eventCategory: self.eventCategory, lookupAttributes: self.lookupAttributes, maxResults: self.maxResults, nextToken: token, startTime: self.startTime ) } }
45.289474
777
0.64846
abfa0b3e58ad0c5d469bfb61aed08e8447c32de0
1,026
/* These structs define all of the types that Elasticsearch can store, how they map to Swift types and allows the user to configure what the mapping should be like in their index. The list of types in Elasticsearch can be found at: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html */ public struct MapScaledFloat: Mappable { static var typeKey = MapType.scaledFloat let type = typeKey.rawValue var coerce: Bool? = true var boost: Float? = 1.0 var docValues: Bool? = true var ignoreMalformed: Bool? = false var index: Bool? = true var nullValue: Float? = nil var store: Bool? = false var scalingFactor: Int? = 0 enum CodingKeys: String, CodingKey { case type case coerce case boost case docValues = "doc_values" case ignoreMalformed = "ignore_malformed" case index case nullValue = "null_value" case store case scalingFactor = "scaling_factor" } }
27.72973
83
0.663743
017f3163c6e605a6edd6c3c0a1b8f55d46ac8547
2,183
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Services is the client that can be used to manage Azure Search services and API keys. import Foundation import azureSwiftRuntime extension Commands { public struct Services { public static func CheckNameAvailability(subscriptionId: String, checkNameAvailabilityInput: CheckNameAvailabilityInputProtocol) -> ServicesCheckNameAvailability { return CheckNameAvailabilityCommand(subscriptionId: subscriptionId, checkNameAvailabilityInput: checkNameAvailabilityInput) } public static func CreateOrUpdate(resourceGroupName: String, searchServiceName: String, subscriptionId: String, service: SearchServiceProtocol) -> ServicesCreateOrUpdate { return CreateOrUpdateCommand(resourceGroupName: resourceGroupName, searchServiceName: searchServiceName, subscriptionId: subscriptionId, service: service) } public static func Delete(resourceGroupName: String, searchServiceName: String, subscriptionId: String) -> ServicesDelete { return DeleteCommand(resourceGroupName: resourceGroupName, searchServiceName: searchServiceName, subscriptionId: subscriptionId) } public static func Get(resourceGroupName: String, searchServiceName: String, subscriptionId: String) -> ServicesGet { return GetCommand(resourceGroupName: resourceGroupName, searchServiceName: searchServiceName, subscriptionId: subscriptionId) } public static func ListByResourceGroup(resourceGroupName: String, subscriptionId: String) -> ServicesListByResourceGroup { return ListByResourceGroupCommand(resourceGroupName: resourceGroupName, subscriptionId: subscriptionId) } public static func Update(resourceGroupName: String, searchServiceName: String, subscriptionId: String, service: SearchServiceProtocol) -> ServicesUpdate { return UpdateCommand(resourceGroupName: resourceGroupName, searchServiceName: searchServiceName, subscriptionId: subscriptionId, service: service) } } }
70.419355
176
0.797068
20ba2128f36ba43e0c51c85c9d409c5929c6e25a
5,112
import Benchmark import Foundation import Parsing /// This benchmark demonstrates how to parse raw data, which is just a collection of `UInt8` values /// (bytes). /// /// The data format we parse is the header for DNS packets, as specified /// [here](https://tools.ietf.org/html/rfc1035#page-26). It consists of 12 bytes, and contains /// information for 13 fields: /// /// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | ID | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// |QR| Opcode |AA|TC|RD|RA| Z | RCODE | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | QDCOUNT | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | ANCOUNT | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | NSCOUNT | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ /// | ARCOUNT | /// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ let binaryDataSuite = BenchmarkSuite(name: "BinaryData") { suite in struct Word16Parser: Parser { func parse(_ input: inout ArraySlice<UInt8>) throws -> UInt16 { guard input.count >= 2 else { struct ParsingError: Error {} throw ParsingError() } let output = UInt16(input[input.startIndex]) + UInt16(input[input.startIndex + 1]) << 8 input.removeFirst(2) return output } } let id = Word16Parser() let fields1 = First<ArraySlice<UInt8>>().map { (byte: UInt8) in ( qr: Bit(rawValue: byte & 0b00000001)!, opcode: Opcode(rawValue: (byte & 0b00011110) >> 1), aa: Bit(rawValue: (byte & 0b00100000) >> 5)!, tc: Bit(rawValue: (byte & 0b01000000) >> 6)!, rd: Bit(rawValue: (byte & 0b10000000) >> 7)! ) } let fields2 = First<ArraySlice<UInt8>>().map { byte in ( ra: Bit(rawValue: byte & 0b00000001)!, z: UInt3(uint8: (byte & 0b00001110) >> 1)!, rcode: Rcode(rawValue: (byte & 0b11110000) >> 4) ) } let counts = Parse { (qd: $0, an: $1, ns: $2, ar: $3) } with: { Word16Parser() Word16Parser() Word16Parser() Word16Parser() } let header = Parse { id, fields1, fields2, counts in DnsHeader( id: id, qr: fields1.qr, opcode: fields1.opcode, aa: fields1.aa, tc: fields1.tc, rd: fields1.rd, ra: fields2.ra, z: fields2.z, rcode: fields2.rcode, qdcount: counts.qd, ancount: counts.an, nscount: counts.ns, arcount: counts.ar ) } with: { id fields1 fields2 counts } let input: [UInt8] = [ // header 42, 142, 0b10100011, 0b00110000, 128, 0, 100, 200, 254, 1, 128, 128, // rest of packet 0xDE, 0xAD, 0xBE, 0xEF, ] var output: DnsHeader! var rest: ArraySlice<UInt8>! suite.benchmark("Parser") { var input = input[...] output = try header.parse(&input) rest = input } tearDown: { precondition( output == DnsHeader( id: 36_394, qr: .one, opcode: .inverseQuery, aa: .one, tc: .zero, rd: .one, ra: .zero, z: UInt3(uint8: 0)!, rcode: .nameError, qdcount: 128, ancount: 51_300, nscount: 510, arcount: 32_896 ) ) precondition(rest == [0xDE, 0xAD, 0xBE, 0xEF]) } struct DnsHeader: Equatable { let id: UInt16 let qr: Bit let opcode: Opcode let aa: Bit let tc: Bit let rd: Bit let ra: Bit let z: UInt3 let rcode: Rcode let qdcount: UInt16 let ancount: UInt16 let nscount: UInt16 let arcount: UInt16 } enum Bit: Equatable { case zero, one init?(rawValue: UInt8) { if rawValue == 0 { self = .zero } else if rawValue == 1 { self = .one } else { return nil } } } struct UInt3: Equatable { let bit0: Bit let bit1: Bit let bit2: Bit init?(uint8: UInt8) { guard uint8 & 0b11111000 == 0, let bit0 = Bit(rawValue: uint8 & 0b001), let bit1 = Bit(rawValue: uint8 & 0b010), let bit2 = Bit(rawValue: uint8 & 0b100) else { return nil } self.bit0 = bit0 self.bit1 = bit1 self.bit2 = bit2 } } struct Rcode: Equatable, RawRepresentable { let rawValue: UInt8 static let noError = Self(rawValue: 0) static let formatError = Self(rawValue: 1) static let serverFailure = Self(rawValue: 2) static let nameError = Self(rawValue: 3) static let notImplemented = Self(rawValue: 4) static let refused = Self(rawValue: 5) } struct Opcode: Equatable, RawRepresentable { let rawValue: UInt8 static let standardQuery = Self(rawValue: 0) static let inverseQuery = Self(rawValue: 1) static let status = Self(rawValue: 2) } }
25.432836
99
0.498044
0ebd85a29f29901f0ff20115bfd64b693e00fb96
652
// // ForecastState.swift // weather_forecast // // Created by User on 10/1/20. // Email: [email protected] // import Foundation import RxSwift import RxCocoa enum ForecastStateType: String { case GetForecast case GetForecastByCoordinate } struct ForecastState { // MARK: getForecastState let getForecastState = BehaviorRelay<EntityState<Forecast>>(value: .result(nil)) let getForecastByCoordinateState = PublishRelay<EntityState<Forecast>>() } // MARK: - Typealias typealias GetForecastObservable = Observable<EntityState<Forecast>> typealias GetForecastByCoordinateObservable = Observable<EntityState<Forecast>>
23.285714
84
0.771472
90e131c5239c59c65e1ee864b77dd04f143c54b5
873
// // LocalizedTextAlignment.swift // goSellSDK // // Copyright © 2019 Tap Payments. All rights reserved. // import enum UIKit.NSText.NSTextAlignment internal enum LocalizedTextAlignment: String, Decodable { case left = "left" case center = "center" case right = "right" case leading = "leading" case trailing = "trailing" case natural = "natural" case justified = "justified" // MARK: Properties internal var textAlignment: NSTextAlignment { switch self { case .left: return .left case .center: return .center case .right: return .right case .leading: return LocalizationManager.shared.layoutDirection == .leftToRight ? .left : .right case .trailing: return LocalizationManager.shared.layoutDirection == .leftToRight ? .right : .left case .natural: return .natural case .justified: return .justified } } }
23.594595
102
0.701031
18e59fb177823617a0c31cd58dd1ba1260de973f
2,409
// -------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // -------------------------------------------------------------------------- import AzureCore import Foundation // swiftlint:disable superfluous_disable_command // swiftlint:disable identifier_name // swiftlint:disable line_length extension Paths { /// User-configurable options for the `AutoRestUrlTestService.ByteMultiByte` operation. public struct ByteMultiByteOptions: RequestOptions { /// A client-generated, opaque value with 1KB character limit that is recorded in analytics logs. /// Highly recommended for correlating client-side activites with requests received by the server. public let clientRequestId: String? /// A token used to make a best-effort attempt at canceling a request. public let cancellationToken: CancellationToken? /// A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`. public var dispatchQueue: DispatchQueue? /// A `PipelineContext` object to associate with the request. public var context: PipelineContext? /// Initialize a `ByteMultiByteOptions` structure. /// - Parameters: /// - clientRequestId: A client-generated, opaque value with 1KB character limit that is recorded in analytics logs. /// - cancellationToken: A token used to make a best-effort attempt at canceling a request. /// - dispatchQueue: A dispatch queue on which to call the completion handler. Defaults to `DispatchQueue.main`. /// - context: A `PipelineContext` object to associate with the request. public init( clientRequestId: String? = nil, cancellationToken: CancellationToken? = nil, dispatchQueue: DispatchQueue? = nil, context: PipelineContext? = nil ) { self.clientRequestId = clientRequestId self.cancellationToken = cancellationToken self.dispatchQueue = dispatchQueue self.context = context } } }
45.45283
126
0.651723
ac65bfde40777ee9bed7230bd21bfb32e1520586
249
// // swfit_single_pageApp.swift // swfit-single-page // // Created by Havelio on 25/03/21. // import SwiftUI @main struct swfit_single_pageApp: App { var body: some Scene { WindowGroup { ContentView() } } }
13.833333
35
0.594378
14f9e1294ec7ada1c3a8ddc10aaea8ef2d994933
12,143
import XCTest @testable import ArtistHubCore class NetworkClientTests: XCTestCase { var networkSessionStub: NetworkSessionStub! var sut: NetworkClient! override func setUp() { super.setUp() networkSessionStub = NetworkSessionStub() sut = NetworkClient(networkSession: networkSessionStub) } override func tearDown() { super.tearDown() sut = nil networkSessionStub = nil } func test_dataTask_whenUrlIsMalformed_shouldReturnInvalidParams() { let malformedUrl = "<not_an_url>" var capturedResult: Result<TestModel, ApiError>! sut.request(url: malformedUrl) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.invalidParams)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 0) } func test_dataTask_whenSessionReturnsError_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! networkSessionStub.stubbedError = NSError(domain: "test", code: -1) sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsErrorWithCancelledCode_shouldReturnCancelledError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! networkSessionStub.stubbedError = URLError(.cancelled) sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.cancelled)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsEmptyResponse_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! networkSessionStub.stubbedResponse = nil sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsStatusCodeLowerThan200_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.info sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsStatusCodeHigherThan299_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.redirect sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsEmptyData_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedData = nil sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsCompleteData_shouldReturnSuccess() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! let json = """ { "id": "<id>", "name": "<name>" } """ networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedData = json.data(using: .utf8) sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .success(TestModel(id: "<id>", name: "<name>"))) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsMalformedData_shouldReturnParseError() { let url = "https://example.com" var capturedResult: Result<TestModel, ApiError>! let json = """ { "malformed... "id": "<id>", "name": "<name>" } """ networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedData = json.data(using: .utf8) sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.parseError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsCompleteDataAndTryToParseToIncompleteModel_shouldReturnSuccess() { let url = "https://example.com" var capturedResult: Result<TestIncompleteModel, ApiError>! let json = """ { "id": "<id>", "name": "<name>" } """ networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedData = json.data(using: .utf8) sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .success(TestIncompleteModel(id: "<id>"))) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_dataTask_whenSessionReturnsCompleteDataAndTryToParseToWrongModel_shouldReturnSuccess() { let url = "https://example.com" var capturedResult: Result<TestWrongModel, ApiError>! let json = """ { "id": "<id>", "name": "<name>" } """ networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedData = json.data(using: .utf8) sut.request(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.parseError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenUrlIsMalformed_shouldReturnInvalidParams() { let malformedUrl = "<not_an_url>" var capturedResult: Result<Data, ApiError>! sut.download(url: malformedUrl) { result in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.invalidParams)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 0) } func test_downloadTask_whenSessionReturnsCompleteData_shouldReturnProperData() { let malformedUrl = "https://example.com" let resourceUrl = Bundle.test.url(forResource: "vincent", withExtension: "png")! networkSessionStub.stubbedLocationUrl = resourceUrl networkSessionStub.stubbedResponse = HTTPURLResponse.ok var capturedResult: Result<Data, ApiError>! sut.download(url: malformedUrl) { result in capturedResult = result } let data = try! Data(contentsOf: resourceUrl) XCTAssertEqual(capturedResult, .success(data)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenSessionReturnsError_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedError = NSError(domain: "test", code: -1) sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenSessionReturnsErrorWithCancelledCode_shouldReturnCancelledError() { let url = "https://example.com" let resourceUrl = Bundle.test.url(forResource: "vincent", withExtension: "png")! var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedError = URLError(.cancelled) networkSessionStub.stubbedLocationUrl = resourceUrl networkSessionStub.stubbedData = Data() sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.cancelled)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenSessionReturnsEmptyResponse_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedResponse = nil sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenSessionReturnsStatusCodeLowerThan200_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.info sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenSessionReturnsStatusCodeHigherThan299_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.redirect sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenSessionReturnsEmptyData_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedData = nil sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } func test_downloadTask_whenCantDecodeDataFromLocation_shouldReturnGeneralError() { let url = "https://example.com" var capturedResult: Result<Data, ApiError>! networkSessionStub.stubbedError = nil networkSessionStub.stubbedResponse = HTTPURLResponse.ok networkSessionStub.stubbedLocationUrl = URL(string: "file://not/a/resource") sut.download(url: url) { (result) in capturedResult = result } XCTAssertEqual(capturedResult, .failure(.generalError)) XCTAssertEqual(networkSessionStub.stubbedTask.invokedResume, 1) } } private struct TestModel: Equatable, Decodable { let id: String let name: String } private struct TestIncompleteModel: Equatable, Decodable { let id: String } private struct TestWrongModel: Equatable, Decodable { let ids: String let name: String }
33.824513
107
0.67438
1ae4e66889959c38393e611a2aeb747912e679c6
756
// // KDurationFormatter.swift // Krake // // Created by joel on 08/05/17. // Copyright © 2017 Laser Group srl. All rights reserved. // import UIKit public class KDurationFormatter: Formatter { public func string(from duration: Double) -> String { var minutes = Int(duration / 60) let hours = minutes / 60 minutes = minutes % 60 var format = "" if hours > 0{ format.append(String(hours)) format.append(KLocalization.Date.hour) } if minutes > 0{ if !format.isEmpty { format.append(" ") } format.append(String(format: "%d %@", minutes, KLocalization.Date.minute)) } return format } }
18.9
86
0.547619
7996f63e5e4b4aa4d065f17d5a87112beed1ce03
1,117
// // LineView.swift // react-native-painter // // Created by Juan J LF on 8/29/21. // import Foundation import UIKit @objc(LinePaintableView) class LinePaintableView: PaintableView { private var mLayer = LineLayer() override init() { super.init() layer.addSublayer(mLayer) } @objc func setX1(_ v:NSNumber?){ let ev = CGFloat(truncating: v ?? 0) mLayer.setX1(ev) } @objc func setY1(_ v:NSNumber?){ let ev = CGFloat(truncating: v ?? 0) mLayer.setY1(ev) } @objc func setX2(_ v:NSNumber?){ let ev = CGFloat(truncating: v ?? 0) mLayer.setX2(ev) } @objc func setY2(_ v:NSNumber?){ let ev = CGFloat(truncating: v ?? 0) mLayer.setY2(ev) } override func getLayer() -> Paintable? { return mLayer } override func getCALayer() -> CALayer? { return mLayer } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
18.932203
60
0.529096
cc8a44feb3cf562d21c3ba8e9734cc1e535d6887
2,089
// // ViewController.swift // AugmentedCard // // Copyright © 2019 Isaac Raval. All rights reserved. // import UIKit import ARKit class ViewController: UIViewController { /// Primary SceneKit view that renders the AR session @IBOutlet var sceneView: ARSCNView! /// A serial queue for thread safety when modifying SceneKit's scene graph. let updateQueue = DispatchQueue(label: "\(Bundle.main.bundleIdentifier!).serialSCNQueue") // MARK: - Lifecycle // Called after the controller'€™s view is loaded into memory. override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as FPS and timing information (useful during development) sceneView.showsStatistics = true // Enable environment-based lighting sceneView.autoenablesDefaultLighting = true sceneView.automaticallyUpdatesLighting = true } // Notifies the view controller that its view is about to be added to a view hierarchy. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let refImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: Bundle.main) else { fatalError("Missing expected asset catalog resources.") } // Create a session configuration let configuration = ARImageTrackingConfiguration() configuration.trackingImages = refImages configuration.maximumNumberOfTrackedImages = 1 // Run the view's session sceneView.session.run(configuration, options: ARSession.RunOptions(arrayLiteral: [.resetTracking, .removeExistingAnchors])) } // Notifies the view controller that its view is about to be removed from a view hierarchy. override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() } }
33.693548
131
0.670656
2643175ead580c9c407e9d0a40ed06a58d830c52
2,121
/// Copyright (c) 2018 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 import CommonCrypto extension String { var md5: String { let length = Int(CC_MD5_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: length) if let data = data(using: String.Encoding.utf8) { _ = data.withUnsafeBytes { (body: UnsafePointer<UInt8>) in CC_MD5(body, CC_LONG(data.count), &digest) } } return (0..<length).reduce("") { $0 + String(format: "%02x", digest[$1]) } } }
45.12766
83
0.727016
f7cba1aab32d581b54e3b98e05875f1d21ee3654
913
// // SceneDelegate.swift // Uber-Clone-App // // Created by Paolo Prodossimo Lopes on 07/11/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: windowScene) let orchestrator: UIViewController = Orchestrador() self.window?.rootViewController = orchestrator self.window?.makeKeyAndVisible() } func sceneDidDisconnect(_ scene: UIScene) { } func sceneDidBecomeActive(_ scene: UIScene) {} func sceneWillResignActive(_ scene: UIScene) {} func sceneWillEnterForeground(_ scene: UIScene) {} func sceneDidEnterBackground(_ scene: UIScene) {} }
28.53125
127
0.695509
61debe4febc4bc388d56c9bf906bfc4f745de45e
8,576
// // DiscussionTopicsViewController.swift // edX // // Created by Jianfeng Qiu on 11/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit public class DiscussionTopicsViewController: OfflineSupportViewController, UITableViewDataSource, UITableViewDelegate, InterfaceOrientationOverriding { public typealias Environment = protocol<DataManagerProvider, OEXRouterProvider, OEXAnalyticsProvider, ReachabilityProvider> private enum TableSection : Int { case AllPosts case Following case CourseTopics } private let topics = BackedStream<[DiscussionTopic]>() private let environment: Environment private let courseID : String private let searchBar = UISearchBar() private var searchBarDelegate : DiscussionSearchBarDelegate? private let loadController : LoadStateViewController private let contentView = UIView() private let tableView = UITableView() private let searchBarSeparator = UIView() public init(environment: Environment, courseID: String) { self.environment = environment self.courseID = courseID self.loadController = LoadStateViewController() super.init(env: environment) let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) tableView.estimatedRowHeight = 80.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = UIView(frame: CGRectZero) } public required init?(coder aDecoder: NSCoder) { // required by the compiler because UIViewController implements NSCoding, // but we don't actually want to serialize these things fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = Strings.discussionTopics self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil) view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor() searchBarSeparator.backgroundColor = OEXStyles.sharedStyles().neutralLight() self.view.addSubview(contentView) self.contentView.addSubview(tableView) self.contentView.addSubview(searchBar) self.contentView.addSubview(searchBarSeparator) // Set up tableView tableView.dataSource = self tableView.delegate = self if #available(iOS 9.0, *) { tableView.cellLayoutMarginsFollowReadableWidth = false } searchBar.applyStandardStyles(withPlaceholder: Strings.searchAllPosts) searchBarDelegate = DiscussionSearchBarDelegate() { [weak self] text in if let owner = self { owner.environment.router?.showPostsFromController(owner, courseID: owner.courseID, queryString : text) } } searchBar.delegate = searchBarDelegate contentView.snp_makeConstraints {make in make.edges.equalTo(self.view) } searchBar.snp_makeConstraints { (make) -> Void in make.top.equalTo(contentView) make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.bottom.equalTo(searchBarSeparator.snp_top) } searchBarSeparator.snp_makeConstraints { (make) -> Void in make.height.equalTo(OEXStyles.dividerSize()) make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.bottom.equalTo(tableView.snp_top) } tableView.snp_makeConstraints { make -> Void in make.leading.equalTo(contentView) make.trailing.equalTo(contentView) make.bottom.equalTo(contentView) } // Register tableViewCell tableView.registerClass(DiscussionTopicCell.classForCoder(), forCellReuseIdentifier: DiscussionTopicCell.identifier) loadController.setupInController(self, contentView: contentView) loadTopics() } private func loadTopics() { topics.listen(self, success : {[weak self]_ in self?.loadedData() }, failure : {[weak self] error in self?.loadController.state = LoadState.failed(error) }) } private func refreshTopics() { loadController.state = .Initial let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) loadTopics() } func loadedData() { self.loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded self.tableView.reloadData() } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(indexPath, animated: false) } self.environment.analytics.trackScreenWithName(OEXAnalyticsScreenViewTopics, courseID: self.courseID, value: nil) self.navigationController?.setNavigationBarHidden(false, animated: animated) } override func reloadViewData() { refreshTopics() } override public func shouldAutorotate() -> Bool { return true } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return .AllButUpsideDown } // MARK: - TableView Data and Delegate public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch (section) { case TableSection.AllPosts.rawValue: return 1 case TableSection.Following.rawValue: return 1 case TableSection.CourseTopics.rawValue: return self.topics.value?.count ?? 0 default: return 0 } } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(DiscussionTopicCell.identifier, forIndexPath: indexPath) as! DiscussionTopicCell var topic : DiscussionTopic? = nil switch (indexPath.section) { case TableSection.AllPosts.rawValue: topic = DiscussionTopic(id: nil, name: Strings.allPosts, children: [DiscussionTopic](), depth: 0, icon:nil) case TableSection.Following.rawValue: topic = DiscussionTopic(id: nil, name: Strings.postsImFollowing, children: [DiscussionTopic](), depth: 0, icon: Icon.FollowStar) case TableSection.CourseTopics.rawValue: if let discussionTopic = self.topics.value?[indexPath.row] { topic = discussionTopic } default: assert(true, "Unknown section type.") } if let discussionTopic = topic { cell.topic = discussionTopic } return cell } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.view.endEditing(true) switch (indexPath.section) { case TableSection.AllPosts.rawValue: environment.router?.showAllPostsFromController(self, courseID: courseID, followedOnly: false) case TableSection.Following.rawValue: environment.router?.showAllPostsFromController(self, courseID: courseID, followedOnly: true) case TableSection.CourseTopics.rawValue: if let topic = self.topics.value?[indexPath.row] { environment.router?.showPostsFromController(self, courseID: courseID, topic: topic) } default: () } } public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } } extension DiscussionTopicsViewController { public func t_topicsLoaded() -> Stream<[DiscussionTopic]> { return topics } }
36.493617
152
0.651353
e89d9c1ccc1701e2fe903672956c86fa74987a92
1,652
// // AQTextField.swift // TestingGitLink // // Created by Akash Yashavanthrao Shindhe on 17/01/21. // import SwiftUI struct AQTextField: View { @State var name: String = "Click Here" var body: some View { Form { SectionView(title: "TextField", description: "A control that displays an editable text interface. ", content: { TextField("PlaceHolder", text: $name) .foregroundColor(.blue) }) SectionView(title: "RoundedBorderTextFieldStyle", description: "A text field style with a system-defined rounded border. ", content: { TextField("PlaceHolder", text: $name) .foregroundColor(.blue) .textFieldStyle(RoundedBorderTextFieldStyle()) }) #if os(OSX) SectionView(title: "SquareBorderTextFieldStyle", description: "A text field style with a system-defined Square border. ", content: { TextField("PlaceHolder", text: $name) .foregroundColor(.blue) .textFieldStyle(SquareBorderTextFieldStyle()) }) #endif SectionView(title: "DefaultTextFieldStyle", description: "A control that displays an editable text interface. It changes on OSX and iOS ", content: { TextField("PlaceHolder", text: $name) .foregroundColor(.blue) .textFieldStyle(DefaultTextFieldStyle()) }) } } } struct AQTextField_Previews: PreviewProvider { static var previews: some View { AQTextField() } }
35.913043
161
0.581719
d77d5014d46d9ae63a28bea0daef876f57129664
1,632
// // StaticListViewController.swift // ListKitExamples // // Created by burt on 2021/09/17. // import UIKit import ListKit class StaticListViewController: BaseViewController { override func render() { renderer.render { Section(id: UUID()) { HGroup(width: .fractionalWidth(1.0), height: .estimated(30)) { NumberBoxComponent(number: 1) for n in 2...30 { NumberBoxComponent(number: n) } } } .contentInsets(top: 8, leading: 8, bottom: 8, trailing: 8) Section(id: UUID()) { HGroup(width: .fractionalWidth(1.0), height: .estimated(30)) { for n in 1...40 { if n % 2 == 1 { NumberBoxComponent(number: n) } } } } .contentInsets(top: 8, leading: 8, bottom: 8, trailing: 8) Section(id: UUID()) { HGroup(width: .fractionalWidth(1.0), height: .fractionalHeight(1.0)) { for n in 1...10 { VGroup(of: Array(n...n*5), width: .absolute(30), height: .absolute(150)) { i in NumberBoxComponent(number: i, width: .absolute(30), height: .absolute(30)) } } } } .orthogonalScrollingBehavior(.continuous) .contentInsets(top: 8, leading: 8, bottom: 8, trailing: 8) } } }
33.306122
103
0.44424
768dd8439ad1cb3a1e987ee31e2ca5a5490dfdc5
681
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol P { return z: C<T, T : A> : AnyObject) -> { } case c<3] = Int>(e> : U) -> { } convenience init(n: AnyObject)) } func compose() -> { self.Iterator.Type) -> Any) -> String { var b = { c> T> String { } } } 0.startIndex)?) -> : Int>>(() -> { A" class func g<T { class B : P> St
26.192308
79
0.659325
cc96e0e8b587727582bd36caf2250e91fcc15844
1,725
// // FavoriteListView.swift // WeatherRx // // Created by MacOS on 5.03.2022. // import Foundation import UIKit import Material class FavoritesListView: UIView { lazy var favoritesListContentView: UIView = { let view = UIView() view.backgroundColor = .white view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var favoritesListToolBarView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var favoritesListDeleteButton: UIButton = { let button = UIButton(type: .custom) button.setImage(UIImage(named: "delete")?.withRenderingMode(.alwaysTemplate), for: .normal) button.tintColor = .red button.translatesAutoresizingMaskIntoConstraints = false button.clipsToBounds = true return button }() lazy var favoritesListToolBarLineView: UIView = { let view = UIView() view.backgroundColor = .lightGray view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var favoritesListCollectionView: UICollectionView = { let layout = ListFlowLayout() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = .clear return collectionView }() override init(frame: CGRect) { super.init(frame: frame) setUpFavoritesListContentView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
27.380952
99
0.656232
5b6a6e99415c1c0663daa80ad30e08712f4cd822
352
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 } }
32
144
0.772727
381746ae1626af0709be839df1eb5c457dbb2bd3
495
// // CassbySDK.swift // CassbySDK // // Created by Alexey on 08/02/2019. // Copyright © 2019 Alexey. All rights reserved. // import Foundation public class CassbySDK { public static let shared = CassbySDK() var token: String = "" var timer: Repeater? public func launch(token: String) { self.token = token self.timer = Repeater.every(.seconds(40), { (repeater) in let sync = Sync() sync.syncData() }) } }
19.038462
65
0.575758
4ab02574cc64b04626768f7b345e65d115a4a247
4,906
/* !!! NOT RUNNING !!! Object Oriented Programming - methods, subscripts, inheritance, initialization, deinitialization !!! NOT RUNNING !!! */ class Counter { var count = 0 func increment() { count += 1 } func incrementBy(_ amount: Int) { count += amount } func reset() { count = 0 } } let counter = Counter() print(counter.count) counter.increment() print(counter.count) counter.incrementBy(5) print(counter.count) counter.reset() print(counter.count) class Student { var age = 0 func printAge() { print(age) } } var st = Student() st.printAge() // Self struct Point { var x = 0.0, y = 0.0 func isToTheRight(x: Double) -> Bool { return self.x > x } mutating func moveByX(dX: Double, dY: Double) { x += dX y += dY } } var p = Point() print(p.isToTheRight(x: 1.1), p) p.moveByX(dX: 2.2, dY: 2.4) print(p) struct Person{ var age = 0 mutating func AddOne() { age += 1 } } var pers = Person() pers.AddOne() print(pers.age) class SomeClass { static func someTypeMethod() { print("I amd a type method") } } SomeClass.someTypeMethod() // Subscripts struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print(threeTimesTable[5]) struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns grid = Array(repeating: 0.0, count: rows * columns) } subscript(row: Int, column: Int) -> Double { get { return grid[(row * columns) + column] } set { grid[(row * columns) + column] = newValue } } } var matrix = Matrix(rows: 3, columns: 2) matrix[0, 1] = 1.5 matrix[1, 0] = 3.2 print(matrix.grid) struct Test { var num = 0 subscript(tmp: Int) -> Int { return tmp * num } } var t = Test(num: 8) print(t[2]) // inheritance class Vehincle { var currentSpeed: Double = 0.0 var desc: String { return "traveling at \(currentSpeed) mph" } func makeNoise() { // do nothing } } class Bicycle : Vehincle { var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 25.0 print("Bicycle: \(bicycle.desc)") class Tandem : Bicycle { var currNumOfPassengers = 0 } let tandem = Tandem() tandem.hasBasket = true tandem.currNumOfPassengers = 2 tandem.currentSpeed = 20.0 print("Tandem: \(tandem.desc)") // Overriding class Train : Vehincle { override func makeNoise() { print("Choo Choo") } } class Car : Vehincle { var gear = 1 override var desc: String { return super.desc + " in gear \(gear)" } } let train = Train() train.makeNoise() let car = Car() print("Car: \(car.desc)") class Human { var name: "" func hello() { print("Hi from Person!") } } class Woman : Human { var year = 0 override func hello() { print("Hi from Woman!") } } let woman = Woman() woman.hello() // initialization struct Fahrenheit { var temp: Double init() { temp = 32.0 } } var f = Fahrenheit() struct Celsius { var tempInCelsius: Double init(fromFahrenheit fahrenheit: Double) { tempInCelsius = (fahrenheit - 32.0) / 1.8 } init(fromKelvin: kelvin: Double) { tempInCelsius = kelvin - 273.15 } } let boilingPoint = Celsius(fromFahrenheit: 212.0) let freezingPoint = Celsius(fromKelvin: 273.15) print(boilingPoint.tempInCelsius, freezingPoint.tempInCelsius) struct Size { var width = 0.0, height = 0.0 } let twoByTwo = Size(width: 2.0, height: 2.0) print(twoByTwo) class Size2 { var width: Double, height: Double init(w: Double, h: Double) { width = w height = h } deinit { print("Deinit is called") } } let threeByThree = Size(w: 3.0, h: 3.0) print("Width: \(threeByThree.width)\nHeight: \(threeByThree.height)") threeByThree = nil class NewPerson { var age: Int init(a: Int) { age = a } } let p1 = NewPerson(a: 18) let p2 = NewPerson(a: 22) print(p1.age, p2.age) // Required initialization class SomeClass2 { var a: Int required init() { self.a = 1 } } class SomeSubclass : SomeClass2 { required init() { self.a = 2 } } let some = SomeSubclass() print(some.a)
15.624204
101
0.550347
1aaae753553b3be0cdc227f73b3d0e01394e90ce
709
// // CollectionCycleCell.swift // DYTV // // Created by 谭安溪 on 2016/10/18. // Copyright © 2016年 谭安溪. All rights reserved. // import UIKit import Kingfisher class CollectionCycleCell: UICollectionViewCell { @IBOutlet weak var picImageVIew: UIImageView! @IBOutlet weak var titleLabel: UILabel! var cycleModel: CycleModel?{ didSet{ guard let cycleModel = cycleModel else { return } picImageVIew.kf.setImage(with: URL(string: cycleModel.pic_url), placeholder:UIImage(named: "Img_default")) titleLabel.text = cycleModel.title } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
24.448276
118
0.657264
226938b936bb7f688afb1120b50e1b26bff6dbff
5,012
// // FilterProducer.swift // // // Created by Sergej Jaskiewicz on 23.10.2019. // /// A helper class that acts like both subscriber and subscription. /// /// Filter-like operators send an instance of their `Inner` class that is subclass /// of this class to the upstream publisher (as subscriber) and /// to the downstream subcriber (as subscription). /// /// Filter-like operators include `Publishers.Filter`, /// `Publishers.RemoveDuplicates`, `Publishers.PrefixWhile` and more. /// /// Subclasses must override the `receive(newValue:)` and `description`. internal class FilterProducer<Downstream: Subscriber, Input, Output, UpstreamFailure: Error, Filter> : CustomStringConvertible, CustomReflectable where Downstream.Input == Output { // NOTE: This class has been audited for thread safety // MARK: - State private enum State { case awaitingSubscription case connected(Subscription) case completed } internal final let filter: Filter internal final let downstream: Downstream private let lock = UnfairLock.allocate() private var state = State.awaitingSubscription internal init(downstream: Downstream, filter: Filter) { self.downstream = downstream self.filter = filter } deinit { lock.deallocate() } // MARK: - Abstract methods internal func receive( newValue: Input ) -> PartialCompletion<Output?, Downstream.Failure> { abstractMethod() } internal var description: String { abstractMethod() } // MARK: - CustomReflectable internal var customMirror: Mirror { let children = CollectionOfOne<Mirror.Child>(("downstream", downstream)) return Mirror(self, children: children) } } extension FilterProducer: Subscriber { internal func receive(subscription: Subscription) { lock.lock() guard case .awaitingSubscription = state else { lock.unlock() subscription.cancel() return } state = .connected(subscription) lock.unlock() downstream.receive(subscription: self) } internal func receive(_ input: Input) -> Subscribers.Demand { lock.lock() switch state { case .awaitingSubscription: lock.unlock() fatalError("Invalid state: Received value before receiving subscription") case .completed: lock.unlock() case let .connected(subscription): lock.unlock() switch receive(newValue: input) { case let .continue(output?): return downstream.receive(output) case .continue(nil): return .max(1) case .finished: lock.lock() state = .completed lock.unlock() subscription.cancel() downstream.receive(completion: .finished) case let .failure(error): lock.lock() state = .completed lock.unlock() subscription.cancel() downstream.receive(completion: .failure(error)) } } return .none } internal func receive(completion: Subscribers.Completion<UpstreamFailure>) { lock.lock() switch state { case .awaitingSubscription: lock.unlock() fatalError("Invalid state: Received completion before receiving subscription") case .completed: lock.unlock() return case .connected: state = .completed lock.unlock() switch completion { case .finished: downstream.receive(completion: .finished) case let .failure(failure): downstream.receive(completion: .failure(failure as! Downstream.Failure)) } } } } extension FilterProducer: Subscription { internal func request(_ demand: Subscribers.Demand) { demand.assertNonZero() lock.lock() switch state { case .awaitingSubscription: lock.unlock() fatalError("Invalid state: Received request before sending subscription") case .completed: lock.unlock() return case let .connected(subscription): lock.unlock() subscription.request(demand) } } internal func cancel() { lock.lock() guard case let .connected(subscription) = state else { state = .completed lock.unlock() return } state = .completed lock.unlock() subscription.cancel() } } extension FilterProducer: CustomPlaygroundDisplayConvertible { internal var playgroundDescription: Any { return description } }
28.316384
90
0.5834
1cfeafe260ef109b30d8665efd2456eab952db10
1,869
/// Copyright (c) 2020 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 import KooberKit protocol ObserverForProfileEventResponder: class { func received(newUserProfile userProfile: UserProfile) func received(newErrorMessage errorMessage: ErrorMessage) }
50.513514
83
0.76779
9b6cf81703489e2112f9f2704a5e0cfb8970ddde
620
// // AppDelegate.swift // LUTConverter // // Created by Yu Ao on 2018/10/12. // Copyright © 2018 Meteor. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } }
20.666667
91
0.706452
3a67ed73b4d8b82483f8a6194a16970d41718382
2,638
// // MIT License // // Copyright (c) 2017 Trifork Kraków Office // // 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 /// Base class for asynchronous `NSOperation`s. Handles thread-safe execution state management. open class AsynchronousOperation: Operation { private enum State { case idle case executing case finished } private var state: State = .idle { willSet { willChangeValue(forKey: "isExecuting") willChangeValue(forKey: "isFinished") } didSet { didChangeValue(forKey: "isFinished") didChangeValue(forKey: "isExecuting") } } private var stateSynchronized: State { get { return synchronized { self.state } } set { synchronized { self.state = newValue } } } override public final var isExecuting: Bool { return stateSynchronized == .executing } override public final var isFinished: Bool { return stateSynchronized == .finished } override public final var isAsynchronous: Bool { return true } override public final func start() { guard isCancelled == false else { markFinished() return } stateSynchronized = .executing didStart() } /// To be overridden in subclasses, invoked after operation is successfully started. open func didStart() { fatalError("Template method. Must be overriden") } /// Called to mark execution as finished. public final func markFinished() { stateSynchronized = .finished } }
35.648649
95
0.683093
18ebc933da8a9042473c78c77909e192606382a6
2,364
import Foundation import azureSwiftRuntime public protocol WebAppsDeleteSiteExtension { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var name : String { get set } var siteExtensionId : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (Error?) -> Void) -> Void; } extension Commands.WebApps { // DeleteSiteExtension remove a site extension from a web site, or a deployment slot. internal class DeleteSiteExtensionCommand : BaseCommand, WebAppsDeleteSiteExtension { public var resourceGroupName : String public var name : String public var siteExtensionId : String public var subscriptionId : String public var apiVersion = "2016-08-01" public init(resourceGroupName: String, name: String, siteExtensionId: String, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.name = name self.siteExtensionId = siteExtensionId self.subscriptionId = subscriptionId super.init() self.method = "Delete" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/siteextensions/{siteExtensionId}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{name}"] = String(describing: self.name) self.pathParameters["{siteExtensionId}"] = String(describing: self.siteExtensionId) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public func execute(client: RuntimeClient, completionHandler: @escaping (Error?) -> Void) -> Void { client.executeAsync(command: self) { (error) in completionHandler(error) } } } }
44.603774
163
0.647208
f9a3332edc17518929c96063a6426ad0d0818cbe
24,095
// // UartMqttSettingsViewController.swift // Bluefruit Connect // // Created by Antonio García on 07/02/16. // Copyright © 2016 Adafruit. All rights reserved. // import UIKit class UartMqttSettingsViewController: UIViewController { // Constants fileprivate static let kDefaultHeaderCellHeight: CGFloat = 50 // Types fileprivate enum SettingsSections: Int { case status = 0 case server = 1 case publish = 2 case subscribe = 3 case advanced = 4 } fileprivate enum PickerViewType { case qos case action } // UI @IBOutlet weak var baseTableView: UITableView! fileprivate var openCellIndexPath: IndexPath? fileprivate var pickerViewType = PickerViewType.qos // Data private var previousSubscriptionTopic: String? // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = LocalizationManager.shared.localizedString("uart_mqtt_settings_title") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) previousSubscriptionTopic = MqttSettings.shared.subscribeTopic MqttManager.shared.delegate = self baseTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate func headerTitleForSection(_ section: Int) -> String? { var key: String? switch SettingsSections(rawValue: section)! { case .status: key = "uart_mqtt_settings_group_status" case .server: key = "uart_mqtt_settings_group_server" case .publish: key = "uart_mqtt_settings_group_publish" case .subscribe: key = "uart_mqtt_settings_group_subscribe" case .advanced: key = "uart_mqtt_settings_group_advanced" } return (key==nil ? nil : LocalizationManager.shared.localizedString(key!).uppercased()) } fileprivate func subscriptionTopicChanged(_ newTopic: String?, qos: MqttManager.MqttQos) { DLog("subscription changed from: \(previousSubscriptionTopic != nil ? previousSubscriptionTopic!:"") to: \(newTopic != nil ? newTopic!:"")") let mqttManager = MqttManager.shared if previousSubscriptionTopic != nil { mqttManager.unsubscribe(topic: previousSubscriptionTopic!) } if let newTopic = newTopic { mqttManager.subscribe(topic: newTopic, qos: qos) } previousSubscriptionTopic = newTopic } // MARK: - Cell Utils fileprivate func tagFromIndexPath(_ indexPath: IndexPath, scale: Int) -> Int { // To help identify each textfield a tag is added with this format: ab (a is the section, b is the row) return indexPath.section * scale + indexPath.row } fileprivate func indexPathFromTag(_ tag: Int, scale: Int) -> IndexPath { // To help identify each textfield a tag is added with this format: 12 (1 is the section, 2 is the row) return IndexPath(row: tag % scale, section: tag / scale) } } // MARK: UITableViewDataSource extension UartMqttSettingsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return SettingsSections.advanced.rawValue + 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var numberOfRows = 0 switch SettingsSections(rawValue: section)! { case .status: numberOfRows = 1 case .server: numberOfRows = 2 case .publish: numberOfRows = 2 case .subscribe: numberOfRows = 2 case .advanced: numberOfRows = 2 } if let openCellIndexPath = openCellIndexPath { if openCellIndexPath.section == section { numberOfRows += 1 } } return numberOfRows } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = SettingsSections(rawValue: indexPath.section)! let cell: UITableViewCell let localizationManager = LocalizationManager.shared if indexPath == openCellIndexPath { let pickerCell = tableView.dequeueReusableCell(withIdentifier: "PickerCell", for: indexPath) as! MqttSettingPickerCell pickerCell.pickerView.tag = indexPath.section * 100 + indexPath.row-1 pickerCell.pickerView.dataSource = self pickerCell.pickerView.delegate = self pickerCell.backgroundColor = .groupTableViewBackground //UIColor(hex: 0xe2e1e0) cell = pickerCell } else if section == .status { let statusCell = tableView.dequeueReusableCell(withIdentifier: "StatusCell", for: indexPath) as! MqttSettingsStatusCell let status = MqttManager.shared.status let showWait = status == .connecting || status == .disconnecting if showWait { statusCell.waitView.startAnimating() } else { statusCell.waitView.stopAnimating() } statusCell.actionButton.isHidden = showWait statusCell.statusTitleLabel.text = localizationManager.localizedString("uart_mqtt_action_title") statusCell.statusLabel.text = titleForMqttManagerStatus(status) UIView.performWithoutAnimation({ () -> Void in // Change title disabling animations (if enabled the user can see the old title for a moment) statusCell.actionButton.setTitle(localizationManager.localizedString(status == .connected ?"uart_mqtt_action_disconnect":"uart_mqtt_action_connect"), for: UIControl.State.normal) statusCell.layoutIfNeeded() }) statusCell.onClickAction = { [unowned self] in // End editing self.view.endEditing(true) // Connect / Disconnect let mqttManager = MqttManager.shared let status = mqttManager.status if status == .disconnected || status == .none || status == .error { mqttManager.connectFromSavedSettings() } else { mqttManager.disconnect() MqttSettings.shared.isConnected = false } self.baseTableView?.reloadData() } statusCell.backgroundColor = UIColor.clear cell = statusCell } else { let mqttSettings = MqttSettings.shared let editValueCell: MqttSettingsValueAndSelector let row = indexPath.row switch section { case .server: editValueCell = tableView.dequeueReusableCell(withIdentifier: "ValueCell", for: indexPath) as! MqttSettingsValueAndSelector editValueCell.reset() let labels = ["uart_mqtt_settings_server_address", "uart_mqtt_settings_server_port"] editValueCell.nameLabel.text = localizationManager.localizedString(labels[row]) let valueTextField = editValueCell.valueTextField! // valueTextField should exist on this cell valueTextField.isSecureTextEntry = false if row == 0 { valueTextField.placeholder = MqttSettings.defaultServerAddress if mqttSettings.serverAddress != MqttSettings.defaultServerAddress { valueTextField.text = mqttSettings.serverAddress } valueTextField.keyboardType = .URL } else if row == 1 { valueTextField.placeholder = "\(MqttSettings.defaultServerPort)" if mqttSettings.serverPort != MqttSettings.defaultServerPort { valueTextField.text = "\(mqttSettings.serverPort)" } valueTextField.keyboardType = UIKeyboardType.numberPad } case .publish: editValueCell = tableView.dequeueReusableCell(withIdentifier: "ValueAndSelectorCell", for: indexPath) as! MqttSettingsValueAndSelector editValueCell.reset() let labels = ["uart_mqtt_settings_publish_rx", "uart_mqtt_settings_publish_tx"] editValueCell.nameLabel.text = localizationManager.localizedString(labels[row]) editValueCell.valueTextField!.text = mqttSettings.getPublishTopic(index: row) editValueCell.valueTextField!.autocorrectionType = .no let typeButton = editValueCell.typeButton! typeButton.tag = tagFromIndexPath(indexPath, scale:100) typeButton.setTitle(titleForQos(mqttSettings.getPublishQos(index: row)), for: .normal) typeButton.addTarget(self, action: #selector(UartMqttSettingsViewController.onClickTypeButton(_:)), for: .touchUpInside) case .subscribe: editValueCell = tableView.dequeueReusableCell(withIdentifier: row==0 ? "ValueAndSelectorCell":"SelectorCell", for: indexPath) as! MqttSettingsValueAndSelector editValueCell.reset() let labels = ["uart_mqtt_settings_subscribe_topic", "uart_mqtt_settings_subscribe_action"] editValueCell.nameLabel.text = localizationManager.localizedString(labels[row]) let typeButton = editValueCell.typeButton! typeButton.tag = tagFromIndexPath(indexPath, scale:100) typeButton.addTarget(self, action: #selector(UartMqttSettingsViewController.onClickTypeButton(_:)), for: .touchUpInside) if row == 0 { editValueCell.valueTextField!.text = mqttSettings.subscribeTopic editValueCell.valueTextField!.autocorrectionType = .no typeButton.setTitle(titleForQos(mqttSettings.subscribeQos), for: .normal) } else if row == 1 { typeButton.setTitle(titleForSubscribeBehaviour(mqttSettings.subscribeBehaviour), for: .normal) } case .advanced: editValueCell = tableView.dequeueReusableCell(withIdentifier: "ValueCell", for: indexPath) as! MqttSettingsValueAndSelector editValueCell.reset() let labels = ["uart_mqtt_settings_advanced_username", "uart_mqtt_settings_advanced_password"] editValueCell.nameLabel.text = localizationManager.localizedString(labels[row]) let valueTextField = editValueCell.valueTextField! if row == 0 { valueTextField.text = mqttSettings.username valueTextField.isSecureTextEntry = false if #available(iOS 11, *) { valueTextField.textContentType = .username } } else if row == 1 { valueTextField.text = mqttSettings.password valueTextField.isSecureTextEntry = true if #available(iOS 11, *) { valueTextField.textContentType = .password } } default: editValueCell = tableView.dequeueReusableCell(withIdentifier: "ValueCell", for: indexPath) as! MqttSettingsValueAndSelector editValueCell.reset() } if let valueTextField = editValueCell.valueTextField { valueTextField.returnKeyType = UIReturnKeyType.next valueTextField.delegate = self valueTextField.isSecureTextEntry = false valueTextField.tag = tagFromIndexPath(indexPath, scale:10) } editValueCell.backgroundColor = .groupTableViewBackground//UIColor(hex: 0xe2e1e0) cell = editValueCell } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return indexPath == openCellIndexPath ? 100 : 44 } @objc func onClickTypeButton(_ sender: UIButton) { let selectedIndexPath = indexPathFromTag(sender.tag, scale:100) let isAction = selectedIndexPath.section == SettingsSections.subscribe.rawValue && selectedIndexPath.row == 1 pickerViewType = isAction ? PickerViewType.action : PickerViewType.qos displayInlineDatePickerForRowAtIndexPath(selectedIndexPath) } fileprivate func displayInlineDatePickerForRowAtIndexPath(_ indexPath: IndexPath) { // display the date picker inline with the table content baseTableView.beginUpdates() var before = false // indicates if the date picker is below "indexPath", help us determine which row to reveal var sameCellClicked = false if let openCellIndexPath = openCellIndexPath { before = openCellIndexPath.section <= indexPath.section && openCellIndexPath.row < indexPath.row sameCellClicked = openCellIndexPath.section == indexPath.section && openCellIndexPath.row - 1 == indexPath.row // remove any date picker cell if it exists baseTableView.deleteRows(at: [openCellIndexPath], with: .fade) self.openCellIndexPath = nil } if !sameCellClicked { // hide the old date picker and display the new one let rowToReveal = before ? indexPath.row - 1 : indexPath.row let indexPathToReveal = IndexPath(row:rowToReveal, section:indexPath.section) toggleDatePickerForSelectedIndexPath(indexPathToReveal) self.openCellIndexPath = IndexPath(row:indexPathToReveal.row + 1, section:indexPathToReveal.section) } // always deselect the row containing the start or end date baseTableView.deselectRow(at: indexPath, animated:true) baseTableView.endUpdates() // inform our date picker of the current date to match the current cell //updateOpenCell() } fileprivate func toggleDatePickerForSelectedIndexPath(_ indexPath: IndexPath) { baseTableView.beginUpdates() let indexPaths = [IndexPath(row:indexPath.row + 1, section:indexPath.section)] // check if 'indexPath' has an attached date picker below it if hasPickerForIndexPath(indexPath) { // found a picker below it, so remove it baseTableView.deleteRows(at: indexPaths, with:.fade) } else { // didn't find a picker below it, so we should insert it baseTableView.insertRows(at: indexPaths, with:.fade) } baseTableView.endUpdates() } fileprivate func hasPickerForIndexPath(_ indexPath: IndexPath) -> Bool { var hasPicker = false if baseTableView.cellForRow(at: IndexPath(row: indexPath.row+1, section: indexPath.section)) is MqttSettingPickerCell { hasPicker = true } return hasPicker } fileprivate func titleForMqttManagerStatus(_ status: MqttManager.ConnectionStatus) -> String { let statusText: String switch status { case .connected: statusText = "uart_mqtt_status_connected" case .connecting: statusText = "uart_mqtt_status_connecting" case .disconnecting: statusText = "uart_mqtt_status_disconnecting" case .error: statusText = "uart_mqtt_status_error" default: statusText = "uart_mqtt_status_disconnected" } let localizationManager = LocalizationManager.shared return localizationManager.localizedString(statusText) } fileprivate func titleForSubscribeBehaviour(_ behaviour: MqttSettings.SubscribeBehaviour) -> String { let textId: String switch behaviour { case .localOnly: textId = "uart_mqtt_subscription_localonly" case .transmit: textId = "uart_mqtt_subscription_transmit" } let localizationManager = LocalizationManager.shared return localizationManager.localizedString(textId) } fileprivate func titleForQos(_ qos: MqttManager.MqttQos) -> String { let textId: String switch qos { case .atLeastOnce: textId = "uart_mqtt_qos_atleastonce" case .atMostOnce: textId = "uart_mqtt_qos_atmostonce" case .exactlyOnce: textId = "uart_mqtt_qos_exactlyonce" } let localizationManager = LocalizationManager.shared return localizationManager.localizedString(textId) } } // MARK: UITableViewDelegate extension UartMqttSettingsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerCell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! MqttSettingsHeaderCell headerCell.backgroundColor = UIColor.clear headerCell.nameLabel.text = headerTitleForSection(section) let hasSwitch = section == SettingsSections.publish.rawValue || section == SettingsSections.subscribe.rawValue headerCell.isOnSwitch.isHidden = !hasSwitch if hasSwitch { let mqttSettings = MqttSettings.shared if section == SettingsSections.publish.rawValue { headerCell.isOnSwitch.isOn = mqttSettings.isPublishEnabled headerCell.isOnChanged = { isOn in mqttSettings.isPublishEnabled = isOn } } else if section == SettingsSections.subscribe.rawValue { headerCell.isOnSwitch.isOn = mqttSettings.isSubscribeEnabled headerCell.isOnChanged = { [unowned self] isOn in mqttSettings.isSubscribeEnabled = isOn self.subscriptionTopicChanged(nil, qos: mqttSettings.subscribeQos) } } } return headerCell.contentView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if headerTitleForSection(section) == nil { return 0.5 // no title, so 0 height (hack: set to 0.5 because 0 height is not correctly displayed) } else { return UartMqttSettingsViewController.kDefaultHeaderCellHeight } } } // MARK: UIPickerViewDataSource extension UartMqttSettingsViewController: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerViewType == .action ? 2:3 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch pickerViewType { case .qos: return titleForQos(MqttManager.MqttQos(rawValue: row)!) case .action: return titleForSubscribeBehaviour(MqttSettings.SubscribeBehaviour(rawValue: row)!) } } } // MARK: UIPickerViewDelegate extension UartMqttSettingsViewController: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let selectedIndexPath = indexPathFromTag(pickerView.tag, scale:100) // Update settings with new values let section = SettingsSections(rawValue: selectedIndexPath.section)! let mqttSettings = MqttSettings.shared switch section { case .publish: mqttSettings.setPublishQos(index: selectedIndexPath.row, qos: MqttManager.MqttQos(rawValue: row)!) case .subscribe: if selectedIndexPath.row == 0 { // Topic Qos let qos = MqttManager.MqttQos(rawValue: row)! mqttSettings.subscribeQos = qos subscriptionTopicChanged(mqttSettings.subscribeTopic, qos: qos) } else if selectedIndexPath.row == 1 { // Action mqttSettings.subscribeBehaviour = MqttSettings.SubscribeBehaviour(rawValue: row)! } default: break } // Refresh cell baseTableView.reloadRows(at: [selectedIndexPath], with: .none) } } // MARK: - UITextFieldDelegate extension UartMqttSettingsViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Go to next textField if textField.returnKeyType == UIReturnKeyType.next { let tag = textField.tag var nextPathForTag = indexPathFromTag(tag+1, scale:10) var nextView = baseTableView.cellForRow(at: nextPathForTag)?.viewWithTag(tag+1) if nextView == nil { let nexSectionTag = ((tag/10)+1)*10 nextPathForTag = indexPathFromTag(nexSectionTag, scale:10) nextView = baseTableView.cellForRow(at: nextPathForTag)?.viewWithTag(nexSectionTag) } if let next = nextView as? UITextField { next.becomeFirstResponder() // Scroll to show it baseTableView.scrollToRow(at: nextPathForTag, at: .middle, animated: true) } else { textField.resignFirstResponder() } } return true } func textFieldDidEndEditing(_ textField: UITextField) { let indexPath = indexPathFromTag(textField.tag, scale:10) let section = indexPath.section let row = indexPath.row let mqttSettings = MqttSettings.shared // Update settings with new values switch section { case SettingsSections.server.rawValue: if row == 0 { // Server Address if let serverAddress = textField.text, !serverAddress.isEmpty { mqttSettings.serverAddress = textField.text } else { mqttSettings.serverAddress = MqttSettings.defaultServerAddress } } else if row == 1 { // Server Port if let port = Int(textField.text!) { mqttSettings.serverPort = port } else { textField.text = nil mqttSettings.serverPort = MqttSettings.defaultServerPort } } case SettingsSections.publish.rawValue: mqttSettings.setPublishTopic(index: row, topic: textField.text) case SettingsSections.subscribe.rawValue: let topic = textField.text mqttSettings.subscribeTopic = topic subscriptionTopicChanged(topic, qos: mqttSettings.subscribeQos) case SettingsSections.advanced.rawValue: if row == 0 { // Username mqttSettings.username = textField.text } else if row == 1 { // Password mqttSettings.password = textField.text } default: break } } } // MARK: - MqttManagerDelegate extension UartMqttSettingsViewController: MqttManagerDelegate { func onMqttConnected() { // Update status DispatchQueue.main.async { self.baseTableView.reloadData() } } func onMqttDisconnected() { // Update status DispatchQueue.main.async { self.baseTableView.reloadData() } } func onMqttMessageReceived(message: String, topic: String) { } func onMqttError(message: String) { DispatchQueue.main.async { let localizationManager = LocalizationManager.shared let alert = UIAlertController(title:localizationManager.localizedString("dialog_error"), message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: localizationManager.localizedString("dialog_ok"), style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) // Update status self.baseTableView.reloadData() } } }
41.831597
194
0.641544
0a80e8e613ed5dceb30cfcdd6716473324ef32fb
1,453
/** * (C) Copyright IBM Corp. 2018. * * 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 /** Field. */ public struct Field: Codable, Equatable { /** The type of the field. */ public enum FieldType: String { case nested = "nested" case string = "string" case date = "date" case long = "long" case integer = "integer" case short = "short" case byte = "byte" case double = "double" case float = "float" case boolean = "boolean" case binary = "binary" } /** The name of the field. */ public var fieldName: String? /** The type of the field. */ public var fieldType: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case fieldName = "field" case fieldType = "type" } }
25.946429
82
0.626979
727b968e6fa23d9750a76d69fc16fd80b4ef1d2d
3,064
// // PoemPickerScreenDataSource.swift // Shuffle100 // // Created by 里 佳史 on 2019/05/11. // Copyright © 2019 里 佳史. All rights reserved. // import Foundation import UIKit extension PoemPickerScreen: UITableViewDataSource, UIPickerViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.isActive { return filteredPoems.count } else { return Poem100.poems.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let poem: Poem if searchController.isActive { poem = filteredPoems[indexPath.row] } else { poem = Poem100.poems[indexPath.row] } let cell = tableView.dequeueReusableCell(withIdentifier: "poems", for: indexPath).then { $0.contentConfiguration = poemPickerCellConfiguration(of: poem) $0.backgroundColor = colorFor(poem: poem) $0.tag = poem.number $0.accessibilityLabel = String(format: "%03d", poem.number) $0.accessoryType = .detailButton } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return fontSizeForPoem() * 3 } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return settings.savedFudaSets.count } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let label = UILabel() let fudaSet = settings.savedFudaSets[row] label.text = fudaSet.name + " (\(fudaSet.state100.selectedNum)首)" label.font = UIFont.systemFont(ofSize: fontSizeOfCell) label.textAlignment = .center return label } private func poemPickerCellConfiguration(of poem: Poem) -> UIListContentConfiguration { var content = UIListContentConfiguration.subtitleCell() content.text = poem.strWithNumberAndLiner() content.textProperties.font = UIFont(name: "HiraMinProN-W6", size: fontSizeForPoem()) ?? UIFont.systemFont(ofSize: fontSizeForPoem()) content.textProperties.numberOfLines = 1 content.secondaryText = " \(poem.poet) \(poem.living_years)" content.textToSecondaryTextVerticalPadding = fontSizeForPoem() * 0.25 return content } private func fontSizeForPoem() -> CGFloat { return UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body).pointSize } private func colorFor(poem: Poem) -> UIColor { if try! settings.state100.ofNumber(poem.number) { return StandardColor.selectedPoemBackColor } return UIColor.systemBackground } }
35.627907
141
0.653394
e22aa2a22c89b3723f55ac33dfb9da7cec59f9f4
1,783
// // CircularWaitingShape.swift // Indicators // // Created by Marlo Kessler on 07.07.20. // Copyright © 2020 Marlo Kessler. All rights reserved. // import SwiftUI @available(iOS 13.0, *) struct CircularWaitingShape: CircularIndicatorShape { var progress: Double init(_ progress: Double) { self.progress = progress } func path(in rect: CGRect) -> Path { var path = Path() path.addPath(waitingPath(in: rect, for: progress)) return path } func waitingPath(in rect: CGRect, for progress: Double) -> Path { let width = rect.width let height = rect.height let angleOffset: Double = -90 let angelProgress1 = 360*progress let angelProgress2 = 360*(progress-0.5) let startAngle: Double = progress < 0.5 ? angelProgress1 + angleOffset : 180 + 3 * angelProgress2 + angleOffset - 1 // -1 prevents the circle from switching clock direction, which would happen, if start and end point wourld be equal. let endAngle: Double = progress < 0.5 ? 3 * angelProgress1 + angleOffset : 540 + angelProgress2 + angleOffset var path = Path() path.addArc(center: CGPoint(x: width / 2, y: height / 2), radius: min(width, height) / 2, startAngle: Angle(degrees: startAngle), endAngle: Angle(degrees: endAngle), clockwise: false) return path } var animatableData: Double { get { return progress } set { progress = newValue } } }
29.716667
157
0.536175
f5c5e21d3e2f3cf2c69502f29cd9ebb4b46b1859
3,349
/* * vector sigma (https://github.com/vectorsigma72) * Copyright 2020 vector sigma All Rights Reserved. * * The source code contained or described herein and all documents related * to the source code ("Material") are owned by vector sigma. * Title to the Material remains with vector sigma or its suppliers and licensors. * The Material is proprietary of vector sigma and is protected by worldwide copyright. * No part of the Material may be used, copied, reproduced, modified, published, * uploaded, posted, transmitted, distributed, or disclosed in any way without * vector sigma's prior express written permission. * * No license under any patent, copyright, trade secret or other intellectual * property right is granted to or conferred upon you by disclosure or delivery * of the Materials, either expressly, by implication, inducement, estoppel or * otherwise. Any license under such intellectual property rights must be * express and approved by vector sigma in writing. * * Unless otherwise agreed by vector sigma in writing, you may not remove or alter * this notice or any other notice embedded in Materials by vector sigma in any way. * * The license is granted for the CloverBootloader project (i.e. https://github.com/CloverHackyColor/CloverBootloader) * and all the users as long as the Material is used only within the * source code and for the exclusive use of CloverBootloader, which must * be free from any type of payment or commercial service for the license to be valid. */ import Cocoa //MARK: TagData final class TagData: NSObject, NSCoding, NSCopying { var key : String var type : PlistTag var value : Any? var placeHolder : String required init(key: String, type: PlistTag, value: Any?) { self.key = key self.type = type self.value = value self.placeHolder = "" super.init() self.type = type // don't hold the value of contenitors, ....save the memory!!!! if self.type == .Array { self.value = nil } else if self.type == .Dictionary { self.value = nil } } // Welocome to NSCoding! required init(coder decoder: NSCoder) { self.key = decoder.decodeObject(forKey: "key") as? String ?? "" self.type = PlistTag(rawValue: (decoder.decodeObject(forKey: "type") as! NSNumber).intValue) ?? .String let val = decoder.decodeObject(forKey: "value") switch self.type { case .String: self.value = val as! String case .Dictionary: self.value = nil case .Array: self.value = nil case .Number: if val is PEInt { self.value = val as! PEInt } else { self.value = val as! PEReal } case .Bool: self.value = val as! Bool case .Date: self.value = val as! Date case .Data: self.value = val as! Data } self.placeHolder = "" } func encode(with coder: NSCoder) { coder.encode(self.key, forKey: "key") coder.encode(NSNumber(value: self.type.rawValue), forKey: "type") coder.encode(self.value, forKey: "value") } func copy(with zone: NSZone? = nil) -> Any { let keyCopy = "\(self.key)" let typeCopy = PlistTag.init(rawValue: self.type.rawValue) let valCopy = (self.value as AnyObject).copy() return TagData(key: keyCopy, type: typeCopy!, value: valCopy) } }
33.828283
118
0.680203
0e06efa4738605525e292d6fed453a63ec40a07e
3,196
// // Restaurant.swift // FuckingYelp // // Created by Taku Tran on 6/6/17. // Copyright © 2017 Taku Tran. All rights reserved. // import UIKit class Business: NSObject { let name: String? let address: String? let imageURL: URL? let categories: String? let distance: String? let ratingImageURL: URL? let reviewCount: NSNumber? init(dictionary: NSDictionary) { name = dictionary["name"] as? String let imageURLString = dictionary["image_url"] as? String if imageURLString != nil { imageURL = URL(string: imageURLString!)! } else { imageURL = nil } let location = dictionary["location"] as? NSDictionary var address = "" if location != nil { let addressArray = location!["address"] as? NSArray if addressArray != nil && addressArray!.count > 0 { address = addressArray![0] as! String } let neighborhoods = location!["neighborhoods"] as? NSArray if neighborhoods != nil && neighborhoods!.count > 0 { if !address.isEmpty { address += ", " } address += neighborhoods![0] as! String } } self.address = address let categoriesArray = dictionary["categories"] as? [[String]] if categoriesArray != nil { var categoryNames = [String]() for category in categoriesArray! { let categoryName = category[0] categoryNames.append(categoryName) } categories = categoryNames.joined(separator: ", ") } else { categories = nil } let distanceMeters = dictionary["distance"] as? NSNumber if distanceMeters != nil { let milesPerMeter = 0.000621371 distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue) } else { distance = nil } let ratingImageURLString = dictionary["rating_img_url_large"] as? String if ratingImageURLString != nil { ratingImageURL = URL(string: ratingImageURLString!) } else { ratingImageURL = nil } reviewCount = dictionary["review_count"] as? NSNumber } class func businesses(array: [NSDictionary]) -> [Business] { var businesses = [Business]() for dictionary in array { let business = Business(dictionary: dictionary) businesses.append(business) } return businesses } class func searchWithTerm(term: String, completion: @escaping ([Business]?, Error?) -> Void) { _ = YelpClient.sharedInstance.searchWithTerm(term, completion: completion) } class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: @escaping ([Business]?, Error?) -> Void) -> Void { _ = YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, completion: completion) } }
33.291667
164
0.568523
38de8e01599abe089e2d5e1cfebcf35fdb8b46bd
1,210
// // NewCategory.swift // collector // // Created by Gabriel Coelho on 1/27/20. // Copyright © 2020 Gabe. All rights reserved. // import SwiftUI struct NewCategory: View { @State private var categoryName: String = "" @Binding var categories: [String] @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode> var body: some View { NavigationView { Form { Section { TextField("Enter Your New Category Name:", text: $categoryName) Button(action: { // Pop view self.presentationMode.wrappedValue.dismiss() self.categories.append(self.categoryName) print("Created new category: \(self.$categoryName)") dump(self.$categories) }, label: { Text("Submit") }) } } .navigationBarTitle("New Category") } } } #if DEBUG struct NewCategory_Previews: PreviewProvider { static var previews: some View { NewCategory(categories: .constant(["Test1", "Test 2"])) } } #endif
26.304348
84
0.538017
dd5cbf844a4be567bdd8b08d1e1a932db0344b47
477
// // AppFlow.swift // ReduxApp // // Created by Ihor Yarovyi on 8/28/21. // import SwiftUI enum AppFlow { case general(GeneralAppFlow) case verifyEmail(onVerify: @autoclosure () -> AnyView) case verifyRestoreToken(onVerify: @autoclosure () -> AnyView) case launchScreen(onLaunch: @autoclosure () -> AnyView) enum GeneralAppFlow { case auth(onAuth: @autoclosure () -> AnyView) case main(onMain: @autoclosure () -> AnyView) } }
22.714286
65
0.647799
89a712de86e20c6d216851ee604d7ea025e5ebed
2,255
class Power { let name: String init(withName name: String) { self.name = name } } protocol HasFlyingPower { func fly() } protocol HasSuperStrengthPower { func hit() } class Superhero { var name:String let powers: [Power] convenience init(withName name: String, andPowers powers: Power...) { self.init(withName: name, andPowers: powers) } init(withName name: String, andPowers powers: [Power]){ self.name = name self.powers = powers } func usePower(power: String) -> String{ //check if power is available let hasPower = self.powers.contains {p in p.name == power } if !hasPower { return "\(self.name) cannot use \(power)"; } return "\(self.name) used \(power)!"; } } class FlyingSuperStrongSuperhero: Superhero, HasFlyingPower, HasSuperStrengthPower { func fly() { } func hit() { } } class UltraHero: Superhero { let ultimate: String init(withName name: String, powers: [Power], andUltimate ultimate: String) { self.ultimate = ultimate super.init(withName: name, andPowers: powers) } override func usePower(power: String) -> String { if(self.ultimate == power){ return "\(self.name) used ultimate \(power)!"; } return super.usePower(power); } } let batman = UltraHero(withName: "Batman", powers: [Power(withName: "Utility belt"), Power(withName: "Martial Arts")], andUltimate: "Throw batarang") let supergirl = Superhero(withName: "Supergirl", andPowers: Power(withName: "Super strength"), Power(withName: "Laser eyes"), Power(withName: "Flying")) batman.usePower("Martial Arts") supergirl.usePower("Flying") supergirl.usePower("Martial Arts") batman.usePower("Throw batarang") //extension Superhero extension Superhero { func sayName() -> String{ return "Hi! I am \(self.name)"; } } func superheroSayName(sh: Superhero) -> String{ return "Hi! I am \(sh.name)"; } supergirl.sayName() batman.sayName() superheroSayName(batman)
19.439655
84
0.591574
f4dcc8fc2a5d795b03f4befba36929dd600e5beb
605
import Foundation protocol Person { var name: String { get } } struct User: Person { let name: String let homes: [Home] } struct Home { let admin: User let address: String let devices: [Device] } struct Address { let street: String let city: String } struct Device { // sourcery: case_properties enum Kind { case light(on: Bool, brightness: Double) case powerSwitch(on: Bool) case blinds(position: Double, angle: Double) case airConditioning(temperature: Double) } let id: Int let name: String let kind: Kind }
16.805556
52
0.628099
bfcea4bf74d43998b85c8545b0da65452c77fdb0
2,904
// ___FILEHEADER___ @testable import ___PROJECTNAME:identifier___ import Nimble import Quick import UIKit final class OnboardingCoordinatorSpec: QuickSpec { override func spec() { describe("OnboardingCoordinator") { // MARK: - Set Up Test Suite var spyRouter: SpyRouter! var spyControllerFactory: SpyControllerFactory! var sut: OnboardingCoordinator! beforeEach { let rootNavController = UINavigationController(nibName: nil, bundle: nil) spyControllerFactory = SpyControllerFactory() spyRouter = SpyRouter(rootNavController: rootNavController) sut = OnboardingCoordinator(router: spyRouter, controllerFactory: spyControllerFactory) sut.start() } afterEach { spyRouter = nil spyControllerFactory = nil sut = nil } describe("start") { // MARK: - showOnboarding describe("should showOnboarding, which") { it("should call makeOnboardingViewController on controllerFactory") { expect(spyControllerFactory.callCountFor["makeOnboardingViewController"]) .to(equal(1)) } it("should call setRootViewController on router") { expect(spyRouter.callCountFor["setRootViewController"]).to(equal(1)) } it("should call setRootViewController with an OnboardingViewController") { expect(spyRouter.setRootViewControllerViewControllerArgs.first!) .to(beAnInstanceOf(OnboardingViewController.self)) } it("should call setRootViewController with hideTopBar set true") { expect(spyRouter.setRootViewControllerHideTopBarArgs.first!) .to(beTrue()) } it("should set onCompleteOnboarding to something in OnboardingViewController") { expect((spyRouter.rootNavController?.viewControllers.first! as! OnboardingViewController).onCompleteOnboarding) .toNot(beNil()) } } // MARK: - onCompleteOnboarding describe("OnboardingViewController onCompleteOnboarding") { it("should call sut onCompleteOnboarding") { let onboardingVC = (spyRouter.rootNavController?.viewControllers.first! as! OnboardingViewController) var calledSutOnCompleteOnboarding = false sut.onCompleteOnboarding = { calledSutOnCompleteOnboarding = true } onboardingVC.onCompleteOnboarding!() expect(calledSutOnCompleteOnboarding).to(beTrue()) } } }///start }//OnboardingCoordinator }///spec }
32.266667
90
0.597452
ff2e09dbd289027ae00d360f03d6d7ed94badc37
23,293
// Copyright (C) 2020 Parrot Drones SAS // // 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. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation import GroundSdk import SwiftProtobuf /// Controller for network control peripheral. class NetworkController: DeviceComponentController, NetworkControlBackend { /// Component settings key. private static let settingKey = "NetworkControl" /// Network control component. private(set) var networkControl: NetworkControlCore! /// Store device specific values. private let deviceStore: SettingsStore? /// Preset store for this component. private var presetStore: SettingsStore? /// Keys for stored settings and capabilities. enum SettingKey: String, StoreKey { case routingPolicyKey = "routingPolicy" case maxCellularBitrateKey = "maxCellularBitrate" case directConnectionModeKey = "directConnectionMode" } /// Stored settings. enum Setting: Hashable { case routingPolicy(NetworkControlRoutingPolicy) case maxCellularBitrate(Int) case directConnectionMode(NetworkDirectConnectionMode) /// Setting storage key. var key: SettingKey { switch self { case .routingPolicy: return .routingPolicyKey case .maxCellularBitrate: return .maxCellularBitrateKey case .directConnectionMode: return .directConnectionModeKey } } /// All values to allow enumerating settings. static let allCases: [Setting] = [ .routingPolicy(.automatic), .maxCellularBitrate(0), .directConnectionMode(.secure)] func hash(into hasher: inout Hasher) { hasher.combine(key) } static func == (lhs: Setting, rhs: Setting) -> Bool { return lhs.key == rhs.key } } /// Stored capabilities for settings. enum Capabilities { case routingPolicy(Set<NetworkControlRoutingPolicy>) case maxCellularBitrate(Int, Int) case directConnectionMode(Set<NetworkDirectConnectionMode>) /// All values to allow enumerating settings static let allCases: [Capabilities] = [ .routingPolicy([]), .maxCellularBitrate(0, 0), .directConnectionMode([])] /// Setting storage key var key: SettingKey { switch self { case .routingPolicy: return .routingPolicyKey case .maxCellularBitrate: return .maxCellularBitrateKey case .directConnectionMode: return .directConnectionModeKey } } } /// Setting values as received from the drone. private var droneSettings = Set<Setting>() /// Decoder for network events. private var arsdkDecoder: ArsdkNetworkEventDecoder! /// Whether `State` message has been received since `GetState` command was sent. private var stateReceived = false /// Constructor. /// /// - Parameter deviceController: device controller owning this component controller (weak) override init(deviceController: DeviceController) { if GroundSdkConfig.sharedInstance.offlineSettings == .off { deviceStore = nil presetStore = nil } else { deviceStore = deviceController.deviceStore.getSettingsStore(key: NetworkController.settingKey) presetStore = deviceController.presetStore.getSettingsStore(key: NetworkController.settingKey) } super.init(deviceController: deviceController) arsdkDecoder = ArsdkNetworkEventDecoder(listener: self) networkControl = NetworkControlCore(store: deviceController.device.peripheralStore, backend: self) // load settings if let deviceStore = deviceStore, let presetStore = presetStore, !deviceStore.new && !presetStore.new { loadPresets() networkControl.publish() } } /// Drone is about to be forgotten. override func willForget() { deviceStore?.clear() networkControl.unpublish() super.willForget() } /// Drone is about to be connected. override func willConnect() { super.willConnect() // remove settings stored while connecting. We will get new one on the next connection. droneSettings.removeAll() stateReceived = false _ = sendGetStateCommand() } /// Drone is disconnected. override func didDisconnect() { super.didDisconnect() // clear all non saved values networkControl.cancelSettingsRollback() .update(link: nil) .update(links: []) // unpublish if offline settings are disabled if GroundSdkConfig.sharedInstance.offlineSettings == .off { networkControl.unpublish() } else { networkControl.notifyUpdated() } } /// Preset has been changed. override func presetDidChange() { super.presetDidChange() // reload preset store presetStore = deviceController.presetStore.getSettingsStore(key: NetworkController.settingKey) loadPresets() if connected { applyPresets() } } /// Load saved settings. private func loadPresets() { if let presetStore = presetStore, let deviceStore = deviceStore { for setting in Setting.allCases { switch setting { case .routingPolicy: if let policies: StorableArray<NetworkControlRoutingPolicy> = deviceStore.read(key: setting.key), let policy: NetworkControlRoutingPolicy = presetStore.read(key: setting.key) { let supportedPolicies = Set(policies.storableValue) if supportedPolicies.contains(policy) { networkControl.update(supportedPolicies: supportedPolicies) .update(policy: policy) } } case .maxCellularBitrate: if let value: Int = presetStore.read(key: setting.key), let range: (min: Int, max: Int) = deviceStore.readRange(key: setting.key) { networkControl.update(maxCellularBitrate: (range.min, value, range.max)) } case .directConnectionMode: if let modes: StorableArray<NetworkDirectConnectionMode> = deviceStore.read(key: setting.key), let mode: NetworkDirectConnectionMode = presetStore.read(key: setting.key) { let supportedModes = Set(modes.storableValue) if supportedModes.contains(mode) { networkControl.update(supportedDirectConnectionModes: supportedModes) .update(directConnectionMode: mode) } } } } networkControl.notifyUpdated() } } /// Applies presets. /// /// Iterates settings received during connection. private func applyPresets() { for setting in droneSettings { switch setting { case .routingPolicy(let routingPolicy): if let preset: NetworkControlRoutingPolicy = presetStore?.read(key: setting.key) { if preset != routingPolicy { _ = sendRoutingPolicyCommand(preset) } networkControl.update(policy: preset).notifyUpdated() } else { networkControl.update(policy: routingPolicy).notifyUpdated() } case .maxCellularBitrate(let value): if let preset: Int = presetStore?.read(key: setting.key) { if preset != value { _ = sendMaxCellularBitrate(preset) } networkControl.update(maxCellularBitrate: (min: nil, value: preset, max: nil)) } else { networkControl.update(maxCellularBitrate: (min: nil, value: value, max: nil)) } case .directConnectionMode(let mode): if let preset: NetworkDirectConnectionMode = presetStore?.read(key: setting.key) { if preset != mode { _ = sendDirectConnectionCommand(preset) } networkControl.update(directConnectionMode: preset).notifyUpdated() } else { networkControl.update(directConnectionMode: mode).notifyUpdated() } } } } /// Called when a command that notifiies a setting change has been received. /// /// - Parameter setting: setting that changed func settingDidChange(_ setting: Setting) { droneSettings.insert(setting) switch setting { case .routingPolicy(let routingPolicy): if connected { networkControl.update(policy: routingPolicy) } case .maxCellularBitrate(let maxCellularBitrate): if connected { networkControl.update(maxCellularBitrate: (min: nil, value: maxCellularBitrate, max: nil)) } case .directConnectionMode(let mode): if connected { networkControl.update(directConnectionMode: mode) } } networkControl.notifyUpdated() } /// Processes stored capabilities changes. /// /// Update network control and device store. /// /// - Parameter capabilities: changed capabilities /// - Note: Caller must call `networkControl.notifyUpdated()` to notify change. func capabilitiesDidChange(_ capabilities: Capabilities) { switch capabilities { case .routingPolicy(let routingPolicies): deviceStore?.write(key: capabilities.key, value: StorableArray(Array(routingPolicies))) networkControl.update(supportedPolicies: routingPolicies) case .maxCellularBitrate(let min, let max): deviceStore?.writeRange(key: capabilities.key, min: min, max: max) networkControl.update(maxCellularBitrate: (min: min, value: nil, max: max)) case .directConnectionMode(let modes): deviceStore?.write(key: capabilities.key, value: StorableArray(Array(modes))) networkControl.update(supportedDirectConnectionModes: modes) } deviceStore?.commit() } /// A command has been received. /// /// - Parameter command: received command override func didReceiveCommand(_ command: OpaquePointer) { arsdkDecoder.decode(command) } /// Sets routing policy. /// /// - Parameter policy: the new policy /// - Returns: true if the command has been sent, false if not connected and the value has been changed immediately func set(policy: NetworkControlRoutingPolicy) -> Bool { presetStore?.write(key: SettingKey.routingPolicyKey, value: policy).commit() if connected { return sendRoutingPolicyCommand(policy) } else { networkControl.update(policy: policy).notifyUpdated() return false } } /// Sets maximum cellular bitrate. /// /// - Parameter maxCellularBitrate: the new maximum cellular bitrate, in kilobits per second /// - Returns: true if the command has been sent, false if not connected and the value has been changed immediately func set(maxCellularBitrate: Int) -> Bool { presetStore?.write(key: SettingKey.maxCellularBitrateKey, value: maxCellularBitrate).commit() if connected { return sendMaxCellularBitrate(maxCellularBitrate) } else { networkControl.update(maxCellularBitrate: (min: nil, value: maxCellularBitrate, max: nil)) .notifyUpdated() return false } } /// Sets direct connection mode. /// /// - Parameter directConnectionMode: the new mode /// - Returns: true if the command has been sent, false if not connected and the value has been changed immediately func set(directConnectionMode: NetworkDirectConnectionMode) -> Bool { presetStore?.write(key: SettingKey.directConnectionModeKey, value: directConnectionMode).commit() if connected { return sendDirectConnectionCommand(directConnectionMode) } else { networkControl.update(directConnectionMode: directConnectionMode).notifyUpdated() return false } } } /// Extension for methods to send Network commands. extension NetworkController { /// Sends to the drone a Network command. /// /// - Parameter command: command to send /// - Returns: `true` if the command has been sent func sendNetworkCommand(_ command: Arsdk_Network_Command.OneOf_ID) -> Bool { var sent = false if let encoder = ArsdkNetworkCommandEncoder.encoder(command) { sendCommand(encoder) sent = true } return sent } /// Sends get state command. /// /// - Returns: `true` if the command has been sent func sendGetStateCommand() -> Bool { var getState = Arsdk_Network_Command.GetState() getState.includeDefaultCapabilities = true return sendNetworkCommand(.getState(getState)) } /// Sends routing policy command. /// /// - Parameter policy: requested routing policy /// - Returns: `true` if the command has been sent func sendRoutingPolicyCommand(_ routingPolicy: NetworkControlRoutingPolicy) -> Bool { var sent = false if let routingPolicy = routingPolicy.arsdkValue { var setRoutingPolicy = Arsdk_Network_Command.SetRoutingPolicy() setRoutingPolicy.policy = routingPolicy sent = sendNetworkCommand(.setRoutingPolicy(setRoutingPolicy)) } return sent } /// Sends maximum cellular bitrate command. /// /// - Parameter maxCellularBitrate: requested maximum cellular bitrate, in kilobytes per second /// - Returns: `true` if the command has been sent func sendMaxCellularBitrate(_ maxCellularBitrate: Int) -> Bool { var setCellularMaxBitrate = Arsdk_Network_Command.SetCellularMaxBitrate() setCellularMaxBitrate.maxBitrate = Int32(maxCellularBitrate) return sendNetworkCommand(.setCellularMaxBitrate(setCellularMaxBitrate)) } /// Sends direct connection command. /// /// - Parameter mode: requested mode /// - Returns: `true` if the command has been sent func sendDirectConnectionCommand(_ mode: NetworkDirectConnectionMode) -> Bool { var sent = false if let arsdkMode = mode.arsdkValue { var setDirectConnection = Arsdk_Network_Command.SetDirectConnection() setDirectConnection.mode = arsdkMode sent = sendNetworkCommand(.setDirectConnection(setDirectConnection)) } return sent } } /// Extension for events processing. extension NetworkController: ArsdkNetworkEventDecoderListener { func onState(_ state: Arsdk_Network_Event.State) { // capabilities if state.hasDefaultCapabilities { let capabilities = state.defaultCapabilities let minBitrate = Int(capabilities.cellularMinBitrate) let maxBitrate = Int(capabilities.cellularMaxBitrate) capabilitiesDidChange(.maxCellularBitrate(minBitrate, maxBitrate)) let supportedModes = Set(capabilities.supportedDirectConnectionModes.compactMap { NetworkDirectConnectionMode(fromArsdk: $0) }) capabilitiesDidChange(.directConnectionMode(supportedModes)) } // routing info if state.hasRoutingInfo { processRoutingInfo(state.routingInfo) } // links status if state.hasLinksStatus { processLinksStatus(state.linksStatus) } // global link quality if state.hasGlobalLinkQuality { processGlobalLinkQuality(state.globalLinkQuality) } // cellular maximum bitrate if state.hasCellularMaxBitrate { processCellularMaxBitrate(state.cellularMaxBitrate) } // direct connection mode if let mode = NetworkDirectConnectionMode(fromArsdk: state.directConnectionMode) { settingDidChange(.directConnectionMode(mode)) } if !stateReceived { stateReceived = true applyPresets() networkControl.publish() } networkControl.notifyUpdated() } /// Processes a `RoutingInfo` message. /// /// - Parameter routingInfo: message to process func processRoutingInfo(_ routingInfo: Arsdk_Network_RoutingInfo) { switch routingInfo.currentLink { case .cellular: networkControl.update(link: .cellular) case .wlan: networkControl.update(link: .wlan) case .any, .UNRECOGNIZED: networkControl.update(link: nil) } if !stateReceived { // first receipt of this message // assume all routing policies are supported capabilitiesDidChange(.routingPolicy(Set(NetworkControlRoutingPolicy.allCases))) } if let routingPolicy = NetworkControlRoutingPolicy.init(fromArsdk: routingInfo.policy) { settingDidChange(.routingPolicy(routingPolicy)) } } /// Processes a `LinksStatus` message. /// /// - Parameter linksStatus: message to process func processLinksStatus(_ linksStatus: Arsdk_Network_LinksStatus) { let links = linksStatus.links.compactMap { $0.gsdkLinkInfo } networkControl.update(links: links) } /// Processes a `GlobalLinkQuality` message. /// /// - Parameter globalLinkQuality: message to process func processGlobalLinkQuality(_ globalLinkQuality: Arsdk_Network_GlobalLinkQuality) { if globalLinkQuality.quality == 0 { networkControl.update(quality: nil) } else { networkControl.update(quality: Int(globalLinkQuality.quality) - 1) } } /// Processes a `CellularMaxBitrate` message. /// /// - Parameter cellularMaxBitrate: message to process func processCellularMaxBitrate(_ cellularMaxBitrate: Arsdk_Network_CellularMaxBitrate) { var maxCellularBitrate = Int(cellularMaxBitrate.maxBitrate) if maxCellularBitrate == 0 { // zero means maximum cellular bitrate is set to its upper range value maxCellularBitrate = networkControl.maxCellularBitrate.max } settingDidChange(.maxCellularBitrate(maxCellularBitrate)) } } /// Extension to make NetworkControlRoutingPolicy storable. extension NetworkControlRoutingPolicy: StorableEnum { static var storableMapper = Mapper<NetworkControlRoutingPolicy, String>([ .all: "all", .cellular: "cellular", .wlan: "wlan", .automatic: "automatic"]) } /// Extension to make NetworkDirectConnectionMode storable. extension NetworkDirectConnectionMode: StorableEnum { static var storableMapper = Mapper<NetworkDirectConnectionMode, String>([ .legacy: "legacy", .secure: "secure"]) } /// Extension that adds conversion from/to arsdk enum. extension NetworkControlRoutingPolicy: ArsdkMappableEnum { static let arsdkMapper = Mapper<NetworkControlRoutingPolicy, Arsdk_Network_RoutingPolicy>([ .all: .all, .cellular: .cellular, .wlan: .wlan, .automatic: .hybrid]) } /// Extension that adds conversion from/to arsdk enum. extension NetworkControlLinkType: ArsdkMappableEnum { static let arsdkMapper = Mapper<NetworkControlLinkType, Arsdk_Network_LinkType>([ .cellular: .cellular, .wlan: .wlan]) } /// Extension that adds conversion from/to arsdk enum. extension NetworkControlLinkStatus: ArsdkMappableEnum { static let arsdkMapper = Mapper<NetworkControlLinkStatus, Arsdk_Network_LinkStatus>([ .down: .down, .up: .up, .running: .running, .ready: .ready, .connecting: .connecting, .error: .error]) } /// Extension that adds conversion from/to arsdk enum. /// /// - Note: NetworkControlLinkError.init(fromArsdk: .none) will return `nil`. extension NetworkControlLinkError: ArsdkMappableEnum { static let arsdkMapper = Mapper<NetworkControlLinkError, Arsdk_Network_LinkError>([ .authentication: .authentication, .communicationLink: .commLink, .connect: .connect, .dns: .dns, .publish: .publish, .timeout: .timeout, .invite: .invite]) } /// Extension that adds conversion from/to arsdk enum. extension NetworkDirectConnectionMode: ArsdkMappableEnum { static let arsdkMapper = Mapper<NetworkDirectConnectionMode, Arsdk_Network_DirectConnectionMode>([ .legacy: .legacy, .secure: .secure]) } /// Extension that adds conversion to gsdk. extension Arsdk_Network_LinksStatus.LinkInfo { /// Creates a new `NetworkControlLinkInfoCore` from `Arsdk_Network_LinksStatus.LinkInfo`. var gsdkLinkInfo: NetworkControlLinkInfoCore? { if let type = NetworkControlLinkType.init(fromArsdk: type), let status = NetworkControlLinkStatus.init(fromArsdk: status) { let gsdkQuality = quality == 0 ? nil : Int(quality) - 1 let error = NetworkControlLinkError.init(fromArsdk: self.error) return NetworkControlLinkInfoCore(type: type, status: status, error: error, quality: gsdkQuality) } return nil } }
39.279933
119
0.645559
d7fccb64ca2bb9b429ffaa6cd52b889c05428e97
1,426
// // PublisherPageProvider.swift // ListController // // Created by Nikolai Timonin on 31.05.2021. // import Combine // MARK: - PublisherPageProvider public protocol PublisherPageProvider: PageProvider, AnyObject { // MARK: - Public properties var subscribes: Set<AnyCancellable> { get set } // MARK: - Public methods func getFirstPage() -> AnyPublisher<PageResult<T>, Error> func getNextPage() -> AnyPublisher<PageResult<T>, Error> } // MARK: - PageProvider Implementation public extension PublisherPageProvider { func getFirstPage(_ completion: @escaping (Result<PageResult<T>, Error>) -> Void) { getFirstPage() .sinkOn(completion) .store(in: &subscribes) } func getNextPage(_ completion: @escaping (Result<PageResult<T>, Error>) -> Void) { getNextPage() .sinkOn(completion) .store(in: &subscribes) } } // MARK: - AnyPublisher + Sink On Closure extension AnyPublisher { func sinkOn(_ completion: @escaping (Result<Self.Output, Self.Failure>) -> Void) -> AnyCancellable { return sink { (result) in switch result { case .finished: break case .failure(let error): completion(.failure(error)) } } receiveValue: { (value) in completion(.success(value)) } } }
24.586207
104
0.600281
1ca94e57d65b0c0d6ec0d785e936587df270e16b
266
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var mySet1 = Set(["One", "Two", "Three", "abc"]) var mySet2 = Set(["abc","def","ghi", "One"]) mySet1.subtract(mySet2) var newSetSubtract = mySet1.subtracting(mySet2)
22.166667
52
0.676692
878a0903df731fa8c026967dccaf3da0d13b03bf
1,841
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Windfish", platforms: [ .macOS("10.15") ], products: [ .library( name: "Windfish", targets: ["Windfish"] ) ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0"), ], targets: [ .target( name: "ocarina", dependencies: [ "Windfish", "Tracing", .product(name: "ArgumentParser", package: "swift-argument-parser"), ] ), .target( name: "Windfish", dependencies: [ "FoundationExtensions", "CPU", "RGBDS", "LR35902", "Tracing", ] ), .target( name: "Tracing", dependencies: [ "LR35902" ] ), .target( name: "LR35902", dependencies: [ "CPU" ] ), .target( name: "CPU", dependencies: [] ), .target( name: "RGBDS", dependencies: [ "FoundationExtensions", ] ), .testTarget( name: "RGBDSTests", dependencies: ["RGBDS"] ), .target( name: "FoundationExtensions", dependencies: [] ), .testTarget( name: "FoundationExtensionsTests", dependencies: ["FoundationExtensions"] ), .testTarget( name: "WindfishTests", dependencies: ["Windfish"], resources: [ .copy("Resources"), ] ), .testTarget( name: "LR35902Tests", dependencies: ["LR35902"] ), .testTarget( name: "TracingTests", dependencies: ["Tracing", "FoundationExtensions"] ), .testTarget( name: "CPUTests", dependencies: ["CPU"] ), ] )
18.979381
96
0.521999
713a1d33cf718dcb9429ca31d19db19819123c62
12,811
// // FileUpload.swift // dracoon-sdk // // Copyright © 2018 Dracoon. All rights reserved. // import Foundation import Alamofire import crypto_sdk public class FileUpload { let sessionManager: Alamofire.SessionManager let serverUrl: URL let apiPath: String let oAuthTokenManager: OAuthTokenManager let encoder: JSONEncoder let decoder: JSONDecoder let account: DracoonAccount let request: CreateFileUploadRequest let resolutionStrategy: CompleteUploadRequest.ResolutionStrategy let filePath: URL var callback: UploadCallback? let crypto: Crypto? fileprivate var isCanceled = false fileprivate var uploadId: String? init(config: DracoonRequestConfig, request: CreateFileUploadRequest, filePath: URL, resolutionStrategy: CompleteUploadRequest.ResolutionStrategy, crypto: Crypto?, account: DracoonAccount) { self.request = request self.sessionManager = config.sessionManager self.serverUrl = config.serverUrl self.apiPath = config.apiPath self.oAuthTokenManager = config.oauthTokenManager self.decoder = config.decoder self.encoder = config.encoder self.crypto = crypto self.account = account self.filePath = filePath self.resolutionStrategy = resolutionStrategy } public func start() { self.createFileUpload(request: request, completion: { result in switch result { case .value(let response): self.uploadId = response.uploadId self.callback?.onStarted?(response.uploadId) self.uploadChunks(uploadId: response.uploadId) case .error(let error): self.callback?.onError?(error) } }) } public func cancel() { guard !isCanceled else { return } self.isCanceled = true if let uploadId = self.uploadId { self.deleteUpload(uploadId: uploadId, completion: { _ in self.callback?.onCanceled?() }) } else { self.callback?.onCanceled?() } } fileprivate func createFileUpload(request: CreateFileUploadRequest, completion: @escaping DataRequest.DecodeCompletion<CreateFileUploadResponse>) { do { let jsonBody = try encoder.encode(request) let requestUrl = serverUrl.absoluteString + apiPath + "/nodes/files/uploads" var urlRequest = URLRequest(url: URL(string: requestUrl)!) urlRequest.httpMethod = "Post" urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = jsonBody self.sessionManager.request(urlRequest) .validate() .decode(CreateFileUploadResponse.self, decoder: self.decoder, completion: completion) } catch { completion(Dracoon.Result.error(DracoonError.nodes(error: error))) } } fileprivate func uploadChunks(uploadId: String) { let totalFileSize = self.calculateFileSize(filePath: self.filePath) ?? 0 as Int64 var cipher: FileEncryptionCipher? if let crypto = self.crypto { do { let fileKey = try crypto.generateFileKey() cipher = try crypto.createEncryptionCipher(fileKey: fileKey) } catch { self.callback?.onError?(DracoonError.encryption_cipher_failure) return } } self.createNextChunk(uploadId: uploadId, offset: 0, fileSize: totalFileSize, cipher: cipher, completion: { if let crypto = self.crypto, let cipher = cipher { self.account.getUserKeyPair(completion: { result in switch result { case .error(let error): self.callback?.onError?(error) return case .value(let userKeyPair): do { let publicKey = UserPublicKey(publicKey: userKeyPair.publicKeyContainer.publicKey, version: userKeyPair.publicKeyContainer.version) let encryptedFileKey = try crypto.encryptFileKey(fileKey: cipher.fileKey, publicKey: publicKey) self.completeRequest(uploadId: uploadId, encryptedFileKey: encryptedFileKey) } catch { self.callback?.onError?(DracoonError.filekey_encryption_failure) } } }) } else { self.completeRequest(uploadId: uploadId, encryptedFileKey: nil) } }) } fileprivate func createNextChunk(uploadId: String, offset: Int, fileSize: Int64, cipher: FileEncryptionCipher?, completion: @escaping () -> Void) { let range = NSMakeRange(offset, DracoonConstants.UPLOAD_CHUNK_SIZE) let lastBlock = Int64(offset + DracoonConstants.UPLOAD_CHUNK_SIZE) >= fileSize do { guard let data = try self.readData(self.filePath, range: range) else { self.callback?.onError?(DracoonError.read_data_failure(at: self.filePath)) return } let uploadData: Data if let cipher = cipher { do { if data.count > 0 { uploadData = try cipher.processBlock(fileData: data) } else { uploadData = data } if lastBlock { try cipher.doFinal() } } catch { self.callback?.onError?(error) return } } else { uploadData = data } self.uploadNextChunk(uploadId: uploadId, chunk: uploadData, offset: offset, totalFileSize: fileSize, retryCount: 0, chunkCallback: { error in if let error = error { self.callback?.onError?(error) return } if lastBlock { completion() } else { let newOffset = offset + data.count self.createNextChunk(uploadId: uploadId, offset: newOffset, fileSize: fileSize, cipher: cipher, completion: completion) } }, callback: callback) } catch { } } fileprivate func uploadNextChunk(uploadId: String, chunk: Data, offset: Int, totalFileSize: Int64, retryCount: Int, chunkCallback: @escaping (Error?) -> Void, callback: UploadCallback?) { if self.isCanceled { return } let requestUrl = serverUrl.absoluteString + apiPath + "/nodes/files/uploads/\(uploadId)" var urlRequest = URLRequest(url: URL(string: requestUrl)!) urlRequest.httpMethod = "Post" urlRequest.addValue("bytes " + String(offset) + "-" + String(offset + chunk.count) + "/*", forHTTPHeaderField: "Content-Range") self.sessionManager.upload(multipartFormData: { (formData) in formData.append(chunk, withName: "file", fileName: "file.name", mimeType: "application/octet-stream") }, with: urlRequest, encodingCompletion: { (encodingResult) in switch encodingResult { case .success(let upload, _, _): upload.responseData { dataResponse in if let error = dataResponse.error { if retryCount < DracoonConstants.CHUNK_UPLOAD_MAX_RETRIES { self.uploadNextChunk(uploadId: uploadId, chunk: chunk, offset: offset, totalFileSize: totalFileSize, retryCount: retryCount + 1, chunkCallback: chunkCallback, callback: callback) } else { chunkCallback(error) } } else { chunkCallback(nil) } } upload.uploadProgress(closure: { progress in self.callback?.onProgress?((Float(progress.fractionCompleted)*Float(chunk.count) + Float(offset))/Float(totalFileSize)) }) case .failure(let error): if retryCount < DracoonConstants.CHUNK_UPLOAD_MAX_RETRIES { self.uploadNextChunk(uploadId: uploadId, chunk: chunk, offset: offset, totalFileSize: totalFileSize, retryCount: retryCount + 1, chunkCallback: chunkCallback, callback: callback) } else { chunkCallback(error) } } }) } fileprivate func completeRequest(uploadId: String, encryptedFileKey: EncryptedFileKey?) { var completeRequest = CompleteUploadRequest() completeRequest.fileName = self.request.name completeRequest.resolutionStrategy = self.resolutionStrategy completeRequest.fileKey = encryptedFileKey self.completeUpload(uploadId: uploadId, request: completeRequest, completion: { result in switch result { case .value(let node): self.callback?.onComplete?(node) case .error(let error): self.callback?.onError?(error) } }) } fileprivate func completeUpload(uploadId: String, request: CompleteUploadRequest, completion: @escaping DataRequest.DecodeCompletion<Node>) { do { let jsonBody = try encoder.encode(request) let requestUrl = serverUrl.absoluteString + apiPath + "/nodes/files/uploads/\(uploadId)" var urlRequest = URLRequest(url: URL(string: requestUrl)!) urlRequest.httpMethod = "Put" urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = jsonBody self.sessionManager.request(urlRequest) .validate() .decode(Node.self, decoder: self.decoder, completion: completion) } catch { completion(Dracoon.Result.error(DracoonError.nodes(error: error))) } } fileprivate func deleteUpload(uploadId: String, completion: @escaping (Dracoon.Response) -> Void) { let requestUrl = serverUrl.absoluteString + apiPath + "/nodes/files/uploads/\(uploadId)" self.sessionManager.request(requestUrl, method: .delete, parameters: Parameters()) .validate() .response(completionHandler: { response in if let error = response.error { completion(Dracoon.Response(error: error)) } else { completion(Dracoon.Response(error: nil)) } }) } // MARK: Helper fileprivate func calculateFileSize(filePath: URL) -> Int64? { do { let fileAttribute: [FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: filePath.path) let fileSize = fileAttribute[FileAttributeKey.size] as? Int64 return fileSize } catch {} return nil } func readData(_ path: URL?, range: NSRange) throws -> Data? { guard let path = path, let fileHandle = try? FileHandle(forReadingFrom: path) else { return nil } let offset = UInt64(range.location) let length = UInt64(range.length) let size = fileHandle.seekToEndOfFile() let maxLength = size - offset guard maxLength >= 0 else { return nil } let secureLength = Int(min(length, maxLength)) fileHandle.seek(toFileOffset: offset) let data = fileHandle.readData(ofLength: secureLength) return data } }
42.703333
230
0.54383
91ee90e4a376bc8a57abff41f9fa7e259563382c
3,477
// // ProfileViewController.swift // SHWMark // // Created by yehot on 2017/11/15. // Copyright © 2017年 Xin Hua Zhi Yun. All rights reserved. // import UIKit import SnapKit //import SHWAccountSDK class ProfileViewController: UIViewController { private lazy var _unLoginheaderView = ProfileUnLoginHeaderView() private lazy var _loginheaderView: ProfileLoginHeaderView = { let v = Bundle.main.loadNibNamed("ProfileLoginHeaderView", owner: self, options: nil)?.first as! ProfileLoginHeaderView return v }() private lazy var _tableView: UITableView = { let tabView = UITableView() tabView.delegate = self tabView.dataSource = self tabView.frame = self.view.bounds tabView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tabView.tableFooterView = UIView() tabView.separatorStyle = .none tabView.isScrollEnabled = false return tabView }() typealias model = (imgName: String, title: String) private lazy var dataSource: [model] = { return [ // temp ("test_p_img_1", "新手指南"), ("test_p_img_2", "消息通知"), ("test_p_img_3", "意见反馈"), ("test_p_img_4", "关于"), ("test_p_img_4", "退出登录") ] }() override func viewDidLoad() { super.viewDidLoad() self.title = "我的" view.addSubview(_tableView) _unLoginheaderView.onLoginButtonClickedCallback { [weak self] in let loginVC = LoginViewController.instantiate() loginVC.delegate = self self?.navigationController?.present(loginVC, animated: true, completion: nil) } } fileprivate func sendLogoutRequest() { // SHWAccountSDK.logoutAsync(success: { // AccountManager.shared.logout() // self._tableView.reloadData() // }) { (code, msg) in // print("log out faile") // } } } extension ProfileViewController: LoginSuccessDelegate { func loginSuccess() { _tableView.reloadData() } } extension ProfileViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // temp if indexPath.row == (dataSource.count - 1) { sendLogoutRequest() } } } extension ProfileViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let model = dataSource[indexPath.row] cell.imageView?.image = UIImage.init(named: model.imgName) cell.textLabel?.text = model.title cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 200 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if AccountManager.shared.isLoggedIn() == true { _loginheaderView.updateUserInfo(user: AccountManager.shared.currentUser) return _loginheaderView } return _unLoginheaderView } }
30.5
127
0.629853
6af63bb2445646080060ca7023085113b9735650
303
// // GlobalAliases.swift // AVNetworkKit // // Created by Atharva Vaidya on 11/14/19. // Copyright © 2019 Atharva Vaidya. All rights reserved. // import Foundation public typealias ParamsDict = [String: Any?] public typealias HeadersDict = [String: String] public typealias JSON = [String: Any?]
21.642857
57
0.722772
714ddf88adcd2eb901b64a6657f0f52145329440
2,567
// // MediaGroupFilter.swift // PhotosExporter // // Created by Kai Unger on 01.01.21. // Copyright © 2021 Andreas Bentele. All rights reserved. // import Foundation import MediaLibrary struct MediaGroupFilter { func matches(_ group: MLMediaGroup) -> Bool { switch group.typeIdentifier { case MLPhotosMomentGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Moments) case MLPhotosCollectionGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Collections) case MLPhotosYearGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Years) case "com.apple.Photos.PlacesCountryAlbum": return self.photoGroups.contains(PhotoGroups.Places) case "com.apple.Photos.PlacesProvinceAlbum": return self.photoGroups.contains(PhotoGroups.Places) case "com.apple.Photos.PlacesCityAlbum": return self.photoGroups.contains(PhotoGroups.Places) case "com.apple.Photos.PlacesPointOfInterestAlbum": return self.photoGroups.contains(PhotoGroups.Places) case MLPhotosFacesAlbumTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Faces) // Photos' "Faces" album has typeIdentifier MLPhotosFacesAlbumTypeIdentifier // and all the faces albums of individual persons have the same identifier, too. // The individual faces albums are children of the "Faces" album. // We are only interested in the individual faces albums, thus we // match only the faces albums which are children of the top level "Faces" album: && (group.parent?.typeIdentifier == MLPhotosFacesAlbumTypeIdentifier) case MLPhotosVideosGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Videos) case MLPhotosFrontCameraGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Selfies) case MLPhotosPanoramasGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Panoramas) case MLPhotosScreenshotGroupTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Screenshots) case MLPhotosAlbumTypeIdentifier: return self.photoGroups.contains(PhotoGroups.Albums) case MLPhotosSmartAlbumTypeIdentifier: return self.photoGroups.contains(PhotoGroups.SmartAlbums) default: return false } } var photoGroups: [PhotoGroups] }
45.839286
97
0.700039
d53ffb6519b581ea16c08165d9255bcce4036a21
11,367
// // CalendarView+Extension.swift // KVKCalendar // // Created by Sergei Kviatkovskii on 14.12.2020. // #if os(iOS) import UIKit import EventKit extension CalendarView { // MARK: Public methods /// **DEPRECATED** @available(*, deprecated, renamed: "CalendarDataSource.willDisplayEventViewer") public func addEventViewToDay(view: UIView) {} public func set(type: CalendarType, date: Date? = nil) { parameters.type = type switchTypeCalendar(type: type) if let dt = date { scrollTo(dt) } } public func reloadData() { func reload(systemEvents: [EKEvent] = []) { let events = dataSource?.eventsForCalendar(systemEvents: systemEvents) ?? [] switch parameters.type { case .day: dayView.reloadData(events) case .week: weekView.reloadData(events) case .month: monthView.reloadData(events) case .list: listView.reloadData(events) default: break } } if !style.systemCalendars.isEmpty { requestAccessSystemCalendars(style.systemCalendars, store: eventStore) { [weak self] (result) in guard let self = self else { DispatchQueue.main.async { reload() } return } if result { self.getSystemEvents(store: self.eventStore, calendars: self.style.systemCalendars) { (systemEvents) in DispatchQueue.main.async { reload(systemEvents: systemEvents) } } } else { DispatchQueue.main.async { reload() } } } } else { reload() } } public func scrollTo(_ date: Date, animated: Bool? = nil) { switch parameters.type { case .day: dayView.setDate(date) case .week: weekView.setDate(date) case .month: monthView.setDate(date, animated: animated) case .year: yearView.setDate(date) case .list: listView.setDate(date) } } public func deselectEvent(_ event: Event, animated: Bool) { switch parameters.type { case .day: dayView.timelinePage.timelineView?.deselectEvent(event, animated: animated) case .week: weekView.timelinePage.timelineView?.deselectEvent(event, animated: animated) default: break } } public func activateMovingEventInMonth(eventView: EventViewGeneral, snapshot: UIView, gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: monthView.didStartMoveEvent(eventView, snapshot: snapshot, gesture: gesture) case .cancelled, .ended, .failed: monthView.didEndMoveEvent(gesture: gesture) default: break } } public func movingEventInMonth(eventView: EventViewGeneral, snapshot: UIView, gesture: UIPanGestureRecognizer) { switch gesture.state { case .changed: monthView.didChangeMoveEvent(gesture: gesture) default: break } } public func showSkeletonLoading(_ visible: Bool) { switch parameters.type { case .month: monthView.showSkeletonVisible(visible) case .list: listView.showSkeletonVisible(visible) default: break } } // MARK: Private methods private var calendarQueue: DispatchQueue { DispatchQueue(label: "kvk.calendar.com", qos: .default, attributes: .concurrent) } private func getSystemEvents(store: EKEventStore, calendars: Set<String>, completion: @escaping ([EKEvent]) -> Void) { guard !calendars.isEmpty else { completion([]) return } let systemCalendars = store.calendars(for: .event).filter({ calendars.contains($0.title) }) guard !systemCalendars.isEmpty else { completion([]) return } calendarQueue.async { [weak self] in guard let self = self else { completion([]) return } var startOffset = 0 var endOffset = 1 if self.calendarData.yearsCount.count > 1 { startOffset = self.calendarData.yearsCount.first ?? 0 endOffset = self.calendarData.yearsCount.last ?? 1 } guard let startDate = self.style.calendar.date(byAdding: .year, value: startOffset, to: self.calendarData.date), let endDate = self.style.calendar.date(byAdding: .year, value: endOffset, to: self.calendarData.date) else { completion([]) return } let predicate = store.predicateForEvents(withStart: startDate, end: endDate, calendars: systemCalendars) let items = store.events(matching: predicate) completion(items) } } private func requestAccessSystemCalendars(_ calendars: Set<String>, store: EKEventStore, completion: @escaping (Bool) -> Void) { let status = EKEventStore.authorizationStatus(for: .event) store.requestAccess(to: .event) { (access, error) in print("System calendars = \(calendars) - access = \(access), error = \(error?.localizedDescription ?? "nil"), status = \(status.rawValue)") completion(access) } } private func switchTypeCalendar(type: CalendarType) { parameters.type = type currentViewCache?.removeFromSuperview() switch parameters.type { case .day: addSubview(dayView) currentViewCache = dayView case .week: addSubview(weekView) currentViewCache = weekView case .month: addSubview(monthView) currentViewCache = monthView case .year: addSubview(yearView) currentViewCache = yearView case .list: addSubview(listView) currentViewCache = listView reloadData() } if let cacheView = currentViewCache as? CalendarSettingProtocol, cacheView.style != style { cacheView.updateStyle(style) } } } extension CalendarView: DisplayDataSource { public func dequeueCell<T>(dateParameter: DateParameter, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarCellProtocol? where T : UIScrollView { dataSource?.dequeueCell(dateParameter: dateParameter, type: type, view: view, indexPath: indexPath) } public func dequeueHeader<T>(date: Date?, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarHeaderProtocol? where T : UIScrollView { dataSource?.dequeueHeader(date: date, type: type, view: view, indexPath: indexPath) } public func willDisplayCollectionView(frame: CGRect, type: CalendarType) -> UICollectionView? { dataSource?.willDisplayCollectionView(frame: frame, type: type) } public func willDisplayEventView(_ event: Event, frame: CGRect, date: Date?) -> EventViewGeneral? { dataSource?.willDisplayEventView(event, frame: frame, date: date) } public func willDisplayHeaderSubview(date: Date?, frame: CGRect, type: CalendarType) -> UIView? { dataSource?.willDisplayHeaderSubview(date: date, frame: frame, type: type) } /// **Temporary disabled** private func willDisplayHeaderView(date: Date?, frame: CGRect, type: CalendarType) -> UIView? { dataSource?.willDisplayHeaderView(date: date, frame: frame, type: type) } public func willDisplayEventViewer(date: Date, frame: CGRect) -> UIView? { dataSource?.willDisplayEventViewer(date: date, frame: frame) } @available(iOS 14.0, *) public func willDisplayEventOptionMenu(_ event: Event, type: CalendarType) -> (menu: UIMenu, customButton: UIButton?)? { dataSource?.willDisplayEventOptionMenu(event, type: type) } public func dequeueMonthViewEvents(_ events: [Event], date: Date, frame: CGRect) -> UIView? { dataSource?.dequeueMonthViewEvents(events, date: date, frame: frame) } } extension CalendarView: DisplayDelegate { public func sizeForHeader(_ date: Date?, type: CalendarType) -> CGSize? { delegate?.sizeForHeader(date, type: type) } public func sizeForCell(_ date: Date?, type: CalendarType) -> CGSize? { delegate?.sizeForCell(date, type: type) } func didDisplayEvents(_ events: [Event], dates: [Date?], type: CalendarType) { guard parameters.type == type else { return } delegate?.didDisplayEvents(events, dates: dates) } public func didSelectDates(_ dates: [Date], type: CalendarType, frame: CGRect?) { delegate?.didSelectDates(dates, type: type, frame: frame) } public func didDeselectEvent(_ event: Event, animated: Bool) { delegate?.didDeselectEvent(event, animated: animated) } public func didSelectEvent(_ event: Event, type: CalendarType, frame: CGRect?) { delegate?.didSelectEvent(event, type: type, frame: frame) } public func didSelectMore(_ date: Date, frame: CGRect?) { delegate?.didSelectMore(date, frame: frame) } public func didAddNewEvent(_ event: Event, _ date: Date?) { delegate?.didAddNewEvent(event, date) } public func didChangeEvent(_ event: Event, start: Date?, end: Date?) { delegate?.didChangeEvent(event, start: start, end: end) } public func didChangeViewerFrame(_ frame: CGRect) { var newFrame = frame newFrame.origin = .zero delegate?.didChangeViewerFrame(newFrame) } } extension CalendarView: CalendarSettingProtocol { var style: Style { parameters.style } public func reloadFrame(_ frame: CGRect) { self.frame = frame if let currentView = currentViewCache as? CalendarSettingProtocol { currentView.reloadFrame(frame) } } public func updateStyle(_ style: Style) { parameters.style = style.checkStyle if let currentView = currentViewCache as? CalendarSettingProtocol { currentView.updateStyle(self.style) } } func setUI() { } } #endif
34.135135
164
0.565409
794f0d6807aa7c45093373026333399a9f1db3db
12,198
// // OfferingsTests.swift // PurchasesTests // // Created by RevenueCat. // Copyright © 2019 Purchases. All rights reserved. // import Foundation import Nimble import StoreKit import XCTest @testable import RevenueCat class OfferingsTests: XCTestCase { let offeringsFactory = OfferingsFactory() func testPackageIsNotCreatedIfNoValidProducts() { let package = offeringsFactory.createPackage(with: [ "identifier": "$rc_monthly", "platform_product_identifier": "com.myproduct.monthly" ], storeProductsByID: [ "com.myproduct.annual": StoreProduct(sk1Product: SK1Product()) ], offeringIdentifier: "offering") expect(package).to(beNil()) } func testPackageIsCreatedIfValidProducts() throws { let productIdentifier = "com.myproduct.monthly" let product = MockSK1Product(mockProductIdentifier: productIdentifier) let packageIdentifier = "$rc_monthly" let package = try XCTUnwrap( offeringsFactory.createPackage(with: [ "identifier": packageIdentifier, "platform_product_identifier": productIdentifier ], storeProductsByID: [ productIdentifier: StoreProduct(sk1Product: product) ], offeringIdentifier: "offering") ) expect(package.storeProduct.product).to(beAnInstanceOf(SK1StoreProduct.self)) let sk1StoreProduct = try XCTUnwrap(package.storeProduct.product as? SK1StoreProduct) expect(sk1StoreProduct.underlyingSK1Product).to(equal(product)) expect(package.identifier).to(equal(packageIdentifier)) expect(package.packageType).to(equal(PackageType.monthly)) } func testOfferingIsNotCreatedIfNoValidPackage() { let products = ["com.myproduct.bad": StoreProduct(sk1Product: SK1Product())] let offering = offeringsFactory.createOffering(from: products, offeringData: [ "identifier": "offering_a", "description": "This is the base offering", "packages": [ ["identifier": "$rc_monthly", "platform_product_identifier": "com.myproduct.monthly"], ["identifier": "$rc_annual", "platform_product_identifier": "com.myproduct.annual"] ] ]) expect(offering).to(beNil()) } func testOfferingIsCreatedIfValidPackages() { let annualProduct = MockSK1Product(mockProductIdentifier: "com.myproduct.annual") let monthlyProduct = MockSK1Product(mockProductIdentifier: "com.myproduct.monthly") let products = [ "com.myproduct.annual": StoreProduct(sk1Product: annualProduct), "com.myproduct.monthly": StoreProduct(sk1Product: monthlyProduct) ] let offeringIdentifier = "offering_a" let serverDescription = "This is the base offering" let offering = offeringsFactory.createOffering(from: products, offeringData: [ "identifier": offeringIdentifier, "description": serverDescription, "packages": [ ["identifier": "$rc_monthly", "platform_product_identifier": "com.myproduct.monthly"], ["identifier": "$rc_annual", "platform_product_identifier": "com.myproduct.annual"], ["identifier": "$rc_six_month", "platform_product_identifier": "com.myproduct.sixMonth"] ] ]) expect(offering).toNot(beNil()) expect(offering?.identifier).to(equal(offeringIdentifier)) expect(offering?.serverDescription).to(equal(serverDescription)) expect(offering?.availablePackages).to(haveCount(2)) expect(offering?.monthly).toNot(beNil()) expect(offering?.annual).toNot(beNil()) expect(offering?.sixMonth).to(beNil()) } func testListOfOfferingsIsNilIfNoValidOffering() { let offerings = offeringsFactory.createOfferings(from: [:], data: [ "offerings": [ [ "identifier": "offering_a", "description": "This is the base offering", "packages": [ ["identifier": "$rc_six_month", "platform_product_identifier": "com.myproduct.sixMonth"] ] ], [ "identifier": "offering_b", "description": "This is the base offering b", "packages": [ ["identifier": "$rc_monthly", "platform_product_identifier": "com.myproduct.monthly"] ] ] ], "current_offering_id": "offering_a" ]) expect(offerings).to(beNil()) } func testOfferingsIsCreated() throws { let annualProduct = MockSK1Product(mockProductIdentifier: "com.myproduct.annual") let monthlyProduct = MockSK1Product(mockProductIdentifier: "com.myproduct.monthly") let products = [ "com.myproduct.annual": StoreProduct(sk1Product: annualProduct), "com.myproduct.monthly": StoreProduct(sk1Product: monthlyProduct) ] let offerings = try XCTUnwrap( offeringsFactory.createOfferings(from: products, data: [ "offerings": [ [ "identifier": "offering_a", "description": "This is the base offering", "packages": [ ["identifier": "$rc_six_month", "platform_product_identifier": "com.myproduct.annual"] ] ], [ "identifier": "offering_b", "description": "This is the base offering b", "packages": [ ["identifier": "$rc_monthly", "platform_product_identifier": "com.myproduct.monthly"] ] ] ], "current_offering_id": "offering_a" ]) ) expect(offerings["offering_a"]).toNot(beNil()) expect(offerings["offering_b"]).toNot(beNil()) expect(offerings.current).to(be(offerings["offering_a"])) } func testLifetimePackage() throws { try testPackageType(packageType: PackageType.lifetime) } func testAnnualPackage() throws { try testPackageType(packageType: PackageType.annual) } func testSixMonthPackage() throws { try testPackageType(packageType: PackageType.sixMonth) } func testThreeMonthPackage() throws { try testPackageType(packageType: PackageType.threeMonth) } func testTwoMonthPackage() throws { try testPackageType(packageType: PackageType.twoMonth) } func testMonthlyPackage() throws { try testPackageType(packageType: PackageType.monthly) } func testWeeklyPackage() throws { try testPackageType(packageType: PackageType.weekly) } func testCustomPackage() throws { try testPackageType(packageType: PackageType.custom) } @available(iOS 11.2, macCatalyst 13.0, tvOS 11.2, macOS 10.13.2, *) func testCustomNonSubscriptionPackage() throws { let sk1Product = MockSK1Product(mockProductIdentifier: "com.myProduct") sk1Product.mockSubscriptionPeriod = nil try testPackageType(packageType: PackageType.custom, product: StoreProduct(sk1Product: sk1Product)) } func testUnknownPackageType() throws { try testPackageType(packageType: PackageType.unknown) } func testOfferingsIsNilIfNoOfferingCanBeCreated() throws { let data = [ "offerings": [], "current_offering_id": nil ] let offerings = offeringsFactory.createOfferings(from: [:], data: data as [String: Any]) expect(offerings).to(beNil()) } func testCurrentOfferingWithBrokenProductReturnsNilForCurrentOfferingButContainsOtherOfferings() throws { let storeProductsByID = [ "com.myproduct.annual": StoreProduct( sk1Product: MockSK1Product(mockProductIdentifier: "com.myproduct.annual") ) ] let data: [String: Any] = [ "offerings": [ [ "identifier": "offering_a", "description": "This is the base offering", "packages": [ ["identifier": "$rc_six_month", "platform_product_identifier": "com.myproduct.annual"] ] ] ], "current_offering_id": "offering_with_broken_product" ] let offerings = offeringsFactory.createOfferings(from: storeProductsByID, data: data) let unwrappedOfferings = try XCTUnwrap(offerings) expect(unwrappedOfferings.current).to(beNil()) } func testBadOfferingsDataReturnsNil() { let data = [:] as [String: Any] let offerings = offeringsFactory.createOfferings(from: [:], data: data as [String: Any]) expect(offerings).to(beNil()) } } private extension OfferingsTests { func testPackageType(packageType: PackageType, product: StoreProduct? = nil) throws { var identifier = Package.string(from: packageType) if identifier == nil { if packageType == PackageType.unknown { identifier = "$rc_unknown_id_from_the_future" } else { identifier = "custom" } } let productIdentifier = product?.productIdentifier ?? "com.myproduct" let products = [ productIdentifier: product ?? StoreProduct(sk1Product: MockSK1Product(mockProductIdentifier: productIdentifier)) ] let offerings = try XCTUnwrap( offeringsFactory.createOfferings(from: products, data: [ "offerings": [ [ "identifier": "offering_a", "description": "This is the base offering", "packages": [ ["identifier": identifier, "platform_product_identifier": productIdentifier] ] ] ], "current_offering_id": "offering_a" ]) ) expect(offerings.current).toNot(beNil()) if packageType == PackageType.lifetime { expect(offerings.current?.lifetime).toNot(beNil()) } else { expect(offerings.current?.lifetime).to(beNil()) } if packageType == PackageType.annual { expect(offerings.current?.annual).toNot(beNil()) } else { expect(offerings.current?.annual).to(beNil()) } if packageType == PackageType.sixMonth { expect(offerings.current?.sixMonth).toNot(beNil()) } else { expect(offerings.current?.sixMonth).to(beNil()) } if packageType == PackageType.threeMonth { expect(offerings.current?.threeMonth).toNot(beNil()) } else { expect(offerings.current?.threeMonth).to(beNil()) } if packageType == PackageType.twoMonth { expect(offerings.current?.twoMonth).toNot(beNil()) } else { expect(offerings.current?.twoMonth).to(beNil()) } if packageType == PackageType.monthly { expect(offerings.current?.monthly).toNot(beNil()) } else { expect(offerings.current?.monthly).to(beNil()) } if packageType == PackageType.weekly { expect(offerings.current?.weekly).toNot(beNil()) } else { expect(offerings.current?.weekly).to(beNil()) } let package = offerings["offering_a"]?.package(identifier: identifier) expect(package?.packageType).to(equal(packageType)) } }
38
109
0.581161
6a65a8e5dc8e41ee7324be730fcd52ebe9bbe2cf
3,053
import MBProgressHUD import UIKit extension UIViewController { func showError(message: String, completion: (() -> Void)? = nil) { let ac = UIAlertController(title: "Error", message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .cancel) { _ in completion?() } ac.addAction(okAction) present(ac, animated: true, completion: nil) } func showAutoCloseMessage(image: UIImage?, title: String?, message: String?, interval: TimeInterval = 2, completion: (() -> Void)? = nil) { if let image = image { let hud = MBProgressHUD.showAdded(to: self.view, animated: true) hud.mode = .customView hud.customView = UIImageView(image: image) hud.label.text = title hud.detailsLabel.text = message after(interval: interval) { MBProgressHUD.hide(for: self.view, animated: true) completion?() } } else { let ac = UIAlertController(title: title, message: message, preferredStyle: .alert) after(interval: interval) { ac.dismiss(animated: true, completion: completion) } present(ac, animated: true, completion: nil) } } func removeBackButtonTitle() { if let topItem = self.navigationController?.navigationBar.topItem { topItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } func topMostViewController() -> UIViewController? { if let navigation = self as? UINavigationController { return navigation.visibleViewController?.topMostViewController() } if let tab = self as? UITabBarController { if let selectedTab = tab.selectedViewController { return selectedTab.topMostViewController() } return tab.topMostViewController() } if self.presentedViewController == nil { return self } if let navigation = self.presentedViewController as? UINavigationController { if let visibleController = navigation.visibleViewController { return visibleController.topMostViewController() } } if let tab = self.presentedViewController as? UITabBarController { if let selectedTab = tab.selectedViewController { return selectedTab.topMostViewController() } return tab.topMostViewController() } return self.presentedViewController?.topMostViewController() } }
39.141026
115
0.558795
09fe2e785e1d19ac2a56a3d54bb0424b7f017a1e
1,338
// // AppDelegate.swift // Doit! // // Created by 순진이 on 2021/12/12. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.162162
179
0.743647
28e723c9f4cf6cec0343ba698c88d1d6f8ddd8b6
10,167
// // LoadView.swift // weibo // // Created by 侯玉昆 on 16/3/3. // Copyright © 2016年 侯玉昆. All rights reserved. // import UIKit import SnapKit @objc protocol VisitorViewDelegate :NSObjectProtocol{ optional func visitorView(visitorView:VisitorView,loginDidClickButton: UIButton); } class VisitorView: UIView { weak var delegate:VisitorViewDelegate? override init(frame: CGRect) { super.init(frame: frame) setupUI() startAnimation() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setPage(imageName:String?, title:String?){ if imageName == nil{ startAnimation() }else{ circleView.hidden = true iconView.image = UIImage(named: imageName!) messageLabel.text = title } } //开启旋转画核心动画 func startAnimation(){ let anim = CABasicAnimation(keyPath: "transform.rotation") anim.toValue = 2 * M_PI anim.repeatCount = MAXFLOAT anim.duration = 20 anim.removedOnCompletion = false //添加动画 circleView.layer.addAnimation(anim, forKey: nil) } @objc private func loginClickBtn(btn:UIButton){ delegate?.visitorView?(self, loginDidClickButton: btn) } //MARK: - 懒加载 //大图 private lazy var iconView:UIImageView = UIImageView(image:UIImage(named: "visitordiscover_feed_image_house")) //圆圈 private lazy var circleView:UIImageView = UIImageView(image:UIImage(named: "visitordiscover_feed_image_smallicon")) //文字 private lazy var messageLabel:UILabel = { let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 14) label.numberOfLines = 2 label.textAlignment = .Center label.text = "关注一些人,看看有什么惊喜" return label }() //注册按钮 private lazy var redistBtn:UIButton = { let btn = UIButton(textColor: UIColor.darkGrayColor(), fontSize: 14) btn.addTarget(self, action:"loginClickBtn:", forControlEvents: UIControlEvents.TouchUpInside) btn.setTitle("注册", forState: .Normal) btn.setBackgroundImage(UIImage(named: "common_button_white"), forState: .Normal) return btn }() //登录按钮 private lazy var loginBtn:UIButton = { let btn = UIButton(textColor: UIColor.darkGrayColor(), fontSize: 14) btn.addTarget(self, action:"loginClickBtn:", forControlEvents: UIControlEvents.TouchUpInside) btn.setTitle("登录", forState: .Normal) btn.setBackgroundImage(UIImage(named: "common_button_white"), forState: .Normal) return btn }() //遮罩层 private lazy var maskerView:UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) } extension VisitorView { //第三方框架约束 private func setupUI(){ backgroundColor = UIColor(red: 237/255, green: 237/255, blue: 237/255, alpha: 1) //MARK: - 添加子控件 addSubview(circleView) addSubview(maskerView) addSubview(iconView) addSubview(messageLabel) addSubview(redistBtn) addSubview(loginBtn) //MARK: - 开始设置约束 //首页房子(居中) iconView.snp_makeConstraints { (make) -> Void in // make.centerX.equalTo(self.snp_centerX) // make.centerY.equalTo(self.snp_centerY) make.center.equalTo(self) } //圆圈(参照首页居中) circleView.snp_makeConstraints { (make) -> Void in // make.centerX.equalTo(iconView.snp_centerX) // make.centerY.equalTo(iconView.snp_centerY) make.center.equalTo(iconView) } //文字(x居中,宽度,上边距) messageLabel.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(iconView) make.top.equalTo(circleView.snp_bottom) make.width.equalTo(224) } //注册按钮(上,宽,头对齐) redistBtn.snp_makeConstraints { (make) -> Void in make.leading.equalTo(messageLabel) make.width.equalTo(100) make.top.equalTo(messageLabel.snp_bottom).offset(16) } //登录按钮(上,宽度,和消息头对齐) loginBtn.snp_makeConstraints { (make) -> Void in make.top.equalTo(redistBtn) make.width.equalTo(100) make.trailing.equalTo(messageLabel.snp_trailing) } //遮罩(参照首页居中) maskerView.snp_makeConstraints { (make) -> Void in // make.centerX.equalTo(iconView.snp_centerX) // make.centerY.equalTo(iconView.snp_centerY) make.center.equalTo(iconView) } } //普通约束 private func setupUI2(){ backgroundColor = UIColor(red: 237/255, green: 237/255, blue: 237/255, alpha: 1) //MARK: - 添加子控件 addSubview(circleView) addSubview(maskerView) addSubview(iconView) addSubview(messageLabel) addSubview(redistBtn) addSubview(loginBtn) //MARK: - 开始设置约束 //首页房子 iconView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) // 圆圈 circleView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: circleView, attribute:NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal , toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: circleView, attribute:NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal , toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) // 文字 messageLabel.translatesAutoresizingMaskIntoConstraints = false //参照当前View中心对齐 addConstraint(NSLayoutConstraint(item: messageLabel, attribute:NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal , toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) //参照圆圈距顶部距离 addConstraint(NSLayoutConstraint(item: messageLabel, attribute:NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal , toItem: circleView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16)) // addConstraint(NSLayoutConstraint(item: messageLabel, attribute:NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal , toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 225)) // 注册按钮(上,左,头对其) redistBtn.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: redistBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 20)) addConstraint(NSLayoutConstraint(item: redistBtn, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: redistBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)) // 登录按钮(跟注册按钮等不对齐) loginBtn.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 20)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: loginBtn, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100)) // 遮罩 maskerView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: maskerView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: maskerView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) } }
33.334426
228
0.599193
ed69af204341ed5dab06dbdf6bf20bf43ed879eb
2,212
// // Created by Alan on 2020/02/05. // Copyright (c) 2020 Wiss. All rights reserved. // import Foundation public struct Wiss<WissBase> { public let base: WissBase public init(_ base: WissBase) { self.base = base } } extension Wiss { public static func value<ValueType>(forKey key: WissStoreKey<ValueType>) throws -> ValueType { try WissStore.shared.value(forType: WissBase.self, key: key) } public static func value<ValueType>(forKey key: WissStoreKey<ValueType?>) throws -> ValueType? { try WissStore.shared.value(forType: WissBase.self, key: key) } public static func value<ValueType: Codable>(forKey key: WissStoreKey<ValueType>) throws -> ValueType { try WissStore.shared.value(forType: WissBase.self, key: key) } public static func value<ValueType: Codable>(forKey key: WissStoreKey<ValueType?>) throws -> ValueType? { try WissStore.shared.value(forType: WissBase.self, key: key) } public static func set<ValueType>(_ value: ValueType, forKey key: WissStoreKey<ValueType>) throws { try WissStore.shared.set(value, forType: WissBase.self, key: key) } public static func set<ValueType: Codable>(_ value: ValueType, forKey key: WissStoreKey<ValueType>) throws { try WissStore.shared.set(value, forType: WissBase.self, key: key) } public static func set<ValueType: Codable>(_ value: ValueType?, forKey key: WissStoreKey<ValueType?>) throws { try WissStore.shared.set(value, forType: WissBase.self, key: key) } } extension Wiss where WissBase: Hashable { public func value<ValueType>(forKey key: WissStoreKey<ValueType>) throws -> ValueType { try WissStore.shared.value(forInstance: self.base, key: key) } public func value<ValueType>(forKey key: WissStoreKey<ValueType?>) throws -> ValueType? { try WissStore.shared.value(forInstance: self.base, key: key) } public func set<T>(_ value: T, forKey key: WissStoreKey<T>) throws { try WissStore.shared.set(value, forInstance: self.base, key: key) } public func flushStoredValues() { WissStore.shared.flush(for: self.base) } }
26.650602
114
0.679476
bbafb6239f0a21709f65e238f6891e0e0d0b4bcf
438
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "LoggerKit", products: [ .library( name: "LoggerKit", targets: ["LoggerKit"]), ], dependencies: [ ], targets: [ .target( name: "LoggerKit", dependencies: []), .testTarget( name: "LoggerKitTests", dependencies: ["LoggerKit"]), ] )
19.043478
41
0.493151
69a220d8401d138af96ce1d811c78c2b06806fda
12,799
// // StepChangeCheckViewController.swift // Cosmostation // // Created by yongjoo on 23/05/2019. // Copyright © 2019 wannabit. All rights reserved. // import UIKit import Alamofire import BitcoinKit import SwiftKeychainWrapper class StepChangeCheckViewController: BaseViewController, PasswordViewDelegate { @IBOutlet weak var btnBack: UIButton! @IBOutlet weak var btnConfirm: UIButton! @IBOutlet weak var rewardAddressChangeFee: UILabel! @IBOutlet weak var rewardAddressChangeDenom: UILabel! @IBOutlet weak var currentRewardAddress: UILabel! @IBOutlet weak var newRewardAddress: UILabel! @IBOutlet weak var memoLabel: UILabel! var pageHolderVC: StepGenTxViewController! override func viewDidLoad() { super.viewDidLoad() pageHolderVC = self.parent as? StepGenTxViewController WUtils.setDenomTitle(pageHolderVC.chainType!, rewardAddressChangeDenom) } func onUpdateView() { let feeAmout = WUtils.stringToDecimal((pageHolderVC.mFee?.amount[0].amount)!) if (pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_COSMOS_MAIN) { rewardAddressChangeFee.attributedText = WUtils.displayAmount(feeAmout.stringValue, rewardAddressChangeFee.font, 6, pageHolderVC.chainType!) } else if (pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_IRIS_MAIN) { rewardAddressChangeFee.attributedText = WUtils.displayAmount(feeAmout.stringValue, rewardAddressChangeFee.font, 18, pageHolderVC.chainType!) } currentRewardAddress.text = pageHolderVC.mCurrentRewardAddress newRewardAddress.text = pageHolderVC.mToChangeRewardAddress currentRewardAddress.adjustsFontSizeToFitWidth = true newRewardAddress.adjustsFontSizeToFitWidth = true memoLabel.text = pageHolderVC.mMemo } override func enableUserInteraction() { self.onUpdateView() self.btnBack.isUserInteractionEnabled = true self.btnConfirm.isUserInteractionEnabled = true } @IBAction func onClickBefore(_ sender: UIButton) { self.btnBack.isUserInteractionEnabled = false self.btnConfirm.isUserInteractionEnabled = false pageHolderVC.onBeforePage() } @IBAction func onClickConfirm(_ sender: UIButton) { let noticeAlert = UIAlertController(title: NSLocalizedString("reward_address_warnning_title", comment: ""), message: NSLocalizedString("reward_address_notice_msg", comment: ""), preferredStyle: .alert) noticeAlert.addAction(UIAlertAction(title: NSLocalizedString("continue", comment: ""), style: .destructive, handler: { _ in self.onShowPasswordCheck() })) noticeAlert.addAction(UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .default, handler: { _ in self.dismiss(animated: true, completion: nil) })) self.present(noticeAlert, animated: true) { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissAlertController)) noticeAlert.view.superview?.subviews[0].addGestureRecognizer(tapGesture) } } func onShowPasswordCheck() { let passwordVC = UIStoryboard(name: "Password", bundle: nil).instantiateViewController(withIdentifier: "PasswordViewController") as! PasswordViewController self.navigationItem.title = "" self.navigationController!.view.layer.add(WUtils.getPasswordAni(), forKey: kCATransition) passwordVC.mTarget = PASSWORD_ACTION_CHECK_TX passwordVC.resultDelegate = self self.navigationController?.pushViewController(passwordVC, animated: false) } func passwordResponse(result: Int) { if (result == PASSWORD_RESUKT_OK) { self.onFetchAccountInfo(pageHolderVC.mAccount!) } } func onFetchAccountInfo(_ account: Account) { self.showWaittingAlert() if (pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_COSMOS_MAIN) { let request = Alamofire.request(CSS_LCD_URL_ACCOUNT_INFO + account.account_address, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]) request.responseJSON { (response) in switch response.result { case .success(let res): // guard let responseData = res as? NSDictionary, // let info = responseData.object(forKey: "result") as? [String : Any] else { // _ = BaseData.instance.deleteBalance(account: account) // self.hideWaittingAlert() // self.onShowToast(NSLocalizedString("error_network", comment: "")) // return // } //TODO rollback cosmos-hub2 guard let info = res as? [String : Any] else { _ = BaseData.instance.deleteBalance(account: account) self.hideWaittingAlert() self.onShowToast(NSLocalizedString("error_network", comment: "")) return } let accountInfo = AccountInfo.init(info) _ = BaseData.instance.updateAccount(WUtils.getAccountWithAccountInfo(account, accountInfo)) BaseData.instance.updateBalances(account.account_id, WUtils.getBalancesWithAccountInfo(account, accountInfo)) self.onGenModifyRewardAddressTx() case .failure( _): self.hideWaittingAlert() self.onShowToast(NSLocalizedString("error_network", comment: "")) } } } else if (pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_IRIS_MAIN) { let request = Alamofire.request(IRIS_LCD_URL_ACCOUNT_INFO + account.account_address, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]) request.responseJSON { (response) in switch response.result { case .success(let res): guard let info = res as? [String : Any] else { _ = BaseData.instance.deleteBalance(account: account) self.hideWaittingAlert() self.onShowToast(NSLocalizedString("error_network", comment: "")) return } let accountInfo = AccountInfo.init(info) _ = BaseData.instance.updateAccount(WUtils.getAccountWithAccountInfo(account, accountInfo)) BaseData.instance.updateBalances(account.account_id, WUtils.getBalancesWithAccountInfo(account, accountInfo)) self.onGenModifyRewardAddressTx() case .failure( _): self.hideWaittingAlert() self.onShowToast(NSLocalizedString("error_network", comment: "")) } } } } func onGenModifyRewardAddressTx() { print("onGenModifyRewardAddressTx") DispatchQueue.global().async { var stdTx:StdTx! guard let words = KeychainWrapper.standard.string(forKey: self.pageHolderVC.mAccount!.account_uuid.sha1())?.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ") else { return } do { let pKey = WKey.getHDKeyFromWords(mnemonic: words, path: UInt32(self.pageHolderVC.mAccount!.account_path)!, chain: self.pageHolderVC.chainType!) let msg = MsgGenerator.genGetModifyRewardAddressMsg(self.pageHolderVC.mAccount!.account_address, self.pageHolderVC.mToChangeRewardAddress!, self.pageHolderVC.chainType!) var msgList = Array<Msg>() msgList.append(msg) let stdMsg = MsgGenerator.getToSignMsg(WUtils.getChainName(self.pageHolderVC.mAccount!.account_base_chain), String(self.pageHolderVC.mAccount!.account_account_numner), String(self.pageHolderVC.mAccount!.account_sequence_number), msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!) let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys let data = try? encoder.encode(stdMsg) let rawResult = String(data:data!, encoding:.utf8)?.replacingOccurrences(of: "\\/", with: "/") let rawData: Data? = rawResult!.data(using: .utf8) let hash = Crypto.sha256(rawData!) let signedData: Data? = try Crypto.sign(hash, privateKey: pKey.privateKey()) var genedSignature = Signature.init() var genPubkey = PublicKey.init() genPubkey.type = COSMOS_KEY_TYPE_PUBLIC genPubkey.value = pKey.privateKey().publicKey().raw.base64EncodedString() genedSignature.pub_key = genPubkey genedSignature.signature = WKey.convertSignature(signedData!) genedSignature.account_number = String(self.pageHolderVC.mAccount!.account_account_numner) genedSignature.sequence = String(self.pageHolderVC.mAccount!.account_sequence_number) var signatures: Array<Signature> = Array<Signature>() signatures.append(genedSignature) stdTx = MsgGenerator.genSignedTx(msgList, self.pageHolderVC.mFee!, self.pageHolderVC.mMemo!, signatures) } catch { if(SHOW_LOG) { print(error) } } DispatchQueue.main.async(execute: { let postTx = PostTx.init("sync", stdTx.value) let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys let data = try? encoder.encode(postTx) do { let params = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] var url = ""; if (self.pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_COSMOS_MAIN) { url = CSS_LCD_URL_BORAD_TX } else if (self.pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_IRIS_MAIN) { url = IRIS_LCD_URL_BORAD_TX } let request = Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]) request.responseJSON { response in var txResult = [String:Any]() switch response.result { case .success(let res): if(SHOW_LOG) { print("AddressChange ", res) } if let result = res as? [String : Any] { txResult = result } case .failure(let error): if(SHOW_LOG) { print("AddressChange error ", error) } if (response.response?.statusCode == 500) { txResult["net_error"] = 500 } } if (self.waitAlert != nil) { self.waitAlert?.dismiss(animated: true, completion: { if (self.pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_COSMOS_MAIN) { txResult["type"] = COSMOS_MSG_TYPE_WITHDRAW_MIDIFY } else if (self.pageHolderVC.chainType! == ChainType.SUPPORT_CHAIN_IRIS_MAIN) { txResult["type"] = IRIS_MSG_TYPE_WITHDRAW_MIDIFY } print("txResult ", txResult) self.onStartTxResult(txResult) }) } } }catch { print(error) } }); } } }
52.028455
209
0.565591
14bf181e11227e23fbbdd35f15445171730e37a1
6,328
// // ObjectEvent.swift // // PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks // Copyright © 2019 PubNub Inc. // https://www.pubnub.com/ // https://www.pubnub.com/terms // // 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 /// An event that contains a unique identifier public typealias IdentifierEvent = SimpleIdentifiableObject // MARK: - User Events /// An event that made changes to a User object public typealias UserEvent = UserPatch public typealias UserPatch = ObjectPatch<UserChangeEvent> public extension UserPatch { func update<T: PubNubUser>(_ user: T?) throws -> T? { if let pubnubUser = updatePatch(user) { return try T(from: pubnubUser) } return nil } } /// All the changes that can be received for User objects public enum UserEvents { /// A User object has been updated case updated(UserEvent) /// The ID of the User object that was deleted case deleted(IdentifierEvent) } // MARK: - Space Events /// An event that made changes to a Space object public typealias SpaceEvent = SpacePatch public typealias SpacePatch = ObjectPatch<SpaceChangeEvent> public extension SpacePatch { func update<T: PubNubSpace>(_ space: T?) throws -> T? { if let pubnubSpace = updatePatch(space) { return try T(from: pubnubSpace) } return nil } } /// All the changes that can be received for Space objects public enum SpaceEvents { /// A Space object has been updated case updated(SpaceEvent) /// The ID of the Space object that was deleted case deleted(IdentifierEvent) } // MARK: - Membership /// All the changes that can be received for Membership objects public enum MembershipEvents { /// The IDs of the User and Space whose membership was added case userAddedOnSpace(MembershipEvent) /// The IDs of the User and Space whose membership was updated case userUpdatedOnSpace(MembershipEvent) /// The IDs of the User and Space that have become separated case userDeletedFromSpace(MembershipIdentifiable) } /// Uniquely identifies a Membership between a User and a Space public struct MembershipIdentifiable: Codable, Hashable { /// The unique identifier of the User object public let userId: String /// The unique identifier of the Space object public let spaceId: String public init(userId: String, spaceId: String) { self.userId = userId self.spaceId = spaceId } } /// An event to alert the changes made to a Membership between a User and a Space public struct MembershipEvent: Codable, Equatable { /// Unique identifier of the User object public let userId: String /// Unique identifier of the Space object public let spaceId: String /// Custom data contained in the Membership public let custom: [String: JSONCodableScalar]? /// Date the Membership was created public let created: Date /// Date the Membership was last updated public let updated: Date /// The unique cache key used to evaluate if a change has occurred with this object public let eTag: String public init( userId: String, spaceId: String, custom: [String: JSONCodableScalar]?, created: Date = Date(), updated: Date? = nil, eTag: String ) { self.userId = userId self.spaceId = spaceId self.custom = custom self.created = created self.updated = updated ?? created self.eTag = eTag } enum CodingKeys: String, CodingKey { case userId case spaceId case custom case created case updated case eTag } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) userId = try container.decode(String.self, forKey: .userId) spaceId = try container.decode(String.self, forKey: .spaceId) custom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom) created = try container.decode(Date.self, forKey: .created) updated = try container.decode(Date.self, forKey: .updated) eTag = try container.decode(String.self, forKey: .eTag) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(userId, forKey: .userId) try container.encode(spaceId, forKey: .spaceId) try container.encodeIfPresent(custom?.mapValues { $0.codableValue }, forKey: .custom) try container.encode(created, forKey: .created) try container.encode(updated, forKey: .updated) try container.encode(eTag, forKey: .eTag) } public static func == (lhs: MembershipEvent, rhs: MembershipEvent) -> Bool { return lhs.userId == rhs.userId && lhs.spaceId == rhs.spaceId && lhs.created == lhs.created && lhs.updated == rhs.updated && lhs.eTag == rhs.eTag && lhs.custom?.allSatisfy { rhs.custom?[$0]?.scalarValue == $1.scalarValue } ?? true } public var asMember: PubNubMember { return SpaceObjectMember(id: userId, custom: custom, user: nil, created: created, updated: updated, eTag: eTag) } public var asMembership: PubNubMembership { return UserObjectMembership(id: spaceId, custom: custom, space: nil, created: created, updated: updated, eTag: eTag) } }
33.13089
97
0.712231
1e07ea75753a5228f5668996f395b7178fd6f9b5
389
// // ActionStore.swift // // Created by ToKoRo on 2017-09-02. // import HomeKit protocol ActionStore { var actionStoreKind: ActionStoreKind { get } var actions: Set<HMAction> { get } } enum ActionStoreKind { case actionSet(HMActionSet) } // MARK: - HMActionSet extension HMActionSet: ActionStore { var actionStoreKind: ActionStoreKind { return .actionSet(self) } }
16.913043
68
0.70437
1c1234b1d125e5e32f0628605cd1c358ed69d437
2,680
// // AppDelegate.swift // Pro Search for iTune // // Created by surendra kumar on 2/19/17. // Copyright © 2017 weza. All rights reserved. // import UIKit extension UIApplication { var statusBarView: UIView? { return value(forKey: "statusBar") as? UIView } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let proxy = UINavigationBar.appearance() proxy.tintColor = RED window?.tintColor = RED UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default) UIApplication.shared.statusBarView?.backgroundColor = RED UIApplication.shared.statusBarStyle = .lightContent return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
44.666667
285
0.742164
01430bc206fe09aa0c9aa29a81e3d11402c41a0c
1,564
// ******************************************************************************** // // This source file is part of the Open Banking Connector project // ( https://github.com/finlabsuk/open-banking-connector ). // // Copyright (C) 2019 Finnovation Labs and the Open Banking Connector project authors. // // Licensed under Apache License v2.0. See LICENSE.txt for licence information. // SPDX-License-Identifier: Apache-2.0 // // ******************************************************************************** import PaymentInitiationTypeRequirements public typealias OBWriteDomesticResponseApi = OBWriteDomesticResponse3 public typealias OBWriteDomesticResponseDataApi = OBWriteDomesticResponse3Data public typealias OBWriteDomesticResponseDataMultiAuthorisationApi = OBWriteDomesticResponse3DataMultiAuthorisation extension OBWriteDomesticResponseApi: OBWriteDomesticResponseApiProtocol { public var linksOptional: Links? { return links } public var metaOptional: Meta? { return meta } } extension OBWriteDomesticResponseDataApi: OBWriteDomesticResponseDataApiProtocol { public var statusEnum: OBWritePaymentResponseDataApiStatusEnum? { return OBWritePaymentResponseDataApiStatusEnum(rawValue: status.rawValue) } } extension OBWriteDomesticResponseDataMultiAuthorisationApi: OBWriteDomesticResponseDataMultiAuthorisationApiProtocol { public var statusEnum: OBWriteDomesticResponseDataMultiAuthorisationApiStatusEnum? { return OBWriteDomesticResponseDataMultiAuthorisationApiStatusEnum(rawValue: status.rawValue) } }
46
118
0.742967
e6729c5f5118efa1c50390a556d20d1d4d344c22
18,359
// // File.swift // // // Created by Beau Nouvelle on 2020-03-29. // import Foundation import CoreGraphics #if os(iOS) import UIKit #else import AppKit #endif public struct ChordPosition: Codable, Identifiable, Equatable { public var id: UUID = UUID() public let frets: [Int] public let fingers: [Int] public let baseFret: Int public let barres: [Int] public var capo: Bool? public let midi: [Int] public let key: Chords.Key public let suffix: Chords.Suffix static private let numberOfStrings = 6 - 1 static private let numberOfFrets = 5 private enum CodingKeys: String, CodingKey { case frets, fingers, baseFret, barres, capo, midi, key, suffix } /// This is THE place to pull out a CAShapeLayer that includes all parts of the chord chart. This is what to use when adding a layer to your UIView/NSView. /// - Parameters: /// - rect: The area for which the chord will be drawn to. This determines it's size. Chords have a set aspect ratio, and so the size of the chord will be based on the shortest side of the rect. /// - showFingers: Determines if the finger numbers should be drawn on top of the dots. Default `true`. /// - showChordName: Determines if the chord name should be drawn above the chord. Choosing this option will reduce the size of the chord chart slightly to account for the text. Default `true`. /// - forPrint: If set to `true` the diagram will be colored Black, not matter the users device settings. If set to false, the color of the diagram will match the system label color. Dark text for light mode, and Light text for dark mode. Default `false`. /// - mirror: For lefthanded users. This will flip the chord along its y axis. Default `false`. /// - Returns: A CAShapeLayer that can be added as a sublayer to a view, or rendered to an image. public func shapeLayer(rect: CGRect, showFingers: Bool = true, showChordName: Bool = true, forPrint: Bool = false, mirror: Bool = false) -> CAShapeLayer { return privateLayer(rect: rect, showFingers: showFingers, showChordName: showChordName, forScreen: !forPrint, mirror: mirror) } /// Now deprecated. Please see the shapeLayer() function. /// - Parameters: /// - rect: The area for which the chord will be drawn to. This determines it's size. Chords have a set aspect ratio, and so the size of the chord will be based on the shortest side of the rect. /// - showFingers: Determines if the finger numbers should be drawn on top of the dots. /// - showChordName: Determines if the chord name should be drawn above the chord. Choosing this option will reduce the size of the chord chart slightly to account for the text. /// - forScreen: This takes care of Dark/Light mode. If it's on device ONLY, set this to true. When adding to a PDF, you'll want to set this to false. /// - mirror: For lefthanded users. This will flip the chord along its y axis. /// - Returns: A CAShapeLayer that can be added to a view, or rendered to an image. @available(*, deprecated, message: "For screen should have been defaulted to 'true'. Please use the better worded function instead.", renamed: "shapeLayer") public func layer(rect: CGRect, showFingers: Bool, showChordName: Bool, forScreen: Bool, mirror: Bool = false) -> CAShapeLayer { return privateLayer(rect: rect, showFingers: showFingers, showChordName: showChordName, forScreen: forScreen, mirror: mirror) } private func privateLayer(rect: CGRect, showFingers: Bool, showChordName: Bool, forScreen: Bool, mirror: Bool = false) -> CAShapeLayer { let heightMultiplier: CGFloat = showChordName ? 1.3 : 1.2 let horScale = rect.height / heightMultiplier let scale = min(horScale, rect.width) let newHeight = scale * heightMultiplier let size = CGSize(width: scale, height: newHeight) let stringMargin = size.width / 10 let fretMargin = size.height / 10 let fretLength = size.width - (stringMargin * 2) let stringLength = size.height - (fretMargin * (showChordName ? 2.8 : 2)) let origin = CGPoint(x: rect.origin.x, y: showChordName ? fretMargin * 1.2 : 0) let fretSpacing = stringLength / CGFloat(ChordPosition.numberOfFrets) let stringSpacing = fretLength / CGFloat(ChordPosition.numberOfStrings) let fretConfig = LineConfig(spacing: fretSpacing, margin: fretMargin, length: fretLength, count: ChordPosition.numberOfFrets) let stringConfig = LineConfig(spacing: stringSpacing, margin: stringMargin, length: stringLength, count: ChordPosition.numberOfStrings) let layer = CAShapeLayer() let stringsAndFrets = stringsAndFretsLayer(fretConfig: fretConfig, stringConfig: stringConfig, origin: origin, forScreen: forScreen) let barre = barreLayer(fretConfig: fretConfig, stringConfig: stringConfig, origin: origin, showFingers: showFingers, forScreen: forScreen) let dots = dotsLayer(stringConfig: stringConfig, fretConfig: fretConfig, origin: origin, showFingers: showFingers, forScreen: forScreen, rect: rect, mirror: mirror) layer.addSublayer(stringsAndFrets) layer.addSublayer(barre) layer.addSublayer(dots) if showChordName { let shapeLayer = nameLayer(fretConfig: fretConfig, origin: origin, center: size.width / 2 + origin.x, forScreen: forScreen) layer.addSublayer(shapeLayer) } layer.frame = CGRect(x: 0, y: 0, width: scale, height: newHeight) return layer } private func stringsAndFretsLayer(fretConfig: LineConfig, stringConfig: LineConfig, origin: CGPoint, forScreen: Bool) -> CAShapeLayer { let layer = CAShapeLayer() // Strings let stringPath = CGMutablePath() for string in 0...stringConfig.count { let x = stringConfig.spacing * CGFloat(string) + stringConfig.margin + origin.x stringPath.move(to: CGPoint(x: x, y: fretConfig.margin + origin.y)) stringPath.addLine(to: CGPoint(x: x, y: stringConfig.length + fretConfig.margin + origin.y)) } let stringLayer = CAShapeLayer() stringLayer.path = stringPath stringLayer.lineWidth = stringConfig.spacing / 24 #if !os(macOS) stringLayer.strokeColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else stringLayer.strokeColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif layer.addSublayer(stringLayer) // Frets let fretLayer = CAShapeLayer() for fret in 0...fretConfig.count { let fretPath = CGMutablePath() let lineWidth: CGFloat if baseFret == 1 && fret == 0 { lineWidth = fretConfig.spacing / 5 } else { lineWidth = fretConfig.spacing / 24 } // Draw fret number if baseFret != 1 { let txtLayer = CAShapeLayer() #if os(iOS) let txtFont = UIFont.systemFont(ofSize: fretConfig.margin * 0.5) #else let txtFont = NSFont.systemFont(ofSize: fretConfig.margin * 0.5) #endif let txtRect = CGRect(x: 0, y: 0, width: stringConfig.margin, height: fretConfig.spacing) let transX = stringConfig.margin / 5 + origin.x let transY = origin.y + (fretConfig.spacing / 2) + fretConfig.margin let txtPath = "\(baseFret)".path(font: txtFont, rect: txtRect, position: CGPoint(x: transX, y: transY)) txtLayer.path = txtPath #if os(iOS) txtLayer.fillColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else txtLayer.fillColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif fretLayer.addSublayer(txtLayer) } let y = fretConfig.spacing * CGFloat(fret) + fretConfig.margin + origin.y let x = origin.x + stringConfig.margin fretPath.move(to: CGPoint(x: x, y: y)) fretPath.addLine(to: CGPoint(x: fretConfig.length + x, y: y)) let fret = CAShapeLayer() fret.path = fretPath fret.lineWidth = lineWidth fret.lineCap = .square #if os(iOS) fret.strokeColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else fret.strokeColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif fretLayer.addSublayer(fret) } layer.addSublayer(fretLayer) return layer } private func nameLayer(fretConfig: LineConfig, origin: CGPoint, center: CGFloat, forScreen: Bool) -> CAShapeLayer { #if os(iOS) let txtFont = UIFont.systemFont(ofSize: fretConfig.margin, weight: .medium) #else let txtFont = NSFont.systemFont(ofSize: fretConfig.margin, weight: .medium) #endif let txtRect = CGRect(x: 0, y: 0, width: fretConfig.length, height: fretConfig.margin + origin.y) let transY = (origin.y + fretConfig.margin) * 0.35 let txtPath = (key.rawValue + " " + suffix.rawValue).path(font: txtFont, rect: txtRect, position: CGPoint(x: center, y: transY)) let shape = CAShapeLayer() shape.path = txtPath #if os(iOS) shape.fillColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else shape.fillColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif return shape } private func barreLayer(fretConfig: LineConfig, stringConfig: LineConfig, origin: CGPoint, showFingers: Bool, forScreen: Bool) -> CAShapeLayer { let layer = CAShapeLayer() for barre in barres { let barrePath = CGMutablePath() // draw barre behind all frets that are above the barre chord var startIndex = (frets.firstIndex { $0 == barre } ?? 0) let barreFretCount = frets.filter { $0 == barre }.count var length = 0 for index in startIndex..<frets.count { let dot = frets[index] if dot >= barre { length += 1 } else if dot < barre && length < barreFretCount { length = 0 startIndex = index + 1 } else { break } } let offset = stringConfig.spacing / 7 let startingX = CGFloat(startIndex) * stringConfig.spacing + stringConfig.margin + (origin.x + offset) let y = CGFloat(barre) * fretConfig.spacing + fretConfig.margin - (fretConfig.spacing / 2) + origin.y barrePath.move(to: CGPoint(x: startingX, y: y)) let endingX = startingX + (stringConfig.spacing * CGFloat(length)) - stringConfig.spacing - (offset * 2) barrePath.addLine(to: CGPoint(x: endingX, y: y)) let barreLayer = CAShapeLayer() barreLayer.path = barrePath barreLayer.lineCap = .round barreLayer.lineWidth = fretConfig.spacing * 0.65 #if os(iOS) barreLayer.strokeColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else barreLayer.strokeColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif layer.addSublayer(barreLayer) if showFingers { let fingerLayer = CAShapeLayer() #if os(iOS) let txtFont = UIFont.systemFont(ofSize: stringConfig.margin, weight: .medium) #else let txtFont = NSFont.systemFont(ofSize: stringConfig.margin, weight: .medium) #endif let txtRect = CGRect(x: 0, y: 0, width: stringConfig.spacing, height: fretConfig.spacing) let transX = startingX + ((endingX - startingX) / 2) let transY = y if let fretIndex = frets.firstIndex(of: barre) { let txtPath = "\(fingers[fretIndex])".path(font: txtFont, rect: txtRect, position: CGPoint(x: transX, y: transY)) fingerLayer.path = txtPath } #if os(iOS) fingerLayer.fillColor = forScreen ? UIColor.systemBackground.cgColor : UIColor.white.cgColor #else fingerLayer.fillColor = forScreen ? NSColor.windowBackgroundColor.cgColor : NSColor.white.cgColor #endif layer.addSublayer(fingerLayer) } } return layer } private func dotsLayer(stringConfig: LineConfig, fretConfig: LineConfig, origin: CGPoint, showFingers: Bool, forScreen: Bool, rect: CGRect, mirror: Bool) -> CAShapeLayer { let layer = CAShapeLayer() for index in 0..<frets.count { let fret = frets[index] // Draw circle above nut ⭕️ if fret == 0 { let size = fretConfig.spacing * 0.33 let circleX = ((CGFloat(index) * stringConfig.spacing + stringConfig.margin) - size / 2 + origin.x).shouldMirror(mirror, offset: rect.width - size) let circleY = fretConfig.margin - size * 1.6 + origin.y let center = CGPoint(x: circleX, y: circleY) let frame = CGRect(origin: center, size: CGSize(width: size, height: size)) let circle = CGMutablePath(roundedRect: frame, cornerWidth: frame.width/2, cornerHeight: frame.height/2, transform: nil) let circleLayer = CAShapeLayer() circleLayer.path = circle circleLayer.lineWidth = fretConfig.spacing / 24 #if os(iOS) circleLayer.strokeColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor circleLayer.fillColor = forScreen ? UIColor.systemBackground.cgColor : UIColor.white.cgColor #else circleLayer.strokeColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor circleLayer.fillColor = forScreen ? NSColor.windowBackgroundColor.cgColor : NSColor.white.cgColor #endif layer.addSublayer(circleLayer) continue } // Draw cross above nut ❌ if fret == -1 { let size = fretConfig.spacing * 0.33 let crossX = ((CGFloat(index) * stringConfig.spacing + stringConfig.margin) - size / 2 + origin.x).shouldMirror(mirror, offset: rect.width - size) let crossY = fretConfig.margin - size * 1.6 + origin.y let center = CGPoint(x: crossX, y: crossY) let frame = CGRect(origin: center, size: CGSize(width: size, height: size)) let cross = CGMutablePath() cross.move(to: CGPoint(x: frame.minX, y: frame.minY)) cross.addLine(to: CGPoint(x: frame.maxX, y: frame.maxY)) cross.move(to: CGPoint(x: frame.maxX, y: frame.minY)) cross.addLine(to: CGPoint(x: frame.minX, y: frame.maxY)) let crossLayer = CAShapeLayer() crossLayer.path = cross crossLayer.lineWidth = fretConfig.spacing / 24 #if os(iOS) crossLayer.strokeColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else crossLayer.strokeColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif layer.addSublayer(crossLayer) continue } if barres.contains(fret) { if index + 1 < frets.count { let next = index + 1 if frets[next] >= fret { continue } } if index - 1 > 0 { let prev = index - 1 if frets[prev] >= fret { continue } } } let dotY = CGFloat(fret) * fretConfig.spacing + fretConfig.margin - (fretConfig.spacing / 2) + origin.y let dotX = (CGFloat(index) * stringConfig.spacing + stringConfig.margin + origin.x).shouldMirror(mirror, offset: rect.width) let dotPath = CGMutablePath() dotPath.addArc(center: CGPoint(x: dotX, y: dotY), radius: fretConfig.spacing * 0.35, startAngle: 0, endAngle: .pi * 2, clockwise: true) let dotLayer = CAShapeLayer() dotLayer.path = dotPath #if os(iOS) dotLayer.fillColor = forScreen ? UIColor.label.cgColor : UIColor.black.cgColor #else dotLayer.fillColor = forScreen ? NSColor.labelColor.cgColor : NSColor.black.cgColor #endif layer.addSublayer(dotLayer) if showFingers { #if os(iOS) let txtFont = UIFont.systemFont(ofSize: stringConfig.margin, weight: .medium) #else let txtFont = NSFont.systemFont(ofSize: stringConfig.margin, weight: .medium) #endif let txtRect = CGRect(x: 0, y: 0, width: stringConfig.spacing, height: fretConfig.spacing) let txtPath = "\(fingers[index])".path(font: txtFont, rect: txtRect, position: CGPoint(x: dotX, y: dotY)) let txtLayer = CAShapeLayer() txtLayer.path = txtPath #if os(iOS) txtLayer.fillColor = forScreen ? UIColor.systemBackground.cgColor : UIColor.white.cgColor #else txtLayer.fillColor = forScreen ? NSColor.windowBackgroundColor.cgColor : NSColor.white.cgColor #endif layer.addSublayer(txtLayer) } } return layer } } extension CGFloat { func shouldMirror(_ mirror: Bool, offset: CGFloat) -> CGFloat { if mirror { return self * -1 + offset } else { return self } } }
46.128141
261
0.605643
f493557d0073db8a2522f58be3a6a344cf83133f
1,688
// // TrackCustomer+CoreDataClass.swift // // // Created by Dominik Hadl on 02/07/2018. // // import Foundation import CoreData public class TrackCustomer: NSManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<TrackCustomer> { return NSFetchRequest<TrackCustomer>(entityName: "TrackCustomer") } @NSManaged public var projectToken: String? @NSManaged public var timestamp: Double @NSManaged public var customer: Customer? @NSManaged public var properties: NSSet? var dataTypes: [DataType] { var data: [DataType] = [] // Add project token. if let token = projectToken { data.append(.projectToken(token)) } // Convert all properties to key value items. if let properties = properties as? Set<KeyValueItem> { var props: [String: JSONValue] = [:] properties.forEach({ DatabaseManager.processProperty(key: $0.key, value: $0.value, into: &props) }) data.append(.properties(props)) } return data } } // MARK: - Core Data - extension TrackCustomer { @objc(addPropertiesObject:) @NSManaged public func addToProperties(_ value: KeyValueItem) @objc(removePropertiesObject:) @NSManaged public func removeFromProperties(_ value: KeyValueItem) @objc(addProperties:) @NSManaged public func addToProperties(_ values: NSSet) @objc(removeProperties:) @NSManaged public func removeFromProperties(_ values: NSSet) }
27.672131
80
0.602488
7a618c0a468f3a2d54e03bf2220dd4325e04b1e7
2,482
import XCTest import class Foundation.Bundle final class YouTubeCLITests: XCTestCase { func test_noArgs_printsUsage() throws { let (result, _) = try executeBinary(arguments: []) let stdOut = result.stdOut let data = stdOut.fileHandleForReading.readDataToEndOfFile() XCTAssertTrue(data.isEmpty) let stdErr = result.stdErr let errorData = stdErr.fileHandleForReading.readDataToEndOfFile() XCTAssertNotNil(errorData) let errorOutput = String(data: errorData, encoding: .utf8) XCTAssertEqual(errorOutput, """ Error: Missing expected argument \'<query>\' Usage: program <query> [--sort <sort>] [--size-to-fit <size-to-fit>] [--ids-only <ids-only>] """) } func test_noArgs_exitsWithErrorStatus() throws { let (_, terminationStatus) = try executeBinary(arguments: []) XCTAssertNotEqual(terminationStatus, 0) } /// Returns path to the built products directory. var productsDirectory: URL { #if os(macOS) for bundle in Bundle.allBundles where bundle.bundlePath.hasSuffix(".xctest") { return bundle.bundleURL.deletingLastPathComponent() } fatalError("couldn't find the products directory") #else return Bundle.main.bundleURL #endif } static var allTests = [ ("test_noArgs_printsUsage", test_noArgs_printsUsage), ("test_noArgs_exitsWithErrorStatus", test_noArgs_exitsWithErrorStatus), ] // MARK: Private private struct ExecuteBinaryResult { let stdOut: PipeProtocol let stdErr: PipeProtocol } /// - Returns: A tuple containing a refrence to standard out and the termination status of the process. private func executeBinary( arguments: [String], standardInput: PipeProtocol? = nil) throws -> (ExecuteBinaryResult, Int32) { let fooBinary = productsDirectory.appendingPathComponent("YouTubeCLI") let process = Process() process.arguments = arguments process.executableURL = fooBinary process.standardInput = standardInput let stdOut = Pipe() process.standardOutput = stdOut let stdErr = Pipe() process.standardError = stdErr try process.run() process.waitUntilExit() let result = ExecuteBinaryResult(stdOut: stdOut, stdErr: stdErr) return (result, process.terminationStatus) } } // MARK: - PipeProtocol protocol PipeProtocol { var fileHandleForReading: FileHandle { get } var fileHandleForWriting: FileHandle { get } } // MARK: - Pipe extension Pipe: PipeProtocol { }
26.404255
106
0.714343
61ac5e2995a9740c95e1085af46a825fe656a38c
3,545
import SwiftUI struct ChartList: View { @ObservedObject var charts = ChartViewModel() @State var artistsLoaded = false @State var tracksLoaded = false @State private var selectedChartsIndex = 0 @State private var isPullLoaderShowing = false var body: some View { NavigationView { ZStack { VStack { Picker("Favorite Color", selection: $selectedChartsIndex, content: { // TODO use enum Text("Artists").tag(0) Text("Tracks").tag(1) }).padding(.horizontal, 20) .padding(.vertical, 5) .pickerStyle(SegmentedPickerStyle()) if selectedChartsIndex == 0 { List { ForEach(charts.artists) { artist in ZStack { Button("") {} NavigationLink( destination: ArtistView(artist: artist), label: { ArtistRow(artist: artist) }) } } } .navigationTitle("Global charts").onAppear { if !artistsLoaded { self.charts.getChartingArtists() // Prevent loading artists again when navigating self.artistsLoaded = true } } .pullToRefresh(isShowing: $isPullLoaderShowing) { self.charts.getChartingArtists() self.isPullLoaderShowing = false } } if selectedChartsIndex == 1 { List(charts.tracks) { track in NavigationLink( destination: TrackView(track: track), label: { TrackRow(track: track) }) }.navigationTitle("Global charts").onAppear { if !tracksLoaded { self.charts.getChartingTracks() // Prevent loading artists again when navigating self.tracksLoaded = true } } .pullToRefresh(isShowing: $isPullLoaderShowing) { self.charts.getChartingTracks() self.isPullLoaderShowing = false } } } // Show loader above the rest of the ZStack if charts.isLoading { ProgressView().scaleEffect(2) } } } } } struct ChartList_Previews: PreviewProvider { static var previews: some View { ForEach(["iPhone 12"], id: \.self) { deviceName in ChartList() .previewDevice(PreviewDevice(rawValue: deviceName)) .previewDisplayName(deviceName) } } }
39.831461
80
0.385331
e01d8b1791040de0ab108a0a9ad5f9ba2d1e6c70
955
// // MiniMockServerExampleTests.swift // MiniMockServerExampleTests // // Created by Ngoc Le on 25/07/2019. // Copyright © 2019 Coder Life. All rights reserved. // import XCTest @testable import MiniMockServerExample class MiniMockServerExampleTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.285714
111
0.672251
61563fd5fc09208c40f989da43704c344ee7bbef
4,859
// // CameraViewController.swift // Metis // // Created by Gina De La Rosa on 11/15/17. // Copyright © 2017 Gina Delarosa. All rights reserved. // import UIKit import AVFoundation class CameraViewController: UIViewController { @IBOutlet weak var photo: UIImageView! @IBOutlet weak var captionTextView: UITextView! @IBOutlet weak var removeButton: UIBarButtonItem! @IBOutlet weak var shareButton: UIButton! var selectedImage: UIImage? var videoUrl: URL? override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto)) photo.addGestureRecognizer(tapGesture) photo.isUserInteractionEnabled = true let aTabArray: [UITabBarItem] = (self.tabBarController?.tabBar.items)! for item in aTabArray { item.image = item.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) item.imageInsets = UIEdgeInsetsMake(7, 0, -7, 0) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) handlePost() } func handlePost() { if selectedImage != nil { self.shareButton.isEnabled = true self.removeButton.isEnabled = true self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) } else { //self.shareButton.isEnabled = true self.removeButton.isEnabled = false self.shareButton.backgroundColor = .lightGray } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } func handleSelectPhoto() { let pickerController = UIImagePickerController() pickerController.delegate = self pickerController.mediaTypes = ["public.image", "public.movie"] present(pickerController, animated: true, completion: nil) } @IBAction func shareButton_TouchUpInside(_ sender: Any) { view.endEditing(true) ProgressHUD.show("Waiting...", interaction: false) if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1) { let ratio = profileImg.size.width / profileImg.size.height HelperService.uploadDataToServer(data: imageData, videoUrl: self.videoUrl, ratio: ratio, caption: captionTextView.text!, onSuccess: { self.clean() self.tabBarController?.selectedIndex = 0 }) } else { ProgressHUD.showError("Error with image uploading") } } @IBAction func remove_TouchUpInside(_ sender: Any) { clean() handlePost() } func clean() { self.captionTextView.text = "" self.photo.image = UIImage(named: "placeholder-photo") self.selectedImage = nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "filter_segue" { let filterVC = segue.destination as! FilterViewController filterVC.selectedImage = self.selectedImage filterVC.delegate = self } } } extension CameraViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { print("did Finish Picking Media") print(info) if let videoUrl = info["UIImagePickerControllerMediaURL"] as? URL { if let thumnailImage = self.thumbnailImageForFileUrl(videoUrl) { selectedImage = thumnailImage photo.image = thumnailImage self.videoUrl = videoUrl } dismiss(animated: true, completion: nil) } if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage{ selectedImage = image photo.image = image dismiss(animated: true, completion: { // self.performSegue(withIdentifier: "filter_segue", sender: nil) }) } } func thumbnailImageForFileUrl(_ fileUrl: URL) -> UIImage? { let asset = AVAsset(url: fileUrl) let imageGenerator = AVAssetImageGenerator(asset: asset) do { let thumbnailCGImage = try imageGenerator.copyCGImage(at: CMTimeMake(7, 1), actualTime: nil) return UIImage(cgImage: thumbnailCGImage) } catch let err { print(err) } return nil } } extension CameraViewController: FilterViewControllerDelegate { func updatePhoto(image: UIImage) { self.photo.image = image self.selectedImage = image } }
34.21831
145
0.630171
d97630bca476bf786fe597b0e989b757e31b0353
699
import UIKit import MapKit class GridOverlayView: MKOverlayRenderer { var overlayImage: UIImage init(overlay:MKOverlay, overlayImage:UIImage) { self.overlayImage = overlayImage super.init(overlay: overlay) } override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) { let imageReference = overlayImage.CGImage let theMapRect = overlay.boundingMapRect let theRect = rectForMapRect(theMapRect) CGContextScaleCTM(context, 1.0, -1.0) CGContextTranslateCTM(context, 0.0, -theRect.size.height) CGContextDrawImage(context, theRect, imageReference) } }
31.772727
105
0.689557
2f02effe4f633d1eee6aca969a009d58180d2958
807
// // Copyright (c) 11.6.2021 Somia Reality Oy. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // import UIKit /// Titlebar implementation using UIKit extension HasTitleBar where Self:ViewController { func addTitleBar(parent: UIView?, adjustToSafeArea: Bool, onCloseAction: @escaping () -> Void) { defer { self.adjustTitlebar(topView: parent, toSafeArea: adjustToSafeArea) } guard hasTitlebar else { return } let titlebar: Titlebar = Titlebar.loadFromNib() titlebar.setupView(sessionManager, view: self, defaultAvatarView: self as? HasDefaultAvatar) titlebar.onCloseTapped = { onCloseAction() } self.shapeTitlebar(titlebar) } }
29.888889
100
0.67658
9b3431b64f86c40effa2482254560147f8cce2e5
3,281
// // AppDelegate.swift // Split Saver // // Created by Niall on 2017-05-28. // Copyright © 2017 nkdev. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UINavigationController(rootViewController: RootViewController()) window?.makeKeyAndVisible() return true } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Split_Saver") 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)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.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)") } } } }
41.531646
199
0.64523
4aa39adec708068c2174b9ff55f0ba9590750008
683
import Foundation class FetchDataInteractor { private let service: FacadeProtocol private let presenter: ProductListPresenterProtocol init(service: FacadeProtocol, presenter: ProductListPresenterProtocol) { self.service = service self.presenter = presenter } } extension FetchDataInteractor: FetchDataInteractorProtocol { func perform() { service.getRecipes(completion: { result in switch result { case .success(let response): self.presenter.on(recipes: response) case .failure(let error): self.presenter.on(error: error) } }) } }
26.269231
60
0.628111
69fcca0288a0cb314e64de04f45433430fcc4e55
5,072
// // LLEqualSpaceCollectionVc.swift // LLmyApp // // Created by 陈耀林 on 2021/1/21. // Copyright © 2021 ManlyCamera. All rights reserved. // import UIKit //import FWPopupView class LLEqualSpaceCollectionVc: UIViewController { private lazy var myCollectionView: UICollectionView = { let insets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let layout = LLEqualSpaceFlowLayout(minInteritem: 10, minLine: 10, edgeInsets: insets) layout.estimatedItemSize = CGSize(width: 100, height: 44) let view = UICollectionView(frame: .zero, collectionViewLayout: layout) view.register(LLEqualSpaceCollectionCell.self) view.dataSource = self view.delegate = self view.backgroundColor = .white return view }() private let myDatePicker = LLDatePickerView.loadFromNib() private let testDatePicker = LLPickerView.loadFromNib() private var sourceTags = [TagModel]() // 数据源 override func viewDidLoad() { super.viewDidLoad() makeUI() loadData() } func loadData() { guard let data = LLUtils.dataModel("LLEqualSpaceData", type: [TagModel].self) else { return } sourceTags = data myCollectionView.reloadData() } func makeUI() { view.backgroundColor = .white view.addSubview(myCollectionView) myCollectionView.frame = CGRect(x: 0, y: 0, width: kAppWidth, height: 200) } func pop() { let popView = LLPopView(withTip: "") popView.frame = CGRect(x: 0, y: 0, width: 300, height: 300) let vProperty = FWPopupViewProperty() vProperty.popupCustomAlignment = .center vProperty.popupAnimationType = .scale vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5) vProperty.touchWildToHide = "1" vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) vProperty.animationDuration = 0.3 popView.vProperty = vProperty popView.show() } func showDatePicker() { // let picker = UIDatePicker(frame: CGRect(x: 0, y: 100, width: kAppWidth, height: 247)) // if #available(iOS 13.4, *) { // picker.preferredDatePickerStyle = .compact // } else { // } // picker.frame = CGRect(x: 0, y: 50, width: kAppWidth, height: 247) // picker.datePickerMode = .dateAndTime self.view.addSubview(testDatePicker) } func showPhotoBroswer() { let image1 = "https://car.autohome.com.cn/photo/series/13452/1/1617513.html?pvareaid=101121" // let image2 = "http://test-upload.carisok.com/uploads/files/20190105/1546652896WDQhVP.jpeg" // let image3 = "http://test-upload.carisok.com/uploads/files/20200508/1588922419lKgADt.jpeg" // let image4 = "http://test-upload.carisok.com/uploads/files/20190105/1546652896WDQhVP.jpeg" // let image5 = "http://test-upload.carisok.com/uploads/files/20200508/1588922419lKgADt.jpeg" let images = [image1] let ibv = ImageBrowserView(imagesArray: images, defaultSelect: 0) ibv?.show() } } extension LLEqualSpaceCollectionVc: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return sourceTags.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(LLEqualSpaceCollectionCell.self, indexPath: indexPath) cell.bindData(sourceTags[indexPath.item]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // myDatePicker.show(WithShowDay: true) // myDatePicker.pickFinishBlock = { [weak self] (date: YearAndMonthModel) -> () in // print("111111 \(date.year)-\(date.month)-\(date.day)-") // } // let tipPopUpView = CRTipPopUpView() // tipPopUpView.frame = UIScreen.main.bounds // tipPopUpView.remark = "哈哈" // tipPopUpView.show() // showDatePicker() showPhotoBroswer() // pop() } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // // var cellText = "" // let tag = sourceTags[indexPath.item] // cellText = tag.tag_name ?? "" //// let spacing: CGFloat = cellText.count <= 2 ? OYUtils.Adapt(32) : OYUtils.Adapt(20) // let spacing: CGFloat = 20 // // let titleLabelSize: CGRect? = cellText.boundingRect(with: CGSize(width: Int(INT32_MAX), height: 20), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 12)], context: nil) // let size = CGSize(width: (titleLabelSize?.size.width ?? 0.0) + spacing, height: 44) // // return size // } }
39.015385
210
0.650237
eb00952e0faa1f19fab1040003528344bfd62dd3
861
import UIKit let BASE_REQURL: String = "https://login.microsoftonline.com/common/oauth2/v2.0" let AUTH_URL: String = BASE_REQURL + "/authorize" let TOKEN_URL: String = BASE_REQURL + "/token" let RESTAPI_URL: String = "https://graph.microsoft.com/v1.0/me/drive" let REDIRECT_URI: String = "http://localhost:12345" let ROOT_DIR: String = "/root" // mark - string constant let HEADER_AUTHORIZATION: String = "Authorization" let ACCESS_TOKEN = "access_token" let REFRESH_TOKEN = "refresh_token" let EXPIRES_IN = "expires_in" let SCOPE = "scope" let AUTHORIZATION_CODE = "authorization_code" class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } }
26.90625
80
0.7259
f8b4513814ccf114ad76ae271982ea0ce91ff971
6,287
// Copyright (c) 2019 Spotify AB. // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 /// A `Fuser<A>` is a stream of events of type `A`. /// It supports: /// - `connect`: start listening to events from the Fuser. A callback function is supplied to connect. /// - `dispose`: stop listening to events. Can be called on objects returned by `connect`. /// - `extract`: apply a function to every event emitted by a Fuser. public class Fuser<A> { public typealias Disposable = _Disposable private let lock = NSRecursiveLock() private let source: AnySource<A>; public init(source: AnySource<A>) { self.source = source } public init(_ children: [Fuser<A>]) { self.source = AnySource { effect in let disposables = children.map { $0.connect(effect) } return AnonymousDisposable { // TODO review thread safety of this operation disposables.forEach { $0.dispose() } } } } public convenience init(_ children: Fuser<A>...) { self.init(children) } /// Start observing the events of a `Fuser`. Remember to call `.dispose()` on the disposable returned when /// connecting. Otherwise you may leak resources. /// /// - Parameter effect: the side-effect which should be performed when the `Fuser` emits an event /// - Returns: a disposable which can be called to unsubscribe from the `Fuser`'s events public func connect(_ effect: @escaping Effect<A>) -> Disposable { var isDisposed = false let safeEffect: Effect<A> = { value in self.lock.synchronized { if !isDisposed { effect(value) } } } let disposable = source.connect(safeEffect) return AnonymousDisposable { self.lock.synchronized { isDisposed = true } disposable.dispose() } } } public extension Fuser { /// Create a `Fuser` when given a `Source`. static func from<S: Source>(_ source: S) -> Fuser<A> where S.A == A { return Fuser(source: AnySource(source)); } /// See `from(Source)` /// This is a shorthand for creating a `Fuser` from a closure directly. static func from(_ source: @escaping (@escaping Effect<A>) -> Disposable) -> Fuser<A> { return from(AnySource(source)) } /// `fromAll` merges a list of `Fuser`s. /// Connecting to this returned `Fuser` will internally connect to each of the merged `Fuser`s, and calling `dispose` /// will disconnect from all of these connections. static func fromAll(_ children: [Fuser<A>]) -> Fuser<A> { return Fuser(children) } /// Vararg variant of `fromAll([Fuser<..>])` static func fromAll(_ children: Fuser<A>...) -> Fuser<A> { return Fuser(children) } /// `extract` takes a function which it applies to each event emitted by a `Fuser`. /// /// We intentionally do not provide other combinators than `extract`, like `flatMap`, `filter`, or `reduce`. The `Fuser` /// is designed for aggregating UI-events and should be placed in the UI-layer of an application. `extract` is primarily /// intended for converting from UIKit types to types from your domain. Any additional interpretation of events should /// be placed outside of the `Fuser` and outside the UI-layer. /// /// - Parameters: /// - transformation: the function to be applied to each event emitted by the `fuser` parameter /// - fuser: the fuser to which the `transformation` function should be applied static func extract<B>( _ transformation: @escaping (B) -> A, _ fuser: Fuser<B> ) -> Fuser<A> { return Fuser<A>(source: AnySource { effect in return fuser.connect { b in let a = transformation(b) effect(a) } }) } /// Extract a constant from each event emitted by a `Fuser`. /// /// - Parameters: /// - constant: the constant that should be emitted everytime the `fuser` parameter emits an event /// - fuser: the fuser to which the `transformation` function should be applied static func extractConstant<B>( _ constant: A, _ fuser: Fuser<B> ) -> Fuser<A> { return Fuser<A>(source: AnySource { effect in return fuser.connect { b in effect(constant) } }) } /// `extractUnlessNil` takes a function which it applies to each event emitted by a `Fuser`. The event is dropped if the function /// returns `nil`. /// /// - Parameters: /// - transformation: the function to be applied to each event emitted by the `fuser` parameter. The event will be ignored if /// this function returns `nil` /// - fuser: the fuser to which the `transformation` function should be applied static func extractUnlessNil<B>( _ transformation: @escaping (B) -> A?, _ fuser: Fuser<B> ) -> Fuser<A> { return Fuser<A>(source: AnySource { effect in return fuser.connect { b in if let a = transformation(b) { effect(a) } } }) } } private extension NSRecursiveLock { @discardableResult func synchronized<R>(closure: () -> R) -> R { lock() defer { self.unlock() } return closure() } }
36.34104
133
0.61651
226ffe44b085dd09223b279c7973d46efff67867
925
// // HasOnlyReadOnly.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class HasOnlyReadOnly: Codable { public var bar: String? public var foo: String? public init(bar: String?, foo: String?) { self.bar = bar self.foo = foo } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: String.self) try container.encodeIfPresent(bar, forKey: "bar") try container.encodeIfPresent(foo, forKey: "foo") } // Decodable protocol methods public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) bar = try container.decodeIfPresent(String.self, forKey: "bar") foo = try container.decodeIfPresent(String.self, forKey: "foo") } }
21.511628
71
0.660541
f8de08e68242ca1305bad8b68fb1e6de994fd131
120
import XCTest import iGeometryTests var tests = [XCTestCaseEntry]() tests += iGeometryTests.allTests() XCTMain(tests)
15
34
0.783333
62a8da9a654c90121ffe76a04ad0806fda992ac7
2,497
// // AssetsRepositoryLocal.swift // WavesWallet-iOS // // Created by Prokofev Ruslan on 04/08/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxSwift import RealmSwift import RxRealm import WavesSDKExtension final class AssetsRepositoryLocal: AssetsRepositoryProtocol { func assets(by ids: [String], accountAddress: String) -> Observable<[DomainLayer.DTO.Asset]> { return Observable.create({ (observer) -> Disposable in guard let realm = try? WalletRealmFactory.realm(accountAddress: accountAddress) else { observer.onError(AssetsRepositoryError.fail) return Disposables.create() } let objects = realm.objects(Asset.self) .filter("id in %@",ids) .toArray() let newIds = objects.map { $0.id } if ids.contains(where: { newIds.contains($0) }) == false { observer.onError(AssetsRepositoryError.notFound) } else { let assets = objects .map { DomainLayer.DTO.Asset($0) } observer.onNext(assets) observer.onCompleted() } return Disposables.create() }) } func saveAssets(_ assets:[DomainLayer.DTO.Asset], by accountAddress: String) -> Observable<Bool> { return Observable.create({ (observer) -> Disposable in guard let realm = try? WalletRealmFactory.realm(accountAddress: accountAddress) else { observer.onNext(false) observer.onError(AssetsRepositoryError.fail) return Disposables.create() } do { try realm.write({ realm.add(assets.map { Asset(asset: $0) }, update: true) }) observer.onNext(true) observer.onCompleted() } catch _ { observer.onNext(false) observer.onError(AssetsRepositoryError.fail) return Disposables.create() } return Disposables.create() }) } func saveAsset(_ asset: DomainLayer.DTO.Asset, by accountAddress: String) -> Observable<Bool> { return saveAssets([asset], by: accountAddress) } func isSmartAsset(_ assetId: String, by accountAddress: String) -> Observable<Bool> { assertMethodDontSupported() return Observable.never() } }
31.607595
102
0.581898
5d65dbc21259c9aecd7d798a7f7e52271d7cd358
908
// // RoleTitleTableViewCell.swift // Riot // // Created by Naurin Afrin on 3/8/20. // Copyright © 2020 matrix.org. All rights reserved. // import UIKit class RoleTitleTableViewCell: UITableViewCell { @IBOutlet weak var heading: UILabel! @IBOutlet weak var primaryText: UILabel! @IBOutlet weak var secondaryText: UILabel! var Role: Role! override func awakeFromNib() { super.awakeFromNib() // Initialization code ThemeService.shared().theme.recursiveApply(on: self.contentView) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setRole(role: Role?) { Role = role heading.text = AlternateHomeTools.getNSLocalized("role_title", in: "Vector") primaryText.text = Role?.Title } }
25.942857
84
0.6663
75f68cfcaf9c87c4f5570b311fb9ca99b570fb63
6,541
import Apollo @testable import KsApi public enum FetchUserBackingsQueryTemplate { case valid case errored var data: GraphAPI.FetchUserBackingsQuery.Data { switch self { case .valid: return GraphAPI.FetchUserBackingsQuery.Data(unsafeResultMap: self.validResultMap) case .errored: return GraphAPI.FetchUserBackingsQuery.Data(unsafeResultMap: self.erroredResultMap) } } // MARK: Private Properties private var validResultMap: [String: Any?] { [ "data": [ "me": [ "__typename": "User", "backings": [ "__typename": "UserBackingsConnection", "nodes": [[ "__typename": "Backing", "addOns": [ "__typename": "RewardTotalCountConnection", "nodes": [] ], "errorReason": "Your card was declined.", "amount": [ "__typename": "Money", "amount": "1.0", "currency": "USD", "symbol": "$" ], "backer": [ "__typename": "User", "chosenCurrency": "USD", "email": "[email protected]", "hasPassword": true, "id": "VXNlci0xNDcwOTUyNTQ1", "imageUrl": "https://ksr-qa-ugc.imgix.net/missing_user_avatar.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=&auto=format&frame=1&q=92&s=e17a7b6f853aa6320cfe67ee783eb3d8", "isAppleConnected": false, "isCreator": false, "isDeliverable": true, "isEmailVerified": true, "name": "Hari Singh", "uid": "1470952545" ], "backerCompleted": false, "bonusAmount": [ "__typename": "Money", "amount": "1.0", "currency": "USD", "symbol": "$" ], "cancelable": false, "creditCard": [ "__typename": "CreditCard", "expirationDate": "2023-01-01", "id": "69021312", "lastFour": "0341", "paymentType": "CREDIT_CARD", "state": "ACTIVE", "type": "VISA" ], "id": "QmFja2luZy0xNDQ5NTI3NTQ=", "location": nil, "pledgedOn": 1_627_592_045, "project": [ "__typename": "Project", "backersCount": 4, "category": [ "__typename": "Category", "id": "Q2F0ZWdvcnktMjg1", "name": "Plays", "parentCategory": [ "__typename": "Category", "id": "Q2F0ZWdvcnktMTc=", "name": "Theater" ] ], "canComment": false, "country": [ "__typename": "Country", "code": "US", "name": "the United States" ], "creator": [ "__typename": "User", "chosenCurrency": nil, "email": "[email protected]", "hasPassword": nil, "id": "VXNlci03NDAzNzgwNzc=", "imageUrl": "https://ksr-qa-ugc.imgix.net/assets/033/406/310/0643a06ea18a1462cc8466af5718d9ef_original.jpeg?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=1620659730&auto=format&frame=1&q=92&s=86608b67fc0b349026722388df683a89", "isAppleConnected": nil, "isCreator": nil, "isDeliverable": true, "isEmailVerified": true, "name": "Afees Lawal", "uid": "740378077" ], "currency": "USD", "deadlineAt": 1_683_676_800, "description": "test blurb", "finalCollectionDate": nil, "fxRate": 1.0, "friends": [ "__typename": "ProjectBackerFriendsConnection", "nodes": [] ], "goal": [ "__typename": "Money", "amount": "19974.0", "currency": "USD", "symbol": "$" ], "image": [ "__typename": "Photo", "id": "UGhvdG8tMTEyNTczMzY=", "url": "https://ksr-qa-ugc.imgix.net/assets/011/257/336/a371c892fb6e936dc1824774bea14a1b_original.jpg?ixlib=rb-4.0.2&crop=faces&w=1024&h=576&fit=crop&v=1463673674&auto=format&frame=1&q=92&s=87715e16f6e9b5a26afa42ea54a33fcc" ], "isProjectWeLove": false, "isWatched": false, "launchedAt": 1_620_662_504, "location": [ "__typename": "Location", "country": "NG", "countryName": "Nigeria", "displayableName": "Nigeria", "id": "TG9jYXRpb24tMjM0MjQ5MDg=", "name": "Nigeria" ], "name": "Mouth Trumpet Robot Cats", "pid": 1_234_627_104, "pledged": [ "__typename": "Money", "amount": "65.0", "currency": "USD", "symbol": "$" ], "slug": "afeestest/mouth-trumpet-robot-cats", "state": "LIVE", "stateChangedAt": 1_620_662_506, "url": "https://staging.kickstarter.com/projects/afeestest/mouth-trumpet-robot-cats", "usdExchangeRate": 1.0 ], "reward": nil, "sequence": 5, "shippingAmount": [ "__typename": "Money", "amount": "0.0", "currency": "USD", "symbol": "$" ], "status": "errored" ]], "totalCount": 1 ], "id": "VXNlci0xNDcwOTUyNTQ1", "imageUrl": "https://ksr-qa-ugc.imgix.net/missing_user_avatar.png?ixlib=rb-4.0.2&blur=false&w=1024&h=1024&fit=crop&v=&auto=format&frame=1&q=92&s=e17a7b6f853aa6320cfe67ee783eb3d8", "name": "Hari Singh", "uid": "1470952545" ] ] ] } private var erroredResultMap: [String: Any?] { return [:] } }
37.164773
249
0.443816
ed14b8575a0f57234e8744e07dcf003ea900b815
545
// Copyright (c) 2019 Razeware LLC // For full license & permission details, see LICENSE.markdown. /*: [Previous Challenge](@previous) ## #2. Balance Parentheses Check for balanced parentheses. Given a string, check if there are `(` and `)` characters, and return `true` if the parentheses in the string are balanced. ``` // 1 h((e))llo(world)() // balanced parentheses // 2 (hello world // unbalanced parentheses ``` */ var testString1 = "h((e))llo(world)()" // your code here // checkParentheses(testString1) // should be true
25.952381
156
0.684404
729ccbd335ddad077c87ec289b0643c14c9048c4
4,794
// // AppDelegate.swift // CheckWeather // // Created by TTN on 24/04/18. // Copyright © 2018 Developer. All rights reserved. // import Foundation import PromiseKit fileprivate let appID = "a6a8c813b66f590f779c18b9e2b2c02d" class WeatherHelper { struct Weather { let tempInK: Double let iconName: String let text: String let name: String init?(jsonDictionary: [String: Any]) { guard let main = jsonDictionary["main"] as? [String: Any], let tempInK = main["temp"] as? Double, let weather = (jsonDictionary["weather"] as? [[String: Any]])?.first, let iconName = weather["icon"] as? String, let text = weather["description"] as? String, let name = jsonDictionary["name"] as? String else { print("Error: invalid jsonDictionary! Verify your appID is correct") return nil } self.tempInK = tempInK self.iconName = iconName self.text = text self.name = name } } func getWeatherTheOldFashionedWay(latitude: Double, longitude: Double, completion: @escaping (Weather?, Error?) -> ()) { assert(appID != "<#Enter Your API Key from http://openweathermap.org/appid#>", "You need to set your API key!") let urlString = "http://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&appid=\(appID)" let url = URL(string: urlString)! let request = URLRequest(url: url) let session = URLSession.shared let dataTask = session.dataTask(with: request) { data, response, error in guard let data = data, let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any], let result = Weather(jsonDictionary: json) else { completion(nil, error) return } completion(result, nil) } dataTask.resume() } func getWeather(latitude: Double, longitude: Double) -> Promise<Weather> { return Promise { fulfill, reject in let urlString = "http://api.openweathermap.org/data/2.5/weather?lat=" + "\(latitude)&lon=\(longitude)&appid=\(appID)" let url = URL(string: urlString)! let request = URLRequest(url: url) let session = URLSession.shared let dataPromise: URLDataPromise = session.dataTask(with: request) _ = dataPromise.asDictionary().then { dictionary -> Void in guard let result = Weather(jsonDictionary: dictionary as! [String : Any]) else { let error = NSError(domain: "PromiseKitTutorial", code: 0, userInfo: [NSLocalizedDescriptionKey: "Unknown error"]) reject(error) return } fulfill(result) }.catch(execute: reject) } } func getIcon(named iconName: String) -> Promise<UIImage> { return wrap { getFile(named: iconName, completion: $0) } .then { image in if image == nil { return self.getIconFromNetwork(named: iconName) } else { return Promise(value: image!) } } } func getIconFromNetwork(named iconName: String) -> Promise<UIImage> { let urlString = "http://openweathermap.org/img/w/\(iconName).png" let url = URL(string: urlString)! let request = URLRequest(url: url) let session = URLSession.shared let dataPromise: URLDataPromise = session.dataTask(with: request) return dataPromise.then(on: DispatchQueue.global(qos: .background)) { data -> Promise<UIImage> in return firstly { return wrap { self.saveFile(named: iconName, data: data, completion: $0)} }.then { Void -> Promise<UIImage> in let image = UIImage(data: data)! return Promise(value: image) } } } private func saveFile(named: String, data: Data, completion: @escaping (Error?) -> Void) { DispatchQueue.global(qos: .background).async { if let path = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent(named+".png") { do { try data.write(to: path) print("Saved image to: " + path.absoluteString) completion(nil) } catch { completion(error) } } } } private func getFile(named: String, completion: @escaping (UIImage?) -> Void) { DispatchQueue.global(qos: .background).async { var image: UIImage? if let path = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent(named+".png") { if let data = try? Data(contentsOf: path) { image = UIImage(data: data) } } DispatchQueue.main.async { completion(image) } } } }
32.612245
134
0.610763
91752ca8e15b173203a972928c463d650d1f1726
11,067
// // Copyright (c) 2021 Related Code - https://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit //----------------------------------------------------------------------------------------------------------------------------------------------- class AuthorsList2View: UITableViewController { private var sections: [String] = [] private var sectionIndex = ["#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] private var authors: [[[String: String]]] = [] //------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() title = "Authors" navigationController?.navigationBar.prefersLargeTitles = false navigationItem.largeTitleDisplayMode = .never navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "text.justifyleft"), style: .plain, target: self, action: #selector(actionShort(_:))) tableView.tintColor = AppColor.Theme tableView.register(UINib(nibName: "AuthorsList2Cell", bundle: Bundle.main), forCellReuseIdentifier: "AuthorsList2Cell") loadData() } // MARK: - Data methods //------------------------------------------------------------------------------------------------------------------------------------------- func loadData() { authors.removeAll() var dataDic1: [[String: String]] = [] var dataDic2: [[String: String]] = [] var dataDic3: [[String: String]] = [] var dataDic4: [[String: String]] = [] var dataDic5: [[String: String]] = [] var dataDic6: [[String: String]] = [] var dataDic7: [[String: String]] = [] var dataDic8: [[String: String]] = [] var dataDic9: [[String: String]] = [] var dataDic10: [[String: String]] = [] var dic1: [String: String] = [:] dic1["name"] = "Agatha Christie" dic1["books"] = "85" dataDic1.append(dic1) var dic2: [String: String] = [:] dic2["name"] = "Akira Toriyama" dic2["books"] = "66" dataDic1.append(dic2) var dic3: [String: String] = [:] dic3["name"] = "Alexander Pushkin" dic3["books"] = "17" dataDic1.append(dic3) var dic4: [String: String] = [:] dic4["name"] = "Corín Tellado" dic4["books"] = "32" dataDic2.append(dic4) var dic5: [String: String] = [:] dic5["name"] = "Catherine Cookson" dic5["books"] = "60" dataDic2.append(dic5) var dic6: [String: String] = [:] dic6["name"] = "Clive Cussler" dic6["books"] = "335" dataDic2.append(dic6) var dic7: [String: String] = [:] dic7["name"] = "Dan Brown" dic7["books"] = "14" dataDic3.append(dic7) var dic8: [String: String] = [:] dic8["name"] = "Danielle Steel" dic8["books"] = "27" dataDic3.append(dic8) var dic9: [String: String] = [:] dic9["name"] = "David Baldacci" dic9["books"] = "11" dataDic3.append(dic9) var dic10: [String: String] = [:] dic10["name"] = "Enid Blyton" dic10["books"] = "100" dataDic4.append(dic10) var dic11: [String: String] = [:] dic11["name"] = "Erskine Caldwell" dic11["books"] = "723" dataDic4.append(dic11) var dic12: [String: String] = [:] dic12["name"] = "Evan Hunter" dic12["books"] = "23" dataDic4.append(dic12) var dic13: [String: String] = [:] dic13["name"] = "Georges Simenon" dic13["books"] = "38" dataDic5.append(dic13) var dic14: [String: String] = [:] dic14["name"] = "Gilbert Patten" dic14["books"] = "103" dataDic5.append(dic14) var dic15: [String: String] = [:] dic15["name"] = "Gérard de Villiers" dic15["books"] = "37" dataDic5.append(dic15) var dic16: [String: String] = [:] dic16["name"] = "Harold Robbins" dic16["books"] = "4000" dataDic6.append(dic16) var dic17: [String: String] = [:] dic17["name"] = "Hermann Hesse" dic17["books"] = "7" dataDic6.append(dic17) var dic18: [String: String] = [:] dic18["name"] = "Horatio Alger" dic18["books"] = "179" dataDic6.append(dic18) var dic19: [String: String] = [:] dic19["name"] = "Jackie Collins" dic19["books"] = "25" dataDic7.append(dic19) var dic20: [String: String] = [:] dic20["name"] = "James A. Michener" dic20["books"] = "91" dataDic7.append(dic20) var dic21: [String: String] = [:] dic21["name"] = "James Patterson" dic21["books"] = "33" dataDic7.append(dic21) var dic22: [String: String] = [:] dic22["name"] = "Kyotaro Nishimura" dic22["books"] = "400" dataDic8.append(dic22) var dic23: [String: String] = [:] dic23["name"] = "Ken Follett" dic23["books"] = "30" dataDic8.append(dic23) var dic24: [String: String] = [:] dic24["name"] = "Karl May" dic24["books"] = "80" dataDic8.append(dic24) var dic25: [String: String] = [:] dic25["name"] = "Leo Tolstoy" dic25["books"] = "48" dataDic9.append(dic25) var dic26: [String: String] = [:] dic26["name"] = "Lewis Carroll" dic26["books"] = "5" dataDic9.append(dic26) var dic27: [String: String] = [:] dic27["name"] = "Louis L'Amour" dic27["books"] = "101" dataDic9.append(dic27) var dic28: [String: String] = [:] dic28["name"] = "Nicholas Sparks" dic28["books"] = "22" dataDic10.append(dic28) var dic29: [String: String] = [:] dic29["name"] = "Nora Roberts" dic29["books"] = "200" dataDic10.append(dic29) var dic30: [String: String] = [:] dic30["name"] = "Norman Bridwell" dic30["books"] = "80" dataDic10.append(dic30) authors.append(dataDic1) authors.append(dataDic2) authors.append(dataDic3) authors.append(dataDic4) authors.append(dataDic5) authors.append(dataDic6) authors.append(dataDic7) authors.append(dataDic8) authors.append(dataDic9) authors.append(dataDic10) for value in authors { guard let name = value.first?["name"] else{ return } if let firstLetter = name.first { sections.append(String(firstLetter).capitalized) } } refreshTableView() } // MARK: - Refresh methods //------------------------------------------------------------------------------------------------------------------------------------------- func refreshTableView() { tableView.reloadData() } // MARK: - User actions //------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionShort(_ sender: UIBarButtonItem) { print(#function) } } // MARK: - UITableViewDataSource //----------------------------------------------------------------------------------------------------------------------------------------------- extension AuthorsList2View { //------------------------------------------------------------------------------------------------------------------------------------------- override func numberOfSections(in tableView: UITableView) -> Int { return authors.count } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return authors[section].count } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AuthorsList2Cell", for: indexPath) as! AuthorsList2Cell cell.bindData(index: indexPath.item + (indexPath.section * 3), data: authors[indexPath.section][indexPath.row]) return cell } //------------------------------------------------------------------------------------------------------------------------------------------- override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return sectionIndex } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { if let index = sections.firstIndex(of: title) { return index } return -1 } } // MARK: - UITableViewDelegate //----------------------------------------------------------------------------------------------------------------------------------------------- extension AuthorsList2View { //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 45 } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 30 } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 1 } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let firstLetter = authors[section].first?["name"]?.first { return String(firstLetter).capitalized } return nil } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { let viewY = header.frame.size.height - 0.5 let view = UIView(frame: CGRect(x: 0, y: viewY, width: header.frame.size.width, height: 1)) view.backgroundColor = .tertiarySystemFill view.tag = 1001 header.contentView.subviews.forEach { (view) in if (view.tag == 1001) { view.removeFromSuperview() } } header.contentView.addSubview(view) header.textLabel?.font = UIFont.systemFont(ofSize: 12) } } //------------------------------------------------------------------------------------------------------------------------------------------- override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectItemAt \(indexPath.row)") } }
33.035821
166
0.508539
8f38c82f4f8e4f37bf9b128cd86009c7cde004c4
380
// // Utils.swift // WidgetsExtension // // Created by WizJin on 2021/6/16. // import SwiftUI extension ColorScheme { public func withAppearance(_ appearance: AppearanceEnum) -> ColorScheme { switch appearance { case .light: return .light case .dark: return .dark default: return self } } }
17.272727
77
0.563158
0e2060faebb769aebb62d96a93408199866534d6
543
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // IotHubSkuDescriptionListResultProtocol is the JSON-serialized array of IotHubSkuDescription objects with a next // link. public protocol IotHubSkuDescriptionListResultProtocol : Codable { var value: [IotHubSkuDescriptionProtocol?]? { get set } var _nextLink: String? { get set } }
45.25
115
0.762431
ef38a29622d06d75e94fb84628ef1111f0af7d20
449
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func a class a{class b:a{enum e{func f func f->Any
37.416667
79
0.750557
8a5728448080b6a418a83e439c983d8b524610f0
2,469
// // DayTests.swift // DayTests // // Created by Oleksandr Kirichenko on 11/22/17. // Copyright © 2017 Oleksandr Kirichenko. All rights reserved. // import XCTest import Day class DayTests: XCTestCase { let formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy.MM.dd HH:mm" return formatter }() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testDayFromString() { let correctResultDate = formatter.date(from: "2018.11.04 00:00") let dayString = Day("2018.11.04")!.rawValue let dateString = Date.date(fromSerializedDay: "2018.11.04") XCTAssertEqual(correctResultDate, dayString) XCTAssertEqual(correctResultDate, dateString) } func testDayTimeFromString() { let correctResultDate = formatter.date(from: "2018.11.04 11:10") let dayString = Date.date(fromSerializedDateAndTimeString: "2018.11.04.11.10") XCTAssertEqual(correctResultDate, dayString) } func testDayString() { let date = formatter.date(from: "2018.11.04 11:10")! let stringFromDay = Day(date).serializedDayString let stringFromDate = date.serializedDayString XCTAssertEqual(stringFromDay, "2018.11.04") XCTAssertEqual(stringFromDate, "2018.11.04") } func testStringFromDayTime() { let date = formatter.date(from: "2018.11.04 11:10")! let string = date.serializedDayAndTimeString XCTAssertEqual(string, "2018.11.04.11.10") } func testDayStringInitFail() { let failedValue = Day("2018+11+04") XCTAssertNil(failedValue) } func testDateStringInitFail() { let failedValue1 = Date.date(fromSerializedDateAndTimeString: "2018.11.04+11:10") let failedValue2 = Date.date(fromSerializedDay: "2018+11+04") XCTAssertNil(failedValue1) XCTAssertNil(failedValue2) } func testDayDescription() { XCTAssertEqual("\(String(describing: Day("2018.11.04")!))", "2018.11.04") XCTAssertEqual(Day("2018.11.04")!.description, "2018.11.04") } }
31.653846
111
0.64196
e6bd987cb97258de28931cfe01be6e75dbf5055c
737
// // InAppWebBrowserRouter.swift // UhooiPicBook // // Created by uhooi on 27/02/2021. // Copyright © 2021 THE Uhooi. All rights reserved. // import UIKit enum InAppWebBrowserRouter { // MARK: Type Methods static func show(_ parent: UIViewController, url: URL) { let vc = assembleModule(url: url) parent.present(vc, animated: true) } // MARK: Other Private Methods private static func assembleModule(url: URL) -> InAppWebBrowserViewController { guard let view = R.storyboard.inAppWebBrowser.instantiateInitialViewController() else { fatalError("Fail to load InAppWebBrowserViewController from Storyboard.") } view.url = url return view } }
23.03125
95
0.667571
abbae0ffcfb15f57f8db3e9ab6dee1512b89a7c2
2,387
/*: ## Exercise - Define a Base Class - Note: The exercises below are based on a game where a spaceship avoids obstacles in space. The ship is positioned at the bottom of a coordinate system and can only move left and right while obstacles "fall" from top to bottom. Throughout the exercises, you'll create classes to represent different types of spaceships that can be used in the game. Create a `Spaceship` class with three variable properties: `name`, `health`, and `position`. The default value of `name` should be an empty string and `health` should be 0. `position` will be represented by an `Int` where negative numbers place the ship further to the left and positive numbers place the ship further to the right. The default value of `position` should be 0. */ class Spaceship { var name = "" var health = 0 var position: Int = 0 func moveLeft() { self.position -= 1 } func moveRight() { self.position += 1 } func wasHit() { self.health -= 5 if health <= 0 { print("Sorry, your ship was hit one too many times. Do you want to play again?") } } } //: Create a `let` constant called `falcon` and assign it to an instance of `Spaceship`. After initialization, set `name` to "Falcon." let falcon = Spaceship() falcon.name = "Falcon" //: Go back and add a method called `moveLeft()` to the definition of `Spaceship`. This method should adjust the position of the spaceship to the left by one. Add a similar method called `moveRight()` that moves the spaceship to the right. Once these methods exist, use them to move `falcon` to the left twice and to the right once. Print the new position of `falcon` after each change in position. falcon.moveLeft() print(falcon.position) falcon.moveLeft() print(falcon.position) falcon.moveRight() print(falcon.position) //: The last thing `Spaceship` needs for this example is a method to handle what happens if the ship gets hit. Go back and add a method `wasHit()` to `Spaceship` that will decrement the ship's health by 5, then if `health` is less than or equal to 0 will print "Sorry, your ship was hit one too many times. Do you want to play again?" Once this method exists, call it on `falcon` and print out the value of `health`. falcon.wasHit() print(falcon.health) /*: page 1 of 4 | [Next: Exercise - Create a Subclass](@next) */
55.511628
417
0.710515
bf78d9df3c53b798f282e6280ad55e4b2c420baa
532
//Problem definition: https://www.hackerrank.com/challenges/find-point/problem import Foundation func findPoint(px: Int, py: Int, qx: Int, qy: Int) -> Void { let rx = 2 * qx - px let ry = 2 * qy - py print("\(rx) \(ry)") } let n = Int(readLine()!)! for _ in 1...n { let inputArray = readLine()!.split(separator: " ").compactMap { Int($0) } let px = inputArray[0] let py = inputArray[1] let qx = inputArray[2] let qy = inputArray[3] findPoint(px: px, py: py, qx: qx, qy: qy) }
21.28
78
0.577068
ab2765c1955680bb863bd73b0a5818b5e59eb318
630
// // NetRequest.swift // MiaoTu-iOS // // Created by 曹宇航 on 2018/9/13. // Copyright © 2018年 yunshang. All rights reserved. // import Alamofire class NetRequest{ var url: String var parameters: Dictionary<String, Any> var headers: Dictionary<String, String> init(url: String , parameters: Dictionary<String, Any>) { self.url = url self.parameters = parameters var headers = [String:String]() if let token = UserDefaults.standard.string(forKey: Constants.CACHE_KEY_TOKEN){ headers["token"] = token } self.headers = headers } }
23.333333
87
0.61746
fb1008817a586bcd80af1fac18c4fc709cdcd433
20,697
// // Station+OpeningTimes.swift // // // Created by Emma on 11/6/21. // import Foundation enum WMATADay { case weekday case saturday case sunday } extension Date { func wmataDay() -> WMATADay { let weekday = Calendar(identifier: .gregorian).component(.weekday, from: self) switch weekday { case 1: return .sunday case 2...6: return .weekday default: return .saturday } } } extension Station { static var openingTimes: [Station: [WMATADay: DateComponents]] = [ .metroCenterUpper: [ .sunday: DateComponents(hour: 8, minute: 14), .weekday: DateComponents(hour: 5, minute: 14), .saturday: DateComponents(hour: 7, minute: 14), ], .farragutNorth: [ .sunday: DateComponents(hour: 8, minute: 24), .weekday: DateComponents(hour: 5, minute: 24), .saturday: DateComponents(hour: 7, minute: 24), ], .dupontCircle: [ .sunday: DateComponents(hour: 8, minute: 23), .weekday: DateComponents(hour: 5, minute: 23), .saturday: DateComponents(hour: 7, minute: 23), ], .woodleyPark: [ .sunday: DateComponents(hour: 8, minute: 21), .weekday: DateComponents(hour: 5, minute: 21), .saturday: DateComponents(hour: 7, minute: 21), ], .clevelandPark: [ .sunday: DateComponents(hour: 8, minute: 19), .weekday: DateComponents(hour: 5, minute: 19), .saturday: DateComponents(hour: 7, minute: 19), ], .vanNess: [ .sunday: DateComponents(hour: 8, minute: 17), .weekday: DateComponents(hour: 5, minute: 17), .saturday: DateComponents(hour: 7, minute: 17), ], .tenleytown: [ .sunday: DateComponents(hour: 8, minute: 14), .weekday: DateComponents(hour: 5, minute: 14), .saturday: DateComponents(hour: 7, minute: 14), ], .friendshipHeights: [ .sunday: DateComponents(hour: 8, minute: 12), .weekday: DateComponents(hour: 5, minute: 12), .saturday: DateComponents(hour: 7, minute: 12), ], .bethesda: [ .sunday: DateComponents(hour: 8, minute: 9), .weekday: DateComponents(hour: 5, minute: 9), .saturday: DateComponents(hour: 7, minute: 9), ], .medicalCenter: [ .sunday: DateComponents(hour: 8, minute: 6), .weekday: DateComponents(hour: 5, minute: 6), .saturday: DateComponents(hour: 7, minute: 6), ], .grosvenor: [ .sunday: DateComponents(hour: 8, minute: 3), .weekday: DateComponents(hour: 5, minute: 3), .saturday: DateComponents(hour: 7, minute: 3), ], .northBethesda: [ .sunday: DateComponents(hour: 8, minute: 0), .weekday: DateComponents(hour: 5, minute: 0), .saturday: DateComponents(hour: 7, minute: 0), ], .twinbrook: [ .sunday: DateComponents(hour: 7, minute: 57), .weekday: DateComponents(hour: 4, minute: 57), .saturday: DateComponents(hour: 6, minute: 57), ], .rockville: [ .sunday: DateComponents(hour: 7, minute: 54), .weekday: DateComponents(hour: 4, minute: 54), .saturday: DateComponents(hour: 6, minute: 54), ], .shadyGrove: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .galleryPlaceUpper: [ .sunday: DateComponents(hour: 8, minute: 15), .weekday: DateComponents(hour: 5, minute: 15), .saturday: DateComponents(hour: 7, minute: 15), ], .judiciarySquare: [ .sunday: DateComponents(hour: 8, minute: 17), .weekday: DateComponents(hour: 5, minute: 17), .saturday: DateComponents(hour: 7, minute: 17), ], .unionStation: [ .sunday: DateComponents(hour: 8, minute: 15), .weekday: DateComponents(hour: 5, minute: 15), .saturday: DateComponents(hour: 7, minute: 15), ], .rhodeIslandAve: [ .sunday: DateComponents(hour: 8, minute: 11), .weekday: DateComponents(hour: 5, minute: 11), .saturday: DateComponents(hour: 7, minute: 11), ], .brookland: [ .sunday: DateComponents(hour: 8, minute: 8), .weekday: DateComponents(hour: 5, minute: 8), .saturday: DateComponents(hour: 7, minute: 8), ], .fortTottenUpper: [ .sunday: DateComponents(hour: 8, minute: 0), .weekday: DateComponents(hour: 5, minute: 0), .saturday: DateComponents(hour: 7, minute: 0), ], .takoma: [ .sunday: DateComponents(hour: 8, minute: 2), .weekday: DateComponents(hour: 5, minute: 2), .saturday: DateComponents(hour: 7, minute: 2), ], .silverSpring: [ .sunday: DateComponents(hour: 7, minute: 59), .weekday: DateComponents(hour: 4, minute: 59), .saturday: DateComponents(hour: 6, minute: 59), ], .forestGlen: [ .sunday: DateComponents(hour: 7, minute: 56), .weekday: DateComponents(hour: 4, minute: 56), .saturday: DateComponents(hour: 6, minute: 56), ], .wheaton: [ .sunday: DateComponents(hour: 7, minute: 53), .weekday: DateComponents(hour: 4, minute: 53), .saturday: DateComponents(hour: 6, minute: 53), ], .glenmont: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .noma: [ .sunday: DateComponents(hour: 8, minute: 13), .weekday: DateComponents(hour: 5, minute: 13), .saturday: DateComponents(hour: 7, minute: 13), ], .metroCenterLower: [ .sunday: DateComponents(hour: 8, minute: 14), .weekday: DateComponents(hour: 5, minute: 14), .saturday: DateComponents(hour: 7, minute: 14), ], .mcphersonSquare: [ .sunday: DateComponents(hour: 8, minute: 16), .weekday: DateComponents(hour: 5, minute: 16), .saturday: DateComponents(hour: 7, minute: 16), ], .farragutWest: [ .sunday: DateComponents(hour: 8, minute: 18), .weekday: DateComponents(hour: 5, minute: 18), .saturday: DateComponents(hour: 7, minute: 18), ], .foggyBottom: [ .sunday: DateComponents(hour: 8, minute: 16), .weekday: DateComponents(hour: 5, minute: 16), .saturday: DateComponents(hour: 7, minute: 16), ], .rosslyn: [ .sunday: DateComponents(hour: 8, minute: 17), .weekday: DateComponents(hour: 5, minute: 17), .saturday: DateComponents(hour: 7, minute: 17), ], .arlingtonCemetery: [ .sunday: DateComponents(hour: 8, minute: 17), .weekday: DateComponents(hour: 5, minute: 17), .saturday: DateComponents(hour: 7, minute: 17), ], .pentagon: [ .sunday: DateComponents(hour: 8, minute: 7), .weekday: DateComponents(hour: 5, minute: 7), .saturday: DateComponents(hour: 7, minute: 7), ], .pentagonCity: [ .sunday: DateComponents(hour: 8, minute: 5), .weekday: DateComponents(hour: 5, minute: 5), .saturday: DateComponents(hour: 7, minute: 5), ], .crystalCity: [ .sunday: DateComponents(hour: 8, minute: 3), .weekday: DateComponents(hour: 5, minute: 3), .saturday: DateComponents(hour: 7, minute: 3), ], .ronaldReaganWashingtonNationalAirport: [ .sunday: DateComponents(hour: 8, minute: 1), .weekday: DateComponents(hour: 5, minute: 1), .saturday: DateComponents(hour: 7, minute: 1), ], .braddockRoad: [ .sunday: DateComponents(hour: 7, minute: 56), .weekday: DateComponents(hour: 4, minute: 56), .saturday: DateComponents(hour: 6, minute: 56), ], .kingSt: [ .sunday: DateComponents(hour: 7, minute: 54), .weekday: DateComponents(hour: 4, minute: 54), .saturday: DateComponents(hour: 6, minute: 54), ], .eisenhowerAvenue: [ .sunday: DateComponents(hour: 7, minute: 52), .weekday: DateComponents(hour: 4, minute: 52), .saturday: DateComponents(hour: 6, minute: 52), ], .huntington: [ .sunday: DateComponents(hour: 8, minute: 50), .weekday: DateComponents(hour: 5, minute: 50), .saturday: DateComponents(hour: 7, minute: 50), ], .federalTriangle: [ .sunday: DateComponents(hour: 8, minute: 13), .weekday: DateComponents(hour: 5, minute: 13), .saturday: DateComponents(hour: 7, minute: 13), ], .smithsonian: [ .sunday: DateComponents(hour: 8, minute: 11), .weekday: DateComponents(hour: 5, minute: 11), .saturday: DateComponents(hour: 7, minute: 11), ], .lenfantPlazaLower: [ .sunday: DateComponents(hour: 8, minute: 9), .weekday: DateComponents(hour: 5, minute: 9), .saturday: DateComponents(hour: 7, minute: 9), ], .federalCenterSW: [ .sunday: DateComponents(hour: 8, minute: 7), .weekday: DateComponents(hour: 5, minute: 7), .saturday: DateComponents(hour: 7, minute: 7), ], .capitolSouth: [ .sunday: DateComponents(hour: 8, minute: 5), .weekday: DateComponents(hour: 5, minute: 5), .saturday: DateComponents(hour: 7, minute: 5), ], .easternMarket: [ .sunday: DateComponents(hour: 8, minute: 3), .weekday: DateComponents(hour: 5, minute: 3), .saturday: DateComponents(hour: 7, minute: 3), ], .potomacAve: [ .sunday: DateComponents(hour: 8, minute: 1), .weekday: DateComponents(hour: 5, minute: 1), .saturday: DateComponents(hour: 7, minute: 1), ], .stadium: [ .sunday: DateComponents(hour: 7, minute: 59), .weekday: DateComponents(hour: 4, minute: 59), .saturday: DateComponents(hour: 6, minute: 59), ], .minnesotaAve: [ .sunday: DateComponents(hour: 8, minute: 0), .weekday: DateComponents(hour: 5, minute: 0), .saturday: DateComponents(hour: 7, minute: 0), ], .deanwood: [ .sunday: DateComponents(hour: 7, minute: 58), .weekday: DateComponents(hour: 4, minute: 58), .saturday: DateComponents(hour: 6, minute: 58), ], .cheverly: [ .sunday: DateComponents(hour: 7, minute: 56), .weekday: DateComponents(hour: 4, minute: 56), .saturday: DateComponents(hour: 6, minute: 56), ], .landover: [ .sunday: DateComponents(hour: 7, minute: 53), .weekday: DateComponents(hour: 4, minute: 53), .saturday: DateComponents(hour: 6, minute: 53), ], .newCarrollton: [ .sunday: DateComponents(hour: 7, minute: 59), .weekday: DateComponents(hour: 4, minute: 59), .saturday: DateComponents(hour: 6, minute: 59), ], .mtVernonSq7thSt: [ .sunday: DateComponents(hour: 8, minute: 14), .weekday: DateComponents(hour: 5, minute: 14), .saturday: DateComponents(hour: 7, minute: 14), ], .shaw: [ .sunday: DateComponents(hour: 8, minute: 13), .weekday: DateComponents(hour: 5, minute: 13), .saturday: DateComponents(hour: 7, minute: 13), ], .uStreet: [ .sunday: DateComponents(hour: 8, minute: 11), .weekday: DateComponents(hour: 5, minute: 11), .saturday: DateComponents(hour: 7, minute: 11), ], .columbiaHeights: [ .sunday: DateComponents(hour: 8, minute: 9), .weekday: DateComponents(hour: 5, minute: 9), .saturday: DateComponents(hour: 7, minute: 9), ], .georgiaAve: [ .sunday: DateComponents(hour: 8, minute: 6), .weekday: DateComponents(hour: 5, minute: 6), .saturday: DateComponents(hour: 7, minute: 6), ], .fortTottenLower: [ .sunday: DateComponents(hour: 8, minute: 0), .weekday: DateComponents(hour: 5, minute: 0), .saturday: DateComponents(hour: 7, minute: 0), ], .westHyattsville: [ .sunday: DateComponents(hour: 7, minute: 59), .weekday: DateComponents(hour: 4, minute: 59), .saturday: DateComponents(hour: 6, minute: 59), ], .princeGeorgesPlaza: [ .sunday: DateComponents(hour: 7, minute: 56), .weekday: DateComponents(hour: 4, minute: 56), .saturday: DateComponents(hour: 6, minute: 56), ], .collegePark: [ .sunday: DateComponents(hour: 7, minute: 53), .weekday: DateComponents(hour: 4, minute: 53), .saturday: DateComponents(hour: 6, minute: 53), ], .greenbelt: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .galleryPlaceLower: [ .sunday: DateComponents(hour: 8, minute: 15), .weekday: DateComponents(hour: 5, minute: 15), .saturday: DateComponents(hour: 7, minute: 15), ], .archives: [ .sunday: DateComponents(hour: 8, minute: 13), .weekday: DateComponents(hour: 5, minute: 13), .saturday: DateComponents(hour: 7, minute: 13), ], .lenfantPlazaUpper: [ .sunday: DateComponents(hour: 8, minute: 9), .weekday: DateComponents(hour: 5, minute: 9), .saturday: DateComponents(hour: 7, minute: 9), ], .waterfront: [ .sunday: DateComponents(hour: 8, minute: 9), .weekday: DateComponents(hour: 5, minute: 9), .saturday: DateComponents(hour: 7, minute: 9), ], .navyYard: [ .sunday: DateComponents(hour: 8, minute: 7), .weekday: DateComponents(hour: 5, minute: 7), .saturday: DateComponents(hour: 7, minute: 7), ], .anacostia: [ .sunday: DateComponents(hour: 8, minute: 4), .weekday: DateComponents(hour: 5, minute: 4), .saturday: DateComponents(hour: 7, minute: 4), ], .congressHeights: [ .sunday: DateComponents(hour: 8, minute: 1), .weekday: DateComponents(hour: 5, minute: 1), .saturday: DateComponents(hour: 7, minute: 1), ], .southernAvenue: [ .sunday: DateComponents(hour: 7, minute: 59), .weekday: DateComponents(hour: 4, minute: 59), .saturday: DateComponents(hour: 6, minute: 59), ], .naylorRoad: [ .sunday: DateComponents(hour: 7, minute: 56), .weekday: DateComponents(hour: 4, minute: 56), .saturday: DateComponents(hour: 6, minute: 56), ], .suitland: [ .sunday: DateComponents(hour: 7, minute: 53), .weekday: DateComponents(hour: 4, minute: 53), .saturday: DateComponents(hour: 6, minute: 53), ], .branchAve: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .benningRoad: [ .sunday: DateComponents(hour: 7, minute: 55), .weekday: DateComponents(hour: 4, minute: 55), .saturday: DateComponents(hour: 6, minute: 55), ], .capitolHeights: [ .sunday: DateComponents(hour: 7, minute: 52), .weekday: DateComponents(hour: 4, minute: 52), .saturday: DateComponents(hour: 6, minute: 52), ], .addisonRoad: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .morganBoulevard: [ .sunday: DateComponents(hour: 7, minute: 47), .weekday: DateComponents(hour: 4, minute: 47), .saturday: DateComponents(hour: 6, minute: 47), ], .largoTownCenter: [ .sunday: DateComponents(hour: 7, minute: 44), .weekday: DateComponents(hour: 4, minute: 44), .saturday: DateComponents(hour: 6, minute: 44), ], .vanDornStreet: [ .sunday: DateComponents(hour: 7, minute: 56), .weekday: DateComponents(hour: 4, minute: 56), .saturday: DateComponents(hour: 6, minute: 56), ], .franconia: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .courtHouse: [ .sunday: DateComponents(hour: 8, minute: 10), .weekday: DateComponents(hour: 5, minute: 10), .saturday: DateComponents(hour: 7, minute: 10), ], .clarendon: [ .sunday: DateComponents(hour: 8, minute: 8), .weekday: DateComponents(hour: 5, minute: 8), .saturday: DateComponents(hour: 7, minute: 8), ], .virginiaSquare: [ .sunday: DateComponents(hour: 8, minute: 7), .weekday: DateComponents(hour: 5, minute: 7), .saturday: DateComponents(hour: 7, minute: 7), ], .ballston: [ .sunday: DateComponents(hour: 8, minute: 9), .weekday: DateComponents(hour: 5, minute: 9), .saturday: DateComponents(hour: 7, minute: 9), ], .eastFallsChurch: [ .sunday: DateComponents(hour: 8, minute: 1), .weekday: DateComponents(hour: 5, minute: 1), .saturday: DateComponents(hour: 7, minute: 1), ], .westFallsChurch: [ .sunday: DateComponents(hour: 7, minute: 58), .weekday: DateComponents(hour: 4, minute: 58), .saturday: DateComponents(hour: 6, minute: 58), ], .dunnLoring: [ .sunday: DateComponents(hour: 7, minute: 54), .weekday: DateComponents(hour: 4, minute: 54), .saturday: DateComponents(hour: 6, minute: 54), ], .vienna: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], .mcLean: [ .sunday: DateComponents(hour: 8, minute: 3), .weekday: DateComponents(hour: 5, minute: 3), .saturday: DateComponents(hour: 7, minute: 3), ], .tysonsCorner: [ .sunday: DateComponents(hour: 8, minute: 1), .weekday: DateComponents(hour: 5, minute: 1), .saturday: DateComponents(hour: 7, minute: 1), ], .greensboro: [ .sunday: DateComponents(hour: 7, minute: 59), .weekday: DateComponents(hour: 4, minute: 59), .saturday: DateComponents(hour: 6, minute: 59), ], .springHill: [ .sunday: DateComponents(hour: 7, minute: 57), .weekday: DateComponents(hour: 4, minute: 57), .saturday: DateComponents(hour: 6, minute: 57), ], .wiehle: [ .sunday: DateComponents(hour: 7, minute: 50), .weekday: DateComponents(hour: 4, minute: 50), .saturday: DateComponents(hour: 6, minute: 50), ], ] }
40.582353
86
0.533072
899a0a182863e74a4e64bce14aa5c32bd84bc0c5
1,194
// // ObservableType.swift // JDKit // // Created by ZJaDe on 2017/11/23. // Copyright © 2017年 Z_JaDe. All rights reserved. // import Foundation import RxSwift import RxCocoa public extension ObservableType { func mapToVoid() -> Observable<()> { map {_ in ()} } func mapToOptional() -> Observable<Element?> { map { Optional($0) } } } public extension ObservableType where Element == Bool { func filterTrue() -> Observable<Void> { filter({$0}).mapToVoid() } } public extension ObservableType where Element: Equatable { func ignore(values valuesToIgnore: Element...) -> Observable<Element> { return self.asObservable().filter { !valuesToIgnore.contains($0) } } } // MARK: - subscribe extension ObservableType { public func subscribeOnNext(_ onNext: @escaping (Element) -> Void) -> Disposable { subscribe(onNext: onNext, onError: { error in logError("订阅失败 error: \(error)") }) } } extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { public func driveOnNext(_ onNext: @escaping (Element) -> Void) -> Disposable { drive(onNext: onNext) } }
27.136364
88
0.654941
263af8b76d35571f2f930efda4b205f0ddb065a7
13,168
// // DownloadsTableViewController.swift // Sileo // // Created by CoolStar on 8/3/19. // Copyright © 2019 CoolStar. All rights reserved. // import Foundation class DownloadsTableViewController: SileoViewController { @IBOutlet var footerView: UIView? @IBOutlet var cancelButton: UIButton? @IBOutlet var confirmButton: UIButton? @IBOutlet var footerViewHeight: NSLayoutConstraint? @IBOutlet var tableView: UITableView? var transitionController = false var statusBarView: UIView? var upgrades: [DownloadPackage] = [] var installations: [DownloadPackage] = [] var uninstallations: [DownloadPackage] = [] var installdeps: [DownloadPackage] = [] var uninstalldeps: [DownloadPackage] = [] var errors: [[String: Any]] = [] override func viewDidLoad() { super.viewDidLoad() let statusBarView = SileoRootView(frame: .zero) self.view.addSubview(statusBarView) self.statusBarView = statusBarView self.statusBarStyle = UIDevice.current.userInterfaceIdiom == .pad ? .default : .lightContent self.tableView?.separatorStyle = .none self.tableView?.separatorColor = UIColor(red: 234/255, green: 234/255, blue: 236/255, alpha: 1) self.tableView?.isEditing = true self.tableView?.clipsToBounds = true if UIDevice.current.userInterfaceIdiom == .phone { self.tableView?.contentInsetAdjustmentBehavior = .never self.tableView?.contentInset = UIEdgeInsets(top: 43, left: 0, bottom: 0, right: 0) } confirmButton?.layer.cornerRadius = 10 confirmButton?.setTitle(String(localizationKey: "Queue_Confirm_Button"), for: .normal) cancelButton?.setTitle(String(localizationKey: "Queue_Clear_Button"), for: .normal) DownloadManager.shared.reloadData(recheckPackages: false) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard let tableView = self.tableView, let cancelButton = self.cancelButton, let confirmButton = self.confirmButton, let statusBarView = self.statusBarView else { return } statusBarView.frame = CGRect(origin: .zero, size: CGSize(width: self.view.bounds.width, height: tableView.safeAreaInsets.top)) cancelButton.tintColor = confirmButton.tintColor cancelButton.isHighlighted = confirmButton.isHighlighted confirmButton.tintColor = UINavigationBar.appearance().tintColor confirmButton.isHighlighted = confirmButton.isHighlighted } public func loadData() { let manager = DownloadManager.shared upgrades = manager.upgrades.sorted(by: { $0.package.name?.lowercased() ?? "" < $1.package.name?.lowercased() ?? "" }) installations = manager.installations.sorted(by: { $0.package.name?.lowercased() ?? "" < $1.package.name?.lowercased() ?? "" }) uninstallations = manager.uninstallations.sorted(by: { $0.package.name?.lowercased() ?? "" < $1.package.name?.lowercased() ?? "" }) installdeps = manager.installdeps.sorted(by: { $0.package.name?.lowercased() ?? "" < $1.package.name?.lowercased() ?? "" }) uninstalldeps = manager.uninstalldeps.sorted(by: { $0.package.name?.lowercased() ?? "" < $1.package.name?.lowercased() ?? "" }) errors = manager.errors } public func reloadData() { self.loadData() self.tableView?.reloadData() self.reloadControlsOnly() } public func reloadControlsOnly() { let manager = DownloadManager.shared if manager.queuedPackages() > 0 { UIView.animate(withDuration: 0.25) { self.footerViewHeight?.constant = 128 self.footerView?.alpha = 1 } } else { UIView.animate(withDuration: 0.25) { self.footerViewHeight?.constant = 0 self.footerView?.alpha = 0 } } if manager.readyPackages() >= manager.installingPackages() && manager.readyPackages() > 0 && manager.downloadingPackages() == 0 && manager.errors.isEmpty { if !manager.lockedForInstallation { manager.lockedForInstallation = true let installController = InstallViewController(nibName: "InstallViewController", bundle: nil) manager.totalProgress = 0 self.navigationController?.pushViewController(installController, animated: true) TabBarController.singleton?.presentPopupController() } } if manager.errors.isEmpty { self.confirmButton?.isEnabled = true self.confirmButton?.alpha = 1 } else { self.confirmButton?.isEnabled = false self.confirmButton?.alpha = 0.5 } } public func reloadDownload(package: Package?) { guard let package = package else { return } let dlPackage = DownloadPackage(package: package) var rawIndexPath: IndexPath? let installsAndDeps = installations + installdeps if installsAndDeps.contains(dlPackage) { rawIndexPath = IndexPath(row: installsAndDeps.firstIndex(of: dlPackage) ?? -1, section: 0) } else if upgrades.contains(dlPackage) { rawIndexPath = IndexPath(row: upgrades.firstIndex(of: dlPackage) ?? -1, section: 2) } guard let indexPath = rawIndexPath else { return } guard let cell = self.tableView?.cellForRow(at: indexPath) as? DownloadsTableViewCell else { return } cell.updateDownload() cell.layoutSubviews() } @IBAction func cancelQueued(_ sender: Any?) { DownloadManager.shared.cancelUnqueuedDownloads() TabBarController.singleton?.dismissPopupController() DownloadManager.shared.reloadData(recheckPackages: true) } @IBAction func confirmQueued(_ sender: Any?) { DownloadManager.shared.startUnqueuedDownloads() DownloadManager.shared.reloadData(recheckPackages: false) } override func accessibilityPerformEscape() -> Bool { TabBarController.singleton?.dismissPopupController() return true } } extension DownloadsTableViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { 6 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return installations.count + installdeps.count case 1: return uninstallations.count + uninstalldeps.count case 2: return upgrades.count case 3: return errors.count default: return 0 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if tableView.numberOfRows(inSection: section) == 0 { return nil } switch section { case 0: return String(localizationKey: "Queued_Install_Heading") case 1: return String(localizationKey: "Queued_Uninstall_Heading") case 2: return String(localizationKey: "Queued_Update_Heading") case 3: return String(localizationKey: "Download_Errors_Heading") default: return nil } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if (self.tableView?.numberOfRows(inSection: section) ?? 0) > 0 { let headerView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 320, height: 36))) let backgroundView = SileoRootView(frame: CGRect(x: 0, y: -24, width: 320, height: 60)) backgroundView.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin] headerView.addSubview(backgroundView) if let text = self.tableView(tableView, titleForHeaderInSection: section) { let titleView = SileoLabelView(frame: CGRect(x: 16, y: 0, width: 320, height: 28)) titleView.font = UIFont.systemFont(ofSize: 22, weight: .bold) titleView.text = text titleView.autoresizingMask = .flexibleWidth headerView.addSubview(titleView) let separatorView = SileoSeparatorView(frame: CGRect(x: 16, y: 35, width: 304, height: 1)) separatorView.autoresizingMask = .flexibleWidth headerView.addSubview(separatorView) } return headerView } return nil } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if self.tableView(tableView, numberOfRowsInSection: section) > 0 { return 36 } return 0 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { UIView() // do not show extraneous tableview separators } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { 8 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 58 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "DownloadsTableViewCellIdentifier" let cell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? DownloadsTableViewCell) ?? DownloadsTableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier) cell.icon = UIImage(named: "Tweak Icon") if indexPath.section == 3 { // Error listing let error = errors[indexPath.row] if let package = error["package"] as? Package { cell.package = DownloadPackage(package: package) } cell.shouldHaveDownload = false if let key = error["key"] as? String, let otherPkg = error["otherPkg"] as? String { cell.errorDescription = "\(key) \(otherPkg)" } cell.download = nil } else { // Normal operation listing var array: [DownloadPackage] = [] switch indexPath.section { case 0: array = installations + installdeps case 1: array = uninstallations + uninstalldeps case 2: array = upgrades default: break } cell.package = array[indexPath.row] cell.shouldHaveDownload = indexPath.section == 0 || indexPath.section == 2 cell.errorDescription = nil cell.download = nil if cell.shouldHaveDownload { cell.download = DownloadManager.shared.download(package: cell.package?.package.package ?? "") } } return cell } } extension DownloadsTableViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if indexPath.section == 3 { return false } var array: [DownloadPackage] = [] switch indexPath.section { case 0: array = installations case 1: array = uninstallations case 2: array = upgrades default: break } if indexPath.row >= array.count { return false } return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { var queue: DownloadManagerQueue = .none var array: [DownloadPackage] = [] switch indexPath.section { case 0: array = installations queue = .installations case 1: array = uninstallations queue = .uninstallations case 2: array = upgrades queue = .upgrades default: break } if indexPath.section == 3 || indexPath.row >= array.count { fatalError("Invalid section/row (not editable)") } let downloadManager = DownloadManager.shared downloadManager.remove(downloadPackage: array[indexPath.row], queue: queue) self.loadData() tableView.deleteRows(at: [indexPath], with: .fade) downloadManager.reloadData(recheckPackages: true) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
38.502924
139
0.602293
e212f117de9c22f313182ae1fd9e8b614cbc3c58
654
import RxSwift final class APICharatersService: CharactersService { // MARK: - Properties private let apiClient: APIClient // MARK: - Init init(apiClient: APIClient) { self.apiClient = apiClient } // MARK: - CharactersService func getCharacters() -> Observable<[SeriesCharacter]> { return apiClient.perform(request: CharactersRequest()) .filter { $0.data != nil } .map { try JSONDecoder().decode(CharacterResponse.self, from: $0.data!) } .map { $0.characters.filter { character in !character.name.lowercased().contains("rick") } } .asObservable() } }
26.16
104
0.622324
ff1302fb9fcd5364eacb7953dc8a0f9b830f64e2
12,127
// // LNMineInfoCell.swift // TaoKeThird // // Created by 付耀辉 on 2018/10/31. // Copyright © 2018年 付耀辉. All rights reserved. // import UIKit import DeviceKit import SwiftyJSON class LNMineInfoCell: UITableViewCell { @IBOutlet weak var user_icon: UIImageView! @IBOutlet weak var user_name: UILabel! @IBOutlet weak var heHupMark: UILabel! @IBOutlet weak var detail1: UILabel! @IBOutlet weak var invate_code: UILabel! @IBOutlet weak var copy_button: UIButton! @IBOutlet weak var fans_label: UILabel! @IBOutlet weak var express_label: UILabel! @IBOutlet weak var group_value: UILabel! @IBOutlet weak var user_balance: UILabel! // @IBOutlet weak var withdraw_button: UIButton! @IBOutlet weak var Line1: UIView! @IBOutlet weak var total_money: UILabel! @IBOutlet weak var today_money: UILabel! @IBOutlet weak var today1_money: UILabel! @IBOutlet weak var today2_money: UILabel! @IBOutlet weak var invite_partner: UIButton! @IBOutlet weak var option1: UIButton! @IBOutlet weak var option2: UIButton! @IBOutlet weak var option3: UIButton! @IBOutlet weak var option4: UIButton! @IBOutlet weak var bgView1: UIView! @IBOutlet weak var bgView2: UIView! @IBOutlet weak var bgView3: UIView! @IBOutlet weak var bgView4: UIView! @IBOutlet weak var head_height: NSLayoutConstraint! var userModel : LNMemberModel? override func awakeFromNib() { super.awakeFromNib() // Initialization code if Device() == .iPhoneX || kSCREEN_HEIGHT>800 { head_height.constant = 176+24 } bgView1.layer.cornerRadius = 12 bgView1.clipsToBounds = true bgView2.layer.cornerRadius = 8 bgView3.clipsToBounds = true bgView3.layer.cornerRadius = 5 bgView3.clipsToBounds = true bgView4.layer.cornerRadius = 5 bgView4.clipsToBounds = true copy_button.setTitleColor(kSetRGBColor(r: 254, g: 189, b: 189), for: .normal) copy_button.backgroundColor = UIColor.clear heHupMark.layer.cornerRadius = heHupMark.height/2 heHupMark.clipsToBounds = true user_icon.layer.cornerRadius = user_icon.height/2 user_icon.clipsToBounds = true invate_code.layer.cornerRadius = invate_code.height/2 invate_code.clipsToBounds = true invate_code.textColor = kSetRGBColor(r: 252, g: 192, b: 91) invate_code.borderColor = kSetRGBColor(r: 252, g: 192, b: 91) invate_code.borderWidth = 1 option1.layoutButton(with: .top, imageTitleSpace: 0) option2.layoutButton(with: .top, imageTitleSpace: 0) option3.layoutButton(with: .top, imageTitleSpace: 6) option4.layoutButton(with: .top, imageTitleSpace: 0) } @IBAction func applyNextLevl(_ sender: Any) { if userModel!.level.level.count == 0 { setToast(str: "请先登录") return } let part = LNPartnerEquityViewController() if userModel == nil { return } part.model = userModel! viewContainingController()?.navigationController?.pushViewController(part, animated: true) } func setUpUserInfo(model:LNMemberModel,levels:[LNPartnerModel]) { userModel = model heHupMark.text = " "+model.level.name+" " // return user_icon.sd_setImage(with: OCTools.getEfficientAddress(model.headimgurl), placeholderImage: UIImage.init(named: "goodImage_1")) if model.nickname.count != 0 { user_name.text = model.nickname } invate_code.text = " "+model.hashid + " 我的邀请码 " user_balance.text = model.credit1 express_label.text = "成长值 "+OCTools().getStrWithIntStr(model.credit3) group_value.text = "积分 "+OCTools().getStrWithIntStr(model.credit1) fans_label.text = "粉丝 "+model.friends_count let request = SKRequest.init() weak var weakSelf = self request.callGET(withUrl: LNUrls().kChart) { (response) in if !(response?.success)! { return } DispatchQueue.main.async(execute: { let datas = JSON((response?.data["data"])!) weakSelf?.today_money.text = datas["month"].stringValue//今日预估 weakSelf?.total_money.text = datas["today"].stringValue//本月预估 weakSelf?.today1_money.text = datas["lastMonthCommission"].stringValue//上月预估 weakSelf?.today2_money.text = datas["lastMonth"].stringValue//上月结算 }) } } @IBAction func copyCodeAction(_ sender: UIButton) { if userModel != nil { let paste = UIPasteboard.general paste.string = userModel?.hashid setToast(str: "邀请码复制成功") } } @IBAction func showPartnerEquity(_ sender: UIButton) { if userModel!.level.level.count == 0 { setToast(str: "请先登录") return } let part = LNPartnerEquityViewController() if userModel == nil { return } part.model = userModel! viewContainingController()?.navigationController?.pushViewController(part, animated: true) } @IBAction func chooseOptionsAction(_ sender: UIButton) { let tabbar = LNMineInfoTabbarController() switch sender.tag { case 1001://收益 tabbar.selectIndex = 0 break case 1002://订单 tabbar.selectIndex = 1 break case 1003://邀请 tabbar.selectIndex = 2 break case 1004://粉丝 tabbar.selectIndex = 3 break default: break } if userModel != nil { tabbar.personalInfo = userModel! } // tabbar.transitioningDelegate = self // let animation = CATransition.init() // animation.duration = 0.50 // animation.type = kCATransitionFromRight //// animation.subtype = kCATransitionFromRight // let windowLayer = viewContainingController()?.view.window?.layer // windowLayer?.add(animation, forKey: nil) // tabbar.modalTransitionStyle = .coverVertical // viewContainingController()?.tabBarController?.present(tabbar, animated: false, completion: nil) viewContainingController()?.navigationController?.pushViewController(tabbar, animated: true) } @IBAction func chooseToolsAction(_ sender: UIButton) { switch sender.tag { case 2001://新手指引 let newUser = LNNewUserViewController() newUser.isNewUser = true viewContainingController()?.navigationController?.pushViewController(newUser, animated: true) break case 2002://我的收藏 viewContainingController()?.navigationController?.pushViewController(LNShowCollectViewController(), animated: true) break case 2003://常见问题 let newUser = LNNewUserViewController() newUser.isNewUser = false viewContainingController()?.navigationController?.pushViewController(newUser, animated: true) break case 2004://专属客服 let group = LNCustomServiceViewController() if userModel == nil { return } if userModel?.group == nil || userModel?.group.type.count == 0 { isBanding = true let nav = LNNavigationController.init(rootViewController: LNBandingPhoneViewController()) viewContainingController()?.tabBarController?.present(nav, animated: true, completion: nil) return } group.group = (userModel?.group)! viewContainingController()?.navigationController?.pushViewController(group, animated: true) break case 2005://官方公告 viewContainingController()?.navigationController?.pushViewController(LNSystemNoticeViewController(), animated: true) break case 2006://意见反馈 viewContainingController()?.navigationController?.pushViewController(LNSubmitSuggestViewController(), animated: true) break case 2007://关于我们 viewContainingController()?.navigationController?.pushViewController(LNAboutUsViewController(), animated: true) break default: break } } @IBAction func gotoTaobaoCar(_ sender: UIButton) { DispatchQueue.main.async { // UIApplication.shared.statusBarStyle = .default self.viewContainingController()?.navigationController?.navigationBar.isTranslucent = false let showParam = AlibcTradeShowParams.init() showParam.openType = AlibcOpenType.H5 showParam.backUrl="tbopen25316706" showParam.linkKey = "taobao" showParam.isNeedPush=true showParam.nativeFailMode = AlibcNativeFailMode.jumpH5 let page = AlibcTradePageFactory.myCartsPage() AlibcTradeSDK.sharedInstance().tradeService().show(self.viewContainingController()!, page: page, showParams: showParam, taoKeParams: self.getTaokeParam(), trackParam: ALiTradeSDKShareParam.sharedInstance().customParams as? [AnyHashable : Any], tradeProcessSuccessCallback: { (back) in }, tradeProcessFailedCallback: { (error) in }) } } @IBAction func gotoTaobaoOrders(_ sender: UIButton) { DispatchQueue.main.async { // UIApplication.shared.statusBarStyle = .default self.viewContainingController()?.navigationController?.navigationBar.isTranslucent = false let showParam = AlibcTradeShowParams.init() showParam.openType = AlibcOpenType.H5 showParam.backUrl="tbopen25316706" showParam.linkKey = "taobao" showParam.isNeedPush=true showParam.nativeFailMode = AlibcNativeFailMode.jumpH5 let page = AlibcTradePageFactory.myOrdersPage(0, isAllOrder: true) AlibcTradeSDK.sharedInstance().tradeService().show(self.viewContainingController()!, page: page, showParams: showParam, taoKeParams: self.getTaokeParam(), trackParam: ALiTradeSDKShareParam.sharedInstance().customParams as? [AnyHashable : Any], tradeProcessSuccessCallback: { (back) in }, tradeProcessFailedCallback: { (error) in }) } } func getTaokeParam() -> AlibcTradeTaokeParams { if ALiTradeSDKShareParam.sharedInstance().isUseTaokeParam { let taoke = AlibcTradeTaokeParams.init() taoke.pid = ALiTradeSDKShareParam.sharedInstance().taoKeParams.object(forKey: "pid") as? String taoke.subPid = ALiTradeSDKShareParam.sharedInstance().taoKeParams.object(forKey: "subPid") as? String taoke.unionId = ALiTradeSDKShareParam.sharedInstance().taoKeParams.object(forKey: "unionId") as? String taoke.adzoneId = ALiTradeSDKShareParam.sharedInstance().taoKeParams.object(forKey: "adzoneId") as? String taoke.extParams = ALiTradeSDKShareParam.sharedInstance().taoKeParams.object(forKey: "extParams") as? [AnyHashable : Any] return taoke }else{ return AlibcTradeTaokeParams() } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension LNMineInfoCell : UIViewControllerTransitioningDelegate { }
34.948127
296
0.615156
48bc3a87be3bdcc7178d677c660f18448bbcbd95
2,413
import TensorFlow /// Metrics that can be registered into TrainingLoop. public enum TrainingMetrics { case loss case accuracy public var name: String { switch self { case .loss: return "loss" case .accuracy: return "accuracy" } } public var measurer: MetricsMeasurer { switch self { case .loss: return LossMeasurer(self.name) case .accuracy: return AccuracyMeasurer(self.name) } } } /// A protocal defining functionalities of a metrics measurer. public protocol MetricsMeasurer { var name: String { get set } mutating func reset() mutating func accumulate<Output, Target>( loss: Tensor<Float>?, predictions: Output?, labels: Target?) func measure() -> Float } /// A measurer for measuring loss. public struct LossMeasurer: MetricsMeasurer { public var name: String private var totalBatchLoss: Float = 0 private var batchCount: Int32 = 0 public init(_ name: String = "loss") { self.name = name } public mutating func reset() { totalBatchLoss = 0 batchCount = 0 } public mutating func accumulate<Output, Target>( loss: Tensor<Float>?, predictions: Output?, labels: Target? ) { if let newBatchLoss = loss { totalBatchLoss += newBatchLoss.scalarized() batchCount += 1 } } public func measure() -> Float { return totalBatchLoss / Float(batchCount) } } /// A measurer for measuring accuracy public struct AccuracyMeasurer: MetricsMeasurer { public var name: String private var correctGuessCount: Int32 = 0 private var totalGuessCount: Int32 = 0 public init(_ name: String = "accuracy") { self.name = name } public mutating func reset() { correctGuessCount = 0 totalGuessCount = 0 } public mutating func accumulate<Output, Target>( loss: Tensor<Float>?, predictions: Output?, labels: Target? ) { guard let predictions = predictions as? Tensor<Float>, let labels = labels as? Tensor<Int32> else { fatalError( "For accuracy measurements, the model output must be Tensor<Float>, and the labels must be Tensor<Int>." ) } correctGuessCount += Tensor<Int32>(predictions.argmax(squeezingAxis: -1) .== labels).sum() .scalarized() totalGuessCount += Int32(labels.shape.reduce(1, *)) } public func measure() -> Float { return Float(correctGuessCount) / Float(totalGuessCount) } }
24.13
112
0.67385