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
714f4d04865515edab61074a16419633ebe9c20f
2,357
// // ViewController.swift // testSwift // // Created by NATON on 2017/6/2. // Copyright © 2017年 NATON. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ private enum SegueIdentifier { static let showUserDetails = "showUserDetails" } var usernames: [String] = ["Marin"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.setupTableView() } func setupTableView() -> () { let tableView = UITableView(frame: view.frame, style: UITableViewStyle.plain) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) } //MARK: UITableViewDelegate func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return usernames.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if (cell == nil) { cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell") } cell?.textLabel?.text = usernames[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { usernametoSend = usernames[indexPath.row] performSegue(withIdentifier: SegueIdentifier.showUserDetails, sender: nil) } private var usernametoSend: String? override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case SegueIdentifier.showUserDetails?: guard let usernameToSend = usernametoSend else { assertionFailure("No username provided") return } let destination = segue.destination as! UserDetailViewController destination.username = usernameToSend default: break } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.217949
100
0.642342
214841fadbb867ba6164ef3d02a97b6ce9964561
2,177
// // ViewController.swift // Swift-study // // Created by Yi Qing on 2018/4/26. // Copyright © 2018年 Arvin. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.title = "首页" self.view.backgroundColor = .white tableView.dataSource = self tableView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datasource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = CustomViewCell.createCustomCell(tableView) cell.iconView.image = UIImage(named: datasource[indexPath.row]) cell.titleLabel.text = datasource[indexPath.row] return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let sb = UIStoryboard(name: "SliderViewController", bundle: Bundle.main) let vc = sb.instantiateViewController(withIdentifier: "sliderIdentity") self.navigationController?.pushViewController(vc, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } // MARK: - override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - lazy load lazy var datasource: Array = { () -> [String] in return ["images (00)", "images (01)", "images (02)", "images (03)", "images (04)", "images (05)", "images (06)", "images (07)", "images (08)", "images (09)", "images (10)", "images (11)", "images (12)", "images (13)"] }() }
34.015625
120
0.64814
ab2975c8cafcb590d13ac075d55adda9c1b4c63a
1,880
import Foundation import TPPDF import Combine public extension PDFAsyncGenerator { // MARK: - Combine Tasks func generateAsyncTask(to url: URL, info: PDFInfo? = nil, workQueue: DispatchQueue = .global(qos: .background)) -> Future<Void, Error> { Future<Void, Error> { [weak self] promise in workQueue.async { guard let strongSelf = self else { return } do { try strongSelf.generator.generate(to: url, info: info) promise(.success(())) } catch { promise(.failure(error)) } } } } func generateDataAsyncTask(info: PDFInfo? = nil, workQueue: DispatchQueue = .global(qos: .background)) -> Future<Data, Error> { Future<Data, Error> { [weak self] promise in workQueue.async { guard let strongSelf = self else { return } do { let data = try strongSelf.generator.generateData(info: info) promise(.success(data)) } catch { promise(.failure(error)) } } } } func generateURLAsyncTask(filename: String, info: PDFInfo? = nil, workQueue: DispatchQueue = .global(qos: .background)) -> Future<URL, Error> { Future<URL, Error> { [weak self] promise in workQueue.async { guard let strongSelf = self else { return } do { let url = try strongSelf.generator.generateURL(filename: filename, info: info) promise(.success(url)) } catch { promise(.failure(error)) } } } } }
32.982456
147
0.480851
fc1821e183dbcf80d73508d354672762defef5aa
1,591
@testable import CatbirdApp import XCTest final class FileDirectoryPathTests: RequestTestCase { func testPreferredFileURL() { let path = FileDirectoryPath(url: URL(string: "stubs")!) let request = makeRequest( url: "/news", headers: ["Accept": "text/html, application/json"] ) XCTAssertEqual( path.preferredFileURL(for: request), URL(string: "stubs/news.html")! ) } func testPreferredFileURLForURLWithPathExtension() { let path = FileDirectoryPath(url: URL(string: "mocks")!) let request = makeRequest( url: "/user.json", headers: ["Accept": "application/text"] ) XCTAssertEqual( path.preferredFileURL(for: request), URL(string: "mocks/user.json")! ) } func testFilePathsForRequestWithAccept() { let path = FileDirectoryPath(url: URL(string: "files")!) let request = makeRequest( url: "/item/1", headers: [:] ) XCTAssertEqual(path.filePaths(for: request), [ "files/item/1", ]) } func testFilePathsForRequestWithEmptyAccept() { let path = FileDirectoryPath(url: URL(string: "fixtures")!) let request = makeRequest( url: "stores", headers: ["Accept": "text/plain, application/json"] ) XCTAssertEqual(path.filePaths(for: request), [ "fixtures/stores.txt", "fixtures/stores.json", "fixtures/stores" ]) } }
29.462963
67
0.560654
e65716375b095edca1bd4a95de1946f8e61e2d0b
13,681
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @testable import Account import Foundation import FxA import Shared import XCTest class MockFxALoginClient: FxALoginClient { // Fixed per mock client, for testing. let kA = Data.randomOfLength(UInt(KeyLength))! let wrapkB = Data.randomOfLength(UInt(KeyLength))! func keyPair() -> Deferred<Maybe<KeyPair>> { let keyPair: KeyPair = RSAKeyPair.generate(withModulusSize: 512) return Deferred(value: Maybe(success: keyPair)) } func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAKeysResponse(kA: kA, wrapkB: wrapkB) return Deferred(value: Maybe(success: response)) } func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxASignResponse(certificate: "certificate") return Deferred(value: Maybe(success: response)) } func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = [FxAScopedKeyDataResponse(scope: scope, identifier: scope, keyRotationSecret: "0000000000000000000000000000000000000000000000000000000000000000", keyRotationTimestamp: 1510726317123)] return Deferred(value: Maybe(success: response)) } } // A mock client that fails locally (i.e., cannot connect to the network). class MockFxALoginClientWithoutNetwork: MockFxALoginClient { override func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { // Fail! return Deferred(value: Maybe(failure: FxAClientError.local(NSError(domain: NSURLErrorDomain, code: -1000, userInfo: nil)))) } override func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { // Fail! return Deferred(value: Maybe(failure: FxAClientError.local(NSError(domain: NSURLErrorDomain, code: -1000, userInfo: nil)))) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { // Fail! return Deferred(value: Maybe(failure: FxAClientError.local(NSError(domain: NSURLErrorDomain, code: -1000, userInfo: nil)))) } } // A mock client that responds to keys and sign with 401 errors. class MockFxALoginClientAfterPasswordChange: MockFxALoginClient { override func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAClientError.remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } override func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxAClientError.remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = FxAClientError.remote(RemoteError(code: 401, errno: 103, error: "Bad auth", message: "Bad auth message", info: "Bad auth info")) return Deferred(value: Maybe(failure: response)) } } // A mock client that responds to keys with 400/104 (needs verification responses). class MockFxALoginClientBeforeVerification: MockFxALoginClient { override func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> { let response = FxAClientError.remote(RemoteError(code: 400, errno: 104, error: "Unverified", message: "Unverified message", info: "Unverified info")) return Deferred(value: Maybe(failure: response)) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = FxAClientError.remote(RemoteError(code: 400, errno: 104, error: "Unverified", message: "Unverified message", info: "Unverified info")) return Deferred(value: Maybe(failure: response)) } } // A mock client that responds to sign with 503/999 (unknown server error). class MockFxALoginClientDuringOutage: MockFxALoginClient { override func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> { let response = FxAClientError.remote(RemoteError(code: 503, errno: 999, error: "Unknown", message: "Unknown error", info: "Unknown err info")) return Deferred(value: Maybe(failure: response)) } override func scopedKeyData(_ sessionToken: NSData, scope: String) -> Deferred<Maybe<[FxAScopedKeyDataResponse]>> { let response = FxAClientError.remote(RemoteError(code: 503, errno: 999, error: "Unknown", message: "Unknown error", info: "Unknown err info")) return Deferred(value: Maybe(failure: response)) } } class FxALoginStateMachineTests: XCTestCase { let marriedState = FxAStateTests.stateForLabel(FxAStateLabel.married) as! MarriedState override func setUp() { super.setUp() self.continueAfterFailure = false } func withMachine(_ client: FxALoginClient, callback: (FxALoginStateMachine) -> Void) { let stateMachine = FxALoginStateMachine(client: client) callback(stateMachine) } func withMachineAndClient(_ callback: (FxALoginStateMachine, MockFxALoginClient) -> Void) { let client = MockFxALoginClient() withMachine(client) { stateMachine in callback(stateMachine, client) } } func testAdvanceWhenInteractionRequired() { // The simple cases are when we get to Separated and Doghouse. There's nothing to do! // We just have to wait for user interaction. for stateLabel in [FxAStateLabel.separated, FxAStateLabel.doghouse] { let e = expectation(description: "Wait for login state machine.") let state = FxAStateTests.stateForLabel(stateLabel) withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: state, now: 0).upon { newState in XCTAssertEqual(newState.label, stateLabel) e.fulfill() } } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromEngagedBeforeVerified() { // Advancing from engaged before verified stays put. let e = self.expectation(description: "Wait for login state machine.") let engagedState = (FxAStateTests.stateForLabel(.engagedBeforeVerified) as! EngagedBeforeVerifiedState) withMachine(MockFxALoginClientBeforeVerification()) { stateMachine in stateMachine.advance(fromState: engagedState, now: engagedState.knownUnverifiedAt).upon { newState in XCTAssertEqual(newState.label.rawValue, engagedState.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromEngagedAfterVerified() { // Advancing from an Engaged state correctly XORs the keys. withMachineAndClient { stateMachine, client in // let unwrapkB = Bytes.generateRandomBytes(UInt(KeyLength)) let unwrapkB = client.wrapkB // This way we get all 0s, which is easy to test. let engagedState = (FxAStateTests.stateForLabel(.engagedAfterVerified) as! EngagedAfterVerifiedState).withUnwrapKey(unwrapkB) let e = self.expectation(description: "Wait for login state machine.") stateMachine.advance(fromState: engagedState, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.married.rawValue) if let newState = newState as? MarriedState { XCTAssertEqual(newState.kSync.hexEncodedString, "ec830aefab7dc43c66fb56acc16ed3b723f090ae6f50d6e610b55f4675dcbefba1351b80de8cbeff3c368949c34e8f5520ec7f1d4fa24a0970b437684259f946") XCTAssertEqual(newState.kXCS, "66687aadf862bd776c8fc18b8e9f8e20") } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromEngagedAfterVerifiedWithoutNetwork() { // Advancing from engaged after verified, but during outage, stays put. withMachine(MockFxALoginClientWithoutNetwork()) { stateMachine in let engagedState = FxAStateTests.stateForLabel(.engagedAfterVerified) let e = self.expectation(description: "Wait for login state machine.") stateMachine.advance(fromState: engagedState, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, engagedState.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromCohabitingAfterVerifiedDuringOutage() { // Advancing from engaged after verified, but during outage, stays put. let e = self.expectation(description: "Wait for login state machine.") let state = (FxAStateTests.stateForLabel(.cohabitingAfterKeyPair) as! CohabitingAfterKeyPairState) withMachine(MockFxALoginClientDuringOutage()) { stateMachine in stateMachine.advance(fromState: state, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, state.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromCohabitingAfterVerifiedWithoutNetwork() { // Advancing from cohabiting after verified, but when the network is not available, stays put. let e = self.expectation(description: "Wait for login state machine.") let state = (FxAStateTests.stateForLabel(.cohabitingAfterKeyPair) as! CohabitingAfterKeyPairState) withMachine(MockFxALoginClientWithoutNetwork()) { stateMachine in stateMachine.advance(fromState: state, now: 0).upon { newState in XCTAssertEqual(newState.label.rawValue, state.label.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarried() { // Advancing from a healthy Married state is easy. let e = self.expectation(description: "Wait for login state machine.") withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: self.marriedState, now: 0).upon { newState in XCTAssertEqual(newState.label, FxAStateLabel.married) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarriedWithExpiredCertificate() { // Advancing from a Married state with an expired certificate gets back to Married. let e = self.expectation(description: "Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneWeekInMilliseconds + 1 withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.married.rawValue) if let newState = newState as? MarriedState { // We should have a fresh certificate. XCTAssertLessThan(self.marriedState.certificateExpiresAt, now) XCTAssertGreaterThan(newState.certificateExpiresAt, now) } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarriedWithExpiredKeyPair() { // Advancing from a Married state with an expired keypair gets back to Married too. let e = self.expectation(description: "Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneMonthInMilliseconds + 1 withMachineAndClient { stateMachine, _ in stateMachine.advance(fromState: self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.married.rawValue) if let newState = newState as? MarriedState { // We should have a fresh key pair (and certificate, but we don't verify that). XCTAssertLessThan(self.marriedState.keyPairExpiresAt, now) XCTAssertGreaterThan(newState.keyPairExpiresAt, now) } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } func testAdvanceFromMarriedAfterPasswordChange() { // Advancing from a Married state with a 401 goes to Separated if it needs a new certificate. let e = self.expectation(description: "Wait for login state machine.") let now = self.marriedState.certificateExpiresAt + OneDayInMilliseconds + 1 withMachine(MockFxALoginClientAfterPasswordChange()) { stateMachine in stateMachine.advance(fromState: self.marriedState, now: now).upon { newState in XCTAssertEqual(newState.label.rawValue, FxAStateLabel.separated.rawValue) e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } }
49.930657
206
0.680506
7a99ccbba077562cad10342161b6054a54cc2583
2,541
// // TypeColor.swift // Pokedex // // Created by Thiago Vaz on 02/04/20. // Copyright © 2020 Thiago Vaz. All rights reserved. // import UIKit extension UIColor { convenience init(_ colorString: ColorString) { switch colorString { case .bug: self.init(red:198/255, green: 209/255, blue: 209/255, alpha:1.0) case .dark: self.init(red: 162/255, green:146/255, blue: 136/255, alpha:1.0) case .dragon: self.init(red: 162/255, green:125/255, blue: 250/255, alpha:1.0) case .electric: self.init(red: 250/255, green:224/255, blue: 120/255, alpha:1.0) case .fairy: self.init(red: 244/255, green:189/255, blue: 201/255, alpha:1.0) case .fighting: self.init(red: 214/255, green:120/255, blue: 115/255, alpha:1.0) case .fire: self.init(red: 245/255, green:172/255, blue: 120/255, alpha:1.0) case .flying: self.init(red: 198/255, green:183/255, blue: 245/255, alpha:1.0) case .ghost: self.init(red: 162/255, green:146/255, blue: 188/255, alpha:1.0) case .grass: self.init(red: 167/255, green:219/255, blue: 141/255, alpha:1.0) case .ground: self.init(red: 235/255, green:214/255, blue: 157/255, alpha:1.0) case .ice: self.init(red: 188/255, green:230/255, blue: 230/255, alpha:1.0) case .normal: self.init(red: 198/255, green:198/255, blue: 167/255, alpha:1.0) case .poison: self.init(red: 193/255, green:131/255, blue: 193/255, alpha:1.0) case .psychic: self.init(red: 250/255, green:146/255, blue: 178/255, alpha:1.0) case .rock: self.init(red: 209/255, green:193/255, blue: 125/255, alpha:1.0) case .steel: self.init(red: 209/255, green:209/255, blue: 224/255, alpha:1.0) case .metal: self.init(red: 179/255, green:166/255, blue: 161/255, alpha:1.0) case .water: self.init(red: 157/255, green:183/255, blue: 245/255, alpha:1.0) } } enum ColorString: String { case bug case dark case dragon case electric case fairy case fighting case fire case flying case ghost case grass case ground case ice case normal case poison case psychic case rock case steel case metal case water } }
33.434211
77
0.550177
76625812532a13cadb6de5be5d0dae4f7230b10c
3,828
// // AppFont.swift // DesignSystem // import CoreGraphics import UIKit /// Font definitions for Design System. public enum AppFont { /// Font sizes used in Design System. public enum Size { /// Tiny font size: 9 pt. case tiny /// Small font size: 11 pt. case small /// Regular font size: 15 pt. case regular /// Medium font size: 18 pt. case medium /// Large font size: 23 pt. case large /// Huge font size: 32 pt. case huge /// Custom font size (in points). case custom(_: CGFloat) /// Font size in points for given size enum value. var fontSize: CGFloat { switch self { case .tiny: return 9.0 case .small: return 11.0 case .regular: return 15.0 case .medium: return 18.0 case .large: return 23.0 case .huge: return 32.0 case .custom(let size): return size } } } /// Font weights used in Design System. public enum Weight: String, CaseIterable { /// Thin weight (100 units) case thin /// Extra Light weight (200 units) case extraLight /// Light weight (300 units) case light /// Regular weight (400 units) case regular /// Medium weight (500 units) case medium /// Semi-Bold weight (600 units) case semiBold /// Bold weight (700 units) case bold /// Extra-Bold weight (800 units) case extraBold /// Black weight (900 units) case black } /// Design System font for given size and weight parameters. public static func font(size: Size, weight: Weight) -> UIFont { // Ensure fonts are registered. _ = registerCustomFonts let name = fontName(for: weight) guard let font = UIFont(name: name, size: size.fontSize) else { fatalError("Unabled to load font \(String(describing: fontName))") } return font } public static let regularText = font(size: .regular, weight: .regular) static let fontFamily = "Montserrat" private static func fontName(for weight: Weight) -> String { return "\(fontFamily)-\(weight.rawValue.uppercasedFirstCharacter())" } /// Based on https://stackoverflow.com/a/49828127 /// This is needed because the fonts are not in the main target but in a framework /// A static property is used to make sure the registration is done only once private static var registerCustomFonts: Void = { for weight in Weight.allCases { registerFont(name: fontName(for: weight)) } }() private static func registerFont(name: String) { guard let fontUrl = Bundle.designSystem.url(forResource: name, withExtension: "ttf"), let fontData = NSData(contentsOf: fontUrl), let dataProvider = CGDataProvider(data: fontData), let fontRef = CGFont(dataProvider) else { print("Failed to register font - bundle identifier invalid.") return } var errorRef: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) { print("Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.") } } } extension String { fileprivate func uppercasedFirstCharacter() -> String { guard count >= 1 else { return self } return replacingCharacters(in: ...startIndex, with: String(self[startIndex]).uppercased()) } }
27.539568
141
0.571839
71c8e74e4392620cfaa4bcbb0ba04316b48bb600
8,256
// // DocViewController.swift // spdbapp // // Created by tommy on 15/5/8. // Copyright (c) 2015年 shgbit. All rights reserved. // import UIKit import Alamofire class DocViewController: UIViewController,UIWebViewDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate, UIScrollViewDelegate, UIAlertViewDelegate { @IBOutlet weak var middleView: UIView! @IBOutlet weak var btnLeftBottom: UIButton! @IBOutlet weak var btnRightBottom: UIButton! @IBOutlet weak var topView: UIView! @IBOutlet weak var txtShowTotalPage: UITextField! @IBOutlet weak var txtShowCurrentPape: UITextField! @IBOutlet weak var btnPrevious: UIButton! @IBOutlet weak var btnAfter: UIButton! var isScreenLocked: Bool = false var fileIDInfo: String? var fileNameInfo: String? var timer = Poller() var topBarView = TopbarView() var bottomBarView = BottomBarView() var totalPage = 0 var currentPage = 0 // var docPath = String() @IBOutlet weak var docView: UIWebView! override func viewDidLoad() { super.viewDidLoad() // docPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(fileIDInfo!).pdf") loadLocalPDFFile() totalPage = initfile() topBarView = TopbarView.getTopBarView(self) topBarView.backgroundColor = UIColor.clearColor() self.view.addSubview(topBarView) bottomBarView = BottomBarView().getBottomInstance(self) self.view.addSubview(bottomBarView) txtShowCurrentPape.delegate = self txtShowTotalPage.text = "共\(totalPage)页" self.currentPage = 1 self.docView.scrollView.delegate = self var tapGesture = UITapGestureRecognizer(target: self, action: "hideOrShowBottomBar:") tapGesture.cancelsTouchesInView = false self.view.addGestureRecognizer(tapGesture) } // override func viewWillAppear(animated: Bool) { // super.viewWillAppear(animated) // NSNotificationCenter.defaultCenter().addObserver(self, selector: "backToMainVC", name: HistoryInfoDidDeleteNotification, object: nil) // } // // func backToMainVC(){ // var storyBoard = UIStoryboard(name: "Main", bundle: nil) // var registerVC = storyBoard.instantiateViewControllerWithIdentifier("view") as! RegisViewController // self.presentViewController(registerVC, animated: true, completion: nil) // } // // override func viewWillDisappear(animated: Bool) { // super.viewWillDisappear(animated) // NSNotificationCenter.defaultCenter().removeObserver(self, name: HistoryInfoDidDeleteNotification, object: nil) // } func helpClick(){ var newVC = NewFeatureViewController() self.presentViewController(newVC, animated: true, completion: nil) } func shareClick(){ var shareVC = ShareViewController() self.presentViewController(shareVC, animated: true, completion: nil) } func backClick(){ self.dismissViewControllerAnimated(true, completion: nil) } func hideOrShowBottomBar(gesture: UITapGestureRecognizer){ self.bottomBarView.hidden = !self.bottomBarView.hidden } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == self.txtShowCurrentPape{ self.txtShowCurrentPape.endEditing(true) } return false } func textFieldDidEndEditing(textField: UITextField){ if textField == self.txtShowCurrentPape{ if textField.text.isEmpty{ return } var value = self.txtShowCurrentPape.text var temp = String(value) var page = temp.toInt()! if page <= 0{ return } skipToPage(page) currentPage = page } } /** 跳转到pdf指定的页码 :param: num 指定的pdf跳转页码位置 */ func skipToPage(num: Int){ var totalPDFheight = docView.scrollView.contentSize.height var pageHeight = CGFloat(totalPDFheight / CGFloat(totalPage)) var specificPageNo = num if specificPageNo <= totalPage{ var value2 = CGFloat(pageHeight * CGFloat(specificPageNo - 1)) var offsetPage = CGPointMake(0, value2) docView.scrollView.setContentOffset(offsetPage, animated: true) } println("currentpage = \(currentPage)") } /** 跳转到pdf文档第一页 */ @IBAction func btnToFirstPageClick(sender: UIButton) { skipToPage(1) currentPage = 1 self.txtShowCurrentPape.text = String(currentPage) } /** 跳转到pdf文档最后一页 */ @IBAction func btnToLastPageClick(sender: UIButton) { skipToPage(totalPage) currentPage = totalPage self.txtShowCurrentPape.text = String(currentPage) } /** 跳转到pdf文档下一页 */ @IBAction func btnToNextPageClick(sender: UIButton) { if currentPage < totalPage { ++currentPage skipToPage(currentPage) self.txtShowCurrentPape.text = String(currentPage) } } /** 跳转到pdf文档上一页 */ @IBAction func btnToPreviousPageClick(sender: UIButton) { if currentPage > 1 { --currentPage skipToPage(currentPage) self.txtShowCurrentPape.text = String(currentPage) } println("==============1") } func autoHideBottomBarView(timer: NSTimer){ if self.bottomBarView.hidden == false{ self.bottomBarView.hidden = true } } /** 返回当前pdf文件的总页数 :returns: 当前pdf文档总页数 */ func initfile() -> Int { var dataPathFromApp = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(fileIDInfo!).pdf") var path: CFString = CFStringCreateWithCString(nil, dataPathFromApp, CFStringEncoding(CFStringBuiltInEncodings.UTF8.rawValue)) var url: CFURLRef = CFURLCreateWithFileSystemPath(nil , path, CFURLPathStyle.CFURLPOSIXPathStyle, 0) if let document = CGPDFDocumentCreateWithURL(url){ var totalPages = CGPDFDocumentGetNumberOfPages(document) return totalPages }else{ self.docView.hidden = true self.topView.hidden = true UIAlertView(title: "提示", message: "当前服务器中不存在该文件", delegate: self, cancelButtonTitle: "确定").show() return 0 } } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { self.dismissViewControllerAnimated(true, completion: nil) } func scrollViewDidScroll(scrollView: UIScrollView){ var pdfHeight = scrollView.contentSize.height var onePageHeight = pdfHeight / CGFloat(totalPage) var page = (scrollView.contentOffset.y) / onePageHeight var p = Int(page + 0.5) self.txtShowCurrentPape.text = "\(p + 1)" } override func prefersStatusBarHidden() -> Bool { return true } //加锁 @IBAction func addLock(sender: UIButton) { self.isScreenLocked = !self.isScreenLocked var imageName = (self.isScreenLocked == true) ? "Lock-50" : "Unlock-50" sender.setBackgroundImage(UIImage(named: imageName), forState: UIControlState.Normal) topBarView.lblIsLocked.text = (self.isScreenLocked == true) ? "当前屏幕已锁定" : "" } override func shouldAutorotate() -> Bool { return !self.isScreenLocked } /** 加载当前pdf文档 */ func loadLocalPDFFile(){ var filePath: String = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(self.fileIDInfo!).pdf") var urlString = NSURL(fileURLWithPath: "\(filePath)") var request = NSURLRequest(URL: urlString!) self.docView.loadRequest(request) skipToPage(1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.352941
154
0.626575
f8386c8726c647ee677bbb06fe19beaae1fcd3ee
262
// // ApplicationLaunchControllerTests.swift // xDripTests // // Created by Artem Kalmykov on 04.04.2020. // Copyright © 2020 Faifly. All rights reserved. // import XCTest @testable import xDrip final class ApplicationLaunchControllerTests: XCTestCase { }
18.714286
58
0.755725
504347cc4686c566790b302481775714a30cb6e0
798
import Fluent final class CustomIdKey: Entity { let storage = Storage() static var idKey: String { return "custom_id" } static func prepare(_ database: Fluent.Database) throws { try database.create(self) { builder in builder.foreignId(for: CustomIdKey.self) builder.string("label") } } static func revert(_ database: Fluent.Database) throws { try database.delete(self) } var label: String init(id: Identifier?, label: String) { self.label = label self.id = id } init(row: Row) throws { label = try row.get("label") } func makeRow() throws -> Row { var row = Row() try row.set("label", label) return row } }
21.567568
61
0.551378
bbb91523fef51fd6a567d9d6cf22d8e143c2b840
2,571
// // CustomUIView.swift // Nucleus // // Created by Bezaleel Ashefor on 27/10/2017. // Copyright © 2017 Ephod. All rights reserved. // import UIKit class CustomUIView: UIView { let gradientLayer = CAGradientLayer() override func layoutSubviews() { // resize your layers based on the view's new frame super.layoutSubviews() gradientLayer.frame = self.bounds let color1 = hexStringToUIColor(hex: "498207").cgColor //UIColor(red: 0.00392157, green: 0.862745, blue: 0.384314, alpha: 1).cgColor let color2 = hexStringToUIColor(hex: "3D3D3D").cgColor//UIColor(red: 0.0470588, green: 0.486275, blue: 0.839216, alpha: 1).cgColor gradientLayer.colors = [color1, color2] gradientLayer.locations = [0.0, 0.8] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) self.layer.insertSublayer(gradientLayer, at: 0) //self.layer.addSublayer(gradientLayer) } func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(0.6) ) } func UIColorFromRGB(color: String) -> UIColor { return UIColorFromRGB(color: color, alpha: 1.0) } func UIColorFromRGB(color: String, alpha: Double) -> UIColor { assert(alpha <= 1.0, "The alpha channel cannot be above 1") assert(alpha >= 0, "The alpha channel cannot be below 0") var rgbValue : UInt32 = 0 let scanner = Scanner(string: color) scanner.scanLocation = 1 if scanner.scanHexInt32(&rgbValue) { let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 let green = CGFloat((rgbValue & 0xFF00) >> 8) / 255.0 let blue = CGFloat(rgbValue & 0xFF) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: CGFloat(alpha)) } return UIColor.black } }
32.961538
140
0.58382
39e152a62b7c0b9ddea79e5f105747de8a4a3f6c
743
// // KnownFor.swift // SPTest // // Created by Azeem Akram on 03/12/2018. // Copyright © 2018 StarzPlay. All rights reserved. // import UIKit class KnownFor: NSObject, Codable { //Common let poster_path:String? let id:Int64? let overview:String? let genre_ids:[Int]? let media_type:String? let original_language:String? let backdrop_path:String? let popularity:Double? let vote_count:Int? let vote_average:Double? let adult:Bool? let name:String? // Movie let release_date:String? let original_title:String? let title:String? let video:Bool? // TV let first_air_date:String? let origin_country:[String]? let original_name:String? }
19.051282
52
0.655451
c13ee6462b9e0dcff500d36927343288e2c30fc0
2,761
import Foundation import azureSwiftRuntime public protocol NodeList { var nextLink: String? { get } var hasAdditionalPages : Bool { get } var headerParameters: [String: String] { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (NodeResourcesProtocol?, Error?) -> Void) -> Void ; } extension Commands.Node { // List lists nodes in a subscription. internal class ListCommand : BaseCommand, NodeList { var nextLink: String? public var hasAdditionalPages : Bool { get { return nextLink != nil } } public var subscriptionId : String public var apiVersion = "2016-07-01-preview" public init(subscriptionId: String) { self.subscriptionId = subscriptionId super.init() self.method = "Get" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/providers/Microsoft.ServerManagement/nodes" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) if var pageDecoder = decoder as? PageDecoder { pageDecoder.isPagedData = true pageDecoder.nextLinkName = "NextLink" } let result = try decoder.decode(NodeResourcesData?.self, from: data) if var pageDecoder = decoder as? PageDecoder { self.nextLink = pageDecoder.nextLink } return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (NodeResourcesProtocol?, Error?) -> Void) -> Void { if self.nextLink != nil { self.path = nextLink! self.nextLink = nil; self.pathType = .absolute } client.executeAsync(command: self) { (result: NodeResourcesData?, error: Error?) in completionHandler(result, error) } } } }
39.442857
101
0.575516
290d024e4cd7a614e03b9e5f2ca8d52a152f5ddb
2,606
// // TimelineCollection.swift // SwiftDailyAPI // // Created by Nicholas Tian on 15/06/2015. // Copyright © 2015 nickTD. All rights reserved. // import Foundation // //public struct TimelineCollection<T>: CollectionType { // var storage: [DateIndex: T] = [:] // // public var startIndex: DateIndex // public var endIndex: DateIndex // // public init(startDate: NSDate, endDate: NSDate) { // startIndex = DateIndex(startDate) // endIndex = DateIndex(endDate) // } // // // MARK: Subscrit with `DateIndex` // public subscript (i: DateIndex) -> T? { // get { // return storage[i] // } // set { // storage[i] = newValue // // // The `TimelineCollection` expands dynamically to include the earliest and latest dates. // // To implement this functionality, any time a new date-image pair is stored using this // // subscript, we check to see if the date is before the `startIndex` or after the `endIndex`. // if i.date.compare(startIndex.date) == .OrderedAscending { // startIndex = i // } // // let endIndexComparison = i.date.compare(endIndex.date) // if endIndexComparison == .OrderedDescending || endIndexComparison == .OrderedSame { // // The `endIndex` is always one past the end so that iteration and `count` know when // // to stop, so compute the successor before storing the new `endIndex`. // endIndex = i.successor() // } // } // } //} // //// MARK: Subscript with `NSDate` //extension TimelineCollection { // public subscript (date: NSDate) -> T? { // get { // return self[DateIndex(date)] // } // set { // self[DateIndex(date)] = newValue // } // } //} // //// MARK: Subscript with `Int` for use with `UITableView` //extension TimelineCollection { // // Could give dateIndex out of range. // // NOTE: Why it is going back in time? // // Because in `UITableView` sections' indexes start at top. // // The toppest section has index as zero. // // And we want to show the timeline in a reverse chronological order. // public func dateIndexAtIndex(i: Int) -> DateIndex { // return endIndex.advancedBy(-i + -1) // } // // public func indexAtDate(date: NSDate) -> Int { // let index = dateIndexAtIndex(0) // return DateIndex(date).distanceTo(index) // } // // public func dateInRange(date: NSDate) -> Bool { // return startIndex.date < date && date < endIndex.date // } // // public subscript (i: Int) -> T? { // get { // return self[dateIndexAtIndex(i)] // } // set { // self[dateIndexAtIndex(i)] = newValue // } // } //}
29.613636
101
0.623177
879553f3db4c0660570378d9f754f2007b234c0c
3,224
import Foundation import azureSwiftRuntime public protocol GlobalSchedulesUpdate { var headerParameters: [String: String] { get set } var subscriptionId : String { get set } var resourceGroupName : String { get set } var name : String { get set } var apiVersion : String { get set } var schedule : ScheduleFragmentProtocol? { get set } func execute(client: RuntimeClient, completionHandler: @escaping (ScheduleProtocol?, Error?) -> Void) -> Void ; } extension Commands.GlobalSchedules { // Update modify properties of schedules. internal class UpdateCommand : BaseCommand, GlobalSchedulesUpdate { public var subscriptionId : String public var resourceGroupName : String public var name : String public var apiVersion = "2016-05-15" public var schedule : ScheduleFragmentProtocol? public init(subscriptionId: String, resourceGroupName: String, name: String, schedule: ScheduleFragmentProtocol) { self.subscriptionId = subscriptionId self.resourceGroupName = resourceGroupName self.name = name self.schedule = schedule super.init() self.method = "Patch" self.isLongRunningOperation = false self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/schedules/{name}" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{name}"] = String(describing: self.name) self.queryParameters["api-version"] = String(describing: self.apiVersion) self.body = schedule } public override func encodeBody() throws -> Data? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let encoder = try CoderFactory.encoder(for: mimeType) let encodedValue = try encoder.encode(schedule as? ScheduleFragmentData) return encodedValue } throw DecodeError.unknownMimeType } public override func returnFunc(data: Data) throws -> Decodable? { let contentType = "application/json" if let mimeType = MimeType.getType(forStr: contentType) { let decoder = try CoderFactory.decoder(for: mimeType) let result = try decoder.decode(ScheduleData?.self, from: data) return result; } throw DecodeError.unknownMimeType } public func execute(client: RuntimeClient, completionHandler: @escaping (ScheduleProtocol?, Error?) -> Void) -> Void { client.executeAsync(command: self) { (result: ScheduleData?, error: Error?) in completionHandler(result, error) } } } }
45.408451
141
0.62469
23217717c05535989c0d3f5dff3920bfbbb5b34e
1,227
// MIT License // // Copyright (c) 2020 Ralf Ebert // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. @testable import EndpointModel import XCTest final class EndpointLoadingResultTests: XCTestCase {}
45.444444
81
0.769356
f426fa816f839ff5bd24b0896966f39b9c008732
1,247
// // MapAPI.swift // AppTraffic // // Created by MM on 23/12/2020. // Copyright © 2020 Edward Lauv. All rights reserved. // import Foundation import Alamofire class MapAPI { static var shared = MapAPI() func fetchDirection(originPlace: PlaceModel, destinationPlace: PlaceModel ,completion: @escaping (DirectionModel)->Void) { let origin = "\(originPlace.coordinate.latitude),\(originPlace.coordinate.longitude)" let destination = "\(destinationPlace.coordinate.latitude),\(destinationPlace.coordinate.longitude)" AF.request("https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=\(APIKey.shared.googleMapsAPI)").responseJSON { (data) in switch data.result { case .success(_): do { let direction = try JSONDecoder().decode(DirectionModel.self, from: data.data!) completion(direction) } catch let error as NSError{ print("Failed to load: \(error.localizedDescription)") } case .failure(let error): print("Request error: \(error.localizedDescription)") } } } }
36.676471
191
0.622294
392278106166a48e1c7da852731b89349e06af7b
1,545
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // @testable import ___PROJECTNAMEASIDENTIFIER___ import XCTest class ___VARIABLE_sceneName___PresenterTests: XCTestCase { // MARK: Subject under test var sut: ___VARIABLE_sceneName___Presenter! // MARK: Test lifecycle override func setUp() { super.setUp() setup___VARIABLE_sceneName___Presenter() } override func tearDown() { super.tearDown() } // MARK: Test setup func setup___VARIABLE_sceneName___Presenter() { sut = ___VARIABLE_sceneName___Presenter() } // MARK: Test doubles class ___VARIABLE_sceneName___DisplayLogicSpy: ___VARIABLE_sceneName___DisplayLogic { var displaySomethingCalled = false func displaySomething(viewModel: ___VARIABLE_sceneName___.Something.ViewModel) { displaySomethingCalled = true } } // MARK: Tests func testPresentSomething() { // Given let spy = ___VARIABLE_sceneName___DisplayLogicSpy() sut.viewController = spy let response = ___VARIABLE_sceneName___.Something.Response() // When sut.presentSomething(response: response) // Then XCTAssertTrue(spy.displaySomethingCalled, "presentSomething(response:) should ask the view controller to display the result") } }
24.52381
129
0.744337
617e790f3140ba4c4b8ce7cf6e131d6d5e6a571e
3,734
// Created by Robert Bruinier import Foundation public struct Vector3 { public var x: Double public var y: Double public var z: Double public init() { self.x = 0 self.y = 0 self.z = 0 } public init(_ v: Double) { self.x = v self.y = v self.z = v } public init(x: Double, y: Double, z: Double) { self.x = x self.y = y self.z = z } public init(_ x: Double, _ y: Double, _ z: Double) { self.x = x self.y = y self.z = z } public static func - (a: Self, b: Self) -> Self { return .init(x: a.x - b.x, y: a.y - b.y, z: a.z - b.z) } public static func + (a: Self, b: Self) -> Self { return .init(x: a.x + b.x, y: a.y + b.y, z: a.z + b.z) } public static func * (a: Self, b: Self) -> Self { return .init(x: a.x * b.x, y: a.y * b.y, z: a.z * b.z) } public static func / (a: Self, b: Self) -> Self { return .init(x: a.x / b.x, y: a.y / b.y, z: a.z / b.z) } public static func -= (a: inout Self, b: Self) { a.x -= b.x a.y -= b.y a.z -= b.z } public static func += (a: inout Self, b: Self) { a.x += b.x a.y += b.y a.z += b.z } public static func *= (a: inout Self, b: Self) { a.x *= b.x a.y *= b.y a.z *= b.z } public static func /= (a: inout Self, b: Self) { a.x /= b.x a.y /= b.y a.z /= b.z } public static prefix func - (a: Self) -> Self { return .init(-a.x, -a.y, -a.z) } public static func * (a: Double, b: Self) -> Self { return .init(x: a * b.x, y: a * b.y, z: a * b.z) } public static func * (a: Self, b: Double) -> Self { return .init(x: a.x * b, y: a.y * b, z: a.z * b) } public static func + (a: Self, b: Double) -> Self { return .init(x: a.x + b, y: a.y + b, z: a.z + b) } public static func - (a: Self, b: Double) -> Self { return .init(x: a.x - b, y: a.y - b, z: a.z - b) } public static func / (a: Self, b: Double) -> Self { return .init(x: a.x / b, y: a.y / b, z: a.z / b) } public static func dotProduct(a: Self, b: Self) -> Double { return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) } public static func crossProduct(a: Self, b: Self) -> Self { return .init(x: (a.y * b.z) - (a.z * b.y), y: (a.z * b.x) - (a.x * b.z), z: (a.x * b.y) - (a.y * b.x)) } public static func reflect(a: Self, b: Self) -> Self { return a - (2.0 * Self.dotProduct(a: a, b: b) * b) } public static func refract(a: Self, b: Self, etaiOverEtat: Double) -> Self { let cosTheta = min(Self.dotProduct(a: -a, b: b), 1.0) let rOutPerp = etaiOverEtat * (a * cosTheta * b) let rOutParallel = -(abs(1.0 - rOutPerp.lengthSquared).squareRoot()) * b return rOutPerp + rOutParallel } public var length: Double { return ((x * x) + (y * y) + (z * z)).squareRoot() } public var lengthSquared: Double { return (x * x) + (y * y) + (z * z) } public var normalized: Self { let length = ((x * x) + (y * y) + (z * z)).squareRoot() if length == 0.0 { return self } return self * (1.0 / length) } public var isNearZero: Bool { let nearZero: Double = 1e-8 return (fabs(x) < nearZero) && (fabs(y) < nearZero) && (fabs(z) < nearZero) } } public func max(_ a: Vector3, _ b: Double) -> Vector3 { return .init(max(a.x, b), max(a.y, b), max(a.z, b)) }
24.728477
83
0.456883
222c85eaedc4588029adfe5b5bd0b577ae228965
4,196
// // PopBounceButton.swift // PopBounceButton // // Created by Mac Gallagher on 5/25/18. // Copyright © 2018 Mac Gallagher. All rights reserved. // import UIKit import pop open class PopBounceButton: UIButton { ///The effective bounciness of the spring animation. Higher values increase spring movement range resulting in more oscillations and springiness. Defined as a value in the range [0, 20]. Defaults to 19. open var springBounciness: CGFloat = 19 ///The effective speed of the spring animation. Higher values increase the dampening power of the spring. Defined as a value in the range [0, 20]. Defaults to 10. open var springSpeed: CGFloat = 10 ///The initial velocity of the spring animation. Higher values increase the percieved force from the user's touch. Expressed in scale factor per second. Defaults to 6. open var springVelocity: CGFloat = 6 ///The total duration of the scale animation performed after a touchUpOutside event is recognized. Expressed in seconds. Defaults to 0.3. open var cancelTapScaleDuration: TimeInterval = 0.3 ///The factor by which to scale the button after a long-press has been recognized. Defaults to 0.7. open var longPressScaleFactor: CGFloat = 0.7 ///The total duration of the scale animation performed after a long-press has been recognized. Expressed in seconds. Defaults to 0.1. open var longPressScaleDuration: TimeInterval = 0.1 ///The minimum period fingers must press on the button for a long-press to be recognized. Expressed in seconds. Defaults to 0.2. open var minimumPressDuration: TimeInterval = 0.2 private var isScaled: Bool = false private var longPressTimer: Timer = Timer() private var initialBounds: CGSize = .zero public init() { super.init(frame: .zero) initialize() } public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { addTarget(self, action: #selector(handleTouchDown), for: .touchDown) addTarget(self, action: #selector(handleTouchUpInside), for: .touchUpInside) addTarget(self, action: #selector(handleTouchUpOutside), for: .touchUpOutside) layer.rasterizationScale = UIScreen.main.scale layer.shouldRasterize = true } override open func draw(_ rect: CGRect) { super.draw(rect) initialBounds = rect.size } @objc private func handleTouchDown() { longPressTimer = Timer.scheduledTimer(timeInterval: minimumPressDuration, target: self, selector: #selector(handleScale), userInfo: nil, repeats: false) } @objc private func handleScale() { pop_removeAllAnimations() POPAnimator.applyScaleAnimation(to: self, toValue: CGPoint(c: longPressScaleFactor), duration: longPressScaleDuration) isScaled = true } @objc private func handleTouchUpInside() { pop_removeAllAnimations() let scaleFactor = frame.width / initialBounds.width POPAnimator.applySpringScaleAnimation(to: self, fromValue: CGPoint(c: scaleFactor - 0.01), toValue: .one, springBounciness: springBounciness, springSpeed: springSpeed, initialVelocity: isScaled ? .zero : CGPoint(c: -scaleFactor * springVelocity), delay: isScaled ? 0.05 : 0) longPressTimer.invalidate() isScaled = false } @objc private func handleTouchUpOutside() { POPAnimator.applyScaleAnimation(to: self, toValue: .one, duration: cancelTapScaleDuration) longPressTimer.invalidate() isScaled = false } } extension CGPoint { static var one = CGPoint(x: 1, y: 1) init(c: CGFloat) { self.init() self.x = c self.y = c } }
39.584906
206
0.642993
182016f2e0a8d90c3d462fd5002b68e2e7158222
1,731
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import PrebidMobile extension NativeAdConfiguration { convenience init?(json: [String: Any]) { guard let rawAssets = json["assets"] as? [[String: Any]] else { return nil } self.init(assets: rawAssets.compactMap(PBRNativeAsset.parse(json:))) version = json["ver"] as? String context = json["context"] as? Int ?? 0 contextsubtype = json["contextsubtype"] as? Int ?? 0 plcmttype = json["plcmttype"] as? Int ?? 0 // plcmtcnt = json["plcmtcnt"] as? NSNumber seq = json["seq"] as? NSNumber // aurlsupport = json["aurlsupport"] as? NSNumber // durlsupport = json["durlsupport"] as? NSNumber if let rawTrackers = json["eventtrackers"] as? [[String: Any]] { eventtrackers = rawTrackers.compactMap(PBRNativeEventTracker.init(json:)) } privacy = json["privacy"] as? NSNumber try? setExt((json["ext"] as? [String: AnyHashable])!) } private func enumValue<T: RawRepresentable>(_ value: Any?) -> T! where T.RawValue == Int { return T(rawValue: value as? Int ?? 0) } }
36.829787
94
0.657423
46137cd96f8a6b703163c9cdfa1bf2f1e5493b41
1,325
// // VCTypewriterEffect.swift // VideoClap // // Created by lai001 on 2021/2/14. // import Foundation import simd open class VCTypewriterEffect: NSObject, VCTextEffectProviderProtocol { public var isFadeIn: Bool = false open func effectImage(context: VCTextEffectRenderContext) -> CIImage? { let length = CGFloat(context.text.length) * context.progress let textRange = NSRange(location: 0, length: Int(length)) if textRange.length == .zero { return nil } let renderText = context.text.attributedSubstring(from: textRange).mutableCopy() as! NSMutableAttributedString if isFadeIn { let alpha = simd_fract(Float(length)) var foregroundColor: UIColor = (renderText.attribute(.foregroundColor, at: renderText.length - 1, effectiveRange: nil) as? UIColor) ?? .black foregroundColor = foregroundColor.withAlphaComponent(CGFloat(alpha)) renderText.addAttribute(.foregroundColor, value: foregroundColor, range: NSRange(location: renderText.length - 1, length: 1)) } let renderer = VCGraphicsRenderer() renderer.rendererRect.size = context.textSize return renderer.ciImage { (_) in renderText.draw(at: .zero) } } }
33.974359
153
0.65283
bb23f2fdc0b90d4cad03215cbde7c385232a75d5
703
import Intents extension TransactionType { convenience init(transaction: TransactionResource) { self.init(identifier: transaction.id, display: transaction.attributes.description, subtitle: transaction.attributes.amount.valueShort, image: nil) self.transactionDescription = transaction.attributes.description self.transactionCreationDate = transaction.attributes.creationDate self.transactionAmount = transaction.attributes.amount.valueShort self.transactionColour = transaction.attributes.amount.transactionType.colour } } extension Array where Element: TransactionType { var collection: INObjectCollection<TransactionType> { return INObjectCollection(items: self) } }
39.055556
150
0.810811
61dda6d2b1b95d6f61230104bc62a68f43671eb9
514
// // ViewController.swift // TestSudoBuildScript // // Created by Sergey Klimov on 9/14/15. // Copyright (c) 2015 darvin. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.769231
80
0.673152
eff010042d6ee3c6250e267952ad01286bfc98b5
957
//===--- CaptureProp.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// func sum(_ x:Int, y:Int) -> Int { return x + y } @inline(never) func benchCaptureProp<S : Sequence >( _ s: S, _ f: (S.Iterator.Element, S.Iterator.Element) -> S.Iterator.Element) -> S.Iterator.Element { var it = s.makeIterator() let initial = it.next()! return IteratorSequence(it).reduce(initial, f) } public func run_CaptureProp(_ N: Int) { let a = 1...10_000 for _ in 1...100*N { _ = benchCaptureProp(a, sum) } }
29
102
0.586207
21683b70ce912d3d7d5512055146d404895378c6
2,297
// // MovieApiManager.swift // Flix // // Created by Donie Ypon on 10/12/18. // Copyright © 2018 Donie Ypon. All rights reserved. // import Foundation class MovieApiManager { static let baseUrl = "https://api.themoviedb.org/3/movie/" static let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" var session: URLSession init() { session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) } func nowPlayingMovies(completion: @escaping ([Movie]?, Error?) -> ()) { let url = URL(string: MovieApiManager.baseUrl + "now_playing?api_key=\(MovieApiManager.apiKey)")! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let task = session.dataTask(with: request) { (data, response, error) in // This will run when the network request returns if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let movieDictionaries = dataDictionary["results"] as! [[String: Any]] let movies = Movie.movies(dictionaries: movieDictionaries) completion(movies, nil) } else { completion(nil, error) } } task.resume() } func superheroMovies(completion: @escaping ([Movie]?, Error?) -> ()) { let url = URL(string: MovieApiManager.baseUrl + "141052/similar?api_key=\(MovieApiManager.apiKey)")! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let task = session.dataTask(with: request) { (data, response, error) in // This will run when the network request returns if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let movieDictionaries = dataDictionary["results"] as! [[String: Any]] let movies = Movie.movies(dictionaries: movieDictionaries) completion(movies, nil) } else { completion(nil, error) } } task.resume() } }
40.298246
113
0.604702
2278f3d2a58adc92c761a374a55ff102e4bac810
1,766
// // Copyright (c) 2019 Touch Instinct // // 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 Scaremonger final class RenewSessionSubscriber: ScaremongerSubscriber { private let sessionService: SessionService init(sessionService: SessionService) { self.sessionService = sessionService } func onNext(error: Error, callback: @escaping RetryClosureType) -> Disposable { guard error as? ApiError == .sessionExpired else { return ScaremongerDisposable() } return sessionService .renew() .subscribe(onSuccess: { _ in callback(true) }, onError: { _ in callback(false) }) .toScaremongerDisposable() } }
40.136364
83
0.711212
ac1a57acb57107c23e91e2b4c4659616a37d03ab
608
// // StringStack.swift // MyVoice // // Created by Pierre on 12/28/16. // Copyright © 2016 Pierre. All rights reserved. // import Foundation struct StringStack { var items = [String]() mutating func push(_ item: String) { items.append(item) } mutating func pop() -> String { return items.removeLast() } mutating func print() -> String{ var result: String = "" for item in items{ result += item + "/" } return result } mutating func isEmpty() -> Bool{ return items.isEmpty } }
18.424242
49
0.539474
01bc624efaf8aab3c856929cda7e2171cd34086a
549
// // MainViewController.swift // Luke Porupski // // Created by Luke Porupski on 12/11/19. // Copyright © 2019 Luke Porupski. All rights reserved. // import AppKit class MainViewController: NSViewController { override func viewDidAppear() { super.viewDidAppear() // You can use a notification and observe it in a view model where you want to fetch the data for your SwiftUI view every time the popover appears. // NotificationCenter.default.post(name: Notification.Name("ViewDidAppear"), object: nil) } }
27.45
155
0.704918
ef8ce312b30e4635e406659a944240311515154c
3,265
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Distributed Tracing Baggage // open source project // // Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing Baggage // project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import InstrumentationBaggage import XCTest final class BaggageTests: XCTestCase { func test_topLevelBaggageIsEmpty() { let baggage = Baggage.topLevel XCTAssertTrue(baggage.isEmpty) XCTAssertEqual(baggage.count, 0) } func test_readAndWriteThroughSubscript() throws { var baggage = Baggage.topLevel XCTAssertNil(baggage[FirstTestKey.self]) XCTAssertNil(baggage[SecondTestKey.self]) baggage[FirstTestKey.self] = 42 baggage[SecondTestKey.self] = 42.0 XCTAssertFalse(baggage.isEmpty) XCTAssertEqual(baggage.count, 2) XCTAssertEqual(baggage[FirstTestKey.self], 42) XCTAssertEqual(baggage[SecondTestKey.self], 42.0) } func test_forEachIteratesOverAllBaggageItems() { var baggage = Baggage.topLevel baggage[FirstTestKey.self] = 42 baggage[SecondTestKey.self] = 42.0 baggage[ThirdTestKey.self] = "test" var baggageItems = [AnyBaggageKey: Any]() baggage.forEach { key, value in baggageItems[key] = value } XCTAssertEqual(baggageItems.count, 3) XCTAssertTrue(baggageItems.contains(where: { $0.key.name == "FirstTestKey" })) XCTAssertTrue(baggageItems.contains(where: { $0.value as? Int == 42 })) XCTAssertTrue(baggageItems.contains(where: { $0.key.name == "SecondTestKey" })) XCTAssertTrue(baggageItems.contains(where: { $0.value as? Double == 42.0 })) XCTAssertTrue(baggageItems.contains(where: { $0.key.name == "explicit" })) XCTAssertTrue(baggageItems.contains(where: { $0.value as? String == "test" })) } func test_TODO_doesNotCrashWithoutExplicitCompilerFlag() { _ = Baggage.TODO(#function) } func test_automaticPropagationThroughTaskLocal() throws { #if swift(>=5.5) guard #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) else { throw XCTSkip("Task locals are not supported on this platform.") } XCTAssertNil(Baggage.current) var baggage = Baggage.topLevel baggage[FirstTestKey.self] = 42 var propagatedBaggage: Baggage? func exampleFunction() { propagatedBaggage = Baggage.current } Baggage.$current.withValue(baggage, operation: exampleFunction) XCTAssertEqual(propagatedBaggage?.count, 1) XCTAssertEqual(propagatedBaggage?[FirstTestKey.self], 42) #endif } private enum FirstTestKey: BaggageKey { typealias Value = Int } private enum SecondTestKey: BaggageKey { typealias Value = Double } private enum ThirdTestKey: BaggageKey { typealias Value = String static let nameOverride: String? = "explicit" } }
32.009804
87
0.62879
50260aa9f28135d14c1258f3be843f2468506fc5
4,837
// // MapCache.swift // MapCache // // Created by merlos on 13/05/2019. // import Foundation import MapKit /// The real brain public class MapCache : MapCacheProtocol { public var config : MapCacheConfig public var diskCache : DiskCache let operationQueue = OperationQueue() public init(withConfig config: MapCacheConfig ) { self.config = config diskCache = DiskCache(withName: config.cacheName, capacity: config.capacity) } public func url(forTilePath path: MKTileOverlayPath) -> URL { //print("CachedTileOverlay:: url() urlTemplate: \(urlTemplate)") var urlString = config.urlTemplate.replacingOccurrences(of: "{z}", with: String(path.z)) urlString = urlString.replacingOccurrences(of: "{x}", with: String(path.x)) urlString = urlString.replacingOccurrences(of: "{y}", with: String(path.y)) urlString = urlString.replacingOccurrences(of: "{s}", with: config.roundRobinSubdomain() ?? "") Log.debug(message: "MapCache::url() urlString: \(urlString)") return URL(string: urlString)! } public func cacheKey(forPath path: MKTileOverlayPath) -> String { return "\(config.urlTemplate)-\(path.x)-\(path.y)-\(path.z)" } // Fetches tile from server. If it is found updates the cache public func fetchTileFromServer(at path: MKTileOverlayPath, failure fail: ((Error?) -> ())? = nil, success succeed: @escaping (Data) -> ()) { let url = self.url(forTilePath: path) print ("MapCache::fetchTileFromServer() url=\(url)") let task = URLSession.shared.dataTask(with: url) {(data, response, error) in if error != nil { print("!!! MapCache::fetchTileFromServer Error for url= \(url) \(error.debugDescription)") fail!(error) return } guard let data = data else { print("!!! MapCache::fetchTileFromServer No data for url= \(url)") fail!(nil) return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("!!! MapCache::fetchTileFromServer statusCode != 2xx url= \(url)") fail!(nil) return } succeed(data) } task.resume() } public func loadTile(at path: MKTileOverlayPath, result: @escaping (Data?, Error?) -> Void) { let key = cacheKey(forPath: path) // Tries to load the tile from the server. // If it fails returns error to the caller. let tileFromServerFallback = { () -> () in print ("MapCache::tileFromServerFallback:: key=\(key)" ) self.fetchTileFromServer(at: path, failure: {error in result(nil, error)}, success: {data in self.diskCache.setData(data, forKey: key) print ("MapCache::fetchTileFromServer:: Data received saved cacheKey=\(key)" ) result(data, nil)}) } // Tries to load the tile from the cache. // If it fails returns error to the caller. let tileFromCacheFallback = { () -> () in self.diskCache.fetchDataSync(forKey: key, failure: {error in result(nil, error)}, success: {data in result(data, nil)}) } switch config.loadTileMode { case .cacheThenServer: diskCache.fetchDataSync(forKey: key, failure: {error in tileFromServerFallback()}, success: {data in result(data, nil) }) case .serverThenCache: fetchTileFromServer(at: path, failure: {error in tileFromCacheFallback()}, success: {data in result(data, nil) }) case .serverOnly: fetchTileFromServer(at: path, failure: {error in result(nil, error)}, success: {data in result(data, nil)}) case .cacheOnly: diskCache.fetchDataSync(forKey: key, failure: {error in result(nil, error)}, success: {data in result(data, nil)}) } } public var diskSize: UInt64 { get { return diskCache.diskSize } } public func calculateDiskSize() -> UInt64 { return diskCache.calculateDiskSize() } public func clear(completition: (() -> ())? ) { diskCache.removeAllData(completition) } }
38.388889
125
0.542072
d6abbf7eda0518d1ecd5d1c99324c799efbd6bff
2,556
// // SwiftRoutesTests.swift // SwiftRoutesTests // // Created by FUJIKI TAKESHI on 2016/08/27. // Copyright © 2016年 takecian. All rights reserved. // import XCTest @testable import SwiftRoutes class SwiftRoutesTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() SwiftRoutes.removeAllRoutes() } func testExampleWithParams() { var abcRouteHandled = false let testUrl = "http://abc/qqq/aaa?test=aaaaaaa&hatena=bookmark" SwiftRoutes.addRoute(URL(string: "http://abc/:key/aaa")!) { (params) -> Bool in abcRouteHandled = true XCTAssertTrue(params["absoluteString"] == testUrl) XCTAssertTrue(params["key"] == "qqq") XCTAssertTrue(params["test"] == "aaaaaaa") XCTAssertTrue(params["hatena"] == "bookmark") return true } XCTAssertTrue(!abcRouteHandled, "abcRouteHandled handled") XCTAssertTrue(SwiftRoutes.routeUrl(URL(string: testUrl)!), "not handled") XCTAssertTrue(abcRouteHandled, "abcRouteHandled not handled") } func testWithoutSchemeForHttp() { var httpRouteHandled = false SwiftRoutes.addRoute(URL(string: "/abc/:key/aaa")!) { (params) -> Bool in httpRouteHandled = true return true } XCTAssertTrue(!httpRouteHandled, "abcRouteHandled handled") XCTAssertTrue(SwiftRoutes.routeUrl(URL(string: "http://abc/qqq/aaa?test=true")!), "not handled") XCTAssertTrue(httpRouteHandled, "abcRouteHandled not handled") } func testWithoutSchemeForCustom() { var customRouteHandled = false SwiftRoutes.addRoute(URL(string: "/abc/:key/aaa")!) { (params) -> Bool in customRouteHandled = true return true } XCTAssertTrue(!customRouteHandled, "abcRouteHandled handled") XCTAssertTrue(SwiftRoutes.routeUrl(URL(string: "myapp://abc/qqq/aaa?test=true")!), "not handled") XCTAssertTrue(customRouteHandled, "abcRouteHandled not handled") } func testWitDifferentScheme() { var customAbcRouteHandled = false SwiftRoutes.addRoute(URL(string: "http://abc/:key/aaa")!) { (params) -> Bool in customAbcRouteHandled = true return true } XCTAssertTrue(!SwiftRoutes.routeUrl(URL(string: "myapp://abc/qqq/aaa?test=true")!), "not handled") XCTAssertTrue(!customAbcRouteHandled, "abcRouteHandled not handled") } }
32.35443
106
0.638106
5b10f8898542d69642e2e8076be0973e2cc64a0b
1,018
// // JSWebView.swift // FineEpub // // Created by Mehdi Sohrabi on 6/18/18. // import UIKit public class JSWebView: UIWebView, UIWebViewDelegate { public weak var webViewBridgeDelegate: WebViewBridgeDelegate? = nil public override init(frame: CGRect) { super.init(frame: frame) localInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) localInit() } private func localInit() { self.delegate = self } // MARK: - UIWebViewDelegate public func webViewDidFinishLoad(_ webView: UIWebView) { webViewBridgeDelegate?.pageLoadFinished() } public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.url?.absoluteString.range(of: "undefined") != nil { webViewBridgeDelegate?.tapDetected() return false } return true } }
23.674419
137
0.629666
fe2e4d03bcced2179f3f2895277367dd5b3a0b50
2,104
import Environment import Request import UI public struct MergeOrRebase: Procedure { public enum Mode { case merge, rebase } private let branch: String? private let expression: String? private let all: Bool private let parent: Bool private let mode: Mode public init(branch: String?, all: Bool, parent: Bool, expression: String?, mode: Mode) { self.branch = branch self.all = all self.parent = parent self.expression = expression self.mode = mode } public func run() -> Bool { guard let currentBranch = Env.current.git.currentBranch else { Env.current.shell.write("No current branch.") return false } let branchToMerge: String if let branch = branch, !branch.isEmpty { branchToMerge = branch } else if let pattern = expression, let branch = Env.current.git.branch(containing: pattern, excludeCurrent: true, options: .regularExpression) { branchToMerge = branch } else if parent, let currentIssueKey = Env.current.jira.currentIssueKey(), let parentIssueKey = GetIssue(issueKey: currentIssueKey).awaitResponseWithDebugPrinting()?.fields.parent?.key, let parentIssueBranch = Env.current.git.branch(containing: parentIssueKey, excludeCurrent: true) { branchToMerge = parentIssueBranch } else { let branches = Env.current.git.branches(all ? .all : .local) let dataSource = GenericLineSelectorDataSource(items: branches) let lineSelector = LineSelector(dataSource: dataSource) guard let selection = lineSelector?.singleSelection()?.output else { return true } branchToMerge = selection } return Env.current.git.checkout(branchToMerge) && Env.current.git.pull() && Env.current.git.checkout(currentBranch) && (mode == .merge ? Env.current.git.merge : Env.current.git.rebase)(branchToMerge) } }
35.661017
122
0.622624
9153a882678b57a7136401c92ec375837c7bd1c8
5,848
// // URLProtocolTests.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // 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 Alamofire import Foundation import XCTest class ProxyURLProtocol: URLProtocol { // MARK: Properties struct PropertyKeys { static let handledByForwarderURLProtocol = "HandledByProxyURLProtocol" } lazy var session: URLSession = { let configuration: URLSessionConfiguration = { let configuration = URLSessionConfiguration.ephemeral configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return configuration }() let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil) return session }() var activeTask: URLSessionTask? // MARK: Class Request Methods override class func canInit(with request: URLRequest) -> Bool { if URLProtocol.property(forKey: PropertyKeys.handledByForwarderURLProtocol, in: request) != nil { return false } return true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { if let headers = request.allHTTPHeaderFields { do { return try URLEncoding.default.encode(request, with: headers) } catch { return request } } return request } override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool { return false } // MARK: Loading Methods override func startLoading() { // rdar://26849668 - URLProtocol had some API's that didnt make the value type conversion let urlRequest = (request.urlRequest! as NSURLRequest).mutableCopy() as! NSMutableURLRequest URLProtocol.setProperty(true, forKey: PropertyKeys.handledByForwarderURLProtocol, in: urlRequest) activeTask = session.dataTask(with: urlRequest as URLRequest) activeTask?.resume() } override func stopLoading() { activeTask?.cancel() } } // MARK: - extension ProxyURLProtocol: URLSessionDelegate { // MARK: NSURLSessionDelegate func URLSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceiveData data: Data) { client?.urlProtocol(self, didLoad: data) } func URLSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let response = task.response { client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) } client?.urlProtocolDidFinishLoading(self) } } // MARK: - class URLProtocolTestCase: BaseTestCase { var manager: SessionManager! // MARK: Setup and Teardown override func setUp() { super.setUp() manager = { let configuration: URLSessionConfiguration = { let configuration = URLSessionConfiguration.default configuration.protocolClasses = [ProxyURLProtocol.self] configuration.httpAdditionalHeaders = ["session-configuration-header": "foo"] return configuration }() return SessionManager(configuration: configuration) }() } // MARK: Tests func testThatURLProtocolReceivesRequestHeadersAndSessionConfigurationHeaders() { // Given let urlString = "https://httpbin.org/response-headers" let url = URL(string: urlString)! var urlRequest = URLRequest(url: url) urlRequest.httpMethod = HTTPMethod.get.rawValue urlRequest.setValue("foobar", forHTTPHeaderField: "request-header") let expectation = self.expectation(description: "GET request should succeed") var response: DefaultDataResponse? // When manager.request(urlRequest) .response { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil(response?.request) XCTAssertNotNil(response?.response) XCTAssertNotNil(response?.data) XCTAssertNil(response?.error) if let headers = response?.response?.allHeaderFields as? [String: String] { XCTAssertEqual(headers["request-header"], "foobar") // Configuration headers are only passed in on iOS 9.0+ if #available(iOS 9.0, *) { XCTAssertEqual(headers["session-configuration-header"], "foo") } else { XCTAssertNil(headers["session-configuration-header"]) } } else { XCTFail("headers should not be nil") } } }
32.670391
109
0.662962
abedad70f4ae76cf7e1ef0a83e28fcc3d312ad2e
437
// // +NSObject.swift // SugerKit // import UIKit public extension NSObject { /// 交换方法 static func exchange(_ method1: String, _ method2: String) { guard let m1 = class_getInstanceMethod(self, Selector(method1)) else { return } guard let m2 = class_getInstanceMethod(self, Selector(method2)) else { return } method_exchangeImplementations(m1, m2) } }
19
78
0.601831
1c9dc646b6547fc6e239c2e079bee112d617350e
1,450
// // AppDelegate.swift // QuizApp // // Created by 大嶋祐平 on 2021/01/04. // import UIKit import GoogleMobileAds @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. GADMobileAds.sharedInstance().start(completionHandler: nil) 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. } }
35.365854
179
0.738621
566be7f6b7152669ced7efdbc47452962421e8a3
4,703
import Logging import Metrics extension SwiftHooks { func handleMessage(_ message: Messageable, from h: _Hook) { guard config.commands.enabled, message.content.starts(with: self.config.commands.prefix) else { return } let foundCommands = self.findCommands(for: message) foundCommands.forEach { (command) in guard command.hookWhitelist.isEmpty || command.hookWhitelist.contains(h.id) else { return } let event = CommandEvent(hooks: self, cmd: command, msg: message, for: h) do { event.logger.debug("Invoking command") event.logger.trace("Full message: \(message.content)") try Timer.measure(label: "command_duration", dimensions: [("command", command.fullTrigger)]) { try command.invoke(on: event, using: self) } event.logger.debug("Command succesfully invoked.") } catch let e { event.message.error(e, on: command) event.logger.error("\(e.localizedDescription)") Counter(label: "command_failure", dimensions: [("command", command.fullTrigger)]).increment() } Counter(label: "command_success", dimensions: [("command", command.fullTrigger)]).increment() } } func findCommands(for message: Messageable) -> [_ExecutableCommand] { return self.commands.compactMap { return message.content.starts(with: self.config.commands.prefix + $0.fullTrigger) ? $0 : nil } } } /// Errors thrown from command invocations or pre-checking. public enum CommandError: Error { /// User executing this command does not have the required permissions. /// /// Thrown from `CommandPermissionChecker` case InvalidPermissions /// Development error. Consuming arguments should always appear last in the argument chain. /// /// Thrown at `SwiftHooks.register(_ plugin:)` time. case ConsumingArgumentIsNotLast(String) /// Invalid argument passed on command invocation. /// /// Thrown from argument decoding. case UnableToConvertArgument(String, String) /// Invalid or too few arguments passed on command invocation. /// /// Thrown from argument decoding case ArgumentNotFound(String) /// Retrieve the localized description for this error. public var localizedDescription: String { switch self { case .ArgumentNotFound(let arg): return "Missing argument: \(arg)" case .InvalidPermissions: return "Invalid permissions!" case .UnableToConvertArgument(let arg, let type): return "Error converting \(arg) to \(type)" case .ConsumingArgumentIsNotLast(let arg): return "Consuming argument \(arg) is not the last one in the argument chain." } } } /// Event passed in to a command closure containing required data. public struct CommandEvent { /// Refference to `SwiftHooks` instance dispatching this command. public let hooks: SwiftHooks /// User that executed the command. Can be downcast to backend specific type. public let user: Userable /// String arguments passed in to the command. All space separated strings after the commands trigger. public let args: [String] /// Message that executed the command. public let message: Messageable /// Full trigger of the command. Either name or name and group. public let name: String /// Hook that originally dispatched this command. Can be downcast to backend specific type. public let hook: _Hook /// Command specific logger. Has command trigger set as command metadata by default. public private(set) var logger: Logger /// Create a new `CommandEvent` /// /// - parameters: /// - hooks: `SwiftHooks` instance dispatching this command. /// - cmd: Command this event is wrapping. /// - msg: Message that executed the command. /// - h: `_Hook` that originally dispatched this command. public init(hooks: SwiftHooks, cmd: _ExecutableCommand, msg: Messageable, for h: _Hook) { self.logger = Logger(label: "SwiftHooks.Command") self.hooks = hooks self.user = msg.gAuthor self.message = msg var comps = msg.content.split(separator: " ") let hasGroup = cmd.group != nil var name = "\(comps.removeFirst())" if hasGroup { name += " \(comps.removeFirst())" } self.name = name self.args = comps.map(String.init) self.hook = h self.logger[metadataKey: "command"] = "\(cmd.fullTrigger)" } }
43.146789
136
0.642143
2690d90ee1c05ae1c4f1f84834fdbd4c895c1bbd
1,749
// // GlobalData.swift // Salome // // Created by App Designer2 on 17.08.20. // import Foundation import SwiftUI import NaturalLanguage import Combine class GlobalData : ObservableObject { @Published public var image : [UIImage] = [] } //Start Login class Login : ObservableObject { @Published var isLoged = false @Published var pickerPer = false @Published public var perfil : Data = .init(count: 0) @Published public var email : String = UserDefaults.standard.string(forKey: "email") ?? "" { didSet { UserDefaults.standard.set(self.email, forKey: "email") } } @Published public var password : String = UserDefaults.standard.string(forKey: "password") ?? "" { didSet { UserDefaults.standard.set(self.password, forKey: "password") } } } //End Login //Start SignUp class SignUp : ObservableObject { @Published public var perfil : Data = .init(count: 0) @Published public var pickerPer = false @Published public var isTrue = false @Published public var email : String = "" /*UserDefaults.standard.string(forKey: "email") ?? "" { didSet { UserDefaults.standard.set(self.email, forKey: "email") } }*/ @Published public var password : String = "" /*UserDefaults.standard.string(forKey: "password") ?? "" { didSet { UserDefaults.standard.set(self.password, forKey: "password") } }*/ @Published public var repeatPassword : String = "" /*UserDefaults.standard.string(forKey: "repeatPassword") ?? "" { didSet { UserDefaults.standard.set(self.repeatPassword, forKey: "repeatPassword") } }*/ } //End SignUp
26.104478
119
0.621498
691e316ac1bf7de52ff52065a9e5cad99c9627ec
1,807
import UIKit /* A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps. Write a function: class Solution { public int solution(int N); } that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..2,147,483,647]. */ public func solution(_ N : Int) -> Int { let characterArray = [String(N, radix: 2)].flatMap { $0 } let stringArray = characterArray.map { String($0) } print(stringArray) var maxGap = 0 var currentGap = 0 for (index, string) in stringArray.enumerated() { if string == "0" { if index == stringArray.count - 1 { currentGap = 0 }else{ currentGap += 1 } }else{ maxGap = max(currentGap, maxGap) currentGap = 0 } } return maxGap } print(solution(1))
41.068182
437
0.696735
6173dba89d318d943b63a5623dea70264eebaa04
1,110
// // WelcomeViewController.swift // wspr // // Created by Pinto Junior, William James on 13/01/22. // import UIKit class WelcomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func logInPress(_ sender: UIButton) { let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) guard let viewVC = storyboard.instantiateViewController(withIdentifier: "LogInAndSignUpViewController") as? LogInAndSignUpViewController else{ return } viewVC.welcomeType = .login self.navigationController?.pushViewController(viewVC, animated: true) } @IBAction func signUpPress(_ sender: UIButton) { let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) guard let viewVC = storyboard.instantiateViewController(withIdentifier: "LogInAndSignUpViewController") as? LogInAndSignUpViewController else{ return } viewVC.welcomeType = .signup self.navigationController?.pushViewController(viewVC, animated: true) } }
32.647059
150
0.695495
e43b547bfb607e23f027b847ba810722eb18ed0a
12,071
// // KVKCalendarSettings.swift // KVKCalendar_Example // // Created by Sergei Kviatkovskii on 5/1/22. // Copyright © 2022 CocoaPods. All rights reserved. // import Foundation import KVKCalendar import EventKit protocol KVKCalendarSettings { var selectDate: Date { get set } var events: [Event] { get set } var style: Style { get } var eventViewer: EventViewer { get set } } extension KVKCalendarSettings { var topOffset: CGFloat { let barHeight = UIApplication.shared.statusBarHeight if #available(iOS 11.0, *) { return UIApplication.shared.activeWindow?.rootViewController?.view.safeAreaInsets.top ?? barHeight } else { return barHeight } } var bottomOffset: CGFloat { if #available(iOS 11.0, *) { return UIApplication.shared.activeWindow?.rootViewController?.view.safeAreaInsets.bottom ?? 0 } else { return 0 } } var defaultStringDate: String { "14.12.2022" } var defaultDate: Date { onlyDateFormatter.date(from: defaultStringDate) ?? Date() } var onlyDateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "dd.MM.yyyy" return formatter } func handleChangingEvent(_ event: Event, start: Date?, end: Date?) -> (range: Range<Int>, events: [Event])? { var eventTemp = event guard let startTemp = start, let endTemp = end else { return nil } let startTime = timeFormatter(date: startTemp, format: style.timeSystem.format) let endTime = timeFormatter(date: endTemp, format: style.timeSystem.format) eventTemp.start = startTemp eventTemp.end = endTemp eventTemp.title = TextEvent(timeline: "\(startTime) - \(endTime)\n new time", month: "\(startTime) - \(endTime)\n new time", list: "\(startTime) - \(endTime)\n new time") if let idx = events.firstIndex(where: { $0.compare(eventTemp) }) { return (idx..<idx + 1, [eventTemp]) } else { return nil } } func handleSizeCell(type: CalendarType, stye: Style, view: UIView) -> CGSize? { guard type == .month && UIDevice.current.userInterfaceIdiom == .phone else { return nil } switch style.month.scrollDirection { case .vertical: return CGSize(width: view.bounds.width / 7, height: 70) case .horizontal: return nil @unknown default: return nil } } func handleCustomEventView(event: Event, style: Style, frame: CGRect) -> EventViewGeneral? { guard event.ID == "2" else { return nil } return CustomViewEvent(style: style, event: event, frame: frame) } @available(iOS 13.0, *) func handleOptionMenu(type: CalendarType) -> (menu: UIMenu, customButton: UIButton?)? { guard type == .day else { return nil } let action = UIAction(title: "Test", attributes: .destructive) { _ in print("test tap") } return (UIMenu(title: "Test menu", children: [action]), nil) } func handleNewEvent(_ event: Event, date: Date?) -> Event? { var newEvent = event guard let start = date, let end = Calendar.current.date(byAdding: .minute, value: 30, to: start) else { return nil } let startTime = timeFormatter(date: start, format: style.timeSystem.format) let endTime = timeFormatter(date: end, format: style.timeSystem.format) newEvent.start = start newEvent.end = end newEvent.ID = "\(events.count + 1)" newEvent.title = TextEvent(timeline: "\(startTime) - \(endTime)\n new time", month: "\(startTime) - \(endTime)\n new time", list: "\(startTime) - \(endTime)\n new time") return newEvent } func handleCell<T>(parameter: CellParameter, type: CalendarType, view: T, indexPath: IndexPath) -> KVKCalendarCellProtocol? where T: UIScrollView { switch type { case .year where parameter.date?.kvkMonth == Date().kvkMonth: let cell = (view as? UICollectionView)?.kvkDequeueCell(indexPath: indexPath) { (cell: CustomDayCell) in cell.imageView.image = UIImage(named: "ic_stub") } return cell case .day, .week, .month: guard parameter.date?.kvkDay == Date().kvkDay && parameter.type != .empty else { return nil } let cell = (view as? UICollectionView)?.kvkDequeueCell(indexPath: indexPath) { (cell: CustomDayCell) in cell.imageView.image = UIImage(named: "ic_stub") } return cell case .list: guard parameter.date?.kvkDay == 14 else { return nil } let cell = (view as? UITableView)?.kvkDequeueCell { (cell) in cell.backgroundColor = .systemRed } return cell default: return nil } } func handleEvents(systemEvents: [EKEvent]) -> [Event] { // if you want to get a system events, you need to set style.systemCalendars = ["test"] let mappedEvents = systemEvents.compactMap { (event) -> Event in let startTime = timeFormatter(date: event.startDate, format: style.timeSystem.format) let endTime = timeFormatter(date: event.endDate, format: style.timeSystem.format) event.title = "\(startTime) - \(endTime)\n\(event.title ?? "")" return Event(event: event) } return events + mappedEvents } func createCalendarStyle() -> Style { var style = Style() style.timeline.isHiddenStubEvent = false style.startWeekDay = .sunday style.systemCalendars = ["Calendar1", "Calendar2", "Calendar3"] if #available(iOS 13.0, *) { style.event.iconFile = UIImage(systemName: "paperclip") } style.timeline.scrollLineHourMode = .onlyOnInitForDate(defaultDate) style.timeline.showLineHourMode = .always return style } func timeFormatter(date: Date, format: String) -> String { let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: date) } func formatter(date: String) -> Date { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter.date(from: date) ?? Date() } func loadEvents(dateFormat: String, completion: ([Event]) -> Void) { let decoder = JSONDecoder() guard let path = Bundle.main.path(forResource: "events", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), let result = try? decoder.decode(ItemData.self, from: data) else { return } let events = result.data.compactMap({ (item) -> Event in let startDate = formatter(date: item.start) let endDate = formatter(date: item.end) let startTime = timeFormatter(date: startDate, format: dateFormat) let endTime = timeFormatter(date: endDate, format: dateFormat) var event = Event(ID: item.id) event.start = startDate event.end = endDate event.color = Event.Color(item.color) event.isAllDay = item.allDay event.isContainsFile = !item.files.isEmpty if item.allDay { event.title = TextEvent(timeline: " \(item.title)", month: "\(item.title) \(startTime)", list: item.title) } else { event.title = TextEvent(timeline: "\(startTime) - \(endTime)\n\(item.title)", month: "\(item.title) \(startTime)", list: "\(startTime) - \(endTime) \(item.title)") } if item.id == "14" { event.recurringType = .everyDay var customeStyle = style.event customeStyle.defaultHeight = 40 event.style = customeStyle } if item.id == "40" { event.recurringType = .everyDay } return event }) completion(events) } } final class CustomViewEvent: EventViewGeneral { override init(style: Style, event: Event, frame: CGRect) { super.init(style: style, event: event, frame: frame) let imageView = UIImageView(image: UIImage(named: "ic_stub")) imageView.frame = CGRect(origin: CGPoint(x: 3, y: 1), size: CGSize(width: frame.width - 6, height: frame.height - 2)) imageView.contentMode = .scaleAspectFit addSubview(imageView) backgroundColor = event.backgroundColor } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } struct ItemData: Decodable { let data: [Item] enum CodingKeys: String, CodingKey { case data } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) data = try container.decode([Item].self, forKey: CodingKeys.data) } } struct Item: Decodable { let id: String, title: String, start: String, end: String let color: UIColor, colorText: UIColor let files: [String] let allDay: Bool enum CodingKeys: String, CodingKey { case id, title, start, end, color, files case colorText = "text_color" case allDay = "all_day" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: CodingKeys.id) title = try container.decode(String.self, forKey: CodingKeys.title) start = try container.decode(String.self, forKey: CodingKeys.start) end = try container.decode(String.self, forKey: CodingKeys.end) allDay = try container.decode(Int.self, forKey: CodingKeys.allDay) != 0 files = try container.decode([String].self, forKey: CodingKeys.files) let strColor = try container.decode(String.self, forKey: CodingKeys.color) color = UIColor.hexStringToColor(hex: strColor) let strColorText = try container.decode(String.self, forKey: CodingKeys.colorText) colorText = UIColor.hexStringToColor(hex: strColorText) } } extension UIColor { static func hexStringToColor(hex: String) -> UIColor { var cString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if cString.hasPrefix("#") { cString.remove(at: cString.startIndex) } if cString.count != 6 { return .systemGray } var rgbValue: UInt64 = 0 Scanner(string: cString).scanHexInt64(&rgbValue) return UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: 1.0) } } extension UIApplication { var activeWindow: UIWindow? { UIApplication.shared.windows.first(where: { $0.isKeyWindow }) } var statusBarHeight: CGFloat { if #available(iOS 13.0, *) { return activeWindow?.windowScene?.statusBarManager?.statusBarFrame.height ?? 24 } else { return statusBarFrame.height } } }
36.801829
125
0.575346
4627f9e89e264c51dddd7ec87a3318e12aaa0ea7
9,108
// The MIT License (MIT) // // Copyright (c) 2015-2018 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke class ImageRequestTests: XCTestCase { // MARK: - CoW func testStructSemanticsArePreserved() { // Given let url1 = URL(string: "http://test.com/1.png")! let url2 = URL(string: "http://test.com/2.png")! var request = ImageRequest(url: url1) // When var copy = request copy.urlRequest = URLRequest(url: url2) // Then XCTAssertEqual(url2, copy.urlRequest.url) XCTAssertEqual(url1, request.urlRequest.url) } func testCopyOnWrite() { // Given var request = ImageRequest(url: URL(string: "http://test.com/1.png")!) request.memoryCacheOptions.isReadAllowed = false request.loadKey = "1" request.cacheKey = "2" request.userInfo = "3" request.processor = AnyImageProcessor(MockImageProcessor(id: "4")) request.priority = .high // When var copy = request // Requst makes a copy at this point under the hood. copy.urlRequest = URLRequest(url: URL(string: "http://test.com/2.png")!) // Then XCTAssertEqual(copy.memoryCacheOptions.isReadAllowed, false) XCTAssertEqual(copy.loadKey, "1") XCTAssertEqual(copy.cacheKey, "2") XCTAssertEqual(copy.userInfo as? String, "3") XCTAssertEqual(copy.processor, AnyImageProcessor(MockImageProcessor(id: "4"))) XCTAssertEqual(copy.priority, .high) } // MARK: - Misc // Just to make sure that comparison works as expected. func testPriorityComparison() { typealias Priority = ImageRequest.Priority XCTAssertTrue(Priority.veryLow < Priority.veryHigh) XCTAssertTrue(Priority.low < Priority.normal) XCTAssertTrue(Priority.normal == Priority.normal) } } class ImageRequestCacheKeyTests: XCTestCase { func testDefaults() { let request = Test.request AssertHashableEqual(CacheKey(request: request), CacheKey(request: request)) // equal to itself } func testRequestsWithTheSameURLsAreEquivalent() { let request1 = ImageRequest(url: Test.url) let request2 = ImageRequest(url: Test.url) AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testRequestsWithDefaultURLRequestAndURLAreEquivalent() { let request1 = ImageRequest(url: Test.url) let request2 = ImageRequest(urlRequest: URLRequest(url: Test.url)) AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testRequestsWithDifferentURLsAreNotEquivalent() { let request1 = ImageRequest(url: URL(string: "http://test.com/1.png")!) let request2 = ImageRequest(url: URL(string: "http://test.com/2.png")!) XCTAssertNotEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testRequestsWithTheSameProcessorsAreEquivalent() { let request1 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "1")) let request2 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "1")) XCTAssertEqual(MockImageProcessor(id: "1"), MockImageProcessor(id: "1")) AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testRequestsWithDifferentProcessorsAreNotEquivalent() { let request1 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "1")) let request2 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "2")) XCTAssertNotEqual(MockImageProcessor(id: "1"), MockImageProcessor(id: "2")) XCTAssertNotEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testURLRequestParametersAreIgnored() { let request1 = ImageRequest(urlRequest: URLRequest(url: Test.url, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval: 50)) let request2 = ImageRequest(urlRequest: URLRequest(url: Test.url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 0)) AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testSettingDefaultProcessorManually() { let request1 = ImageRequest(url: Test.url) let request2 = ImageRequest(url: Test.url).mutated { $0.processor = request1.processor } AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } // MARK: Custom Cache Key func testRequestsWithSameCustomKeysAreEquivalent() { var request1 = ImageRequest(url: Test.url) request1.cacheKey = "1" var request2 = ImageRequest(url: Test.url) request2.cacheKey = "1" AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testRequestsWithSameCustomKeysButDifferentURLsAreEquivalent() { var request1 = ImageRequest(url: URL(string: "https://example.com/photo1.jpg")!) request1.cacheKey = "1" var request2 = ImageRequest(url: URL(string: "https://example.com/photo2.jpg")!) request2.cacheKey = "1" AssertHashableEqual(CacheKey(request: request1), CacheKey(request: request2)) } func testRequestsWithDifferentCustomKeysAreNotEquivalent() { var request1 = ImageRequest(url: Test.url) request1.cacheKey = "1" var request2 = ImageRequest(url: Test.url) request2.cacheKey = "2" XCTAssertNotEqual(CacheKey(request: request1), CacheKey(request: request2)) } } class ImageRequestLoadKeyTests: XCTestCase { func testDefaults() { let request = ImageRequest(url: Test.url) AssertHashableEqual(LoadKey(request: request), LoadKey(request: request)) } func testRequestsWithTheSameURLsAreEquivalent() { let request1 = ImageRequest(url: Test.url) let request2 = ImageRequest(url: Test.url) AssertHashableEqual(LoadKey(request: request1), LoadKey(request: request2)) } func testRequestsWithDifferentURLsAreNotEquivalent() { let request1 = ImageRequest(url: URL(string: "http://test.com/1.png")!) let request2 = ImageRequest(url: URL(string: "http://test.com/2.png")!) XCTAssertNotEqual(LoadKey(request: request1), LoadKey(request: request2)) } func testRequestsWithTheSameProcessorsAreEquivalent() { let request1 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "1")) let request2 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "1")) XCTAssertEqual(MockImageProcessor(id: "1"), MockImageProcessor(id: "1")) AssertHashableEqual(LoadKey(request: request1), LoadKey(request: request2)) } func testRequestsWithDifferentProcessorsAreEquivalent() { let request1 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "1")) let request2 = ImageRequest(url: Test.url).processed(with: MockImageProcessor(id: "2")) XCTAssertNotEqual(MockImageProcessor(id: "1"), MockImageProcessor(id: "2")) AssertHashableEqual(LoadKey(request: request1), LoadKey(request: request2)) } func testRequestWithDifferentURLRequestParametersAreNotEquivalent() { let request1 = ImageRequest(urlRequest: URLRequest(url: Test.url, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval: 50)) let request2 = ImageRequest(urlRequest: URLRequest(url: Test.url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 0)) XCTAssertNotEqual(LoadKey(request: request1), LoadKey(request: request2)) } // MARK: - Custom Load Key func testRequestsWithSameCustomKeysAreEquivalent() { var request1 = ImageRequest(url: Test.url) request1.loadKey = "1" var request2 = ImageRequest(url: Test.url) request2.loadKey = "1" AssertHashableEqual(LoadKey(request: request1), LoadKey(request: request2)) } func testRequestsWithSameCustomKeysButDifferentURLsAreEquivalent() { var request1 = ImageRequest(url: URL(string: "https://example.com/photo1.jpg")!) request1.loadKey = "1" var request2 = ImageRequest(url: URL(string: "https://example.com/photo2.jpg")!) request2.loadKey = "1" AssertHashableEqual(LoadKey(request: request1), LoadKey(request: request2)) } func testRequestsWithDifferentCustomKeysAreNotEquivalent() { var request1 = ImageRequest(url: Test.url) request1.loadKey = "1" var request2 = ImageRequest(url: Test.url) request2.loadKey = "2" XCTAssertNotEqual(LoadKey(request: request1), LoadKey(request: request2)) } } private typealias CacheKey = ImageRequest.CacheKey private typealias LoadKey = ImageRequest.LoadKey private func AssertHashableEqual<T: Hashable>(_ lhs: T, _ rhs: T, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(lhs.hashValue, rhs.hashValue, file: file, line: line) XCTAssertEqual(lhs, rhs, file: file, line: line) }
42.962264
138
0.688406
330b4aa9c4168ef8bd3a97ee9ff695c9b3627c2d
671
import UIKit class VMovementsMenuTypeItem:UIButton { init(title:String) { super.init(frame:CGRect.zero) translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true setTitle(title, for:UIControlState.normal) setTitleColor( UIColor.bankerOrange, for:UIControlState.highlighted) setTitleColor( UIColor.white, for:UIControlState.selected) setTitleColor( UIColor.bankerBlue, for:UIControlState.normal) titleLabel!.font = UIFont.bold(size:14) } required init?(coder:NSCoder) { return nil } }
23.964286
57
0.611028
01d0a5a10fbe33ca3eee51e84dff9ea25d60e425
8,935
// // UIImageColors.swift // https://github.com/jathu/UIImageColors // // Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto // Original Cocoa version by Panic Inc. - Portland // import UIKit public struct UIImageColors { public var backgroundColor: UIColor! public var primaryColor: UIColor! public var secondaryColor: UIColor! public var detailColor: UIColor! } class PCCountedColor { let color: UIColor let count: Int init(color: UIColor, count: Int) { self.color = color self.count = count } } extension UIColor { public var isDarkColor: Bool { let RGB = CGColorGetComponents(self.CGColor) return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5 } public var isBlackOrWhite: Bool { let RGB = CGColorGetComponents(self.CGColor) return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } public func isDistinct(compareColor: UIColor) -> Bool { let bg = CGColorGetComponents(self.CGColor) let fg = CGColorGetComponents(compareColor.CGColor) let threshold: CGFloat = 0.25 if fabs(bg[0] - fg[0]) > threshold || fabs(bg[1] - fg[1]) > threshold || fabs(bg[2] - fg[2]) > threshold { if fabs(bg[0] - bg[1]) < 0.03 && fabs(bg[0] - bg[2]) < 0.03 { if fabs(fg[0] - fg[1]) < 0.03 && fabs(fg[0] - fg[2]) < 0.03 { return false } } return true } return false } public func colorWithMinimumSaturation(minSaturation: CGFloat) -> UIColor { var hue: CGFloat = 0.0 var saturation: CGFloat = 0.0 var brightness: CGFloat = 0.0 var alpha: CGFloat = 0.0 self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if saturation < minSaturation { return UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha) } else { return self } } public func isContrastingColor(compareColor: UIColor) -> Bool { let bg = CGColorGetComponents(self.CGColor) let fg = CGColorGetComponents(compareColor.CGColor) let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2] let contrast = (bgLum > fgLum) ? (bgLum + 0.05)/(fgLum + 0.05):(fgLum + 0.05)/(bgLum + 0.05) return 1.6 < contrast } } extension UIImage { public func resize(newSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, 0) self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } public func getColors() -> UIImageColors { let ratio = self.size.width/self.size.height let r_width: CGFloat = 250 return self.getColors(CGSizeMake(r_width, r_width/ratio)) } public func getColors(scaleDownSize: CGSize) -> UIImageColors { var result = UIImageColors() let cgImage = self.resize(scaleDownSize).CGImage let width = CGImageGetWidth(cgImage) let height = CGImageGetHeight(cgImage) let bytesPerPixel: Int = 4 let bytesPerRow: Int = width * bytesPerPixel let bitsPerComponent: Int = 8 let randomColorsThreshold = Int(CGFloat(height)*0.01) let sortedColorComparator: NSComparator = { (main, other) -> NSComparisonResult in let m = main as! PCCountedColor, o = other as! PCCountedColor if m.count < o.count { return NSComparisonResult.OrderedDescending } else if m.count == o.count { return NSComparisonResult.OrderedSame } else { return NSComparisonResult.OrderedAscending } } let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) let colorSpace = CGColorSpaceCreateDeviceRGB() let raw = malloc(bytesPerRow * height) let bitmapInfo = CGImageAlphaInfo.PremultipliedFirst.rawValue let ctx = CGBitmapContextCreate(raw, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo) CGContextDrawImage(ctx, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), cgImage) let data = UnsafePointer<UInt8>(CGBitmapContextGetData(ctx)) let leftEdgeColors = NSCountedSet(capacity: height) let imageColors = NSCountedSet(capacity: width * height) for x in 0..<width { for y in 0..<height { let pixel = ((width * y) + x) * bytesPerPixel let color = UIColor( red: CGFloat(data[pixel+1])/255, green: CGFloat(data[pixel+2])/255, blue: CGFloat(data[pixel+3])/255, alpha: 1 ) // A lot of albums have white or black edges from crops, so ignore the first few pixels if 5 <= x && x <= 10 { leftEdgeColors.addObject(color) } imageColors.addObject(color) } } // Get background color var enumerator = leftEdgeColors.objectEnumerator() var sortedColors = NSMutableArray(capacity: leftEdgeColors.count) while let kolor = enumerator.nextObject() as? UIColor { let colorCount = leftEdgeColors.countForObject(kolor) if randomColorsThreshold < colorCount { sortedColors.addObject(PCCountedColor(color: kolor, count: colorCount)) } } sortedColors.sortUsingComparator(sortedColorComparator) var proposedEdgeColor: PCCountedColor if 0 < sortedColors.count { proposedEdgeColor = sortedColors.objectAtIndex(0) as! PCCountedColor } else { proposedEdgeColor = PCCountedColor(color: blackColor, count: 1) } if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count { for i in 1..<sortedColors.count { let nextProposedEdgeColor = sortedColors.objectAtIndex(i) as! PCCountedColor if (CGFloat(nextProposedEdgeColor.count)/CGFloat(proposedEdgeColor.count)) > 0.3 { if !nextProposedEdgeColor.color.isBlackOrWhite { proposedEdgeColor = nextProposedEdgeColor break } } else { break } } } result.backgroundColor = proposedEdgeColor.color // Get foreground colors enumerator = imageColors.objectEnumerator() sortedColors.removeAllObjects() sortedColors = NSMutableArray(capacity: imageColors.count) let findDarkTextColor = !result.backgroundColor.isDarkColor while var kolor = enumerator.nextObject() as? UIColor { kolor = kolor.colorWithMinimumSaturation(0.15) if kolor.isDarkColor == findDarkTextColor { let colorCount = imageColors.countForObject(kolor) sortedColors.addObject(PCCountedColor(color: kolor, count: colorCount)) } } sortedColors.sortUsingComparator(sortedColorComparator) for curContainer in sortedColors { let kolor = (curContainer as! PCCountedColor).color if result.primaryColor == nil { if kolor.isContrastingColor(result.backgroundColor) { result.primaryColor = kolor } } else if result.secondaryColor == nil { if !result.primaryColor.isDistinct(kolor) || !kolor.isContrastingColor(result.backgroundColor) { continue } result.secondaryColor = kolor } else if result.detailColor == nil { if !result.secondaryColor.isDistinct(kolor) || !result.primaryColor.isDistinct(kolor) || !kolor.isContrastingColor(result.backgroundColor) { continue } result.detailColor = kolor break } } let isDarkBackgound = result.backgroundColor.isDarkColor if result.primaryColor == nil { result.primaryColor = isDarkBackgound ? whiteColor:blackColor } if result.secondaryColor == nil { result.secondaryColor = isDarkBackgound ? whiteColor:blackColor } if result.detailColor == nil { result.detailColor = isDarkBackgound ? whiteColor:blackColor } // Release the allocated memory free(raw) return result } }
36.769547
156
0.594292
397560c7550999e7f156908f04f00e7075b69612
520
// // ViewController.swift // dry-api-client-testing // // Created by Kendrick Taylor on 2/11/15. // Copyright (c) 2015 Curious Inc. All rights reserved. // import UIKit class ViewController: UIViewController { override func loadView() { self.view = UIView(); let label = UILabel(frame: CGRectMake(0, 0, 100, 100)); label.text = "Hello World."; self.view.addSubview(label); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
20.8
64
0.638462
dbb6f9be6cc862a1383c4d374f39e2624bf4d798
222
import XCTest @testable import Alicerce class LockTestCase: XCTestCase { func testMake_WithiOS10OrAbove_ShouldReturnAnUnfairLock() { let lock = Lock.make() XCTAssert(lock is Lock.UnfairLock) } }
18.5
63
0.716216
c1139d4fc80ff1719012e52a2e82257f2698cf69
847
// // DBMultValueCondition.swift // tiamo // // Created by wbitos on 2019/9/6. // Copyright © 2019 wbitos. All rights reserved. // import Foundation open class DBMultValueCondition: DBCondition { public enum Operator: String { case `in` = "in" } open var key: String open var value: MultValue open var `operator`: DBMultValueCondition.Operator public init(key: String, value: MultValue, `operator`: DBMultValueCondition.Operator = .`in`) { self.key = key self.value = value self.`operator` = `operator` super.init() } // override func sql() -> String { // let sql = "\(self.key) \(self.`operator`) :\(self.key)" // return sql // } // // override func parameters() -> [String: DBQueryable] { // return [:] // } }
22.891892
99
0.576151
1417ca3d64c1cdae0030f85a643c7856be0a1331
496
// // ViewController.swift // ECZB // // Created by jiaerdong on 2017/2/14. // Copyright © 2017年 spring. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.076923
80
0.665323
fb148b63d851b78e341b59c666b8883f8fa00a81
3,231
// // YPCameraView.swift // YPImgePicker // // Created by Sacha Durand Saint Omer on 2015/11/14. // Copyright © 2015 Yummypets. All rights reserved. // import UIKit import Stevia class YPCameraView: UIView, UIGestureRecognizerDelegate { let focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90)) let previewViewContainer = UIView() let buttonsContainer = UIView() let flipButton = UIButton() let shotButton = UIButton() let flashButton = UIButton() let timeElapsedLabel = UILabel() let progressBar = UIProgressView() convenience init(overlayView: UIView? = nil) { self.init(frame: .zero) if let overlayView = overlayView { // View Hierarchy sv( previewViewContainer, overlayView, progressBar, timeElapsedLabel, flashButton, flipButton, buttonsContainer.sv( shotButton ) ) } else { // View Hierarchy sv( previewViewContainer, progressBar, timeElapsedLabel, flashButton, flipButton, buttonsContainer.sv( shotButton ) ) } // Layout let isIphone4 = UIScreen.main.bounds.height == 480 let sideMargin: CGFloat = isIphone4 ? 20 : 0 layout( 0, |-sideMargin-previewViewContainer-sideMargin-|, -2, |progressBar|, 0, |buttonsContainer|, 0 ) previewViewContainer.heightEqualsWidth() overlayView?.followEdges(previewViewContainer) |-(15+sideMargin)-flashButton.size(42) flashButton.Bottom == previewViewContainer.Bottom - 15 flipButton.size(42)-(15+sideMargin)-| flipButton.Bottom == previewViewContainer.Bottom - 15 timeElapsedLabel-(15+sideMargin)-| timeElapsedLabel.Top == previewViewContainer.Top + 15 shotButton.centerVertically() shotButton.size(84).centerHorizontally() // Style backgroundColor = YPConfig.colors.photoVideoScreenBackground previewViewContainer.backgroundColor = .black timeElapsedLabel.style { l in l.textColor = .white l.text = "00:00" l.isHidden = true l.font = .monospacedDigitSystemFont(ofSize: 13, weight: UIFont.Weight.medium) } progressBar.style { p in p.trackTintColor = .clear p.tintColor = .red } flashButton.setImage(YPConfig.icons.flashOffIcon, for: .normal) flipButton.setImage(YPConfig.icons.loopIcon, for: .normal) shotButton.setImage(YPConfig.icons.capturePhotoImage, for: .normal) shotButton.setImage(YPConfig.icons.captureHighLightPhotoImage, for: .focused) shotButton.setImage(YPConfig.icons.captureHighLightPhotoImage, for: .highlighted) shotButton.setImage(YPConfig.icons.captureHighLightPhotoImage, for: .selected) } }
31.368932
89
0.57753
0a015029999c48e214f53fa989319f2693ccb11b
3,951
// // GenesisWebView.swift // GenesisSwift // import UIKit import WebKit protocol GenesisWebViewDelegate: class { func genesisWebViewDidFinishLoading() func genesisWebViewDidEndWithSuccess() func genesisWebViewDidEndWithCancel() func genesisWebViewDidEndWithFailure(errorCode: GenesisError) } final class GenesisWebView: NSObject { var webView: WKWebView let request: PaymentRequest var genesisWebViewDelegate: GenesisWebViewDelegate? let configuration: Configuration var uniqueId: String? init(configuration: Configuration, request: PaymentRequest) { self.webView = WKWebView(frame: .zero, configuration: WKWebViewConfiguration()) self.request = request self.configuration = configuration super.init() webView.navigationDelegate = self } func requestWPF() { let requestWPF = WPFRequest(configuration: configuration, parameters: ["request": request]) requestWPF.execute(successHandler: { (res) in let response = res as? WPFResponse guard response != nil else { let genesisErrorCode = GenesisError(code: GenesisErrorCode.eDataParsing.rawValue, technicalMessage: "", message: "Data parsing error") self.genesisWebViewDelegate?.genesisWebViewDidEndWithFailure(errorCode: genesisErrorCode) return } if let errorCode = response!.errorCode, errorCode.code != nil { self.genesisWebViewDelegate?.genesisWebViewDidEndWithFailure(errorCode: errorCode) } else { let url = URL(string: response!.redirectUrl) self.uniqueId = response!.uniqueId DispatchQueue.main.async { if (url != nil) { let redirect = URLRequest(url: url!) self.webView.load(redirect) } } } }) { (error) in self.genesisWebViewDelegate?.genesisWebViewDidEndWithFailure(errorCode: error) } } func getErrorFromReconcileAndCallFailure() { let reconcileRequest = ReconcileRequest(configuration: configuration, parameters: ["uniqueId" : uniqueId!]) reconcileRequest.execute(successHandler: { (response) in let reconcileResponse = response as! ReconcileResponse self.genesisWebViewDelegate?.genesisWebViewDidEndWithFailure(errorCode: reconcileResponse.errorCode!) }) { (error) in self.genesisWebViewDelegate?.genesisWebViewDidEndWithFailure(errorCode: error) } } } // MARK: WKNavigationDelegate extension GenesisWebView: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { genesisWebViewDelegate?.genesisWebViewDidFinishLoading() } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) { let absoluteString = navigationAction.request.url?.absoluteString if absoluteString?.lowercased().range(of: self.request.returnSuccessUrl.lowercased()) != nil { genesisWebViewDelegate?.genesisWebViewDidEndWithSuccess() decisionHandler(.cancel) } else if absoluteString?.lowercased().range(of: self.request.returnCancelUrl.lowercased()) != nil { genesisWebViewDelegate?.genesisWebViewDidEndWithCancel() decisionHandler(.cancel) } else if absoluteString?.lowercased().range(of: self.request.returnFailureUrl.lowercased()) != nil { decisionHandler(.cancel) getErrorFromReconcileAndCallFailure() } else { decisionHandler(.allow) } } }
40.316327
163
0.643381
5046a77709d590df35c973adc5874ac5fecbaff7
2,109
// // Extensions.swift // cryptography-in-use // // Created by Mojtaba Mirzadeh on 5/27/1400 AP. // import Foundation extension StringProtocol { var hexaData: Data { .init(hexa) } var hexaBytes: [UInt8] { .init(hexa) } private var hexa: UnfoldSequence<UInt8, Index> { sequence(state: startIndex) { startIndex in guard startIndex < self.endIndex else { return nil } let endIndex = self.index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex defer { startIndex = endIndex } return UInt8(self[startIndex..<endIndex], radix: 16) } } } extension String { //: ### Base64 encoding a string func base64Encoded() -> String? { if let data = self.data(using: .utf8) { return data.base64EncodedString() } return nil } //: ### Base64 decoding a string func base64Decoded() -> String? { if let data = Data(base64Encoded: self) { return String(data: data, encoding: .utf8) } return nil } } protocol UIntToBytesConvertable { var toBytes: [UInt8] { get } } extension UIntToBytesConvertable { func toByteArr<T: UnsignedInteger>(endian: T, count: Int) -> [UInt8] { var _endian = endian let bytePtr = withUnsafePointer(to: &_endian) { $0.withMemoryRebound(to: UInt8.self, capacity: count) { UnsafeBufferPointer(start: $0, count: count) } } return [UInt8](bytePtr) } } extension UInt16: UIntToBytesConvertable { var toBytes: [UInt8] { return toByteArr(endian: self.bigEndian, count: MemoryLayout<UInt16>.size) } } extension Data { struct HexEncodingOptions: OptionSet { let rawValue: Int static let upperCase = HexEncodingOptions(rawValue: 1 << 0) } func hexEncodedString(options: HexEncodingOptions = []) -> String { let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx" return self.map { String(format: format, $0) }.joined() } }
28.12
105
0.600284
7693a29c47067ce2b61225c7eeb08e3cf738a3c5
9,597
// // AqiDetailViewController.swift // BELL // // Created by 최은지 on 31/05/2020. // Copyright © 2020 최은지. All rights reserved. // import UIKit class AqiDetailViewController: UIViewController { var pm10Str: String = "" var pm25Str: String = "" var ozoneStr: String = "" var coStr: String = "" var soStr: String = "" var noStr: String = "" @IBOutlet weak var imageContainView1: UIView! // 실외 활동 @IBOutlet weak var imageContainView2: UIView! // 마스크 @IBOutlet weak var imageContainView3: UIView! // 환기 @IBOutlet weak var activeView: UIView! @IBOutlet weak var activeLabel: UILabel! @IBOutlet weak var pm10Label: UILabel! // 미세먼지 @IBOutlet weak var pm25Label: UILabel! // 초미세먼지 @IBOutlet weak var ozoneLabel: UILabel! // 오존 @IBOutlet weak var coLabel: UILabel! // 일산화탄소 @IBOutlet weak var soLabel: UILabel! // 아황산가스 @IBOutlet weak var noLabel: UILabel! // 이산화질소 @IBOutlet weak var pm10View: UIView! @IBOutlet weak var pm25View: UIView! @IBOutlet weak var ozoneView: UIView! @IBOutlet weak var coView: UIView! @IBOutlet weak var soView: UIView! @IBOutlet weak var noView: UIView! override func viewDidLoad() { super.viewDidLoad() self.imageContainView1.selectImageView() self.imageContainView2.deselectImageView() self.imageContainView3.deselectImageView() self.activeView.setViewShadow() let tap1 = UITapGestureRecognizer(target: self, action: #selector(self.handleClickActiveView1( _:))) self.imageContainView1.addGestureRecognizer(tap1) let tap2 = UITapGestureRecognizer(target: self, action: #selector(self.handleClickActiveView2(_:))) self.imageContainView2.addGestureRecognizer(tap2) let tap3 = UITapGestureRecognizer(target: self, action: #selector(self.handleClickActiveView3(_:))) self.imageContainView3.addGestureRecognizer(tap3) self.settingLabels() } // MARK : ImageContainView 클릭 이벤트 - 실외 활동 @objc func handleClickActiveView1(_ sender: UITapGestureRecognizer? = nil){ self.imageContainView1.selectImageView() self.imageContainView2.deselectImageView() self.imageContainView3.deselectImageView() self.activeLabel.text = "실외 활동 문제 없어요" } // MARK : ImageContainView 클릭 이벤트 - 마스크 @objc func handleClickActiveView2(_ sender: UITapGestureRecognizer? = nil){ self.imageContainView2.selectImageView() self.imageContainView1.deselectImageView() self.imageContainView3.deselectImageView() self.activeLabel.text = "필요해요" } // MARK : ImageContainView 클릭 이벤트 - 환기 @objc func handleClickActiveView3(_ sender: UITapGestureRecognizer? = nil){ self.imageContainView3.selectImageView() self.imageContainView1.deselectImageView() self.imageContainView2.deselectImageView() self.activeLabel.text = "자제해요" } // MARK : 미세먼지 수치에 따른 label & color 지정 func settingLabels(){ self.setPm10String() self.setPm25String() self.setOzoneString() self.setCoString() self.setSoString() self.setNoString() } // MARK : 미세먼지 수치에 따른 view,label 설정 (pm10) func setPm10String() -> Void { let pm10toInt = Int(self.pm10Str)! switch pm10toInt { case let x where x <= 30 : self.pm10View.layer.backgroundColor = UIColor.grade1.cgColor self.pm10Label.text = "좋음 " + self.pm10Str + " ㎍/㎥" self.pm10Label.textColor = UIColor.grade1 case let x where x <= 80 : self.pm10View.layer.backgroundColor = UIColor.grade2.cgColor self.pm10Label.text = "보통 " + self.pm10Str + " ㎍/㎥" self.pm10Label.textColor = UIColor.grade2 case let x where x <= 150 : self.pm10View.layer.backgroundColor = UIColor.grade3.cgColor self.pm10Label.text = "나쁨 " + self.pm10Str + " ㎍/㎥" self.pm10Label.textColor = UIColor.grade3 default: self.pm10View.layer.backgroundColor = UIColor.grade4.cgColor self.pm10Label.text = "매우 나쁨 " + self.pm10Str + " ㎍/㎥" self.pm10Label.textColor = UIColor.grade4 } } // MARK : 초미세먼지 수치에 따른 view,label 설정 (pm25) func setPm25String() -> Void { let pm20ToInt = Int(self.pm25Str)! switch pm20ToInt { case let x where x <= 15: self.pm25View.layer.backgroundColor = UIColor.grade1.cgColor self.pm25Label.text = "좋음 " + self.pm25Str + " ㎍/㎥" self.pm25Label.textColor = UIColor.grade1 case let x where x <= 35 : self.pm25View.layer.backgroundColor = UIColor.grade2.cgColor self.pm25Label.text = "보통 " + self.pm25Str + " ㎍/㎥" self.pm25Label.textColor = UIColor.grade2 case let x where x <= 75 : self.pm25View.layer.backgroundColor = UIColor.grade3.cgColor self.pm25Label.text = "나쁨 " + self.pm25Str + " ㎍/㎥" self.pm25Label.textColor = UIColor.grade3 default: self.pm25View.layer.backgroundColor = UIColor.grade4.cgColor self.pm25Label.text = "매우 나쁨 " + self.pm25Str + " ㎍/㎥" self.pm25Label.textColor = UIColor.grade4 } } // MARK : 오존 수치에 따른 view, label 설정 (ozone) func setOzoneString() -> Void { let ozoneToDouble = Double(self.ozoneStr)! switch ozoneToDouble{ case let x where x<0.031 : self.ozoneView.layer.backgroundColor = UIColor.grade1.cgColor self.ozoneLabel.text = "좋음 " + self.ozoneStr + " ppm" self.ozoneLabel.textColor = UIColor.grade1 case let x where x<0.091 : self.ozoneView.layer.backgroundColor = UIColor.grade2.cgColor self.ozoneLabel.text = "보통 " + self.ozoneStr + " ppm" self.ozoneLabel.textColor = UIColor.grade2 case let x where x<0.151 : self.ozoneView.layer.backgroundColor = UIColor.grade3.cgColor self.ozoneLabel.text = "나쁨 " + self.ozoneStr + " ppm" self.ozoneLabel.textColor = UIColor.grade3 default: self.ozoneView.layer.backgroundColor = UIColor.grade4.cgColor self.ozoneLabel.text = "매우 나쁨 " + self.ozoneStr + " ppm" self.ozoneLabel.textColor = UIColor.grade4 } } // MARK : 일산화탄소 수치에 따른 view, label 설정 (co) func setCoString() -> Void { let coToDouble = Double(self.coStr)! switch coToDouble{ case let x where x<0.031 : self.coView.layer.backgroundColor = UIColor.grade1.cgColor self.coLabel.text = "좋음 " + self.coStr + " ㎍/㎥" self.coLabel.textColor = UIColor.grade1 case let x where x<0.091 : self.coView.layer.backgroundColor = UIColor.grade2.cgColor self.coLabel.text = "보통 " + self.coStr + " ㎍/㎥" self.coLabel.textColor = UIColor.grade2 case let x where x<0.151 : self.coView.layer.backgroundColor = UIColor.grade3.cgColor self.coLabel.text = "나쁨 " + self.coStr + " ㎍/㎥" self.coLabel.textColor = UIColor.grade3 default: self.coView.layer.backgroundColor = UIColor.grade4.cgColor self.coLabel.text = "매우 나쁨 " + self.coStr + " ㎍/㎥" self.coLabel.textColor = UIColor.grade4 } } // MARK : 아황산가스 수치에 따른 view, label 설정 (so) func setSoString() -> Void { let soToDouble = Double(self.soStr)! switch soToDouble { case let x where x<0.021: self.soView.layer.backgroundColor = UIColor.grade1.cgColor self.soLabel.text = "좋음 " + self.soStr + " ㎍/㎥" self.soLabel.textColor = UIColor.grade1 case let x where x<0.051: self.soView.layer.backgroundColor = UIColor.grade2.cgColor self.soLabel.text = "보통 " + self.soStr + " ㎍/㎥" self.soLabel.textColor = UIColor.grade2 case let x where x<0.151: self.soView.layer.backgroundColor = UIColor.grade3.cgColor self.soLabel.text = "나쁨 " + self.soStr + " ㎍/㎥" self.soLabel.textColor = UIColor.grade3 default: self.soView.layer.backgroundColor = UIColor.grade4.cgColor self.soLabel.text = "매우 나쁨 " + self.soStr + " ㎍/㎥" self.soLabel.textColor = UIColor.grade4 } } // MARK : 이산화질소 수치에 따른 view, label 설정 (no) func setNoString() -> Void { let noToDouble = Double(self.noStr)! switch noToDouble { case let x where x<0.031: self.noView.layer.backgroundColor = UIColor.grade1.cgColor self.noLabel.text = "좋음 " + self.soStr + " ppm" self.noLabel.textColor = UIColor.grade1 case let x where x<0.061: self.noView.layer.backgroundColor = UIColor.grade2.cgColor self.noLabel.text = "보통 " + self.soStr + " ppm" self.noLabel.textColor = UIColor.grade2 case let x where x<0.201: self.noView.layer.backgroundColor = UIColor.grade3.cgColor self.noLabel.text = "나쁨 " + self.soStr + " ppm" self.noLabel.textColor = UIColor.grade3 default: self.noView.layer.backgroundColor = UIColor.grade4.cgColor self.noLabel.text = "매우 나쁨 " + self.soStr + " ppm" self.noLabel.textColor = UIColor.grade4 } } }
40.493671
108
0.610295
79dea413a247d7226030c03d143d3d1a643f756d
1,088
// 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: "FlatButton", platforms: [ .macOS(SupportedPlatform.MacOSVersion.v10_10) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "FlatButton", targets: ["FlatButton"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "FlatButton", dependencies: []), .testTarget( name: "FlatButtonTests", dependencies: ["FlatButton"]), ] )
34
117
0.628676
eb2fa9084865d1b1869ad5b86a551dbea5383049
3,892
import XCTest extension AlgorithmComplexityTests { static let __allTests = [ ("testExponential_RecursiveFibonacci", testExponential_RecursiveFibonacci), ("testQuadratic_MatrixAdd", testQuadratic_MatrixAdd), ("testQuadratic_MatrixFill", testQuadratic_MatrixFill), ("testQuadratic_MatrixMultiply", testQuadratic_MatrixMultiply), ("testSquareRoot_Primality", testSquareRoot_Primality), ] } extension ArrayTests { static let __allTests = [ ("testAppend", testAppend), ("testAppendAmortized", testAppendAmortized), ("testCount", testCount), ("testFirst", testFirst), ("testInsert", testInsert), ("testIsEmpty", testIsEmpty), ("testLast", testLast), ("testPartition", testPartition), ("testRemove", testRemove), ("testSort", testSort), ("testSubscriptGetter", testSubscriptGetter), ] } extension BenchmarkTests { static let __allTests = [ ("testMutatingTestPointsCount", testMutatingTestPointsCount), ("testNonMutatingTestPointsCount", testNonMutatingTestPointsCount), ] } extension DictionaryTests { static let __allTests = [ ("testCount", testCount), ("testEqualityOperator", testEqualityOperator), ("testFilter", testFilter), ("testFirst", testFirst), ("testIndex", testIndex), ("testInequalityOperator", testInequalityOperator), ("testIsEmpty", testIsEmpty), ("testKeys", testKeys), ("testRemoveAll", testRemoveAll), ("testRemoveValueHit", testRemoveValueHit), ("testRemoveValueMiss", testRemoveValueMiss), ("testSubscriptGetter", testSubscriptGetter), ("testUpdateValueHit", testUpdateValueHit), ("testUpdateValueMiss", testUpdateValueMiss), ("testValues", testValues), ] } extension PerformanceTestingTests { static let __allTests = [ ("testConstant", testConstant), ("testCubicSlopeOne", testCubicSlopeOne), ("testCubicSlopeThree", testCubicSlopeThree), ("testExponentialBaseTwoSlopeOne", testExponentialBaseTwoSlopeOne), ("testExponentialBaseTwoSlopeThree", testExponentialBaseTwoSlopeThree), ("testLinearSlopeOne", testLinearSlopeOne), ("testLinearSlopeThree", testLinearSlopeThree), ("testLogarithmicBaseESlopeOne", testLogarithmicBaseESlopeOne), ("testLogarithmicBaseESlopeThree", testLogarithmicBaseESlopeThree), ("testLogarithmicBaseTwoSlopeOne", testLogarithmicBaseTwoSlopeOne), ("testLogarithmicBaseTwoSlopeThree", testLogarithmicBaseTwoSlopeThree), ("testQuadraticSlopeOne", testQuadraticSlopeOne), ("testQuadraticSlopeThree", testQuadraticSlopeThree), ("testSquareRootSlopeOne", testSquareRootSlopeOne), ("testSquareRootSlopeThree", testSquareRootSlopeThree), ] } extension SetTests { static let __allTests = [ ("testContainsHit", testContainsHit), ("testContainsMiss", testContainsMiss), ("testCount", testCount), ("testFilter", testFilter), ("testFirst", testFirst), ("testInsert", testInsert), ("testIsEmpty", testIsEmpty), ("testRemoveFirst", testRemoveFirst), ("testRemoveHit", testRemoveHit), ("testRemoveMiss", testRemoveMiss), ("testUnionWithConstantSizedOther", testUnionWithConstantSizedOther), ("testUnionWithLinearSizedOther", testUnionWithLinearSizedOther), ] } #if !os(macOS) public func __allTests() -> [XCTestCaseEntry] { return [ testCase(AlgorithmComplexityTests.__allTests), testCase(ArrayTests.__allTests), testCase(BenchmarkTests.__allTests), testCase(DictionaryTests.__allTests), testCase(PerformanceTestingTests.__allTests), testCase(SetTests.__allTests), ] } #endif
37.066667
83
0.68628
bf95c75eae5887be3b48c1fae340d3efa0d93500
4,699
import UIKit import Crashlytics class EditGroupViewController : UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AvatarViewDelegate { @IBOutlet weak var addPhotoView: AvatarView! @IBOutlet weak var groupNameTextField: UITextField! @IBOutlet weak var createGroupButton: MaterialButton! var suggestedGroupTitle: String? override func viewDidLoad() { super.viewDidLoad() self.addPhotoView.hasDropShadow = false self.addPhotoView.delegate = self self.addPhotoView.setText(NSLocalizedString("ADD\nPHOTO", comment: "Text on top of avatar with no photo in Settings")) self.addPhotoView.setTextColor(UIColor.black) self.addPhotoView.setFont(UIFont.rogerFontOfSize(11)) self.addPhotoView.layer.borderColor = UIColor.darkGray.cgColor self.addPhotoView.layer.borderWidth = 2 self.addPhotoView.shouldAnimate = false self.imagePicker.allowsEditing = true self.imagePicker.delegate = self self.groupNameTextField.delegate = self self.groupNameTextField.becomeFirstResponder() // Prefill group name if possible self.groupNameTextField.text = self.suggestedGroupTitle } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.view.endEditing(true) } override var prefersStatusBarHidden : Bool { return true } @IBAction func createGroupTapped(_ sender: AnyObject) { guard let groupName = self.groupNameTextField.text , !groupName.isEmpty else { let alert = UIAlertController(title: NSLocalizedString("Oops!", comment: "Alert title"), message: NSLocalizedString("A group name is required.", comment: "Alert text"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Try again", comment: "Alert action"), style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) return } var image: Intent.Image? if let photo = self.groupImage, let imageData = UIImageJPEGRepresentation(photo, 0.8) { image = Intent.Image(format: .jpeg, data: imageData) } self.createGroupButton.startLoadingAnimation() // Aliases to search to find a stream on the backend. StreamService.instance.createStream(title: groupName, image: image) { stream, error in self.createGroupButton.stopLoadingAnimation() guard error == nil else { let alert = UIAlertController(title: NSLocalizedString("Oops!", comment: "Alert title"), message: NSLocalizedString("Something went wrong. Please try again!", comment: "Alert text"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment: "Alert action"), style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) return } let streamDetails = self.storyboard?.instantiateViewController(withIdentifier: "StreamDetails") as! StreamDetailsViewController streamDetails.stream = stream self.navigationController?.pushViewControllerModal(streamDetails) } Answers.logCustomEvent(withName: "Create Group Confirmed", customAttributes: ["Group Name": groupName, "Has Image": image != nil]) } @IBAction func backTapped(_ sender: AnyObject) { self.navigationController?.popViewControllerModal() } // MARK: - AvatarViewDelegate func didEndTouch(_ avatarView: AvatarView) { self.present(self.imagePicker, animated: true, completion: nil) } func accessibilityFocusChanged(_ avatarView: AvatarView, focused: Bool) { } // MARK: - UIImagePickerControllerDelegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { defer { picker.dismiss(animated: true, completion: nil) } guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else { return } self.groupImage = image self.addPhotoView.setImage(image) } // MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.createGroupTapped(self.createGroupButton) return false } // MARK: Private fileprivate let imagePicker = UIImagePickerController() fileprivate var groupImage: UIImage? }
39.487395
163
0.674186
2333051d4868254367071bdfbb9520896ef8d7cc
6,308
import UIKit private let lineWidth: CGFloat = 2 // オセロのボードを表示するためのViewクラス public class BoardView: UIView { private var cellViews: [CellView] = [] private var actions: [CellSelectionAction] = [] /// 盤の幅( `8` )を表します。 public let width: Int = 8 /// 盤の高さ( `8` )を返します。 public let height: Int = 8 /// 盤のセルの `x` の範囲( `0 ..< 8` )を返します。 public let xRange: Range<Int> /// 盤のセルの `y` の範囲( `0 ..< 8` )を返します。 public let yRange: Range<Int> /// セルがタップされたときの挙動を移譲するためのオブジェクトです。 public weak var delegate: BoardViewDelegate? override public init(frame: CGRect) { xRange = 0 ..< width yRange = 0 ..< height super.init(frame: frame) setUp() } required public init?(coder: NSCoder) { xRange = 0 ..< width yRange = 0 ..< height super.init(coder: coder) setUp() } private func setUp() { self.backgroundColor = UIColor(named: "DarkColor")! let cellViews: [CellView] = (0 ..< (width * height)).map { _ in let cellView = CellView() cellView.translatesAutoresizingMaskIntoConstraints = false return cellView } self.cellViews = cellViews cellViews.forEach(self.addSubview(_:)) for i in cellViews.indices.dropFirst() { NSLayoutConstraint.activate([ cellViews[0].widthAnchor.constraint(equalTo: cellViews[i].widthAnchor), cellViews[0].heightAnchor.constraint(equalTo: cellViews[i].heightAnchor), ]) } NSLayoutConstraint.activate([ cellViews[0].widthAnchor.constraint(equalTo: cellViews[0].heightAnchor), ]) for y in yRange { for x in xRange { let topNeighborAnchor: NSLayoutYAxisAnchor if let cellView = cellViewAt(x: x, y: y - 1) { topNeighborAnchor = cellView.bottomAnchor } else { topNeighborAnchor = self.topAnchor } let leftNeighborAnchor: NSLayoutXAxisAnchor if let cellView = cellViewAt(x: x - 1, y: y) { leftNeighborAnchor = cellView.rightAnchor } else { leftNeighborAnchor = self.leftAnchor } let cellView = cellViewAt(x: x, y: y)! NSLayoutConstraint.activate([ cellView.topAnchor.constraint(equalTo: topNeighborAnchor, constant: lineWidth), cellView.leftAnchor.constraint(equalTo: leftNeighborAnchor, constant: lineWidth), ]) if y == height - 1 { NSLayoutConstraint.activate([ self.bottomAnchor.constraint(equalTo: cellView.bottomAnchor, constant: lineWidth), ]) } if x == width - 1 { NSLayoutConstraint.activate([ self.rightAnchor.constraint(equalTo: cellView.rightAnchor, constant: lineWidth), ]) } } } reset() for y in yRange { for x in xRange { let cellView: CellView = cellViewAt(x: x, y: y)! let action = CellSelectionAction(boardView: self, x: x, y: y) actions.append(action) // To retain the `action` cellView.addTarget(action, action: #selector(action.selectCell), for: .touchUpInside) } } } /// 盤をゲーム開始時に状態に戻します。このメソッドはアニメーションを伴いません。 public func reset() { for y in yRange { for x in xRange { setDisk(nil, atX: x, y: y, animated: false) } } setDisk(.light, atX: width / 2 - 1, y: height / 2 - 1, animated: false) setDisk(.dark, atX: width / 2, y: height / 2 - 1, animated: false) setDisk(.dark, atX: width / 2 - 1, y: height / 2, animated: false) setDisk(.light, atX: width / 2, y: height / 2, animated: false) } private func cellViewAt(x: Int, y: Int) -> CellView? { guard xRange.contains(x) && yRange.contains(y) else { return nil } return cellViews[y * width + x] } /// `x`, `y` で指定されたセルの状態を返します。 /// セルにディスクが置かれていない場合、 `nil` が返されます。 /// - Parameter x: セルの列です。 /// - Parameter y: セルの行です。 /// - Returns: セルにディスクが置かれている場合はそのディスクの値を、置かれていない場合は `nil` を返します。 public func diskAt(x: Int, y: Int) -> Disk? { cellViewAt(x: x, y: y)?.disk } /// `x`, `y` で指定されたセルの状態を、与えられた `disk` に変更します。 /// `animated` が `true` の場合、アニメーションが実行されます。 /// アニメーションの完了通知は `completion` ハンドラーで受け取ることができます。 /// - Parameter disk: セルに設定される新しい状態です。 `nil` はディスクが置かれていない状態を表します。 /// - Parameter x: セルの列です。 /// - Parameter y: セルの行です。 /// - Parameter animated: セルの状態変更を表すアニメーションを表示するかどうかを指定します。 /// - Parameter completion: アニメーションの完了通知を受け取るハンドラーです。 /// `animated` に `false` が指定された場合は状態が変更された後で即座に同期的に呼び出されます。 /// ハンドラーが受け取る `Bool` 値は、 `UIView.animate()` 等に準じます。 public func setDisk(_ disk: Disk?, atX x: Int, y: Int, animated: Bool, completion: ((Bool) -> Void)? = nil) { guard let cellView = cellViewAt(x: x, y: y) else { preconditionFailure() // FIXME: Add a message. } cellView.setDisk(disk, animated: animated, completion: completion) } } public protocol BoardViewDelegate: AnyObject { /// `boardView` の `x`, `y` で指定されるセルがタップされたときに呼ばれます。 /// - Parameter boardView: セルをタップされた `BoardView` インスタンスです。 /// - Parameter x: セルの列です。 /// - Parameter y: セルの行です。 func boardView(_ boardView: BoardView, didSelectCellAtX x: Int, y: Int) } private class CellSelectionAction: NSObject { private weak var boardView: BoardView? let x: Int let y: Int init(boardView: BoardView, x: Int, y: Int) { self.boardView = boardView self.x = x self.y = y } @objc func selectCell() { guard let boardView = boardView else { return } boardView.delegate?.boardView(boardView, didSelectCellAtX: x, y: y) } }
35.438202
113
0.552632
03ab47004a1f969cbf16069fbae2fb9e91658130
406
// // EmailValidation.swift // Pingo // // Created by Jeff Potter on 11/11/14. // Copyright (c) 2015 jpotts18. All rights reserved. // import Foundation public class EmailRule: RegexRule { static let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" public convenience init(message : String = "Must be a valid email address"){ self.init(regex: EmailRule.regex, message: message) } }
22.555556
77
0.660099
bfc5ccd8aa6449ae69437c3585f6a531e57d23d9
11,571
// // ViewController.swift // WebonoiseAssignment // // Created by Shridhar Mali on 4/15/17. // Copyright © 2017 Shridhar Mali. All rights reserved. // import UIKit import GoogleMaps import SDWebImage class ViewController: UIViewController { @IBOutlet weak var googleMapView: GMSMapView! // GoogleMap IBOutlet @IBOutlet weak var placePhotoGallery: UICollectionView! // Horizontal CollectionView let locationManager = CLLocationManager() // Location Manager instance let objPlaceDetailModel = PlaceDetailModel.shardInstance // PlaceDetailModel Singleton model var placePhotoUrls = [URL]() // Holding photo reference url of google place API var image = UIImage() // Cached Image var latitude: Double = 19.0176147 // first time load location latitude on the map var longitude: Double = 72.8561644 // first time load location longitude on the map var imageFileName = "" //MARK:- ViewLifeCycle override func viewDidLoad() { super.viewDidLoad() self.title = "Google Places" // Show alert for grant user current location access updateLocation() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if SRKUtility.isInternetAvailable() { // Checking internet rechability initGoogleMaps() // intialize google map with current location marker extractPhotoRefenceImageUrls() // extract photo reference url after user come back from auto complete search placePhotoGallery.reloadData() } else { SRKUtility.showErrorMessage(title: "Internet Status", message: "Please check your internet connectivity", viewController: self) } // navigation left bar button for navigation to image gallery view // to see downloaded images which is selected on place photo horizontal scroll self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Images", style: .plain, target: self, action: #selector(self.imagesClicked)) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) placePhotoGallery.reloadData() } //MARK:- Private Methods func updateLocation() { locationManager.delegate = self // CLLocationManager settings locationManager.startMonitoringSignificantLocationChanges() locationManager.requestAlwaysAuthorization() locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } //MARK:- Intialize GoogleMap func initGoogleMaps() { var title: String = "Current Location" // title of pin annotation let subTitle = "" // subTitle of pin annotation kept nil if let lat = objPlaceDetailModel.placeDetailsInfo?.geometry?.location?.latitude, let lng = objPlaceDetailModel.placeDetailsInfo?.geometry?.location?.longitude { // check is selected place lat and lng and // set it to google map camera position latitude = lat longitude = lng if let titleText = objPlaceDetailModel.placeDetailsInfo?.name { // check place info and set to annotation view title of GoogleMap title = titleText } } let camera = GMSCameraPosition.camera(withLatitude: latitude , longitude: longitude, zoom: 17.0) // Set google Map focus on provide lat lng self.googleMapView.camera = camera self.googleMapView.delegate = self self.googleMapView.isMyLocationEnabled = true self.googleMapView.settings.myLocationButton = true //Create a marker in the center of the map let marker = GMSMarker() // Google Map Annotation with title(Place information) marker.position = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) marker.title = title marker.snippet = subTitle marker.map = self.googleMapView } func extractPhotoRefenceImageUrls() { // Photo reference for get place photo using google photo API if let photoReferenceArr = objPlaceDetailModel.placeDetailsInfo?.photos { for(index, _) in photoReferenceArr.enumerated() { objPlaceDetailModel.isPlacePhoto = true if let photoRef = photoReferenceArr[index].photoReference { DispatchQueue.main.async { _ = Server.APIPlacePhoto.invokeAPIPlacePhoto(photoReference: photoRef) { (response:APIPlacePhotoReponse) in OperationQueue.main.addOperation { switch response { case .error(let error): print(error) case .success(let placesDetail): if let url = placesDetail.imageUrl { self.placePhotoUrls.append(url as! URL) // Get image URL response of place photo self.placePhotoGallery.reloadData() } } } } } } } } } // Download image in background which selected by user and store it into // device internal memory i.e device document directory func downloadImageWithUrlAndStoreInDevice(url: URL?) { var downloadTask: URLSessionDownloadTask! var backgroundSession: URLSession! if let imageUrl = url { let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession") backgroundSession = URLSession(configuration: backgroundSessionConfiguration, delegate: self as URLSessionDelegate, delegateQueue: OperationQueue.main) imageFileName = imageUrl.absoluteString downloadTask = backgroundSession.downloadTask(with: imageUrl) downloadTask.resume() } } func showFileWithPath(path: String){ // This method is for the checking for an image isExists / Saved let isFileFound:Bool? = FileManager.default.fileExists(atPath: path) if isFileFound == true{ print(path) } else { print("File not found at path") } } // Navigation to Gallery screen func imagesClicked() { self.performSegue(withIdentifier: "images", sender: self) } //MARK:- Actions @IBAction func searchAddress(_ sender: Any) { // Search button on top of navigation bar (rightBarButtonItem) if SRKUtility.isInternetAvailable() { objPlaceDetailModel.isPlacePhoto = false self.placePhotoUrls.removeAll() self.performSegue(withIdentifier: "autoCompletePlaces", sender: self) } else { SRKUtility.showErrorMessage(title: "Internet Status", message: "Please check your internet connectivity", viewController: self) } } } //MARK:- UICollectionViewDataSource extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.placePhotoUrls.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PlacePhotoCell cell.placePhotoImgView.sd_setShowActivityIndicatorView(true) cell.placePhotoImgView.sd_setIndicatorStyle(.gray) cell.placePhotoImgView.layer.cornerRadius = 10 if self.placePhotoUrls.count != 0 { cell.placePhotoImgView.sd_setImage(with: self.placePhotoUrls[indexPath.row], placeholderImage: UIImage(named: "fab_icon_touch")) } return cell } } //MARK:- UICollectionViewDelegate extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if self.placePhotoUrls.count != 0 { downloadImageWithUrlAndStoreInDevice(url: self.placePhotoUrls[indexPath.row]) } } } //MARK:- CLLocationManagerDelegate extension ViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last latitude = (location?.coordinate.latitude)! longitude = (location?.coordinate.longitude)! let camera = GMSCameraPosition.camera(withLatitude: latitude, longitude: longitude, zoom: 17.0) self.googleMapView.animate(to: camera) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to get the current location of user \(error.localizedDescription)") } } //MARK:- GMSMapViewDelegate extension ViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { self.googleMapView.isMyLocationEnabled = true } func mapView(_ mapView: GMSMapView, willMove gesture: Bool) { self.googleMapView.isMyLocationEnabled = true } func didTapMyLocationButton(for mapView: GMSMapView) -> Bool { print("clicked") if SRKUtility.isInternetAvailable() { initGoogleMaps() } else { SRKUtility.showErrorMessage(title: "Internet Status", message: "Please check your internet connectivity", viewController: self) } return true } } //MARK:- URLSessionDownloadDelegate extension ViewController: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){ objPlaceDetailModel.counter = objPlaceDetailModel.counter + 1 let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true) let documentDirectoryPath:String = path[0] let fileManager = FileManager() let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/\(objPlaceDetailModel.counter).png")) print(destinationURLForFile) if fileManager.fileExists(atPath: destinationURLForFile.path){ showFileWithPath(path: destinationURLForFile.path) } else{ do { try fileManager.copyItem(at: location, to: destinationURLForFile) // show file showFileWithPath(path: destinationURLForFile.path) }catch{ print("An error occurred while moving file to destination url") } } } }
47.617284
257
0.633826
f7bbb1421f5bff5aa2f10370ef1358fe69b37f49
28,997
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/noppoMan/aws-sdk-swift/blob/master/Sources/CodeGenerator/main.swift. DO NOT EDIT. import Foundation import AWSSDKSwiftCore import NIO /** Doc Engage API - Amazon Pinpoint API */ public struct Pinpoint { let client: AWSClient public init(accessKeyId: String? = nil, secretAccessKey: String? = nil, region: AWSSDKSwiftCore.Region? = nil, endpoint: String? = nil) { self.client = AWSClient( accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, region: region, service: "pinpoint", serviceProtocol: ServiceProtocol(type: .restjson, version: ServiceProtocol.Version(major: 1, minor: 1)), apiVersion: "2016-12-01", endpoint: endpoint, middlewares: [], possibleErrorTypes: [PinpointErrorType.self] ) } /// Creates an application. public func createApp(_ input: CreateAppRequest) throws -> Future<CreateAppResponse> { return try client.send(operation: "CreateApp", path: "/v1/apps", httpMethod: "POST", input: input) } /// Creates a new campaign for an application or updates the settings of an existing campaign for an application. public func createCampaign(_ input: CreateCampaignRequest) throws -> Future<CreateCampaignResponse> { return try client.send(operation: "CreateCampaign", path: "/v1/apps/{application-id}/campaigns", httpMethod: "POST", input: input) } /// Creates a new export job for an application. public func createExportJob(_ input: CreateExportJobRequest) throws -> Future<CreateExportJobResponse> { return try client.send(operation: "CreateExportJob", path: "/v1/apps/{application-id}/jobs/export", httpMethod: "POST", input: input) } /// Creates a new import job for an application. public func createImportJob(_ input: CreateImportJobRequest) throws -> Future<CreateImportJobResponse> { return try client.send(operation: "CreateImportJob", path: "/v1/apps/{application-id}/jobs/import", httpMethod: "POST", input: input) } /// Creates a new segment for an application or updates the configuration, dimension, and other settings for an existing segment that's associated with an application. public func createSegment(_ input: CreateSegmentRequest) throws -> Future<CreateSegmentResponse> { return try client.send(operation: "CreateSegment", path: "/v1/apps/{application-id}/segments", httpMethod: "POST", input: input) } /// Disables the ADM channel for an application and deletes any existing settings for the channel. public func deleteAdmChannel(_ input: DeleteAdmChannelRequest) throws -> Future<DeleteAdmChannelResponse> { return try client.send(operation: "DeleteAdmChannel", path: "/v1/apps/{application-id}/channels/adm", httpMethod: "DELETE", input: input) } /// Disables the APNs channel for an application and deletes any existing settings for the channel. public func deleteApnsChannel(_ input: DeleteApnsChannelRequest) throws -> Future<DeleteApnsChannelResponse> { return try client.send(operation: "DeleteApnsChannel", path: "/v1/apps/{application-id}/channels/apns", httpMethod: "DELETE", input: input) } /// Disables the APNs sandbox channel for an application and deletes any existing settings for the channel. public func deleteApnsSandboxChannel(_ input: DeleteApnsSandboxChannelRequest) throws -> Future<DeleteApnsSandboxChannelResponse> { return try client.send(operation: "DeleteApnsSandboxChannel", path: "/v1/apps/{application-id}/channels/apns_sandbox", httpMethod: "DELETE", input: input) } /// Disables the APNs VoIP channel for an application and deletes any existing settings for the channel. public func deleteApnsVoipChannel(_ input: DeleteApnsVoipChannelRequest) throws -> Future<DeleteApnsVoipChannelResponse> { return try client.send(operation: "DeleteApnsVoipChannel", path: "/v1/apps/{application-id}/channels/apns_voip", httpMethod: "DELETE", input: input) } /// Disables the APNs VoIP sandbox channel for an application and deletes any existing settings for the channel. public func deleteApnsVoipSandboxChannel(_ input: DeleteApnsVoipSandboxChannelRequest) throws -> Future<DeleteApnsVoipSandboxChannelResponse> { return try client.send(operation: "DeleteApnsVoipSandboxChannel", path: "/v1/apps/{application-id}/channels/apns_voip_sandbox", httpMethod: "DELETE", input: input) } /// Deletes an application. public func deleteApp(_ input: DeleteAppRequest) throws -> Future<DeleteAppResponse> { return try client.send(operation: "DeleteApp", path: "/v1/apps/{application-id}", httpMethod: "DELETE", input: input) } /// Disables the Baidu channel for an application and deletes any existing settings for the channel. public func deleteBaiduChannel(_ input: DeleteBaiduChannelRequest) throws -> Future<DeleteBaiduChannelResponse> { return try client.send(operation: "DeleteBaiduChannel", path: "/v1/apps/{application-id}/channels/baidu", httpMethod: "DELETE", input: input) } /// Deletes a campaign from an application. public func deleteCampaign(_ input: DeleteCampaignRequest) throws -> Future<DeleteCampaignResponse> { return try client.send(operation: "DeleteCampaign", path: "/v1/apps/{application-id}/campaigns/{campaign-id}", httpMethod: "DELETE", input: input) } /// Disables the email channel for an application and deletes any existing settings for the channel. public func deleteEmailChannel(_ input: DeleteEmailChannelRequest) throws -> Future<DeleteEmailChannelResponse> { return try client.send(operation: "DeleteEmailChannel", path: "/v1/apps/{application-id}/channels/email", httpMethod: "DELETE", input: input) } /// Deletes an endpoint from an application. public func deleteEndpoint(_ input: DeleteEndpointRequest) throws -> Future<DeleteEndpointResponse> { return try client.send(operation: "DeleteEndpoint", path: "/v1/apps/{application-id}/endpoints/{endpoint-id}", httpMethod: "DELETE", input: input) } /// Deletes the event stream for an application. public func deleteEventStream(_ input: DeleteEventStreamRequest) throws -> Future<DeleteEventStreamResponse> { return try client.send(operation: "DeleteEventStream", path: "/v1/apps/{application-id}/eventstream", httpMethod: "DELETE", input: input) } /// Disables the GCM channel for an application and deletes any existing settings for the channel. public func deleteGcmChannel(_ input: DeleteGcmChannelRequest) throws -> Future<DeleteGcmChannelResponse> { return try client.send(operation: "DeleteGcmChannel", path: "/v1/apps/{application-id}/channels/gcm", httpMethod: "DELETE", input: input) } /// Deletes a segment from an application. public func deleteSegment(_ input: DeleteSegmentRequest) throws -> Future<DeleteSegmentResponse> { return try client.send(operation: "DeleteSegment", path: "/v1/apps/{application-id}/segments/{segment-id}", httpMethod: "DELETE", input: input) } /// Disables the SMS channel for an application and deletes any existing settings for the channel. public func deleteSmsChannel(_ input: DeleteSmsChannelRequest) throws -> Future<DeleteSmsChannelResponse> { return try client.send(operation: "DeleteSmsChannel", path: "/v1/apps/{application-id}/channels/sms", httpMethod: "DELETE", input: input) } /// Deletes all the endpoints that are associated with a specific user ID. public func deleteUserEndpoints(_ input: DeleteUserEndpointsRequest) throws -> Future<DeleteUserEndpointsResponse> { return try client.send(operation: "DeleteUserEndpoints", path: "/v1/apps/{application-id}/users/{user-id}", httpMethod: "DELETE", input: input) } /// Disables the voice channel for an application and deletes any existing settings for the channel. public func deleteVoiceChannel(_ input: DeleteVoiceChannelRequest) throws -> Future<DeleteVoiceChannelResponse> { return try client.send(operation: "DeleteVoiceChannel", path: "/v1/apps/{application-id}/channels/voice", httpMethod: "DELETE", input: input) } /// Retrieves information about the status and settings of the ADM channel for an application. public func getAdmChannel(_ input: GetAdmChannelRequest) throws -> Future<GetAdmChannelResponse> { return try client.send(operation: "GetAdmChannel", path: "/v1/apps/{application-id}/channels/adm", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the APNs channel for an application. public func getApnsChannel(_ input: GetApnsChannelRequest) throws -> Future<GetApnsChannelResponse> { return try client.send(operation: "GetApnsChannel", path: "/v1/apps/{application-id}/channels/apns", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the APNs sandbox channel for an application. public func getApnsSandboxChannel(_ input: GetApnsSandboxChannelRequest) throws -> Future<GetApnsSandboxChannelResponse> { return try client.send(operation: "GetApnsSandboxChannel", path: "/v1/apps/{application-id}/channels/apns_sandbox", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the APNs VoIP channel for an application. public func getApnsVoipChannel(_ input: GetApnsVoipChannelRequest) throws -> Future<GetApnsVoipChannelResponse> { return try client.send(operation: "GetApnsVoipChannel", path: "/v1/apps/{application-id}/channels/apns_voip", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the APNs VoIP sandbox channel for an application. public func getApnsVoipSandboxChannel(_ input: GetApnsVoipSandboxChannelRequest) throws -> Future<GetApnsVoipSandboxChannelResponse> { return try client.send(operation: "GetApnsVoipSandboxChannel", path: "/v1/apps/{application-id}/channels/apns_voip_sandbox", httpMethod: "GET", input: input) } /// Retrieves information about an application. public func getApp(_ input: GetAppRequest) throws -> Future<GetAppResponse> { return try client.send(operation: "GetApp", path: "/v1/apps/{application-id}", httpMethod: "GET", input: input) } /// Retrieves information about the settings for an application. public func getApplicationSettings(_ input: GetApplicationSettingsRequest) throws -> Future<GetApplicationSettingsResponse> { return try client.send(operation: "GetApplicationSettings", path: "/v1/apps/{application-id}/settings", httpMethod: "GET", input: input) } /// Retrieves information about all of your applications. public func getApps(_ input: GetAppsRequest) throws -> Future<GetAppsResponse> { return try client.send(operation: "GetApps", path: "/v1/apps", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the Baidu Cloud Push channel for an application. public func getBaiduChannel(_ input: GetBaiduChannelRequest) throws -> Future<GetBaiduChannelResponse> { return try client.send(operation: "GetBaiduChannel", path: "/v1/apps/{application-id}/channels/baidu", httpMethod: "GET", input: input) } /// Retrieves information about the status, configuration, and other settings for a campaign. public func getCampaign(_ input: GetCampaignRequest) throws -> Future<GetCampaignResponse> { return try client.send(operation: "GetCampaign", path: "/v1/apps/{application-id}/campaigns/{campaign-id}", httpMethod: "GET", input: input) } /// Retrieves information about the activity performed by a campaign. public func getCampaignActivities(_ input: GetCampaignActivitiesRequest) throws -> Future<GetCampaignActivitiesResponse> { return try client.send(operation: "GetCampaignActivities", path: "/v1/apps/{application-id}/campaigns/{campaign-id}/activities", httpMethod: "GET", input: input) } /// Retrieves information about the status, configuration, and other settings for a specific version of a campaign. public func getCampaignVersion(_ input: GetCampaignVersionRequest) throws -> Future<GetCampaignVersionResponse> { return try client.send(operation: "GetCampaignVersion", path: "/v1/apps/{application-id}/campaigns/{campaign-id}/versions/{version}", httpMethod: "GET", input: input) } /// Retrieves information about the status, configuration, and other settings for all versions of a specific campaign. public func getCampaignVersions(_ input: GetCampaignVersionsRequest) throws -> Future<GetCampaignVersionsResponse> { return try client.send(operation: "GetCampaignVersions", path: "/v1/apps/{application-id}/campaigns/{campaign-id}/versions", httpMethod: "GET", input: input) } /// Retrieves information about the status, configuration, and other settings for all the campaigns that are associated with an application. public func getCampaigns(_ input: GetCampaignsRequest) throws -> Future<GetCampaignsResponse> { return try client.send(operation: "GetCampaigns", path: "/v1/apps/{application-id}/campaigns", httpMethod: "GET", input: input) } /// Retrieves information about the history and status of each channel for an application. public func getChannels(_ input: GetChannelsRequest) throws -> Future<GetChannelsResponse> { return try client.send(operation: "GetChannels", path: "/v1/apps/{application-id}/channels", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the email channel for an application. public func getEmailChannel(_ input: GetEmailChannelRequest) throws -> Future<GetEmailChannelResponse> { return try client.send(operation: "GetEmailChannel", path: "/v1/apps/{application-id}/channels/email", httpMethod: "GET", input: input) } /// Retrieves information about the settings and attributes of a specific endpoint for an application. public func getEndpoint(_ input: GetEndpointRequest) throws -> Future<GetEndpointResponse> { return try client.send(operation: "GetEndpoint", path: "/v1/apps/{application-id}/endpoints/{endpoint-id}", httpMethod: "GET", input: input) } /// Retrieves information about the event stream settings for an application. public func getEventStream(_ input: GetEventStreamRequest) throws -> Future<GetEventStreamResponse> { return try client.send(operation: "GetEventStream", path: "/v1/apps/{application-id}/eventstream", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of a specific export job for an application. public func getExportJob(_ input: GetExportJobRequest) throws -> Future<GetExportJobResponse> { return try client.send(operation: "GetExportJob", path: "/v1/apps/{application-id}/jobs/export/{job-id}", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of all the export jobs for an application. public func getExportJobs(_ input: GetExportJobsRequest) throws -> Future<GetExportJobsResponse> { return try client.send(operation: "GetExportJobs", path: "/v1/apps/{application-id}/jobs/export", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the GCM channel for an application. public func getGcmChannel(_ input: GetGcmChannelRequest) throws -> Future<GetGcmChannelResponse> { return try client.send(operation: "GetGcmChannel", path: "/v1/apps/{application-id}/channels/gcm", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of a specific import job for an application. public func getImportJob(_ input: GetImportJobRequest) throws -> Future<GetImportJobResponse> { return try client.send(operation: "GetImportJob", path: "/v1/apps/{application-id}/jobs/import/{job-id}", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of all the import jobs for an application. public func getImportJobs(_ input: GetImportJobsRequest) throws -> Future<GetImportJobsResponse> { return try client.send(operation: "GetImportJobs", path: "/v1/apps/{application-id}/jobs/import", httpMethod: "GET", input: input) } /// Retrieves information about the configuration, dimension, and other settings for a specific segment that's associated with an application. public func getSegment(_ input: GetSegmentRequest) throws -> Future<GetSegmentResponse> { return try client.send(operation: "GetSegment", path: "/v1/apps/{application-id}/segments/{segment-id}", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the export jobs for a segment. public func getSegmentExportJobs(_ input: GetSegmentExportJobsRequest) throws -> Future<GetSegmentExportJobsResponse> { return try client.send(operation: "GetSegmentExportJobs", path: "/v1/apps/{application-id}/segments/{segment-id}/jobs/export", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the import jobs for a segment. public func getSegmentImportJobs(_ input: GetSegmentImportJobsRequest) throws -> Future<GetSegmentImportJobsResponse> { return try client.send(operation: "GetSegmentImportJobs", path: "/v1/apps/{application-id}/segments/{segment-id}/jobs/import", httpMethod: "GET", input: input) } /// Retrieves information about the configuration, dimension, and other settings for a specific version of a segment that's associated with an application. public func getSegmentVersion(_ input: GetSegmentVersionRequest) throws -> Future<GetSegmentVersionResponse> { return try client.send(operation: "GetSegmentVersion", path: "/v1/apps/{application-id}/segments/{segment-id}/versions/{version}", httpMethod: "GET", input: input) } /// Retrieves information about the configuration, dimension, and other settings for all versions of a specific segment that's associated with an application. public func getSegmentVersions(_ input: GetSegmentVersionsRequest) throws -> Future<GetSegmentVersionsResponse> { return try client.send(operation: "GetSegmentVersions", path: "/v1/apps/{application-id}/segments/{segment-id}/versions", httpMethod: "GET", input: input) } /// Retrieves information about the configuration, dimension, and other settings for all the segments that are associated with an application. public func getSegments(_ input: GetSegmentsRequest) throws -> Future<GetSegmentsResponse> { return try client.send(operation: "GetSegments", path: "/v1/apps/{application-id}/segments", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the SMS channel for an application. public func getSmsChannel(_ input: GetSmsChannelRequest) throws -> Future<GetSmsChannelResponse> { return try client.send(operation: "GetSmsChannel", path: "/v1/apps/{application-id}/channels/sms", httpMethod: "GET", input: input) } /// Retrieves information about all the endpoints that are associated with a specific user ID. public func getUserEndpoints(_ input: GetUserEndpointsRequest) throws -> Future<GetUserEndpointsResponse> { return try client.send(operation: "GetUserEndpoints", path: "/v1/apps/{application-id}/users/{user-id}", httpMethod: "GET", input: input) } /// Retrieves information about the status and settings of the voice channel for an application. public func getVoiceChannel(_ input: GetVoiceChannelRequest) throws -> Future<GetVoiceChannelResponse> { return try client.send(operation: "GetVoiceChannel", path: "/v1/apps/{application-id}/channels/voice", httpMethod: "GET", input: input) } /// Retrieves all the tags (keys and values) that are associated with an application, campaign, or segment. public func listTagsForResource(_ input: ListTagsForResourceRequest) throws -> Future<ListTagsForResourceResponse> { return try client.send(operation: "ListTagsForResource", path: "/v1/tags/{resource-arn}", httpMethod: "GET", input: input) } /// Retrieves information about a phone number. public func phoneNumberValidate(_ input: PhoneNumberValidateRequest) throws -> Future<PhoneNumberValidateResponse> { return try client.send(operation: "PhoneNumberValidate", path: "/v1/phone/number/validate", httpMethod: "POST", input: input) } /// Creates a new event stream for an application or updates the settings of an existing event stream for an application. public func putEventStream(_ input: PutEventStreamRequest) throws -> Future<PutEventStreamResponse> { return try client.send(operation: "PutEventStream", path: "/v1/apps/{application-id}/eventstream", httpMethod: "POST", input: input) } /// Creates a new event to record for endpoints, or creates or updates endpoint data that existing events are associated with. public func putEvents(_ input: PutEventsRequest) throws -> Future<PutEventsResponse> { return try client.send(operation: "PutEvents", path: "/v1/apps/{application-id}/events", httpMethod: "POST", input: input) } /// Removes one or more attributes, of the same attribute type, from all the endpoints that are associated with an application. public func removeAttributes(_ input: RemoveAttributesRequest) throws -> Future<RemoveAttributesResponse> { return try client.send(operation: "RemoveAttributes", path: "/v1/apps/{application-id}/attributes/{attribute-type}", httpMethod: "PUT", input: input) } /// Creates and sends a direct message. public func sendMessages(_ input: SendMessagesRequest) throws -> Future<SendMessagesResponse> { return try client.send(operation: "SendMessages", path: "/v1/apps/{application-id}/messages", httpMethod: "POST", input: input) } /// Creates and sends a message to a list of users. public func sendUsersMessages(_ input: SendUsersMessagesRequest) throws -> Future<SendUsersMessagesResponse> { return try client.send(operation: "SendUsersMessages", path: "/v1/apps/{application-id}/users-messages", httpMethod: "POST", input: input) } /// Adds one or more tags (keys and values) to an application, campaign, or segment. @discardableResult public func tagResource(_ input: TagResourceRequest) throws -> Future<Void> { return try client.send(operation: "TagResource", path: "/v1/tags/{resource-arn}", httpMethod: "POST", input: input) } /// Removes one or more tags (keys and values) from an application, campaign, or segment. @discardableResult public func untagResource(_ input: UntagResourceRequest) throws -> Future<Void> { return try client.send(operation: "UntagResource", path: "/v1/tags/{resource-arn}", httpMethod: "DELETE", input: input) } /// Updates the ADM channel settings for an application. public func updateAdmChannel(_ input: UpdateAdmChannelRequest) throws -> Future<UpdateAdmChannelResponse> { return try client.send(operation: "UpdateAdmChannel", path: "/v1/apps/{application-id}/channels/adm", httpMethod: "PUT", input: input) } /// Updates the APNs channel settings for an application. public func updateApnsChannel(_ input: UpdateApnsChannelRequest) throws -> Future<UpdateApnsChannelResponse> { return try client.send(operation: "UpdateApnsChannel", path: "/v1/apps/{application-id}/channels/apns", httpMethod: "PUT", input: input) } /// Updates the APNs sandbox channel settings for an application. public func updateApnsSandboxChannel(_ input: UpdateApnsSandboxChannelRequest) throws -> Future<UpdateApnsSandboxChannelResponse> { return try client.send(operation: "UpdateApnsSandboxChannel", path: "/v1/apps/{application-id}/channels/apns_sandbox", httpMethod: "PUT", input: input) } /// Updates the APNs VoIP channel settings for an application. public func updateApnsVoipChannel(_ input: UpdateApnsVoipChannelRequest) throws -> Future<UpdateApnsVoipChannelResponse> { return try client.send(operation: "UpdateApnsVoipChannel", path: "/v1/apps/{application-id}/channels/apns_voip", httpMethod: "PUT", input: input) } /// Updates the settings for the APNs VoIP sandbox channel for an application. public func updateApnsVoipSandboxChannel(_ input: UpdateApnsVoipSandboxChannelRequest) throws -> Future<UpdateApnsVoipSandboxChannelResponse> { return try client.send(operation: "UpdateApnsVoipSandboxChannel", path: "/v1/apps/{application-id}/channels/apns_voip_sandbox", httpMethod: "PUT", input: input) } /// Updates the settings for an application. public func updateApplicationSettings(_ input: UpdateApplicationSettingsRequest) throws -> Future<UpdateApplicationSettingsResponse> { return try client.send(operation: "UpdateApplicationSettings", path: "/v1/apps/{application-id}/settings", httpMethod: "PUT", input: input) } /// Updates the settings of the Baidu channel for an application. public func updateBaiduChannel(_ input: UpdateBaiduChannelRequest) throws -> Future<UpdateBaiduChannelResponse> { return try client.send(operation: "UpdateBaiduChannel", path: "/v1/apps/{application-id}/channels/baidu", httpMethod: "PUT", input: input) } /// Updates the settings for a campaign. public func updateCampaign(_ input: UpdateCampaignRequest) throws -> Future<UpdateCampaignResponse> { return try client.send(operation: "UpdateCampaign", path: "/v1/apps/{application-id}/campaigns/{campaign-id}", httpMethod: "PUT", input: input) } /// Updates the status and settings of the email channel for an application. public func updateEmailChannel(_ input: UpdateEmailChannelRequest) throws -> Future<UpdateEmailChannelResponse> { return try client.send(operation: "UpdateEmailChannel", path: "/v1/apps/{application-id}/channels/email", httpMethod: "PUT", input: input) } /// Creates a new endpoint for an application or updates the settings and attributes of an existing endpoint for an application. You can also use this operation to define custom attributes (Attributes, Metrics, and UserAttributes properties) for an endpoint. public func updateEndpoint(_ input: UpdateEndpointRequest) throws -> Future<UpdateEndpointResponse> { return try client.send(operation: "UpdateEndpoint", path: "/v1/apps/{application-id}/endpoints/{endpoint-id}", httpMethod: "PUT", input: input) } /// Creates a new batch of endpoints for an application or updates the settings and attributes of a batch of existing endpoints for an application. You can also use this operation to define custom attributes (Attributes, Metrics, and UserAttributes properties) for a batch of endpoints. public func updateEndpointsBatch(_ input: UpdateEndpointsBatchRequest) throws -> Future<UpdateEndpointsBatchResponse> { return try client.send(operation: "UpdateEndpointsBatch", path: "/v1/apps/{application-id}/endpoints", httpMethod: "PUT", input: input) } /// Updates the status and settings of the GCM channel for an application. public func updateGcmChannel(_ input: UpdateGcmChannelRequest) throws -> Future<UpdateGcmChannelResponse> { return try client.send(operation: "UpdateGcmChannel", path: "/v1/apps/{application-id}/channels/gcm", httpMethod: "PUT", input: input) } /// Creates a new segment for an application or updates the configuration, dimension, and other settings for an existing segment that's associated with an application. public func updateSegment(_ input: UpdateSegmentRequest) throws -> Future<UpdateSegmentResponse> { return try client.send(operation: "UpdateSegment", path: "/v1/apps/{application-id}/segments/{segment-id}", httpMethod: "PUT", input: input) } /// Updates the status and settings of the SMS channel for an application. public func updateSmsChannel(_ input: UpdateSmsChannelRequest) throws -> Future<UpdateSmsChannelResponse> { return try client.send(operation: "UpdateSmsChannel", path: "/v1/apps/{application-id}/channels/sms", httpMethod: "PUT", input: input) } /// Updates the status and settings of the voice channel for an application. public func updateVoiceChannel(_ input: UpdateVoiceChannelRequest) throws -> Future<UpdateVoiceChannelResponse> { return try client.send(operation: "UpdateVoiceChannel", path: "/v1/apps/{application-id}/channels/voice", httpMethod: "PUT", input: input) } }
70.041063
292
0.736904
697f0a16317aa0bbdceb54f8e91fa77c682142e6
8,080
// // Copyright © 2018-present Amaris Technologies GmbH. All rights reserved. // import XCTest @testable import SplashBuddy class PreferencesTests: XCTestCase { // MARK: - Properties var appDelegate: AppDelegate! var testUserDefaults: UserDefaults! var testPrefs: Preferences! var casperSplashController: MainWindowController! var casperSplashMainController: MainViewController! var assetPath = "" // MARK: - Lifecycle override func setUp() { super.setUp() appDelegate = AppDelegate() // Global Default UserDefaults testUserDefaults = UserDefaults.init(suiteName: "testing") assetPath = Bundle(for: type(of: self)).bundlePath + "/Contents/Resources" testUserDefaults!.set(assetPath, forKey: "TSTAssetPath") let testJamfLog = Bundle(for: type(of: self)).path(forResource: "jamf_1", ofType: "txt") testUserDefaults!.set(testJamfLog, forKey: "TSTJamfLog") testPrefs = Preferences(userDefaults: testUserDefaults) } override func tearDown() { super.tearDown() testPrefs = nil testUserDefaults.removeSuite(named: "testing") testUserDefaults = nil SoftwareArray.sharedInstance.array.removeAll() } // MARK: - Tests func testSetSetupDone() { Preferences.sharedInstance.setupDone = true debugPrint(FileManager.default.currentDirectoryPath) XCTAssertTrue(FileManager.default.fileExists(atPath: "Library/.SplashBuddyDone")) } func testUnsetSetupDone() { Preferences.sharedInstance.setupDone = false XCTAssertFalse(FileManager.default.fileExists(atPath: "Library/.SplashBuddyDone")) } func testSetupDoneSet() { FileManager.default.createFile(atPath: "Library/.SplashBuddyDone", contents: nil, attributes: nil) XCTAssertTrue(Preferences.sharedInstance.setupDone) } func testSetupDoneNotSet() { _ = try? FileManager.default.removeItem(atPath: "Library/.SplashBuddyDone") XCTAssertFalse(Preferences.sharedInstance.setupDone) } func testUserDefaults_MalformedApplication() { let input = [true] testUserDefaults!.set(input, forKey: "applicationsArray") testPrefs = Preferences(userDefaults: testUserDefaults) XCTAssertThrowsError(try testPrefs.getApplicationsFromPreferences(), "") { (error) in XCTAssertEqual(error as? Preferences.Errors, .malformedApplication) } } func testUserDefaults_NoApplicationsArray() { testUserDefaults.set(nil, forKey: "applicationsArray") testPrefs = Preferences(userDefaults: testUserDefaults) XCTAssertThrowsError(try testPrefs.getApplicationsFromPreferences(), "") { (error) in XCTAssertEqual(error as? Preferences.Errors, .noApplicationArray) } } func testUserDefaults_Application() { let input = [[ "displayName": "Enterprise Connect", "description": "SSO", "packageName": "Enterprise Connect", "iconRelativePath": "ec_32x32.png", "canContinue": 1 ]] // Setup user defaults testUserDefaults!.set(input, forKey: "applicationsArray") testPrefs = Preferences(userDefaults: testUserDefaults) try! testPrefs.getApplicationsFromPreferences() XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.packageName, "Enterprise Connect") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.status, Software.SoftwareStatus.pending) XCTAssert(type(of: SoftwareArray.sharedInstance.array.first!.icon!) == type(of: NSImage())) XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.displayName, "Enterprise Connect") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.desc, "SSO") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.canContinue, true) XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.displayToUser, true) testUserDefaults.removeObject(forKey: "applicationsArray") XCTAssertNil(testUserDefaults.object(forKey: "applicationsArray")) } func testUserDefaults_ApplicationCanContinueAsString() { let input = [[ "displayName": "Enterprise Connect", "description": "SSO", "packageName": "Enterprise Connect", "iconRelativePath": "ec_32x32.png", "canContinue": "1" ]] // Setup user defaults testUserDefaults!.set(input, forKey: "applicationsArray") testPrefs = Preferences(userDefaults: testUserDefaults) try! testPrefs.getApplicationsFromPreferences() XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.packageName, "Enterprise Connect") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.status, Software.SoftwareStatus.pending) XCTAssert(type(of: SoftwareArray.sharedInstance.array.first!.icon!) == type(of: NSImage())) XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.displayName, "Enterprise Connect") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.desc, "SSO") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.canContinue, true) XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.displayToUser, true) testUserDefaults.removeObject(forKey: "applicationsArray") XCTAssertNil(testUserDefaults.object(forKey: "applicationsArray")) } func testUserDefaults_ApplicationMultiple() { let input = [[ "displayName": "Enterprise Connect", "description": "SSO", "packageName": "Enterprise Connect", "iconRelativePath": "ec_32x32.png", "canContinue": 1 ], [ "displayName": "Druva", "description": "Backup", "packageName": "DruvaEndPoint", "iconRelativePath": "ec_32x32.png", "canContinue": 1 ] ] // Setup user defaults testUserDefaults!.set(input, forKey: "applicationsArray") testPrefs = Preferences(userDefaults: testUserDefaults) try! testPrefs.getApplicationsFromPreferences() XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.packageName, "Enterprise Connect") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.status, Software.SoftwareStatus.pending) XCTAssert(type(of: SoftwareArray.sharedInstance.array.first!.icon!) == type(of: NSImage())) XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.displayName, "Enterprise Connect") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.desc, "SSO") XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.canContinue, true) XCTAssertEqual(SoftwareArray.sharedInstance.array.first!.displayToUser, true) XCTAssertEqual(SoftwareArray.sharedInstance.array.last!.displayName, "Druva") XCTAssertEqual(SoftwareArray.sharedInstance.array.last!.desc, "Backup") XCTAssertEqual(SoftwareArray.sharedInstance.array.last!.packageName, "DruvaEndPoint") XCTAssert(type(of: SoftwareArray.sharedInstance.array.last!.icon!) == type(of: NSImage())) XCTAssertEqual(SoftwareArray.sharedInstance.array.last!.canContinue, true) XCTAssertEqual(SoftwareArray.sharedInstance.array.last!.status, Software.SoftwareStatus.pending) XCTAssertEqual(SoftwareArray.sharedInstance.array.last!.displayToUser, true) testUserDefaults.removeObject(forKey: "applicationsArray") XCTAssertNil(testUserDefaults.object(forKey: "applicationsArray")) } func testUserDefaults_ApplicationEmptyUserDefaults() { testUserDefaults = UserDefaults.init(suiteName: "none") testPrefs = Preferences(userDefaults: testUserDefaults) // Disabling throwing ".noApplicationArray" _ = try? testPrefs.getApplicationsFromPreferences() XCTAssertTrue(SoftwareArray.sharedInstance.array.isEmpty) } }
41.865285
106
0.694926
769e13789df9d5b145baba875865aac993885e32
2,176
// // AppDelegate.swift // S05L53TableViews // // Created by rjj on 2019.02.23. // Copyright © 2019 Sapient, Inc. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.297872
285
0.755055
1ebe50aa148da05ff7badc222c0da0c98a083739
2,163
// // AppDelegate.swift // EmitterLayer // // Created by Kitty on 2017/4/25. // Copyright © 2017年 RM. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.021277
285
0.75497
08e64a0f16811c2c91942593e3a5b49ffc9e64cc
2,176
// // AppDelegate.swift // ClearTableViewCell // // Created by Phoenix on 2017/3/21. // Copyright © 2017年 Wolkamo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.297872
285
0.756434
e9fb08d085a216475213ff3f3e37c9010d5bf4a3
1,453
// // DummyUser.swift // Caturlog // // Created by Jonathon Rubin on 7/27/14. // Copyright (c) 2014 Jonathon Rubin. All rights reserved. // import Foundation import CoreData import AppKit class DummyUser: UserServiceProtocol { func getCurrentUserID() -> (Int?) { return 1 } func getCurrentUser() -> (User?) { if let userID = getCurrentUserID()? { if let user = getUserWithID(userID)? { return user } else if let user = addUser("jbrjake") { return user } } return nil } // Return user if it exists func getUserWithID(userID: Int) -> (User?) { let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate let services = appDelegate.caturlogServices return services.entityAccessor.getUser(userID) } func addUser(name: String) -> (User?) { let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate let services = appDelegate.caturlogServices if let user = services.entityAccessor.insertUser(1)? { // CHANGE THIS '1' LATER user.name = name // Need another accessor method to pass this instead appDelegate.managedObjectContext?.save(nil) // Oh my god I can't believe I'm doing this to save time :( return user } return nil } }
29.06
115
0.594632
deb8a5df6bea43bb49655d5360dd36667e2b45d1
17,989
import Foundation import LR35902 extension Project { public convenience init(rom: Data?) { var regions: [Region] = [] var dataTypes: [DataType] = [] var globals: [Global] = [] let numberOfRestartAddresses: LR35902.Address = 8 let restartSize: LR35902.Address = 8 let rstAddresses = (0..<numberOfRestartAddresses).map { ($0 * restartSize)..<($0 * restartSize + restartSize) } rstAddresses.forEach { regions.append(Region(regionType: Windfish.Project.Region.Kind.region, name: "RST_\($0.lowerBound.hexString)", bank: 0, address: $0.lowerBound, length: LR35902.Address($0.count))) } regions.append(contentsOf: [ Region(regionType: Windfish.Project.Region.Kind.region, name: "VBlankInterrupt", bank: 0, address: 0x0040, length: 8), Region(regionType: Windfish.Project.Region.Kind.region, name: "LCDCInterrupt", bank: 0, address: 0x0048, length: 8), Region(regionType: Windfish.Project.Region.Kind.region, name: "TimerOverflowInterrupt", bank: 0, address: 0x0050, length: 8), Region(regionType: Windfish.Project.Region.Kind.region, name: "SerialTransferCompleteInterrupt", bank: 0, address: 0x0058, length: 8), Region(regionType: Windfish.Project.Region.Kind.region, name: "JoypadTransitionInterrupt", bank: 0, address: 0x0060, length: 8), Region(regionType: Windfish.Project.Region.Kind.region, name: "Boot", bank: 0, address: 0x0100, length: 4), Region(regionType: Windfish.Project.Region.Kind.image1bpp, name: "HeaderLogo", bank: 0, address: 0x0104, length: 0x0134 - 0x0104), Region(regionType: Windfish.Project.Region.Kind.string, name: "HeaderTitle", bank: 0, address: 0x0134, length: 0x0143 - 0x0134), Region(regionType: Windfish.Project.Region.Kind.label, name: "HeaderNewLicenseeCode", bank: 0, address: 0x0144, length: 0), Region(regionType: Windfish.Project.Region.Kind.label, name: "HeaderOldLicenseeCode", bank: 0, address: 0x014B, length: 0), Region(regionType: Windfish.Project.Region.Kind.label, name: "HeaderMaskROMVersion", bank: 0, address: 0x014C, length: 0), Region(regionType: Windfish.Project.Region.Kind.label, name: "HeaderComplementCheck", bank: 0, address: 0x014D, length: 0), Region(regionType: Windfish.Project.Region.Kind.label, name: "HeaderGlobalChecksum", bank: 0, address: 0x014E, length: 0), ]) dataTypes.append(DataType(name: "hex", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.any, mappings: [])) dataTypes.append(DataType(name: "decimal", representation: Windfish.Project.DataType.Representation.decimal, interpretation: Windfish.Project.DataType.Interpretation.any, mappings: [])) dataTypes.append(DataType(name: "binary", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.any, mappings: [])) dataTypes.append(DataType(name: "bool", representation: Windfish.Project.DataType.Representation.decimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "false", value: 0), DataType.Mapping(name: "true", value: 1) ])) dataTypes.append(DataType(name: "HW_COLORGAMEBOY", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "not_color_gameboy", value: 0x00), DataType.Mapping(name: "is_color_gameboy", value: 0x80), ])) dataTypes.append(DataType(name: "HW_SUPERGAMEBOY", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "not_super_gameboy", value: 0x00), DataType.Mapping(name: "is_super_gameboy", value: 0x80), ])) dataTypes.append(DataType(name: "HW_ROMSIZE", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "romsize_2banks", value: 0), DataType.Mapping(name: "romsize_4banks", value: 1), DataType.Mapping(name: "romsize_8banks", value: 2), DataType.Mapping(name: "romsize_16banks", value: 3), DataType.Mapping(name: "romsize_32banks", value: 4), DataType.Mapping(name: "romsize_64banks", value: 5), DataType.Mapping(name: "romsize_128banks", value: 6), DataType.Mapping(name: "romsize_72banks", value: 0x52), DataType.Mapping(name: "romsize_80banks", value: 0x53), DataType.Mapping(name: "romsize_96banks", value: 0x54), ])) dataTypes.append(DataType(name: "HW_CARTRIDGETYPE", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "cartridge_romonly", value: 0), DataType.Mapping(name: "cartridge_mbc1", value: 1), DataType.Mapping(name: "cartridge_mbc1_ram", value: 2), DataType.Mapping(name: "cartridge_mbc1_ram_battery", value: 3), DataType.Mapping(name: "cartridge_mbc2", value: 5), DataType.Mapping(name: "cartridge_mbc2_battery", value: 6), DataType.Mapping(name: "cartridge_rom_ram", value: 8), DataType.Mapping(name: "cartridge_rom_ram_battery", value: 9), ])) dataTypes.append(DataType(name: "HW_RAMSIZE", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "ramsize_none", value: 0), DataType.Mapping(name: "ramsize_1bank", value: 1), DataType.Mapping(name: "ramsize_1bank_", value: 2), DataType.Mapping(name: "ramsize_4banks", value: 3), DataType.Mapping(name: "ramsize_16banks", value: 4), ])) dataTypes.append(DataType(name: "HW_DESTINATIONCODE", representation: Windfish.Project.DataType.Representation.hexadecimal, interpretation: Windfish.Project.DataType.Interpretation.enumerated, mappings: [ DataType.Mapping(name: "destination_japanese", value: 0), DataType.Mapping(name: "destination_nonjapanese", value: 1), ])) dataTypes.append(DataType(name: "HW_IE", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.bitmask, mappings: [ DataType.Mapping(name: "IE_VBLANK", value: 0b0000_0001), DataType.Mapping(name: "IE_LCDC", value: 0b0000_0010), DataType.Mapping(name: "IE_TIMEROVERFLOW", value: 0b0000_0100), DataType.Mapping(name: "IE_SERIALIO", value: 0b0000_1000), DataType.Mapping(name: "IE_PIN1013TRANSITION", value: 0b0001_0000), ])) dataTypes.append(DataType(name: "HW_AUDIO_ENABLE", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.bitmask, mappings: [ DataType.Mapping(name: "HW_AUDIO_ENABLE", value: 0b1000_0000), ])) dataTypes.append(DataType(name: "LCDCF", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.bitmask, mappings: [ DataType.Mapping(name: "LCDCF_OFF", value: 0b0000_0000), DataType.Mapping(name: "LCDCF_ON", value: 0b1000_0000), DataType.Mapping(name: "LCDCF_TILEMAP_9C00", value: 0b0100_0000), DataType.Mapping(name: "LCDCF_WINDOW_ON", value: 0b0010_0000), DataType.Mapping(name: "LCDCF_BG_CHAR_8000", value: 0b0001_0000), DataType.Mapping(name: "LCDCF_BG_TILE_9C00", value: 0b0000_1000), DataType.Mapping(name: "LCDCF_OBJ_16_16", value: 0b0000_0100), DataType.Mapping(name: "LCDCF_OBJ_DISPLAY", value: 0b0000_0010), DataType.Mapping(name: "LCDCF_BG_DISPLAY", value: 0b0000_0001), ])) dataTypes.append(DataType(name: "STATF", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.bitmask, mappings: [ DataType.Mapping(name: "STATF_LYC", value: 0b0100_0000), DataType.Mapping(name: "STATF_MODE10", value: 0b0010_0000), DataType.Mapping(name: "STATF_MODE01", value: 0b0001_0000), DataType.Mapping(name: "STATF_MODE00", value: 0b0000_1000), DataType.Mapping(name: "STATF_LYCF", value: 0b0000_0100), DataType.Mapping(name: "STATF_OAM", value: 0b0000_0010), DataType.Mapping(name: "STATF_VB", value: 0b0000_0001), DataType.Mapping(name: "STATF_HB", value: 0b0000_0000), ])) dataTypes.append(DataType(name: "BUTTON", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.bitmask, mappings: [ DataType.Mapping(name: "J_RIGHT", value: 0b0000_0001), DataType.Mapping(name: "J_LEFT", value: 0b0000_0010), DataType.Mapping(name: "J_UP", value: 0b0000_0100), DataType.Mapping(name: "J_DOWN", value: 0b0000_1000), DataType.Mapping(name: "J_A", value: 0b0001_0000), DataType.Mapping(name: "J_B", value: 0b0010_0000), DataType.Mapping(name: "J_SELECT", value: 0b0100_0000), DataType.Mapping(name: "J_START", value: 0b1000_0000), ])) dataTypes.append(DataType(name: "JOYPAD", representation: Windfish.Project.DataType.Representation.binary, interpretation: Windfish.Project.DataType.Interpretation.bitmask, mappings: [ DataType.Mapping(name: "JOYPAD_DIRECTIONS", value: 0b0001_0000), DataType.Mapping(name: "JOYPAD_BUTTONS", value: 0b0010_0000), ])) globals.append(contentsOf: [ Global(name: "HeaderIsColorGB", address: 0x0143, dataType: "HW_COLORGAMEBOY"), Global(name: "HeaderSGBFlag", address: 0x0146, dataType: "HW_SUPERGAMEBOY"), Global(name: "HeaderCartridgeType", address: 0x0147, dataType: "HW_CARTRIDGETYPE"), Global(name: "HeaderROMSize", address: 0x0148, dataType: "HW_ROMSIZE"), Global(name: "HeaderRAMSize", address: 0x0149, dataType: "HW_RAMSIZE"), Global(name: "HeaderDestinationCode", address: 0x014A, dataType: "HW_DESTINATIONCODE"), Global(name: "gbVRAM", address: 0x8000, dataType: "hex"), Global(name: "gbBGCHARDAT", address: 0x8800, dataType: "hex"), Global(name: "gbBGDAT0", address: 0x9800, dataType: "hex"), Global(name: "gbBGDAT1", address: 0x9c00, dataType: "hex"), Global(name: "gbCARTRAM", address: 0xa000, dataType: "hex"), Global(name: "gbRAM", address: 0xc000, dataType: "hex"), Global(name: "gbOAMRAM", address: 0xfe00, dataType: "hex"), Global(name: "gbP1", address: 0xff00, dataType: "JOYPAD"), Global(name: "gbSB", address: 0xff01, dataType: "hex"), Global(name: "gbSC", address: 0xff02, dataType: "hex"), Global(name: "gbDIV", address: 0xff04, dataType: "hex"), Global(name: "gbTIMA", address: 0xff05, dataType: "hex"), Global(name: "gbTMA", address: 0xff06, dataType: "hex"), Global(name: "gbTAC", address: 0xff07, dataType: "hex"), Global(name: "gbIF", address: 0xff0f, dataType: "hex"), Global(name: "gbAUD1SWEEP", address: 0xff10, dataType: "hex"), Global(name: "gbAUD1LEN", address: 0xff11, dataType: "hex"), Global(name: "gbAUD1ENV", address: 0xff12, dataType: "hex"), Global(name: "gbAUD1LOW", address: 0xff13, dataType: "hex"), Global(name: "gbAUD1HIGH", address: 0xff14, dataType: "hex"), Global(name: "gbAUD2LEN", address: 0xff16, dataType: "hex"), Global(name: "gbAUD2ENV", address: 0xff17, dataType: "hex"), Global(name: "gbAUD2LOW", address: 0xff18, dataType: "hex"), Global(name: "gbAUD2HIGH", address: 0xff19, dataType: "hex"), Global(name: "gbAUD3ENA", address: 0xff1a, dataType: "hex"), Global(name: "gbAUD3LEN", address: 0xff1b, dataType: "hex"), Global(name: "gbAUD3LEVEL", address: 0xff1c, dataType: "hex"), Global(name: "gbAUD3LOW", address: 0xff1d, dataType: "hex"), Global(name: "gbAUD3HIGH", address: 0xff1e, dataType: "hex"), Global(name: "gbAUD4LEN", address: 0xff20, dataType: "hex"), Global(name: "gbAUD4ENV", address: 0xff21, dataType: "hex"), Global(name: "gbAUD4POLY", address: 0xff22, dataType: "hex"), Global(name: "gbAUD4CONSEC", address: 0xff23, dataType: "hex"), Global(name: "gbAUDVOL", address: 0xff24, dataType: "binary"), Global(name: "gbAUDTERM", address: 0xff25, dataType: "binary"), Global(name: "gbAUDENA", address: 0xff26, dataType: "HW_AUDIO_ENABLE"), Global(name: "gbAUD3WAVERAM", address: 0xff30, dataType: "hex"), Global(name: "gbLCDC", address: 0xff40, dataType: "LCDCF"), Global(name: "gbSTAT", address: 0xff41, dataType: "STATF"), Global(name: "gbSCY", address: 0xff42, dataType: "decimal"), Global(name: "gbSCX", address: 0xff43, dataType: "decimal"), Global(name: "gbLY", address: 0xff44, dataType: "decimal"), Global(name: "gbLYC", address: 0xff45, dataType: "decimal"), Global(name: "gbDMA", address: 0xff46, dataType: "hex"), Global(name: "gbBGP", address: 0xff47, dataType: "hex"), Global(name: "gbOBP0", address: 0xff48, dataType: "hex"), Global(name: "gbOBP1", address: 0xff49, dataType: "hex"), Global(name: "gbWY", address: 0xff4a, dataType: "hex"), Global(name: "gbWX", address: 0xff4b, dataType: "hex"), Global(name: "gbKEY1", address: 0xff4d, dataType: "hex"), Global(name: "gbVBK", address: 0xff4f, dataType: "hex"), Global(name: "gbHDMA1", address: 0xff51, dataType: "hex"), Global(name: "gbHDMA2", address: 0xff52, dataType: "hex"), Global(name: "gbHDMA3", address: 0xff53, dataType: "hex"), Global(name: "gbHDMA4", address: 0xff54, dataType: "hex"), Global(name: "gbHDMA5", address: 0xff55, dataType: "hex"), Global(name: "gbRP", address: 0xff56, dataType: "hex"), Global(name: "gbBCPS", address: 0xff68, dataType: "hex"), Global(name: "gbBCPD", address: 0xff69, dataType: "hex"), Global(name: "gbOCPS", address: 0xff6a, dataType: "hex"), Global(name: "gbOCPD", address: 0xff6b, dataType: "hex"), Global(name: "gbSVBK", address: 0xff70, dataType: "hex"), Global(name: "gbPCM12", address: 0xff76, dataType: "hex"), Global(name: "gbPCM34", address: 0xff77, dataType: "hex"), Global(name: "gbIE", address: 0xffff, dataType: "HW_IE"), ]) self.init(rom: rom, scripts: [], macros: [], globals: globals, dataTypes: dataTypes, regions: regions) } }
70.822835
185
0.570738
89bfd11275406c9c337a62066af6bbbf0f571f51
8,717
// // SectionView.swift // Lifting Buddy // // Created by Christopher Perkins on 7/20/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // /// Sections shown on the bottom of the header view import UIKit class SectionView: UIView { // MARK: View properties // Required view for modifying sectionContentView var mainViewController: MainViewController? // Our sections public let sessionButton: PrettyButton public let workoutsButton: PrettyButton public let exercisesButton: PrettyButton // The view that's currently being selected private var selectedView: PrettyButton? // Determines if the subviews have been laid out private var laidOutSubviews = false // Width constraints with a session active var sessionWidthConstraints = [NSLayoutConstraint]() // Width constraints with no session var noSessionWidthConstraints = [NSLayoutConstraint]() // MARK: Enums public enum ContentViews { case session case workouts case exercises } // MARK: Init functions override init(frame: CGRect) { sessionButton = PrettyButton() workoutsButton = PrettyButton() exercisesButton = PrettyButton() super.init(frame: frame) addSubview(sessionButton) addSubview(workoutsButton) addSubview(exercisesButton) sessionButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) workoutsButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) exercisesButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) createAndActivateButtonConstraints(buttons: [sessionButton, workoutsButton, exercisesButton]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View overrides override func layoutSubviews() { super.layoutSubviews() // Session button setButtonProperties(button: sessionButton) sessionButton.setTitle(NSLocalizedString("Tabs.Session", comment: ""), for: .normal) // Workouts Button workoutsButton.setTitle(NSLocalizedString("Tabs.Workouts", comment: ""), for: .normal) setButtonProperties(button: workoutsButton) // Exercises Button exercisesButton.setTitle(NSLocalizedString("Tabs.Exercises", comment: ""), for: .normal) setButtonProperties(button: exercisesButton) // If this is the first time we laid out a subview, press the workout button if !laidOutSubviews { mainViewController = (viewContainingController() as! MainViewController) // Only sets properties once. laidOutSubviews = true imitateButtonPress(forButton: workoutsButton) } } // MARK: Private functions // Gives a button default properties, overlay of opacic white, and button press event. private func setButtonProperties(button: PrettyButton) { if selectedView != button { button.setDefaultProperties() button.setOverlayColor(color: UIColor.white.withAlphaComponent(0.25)) } } // Shows the session button public func showSessionButton() { for constraint in noSessionWidthConstraints { constraint.isActive = false } for constraint in sessionWidthConstraints { constraint.isActive = true } UIView.animate(withDuration: 0.5, animations: { self.layoutIfNeeded() }) layoutSubviews() buttonPress(sender: sessionButton) } // Hides the session button public func hideSessionButton() { // Animate constraints for constraint in sessionWidthConstraints { constraint.isActive = false } for constraint in noSessionWidthConstraints { constraint.isActive = true } UIView.animate(withDuration: 0.5, animations: { self.layoutIfNeeded() }) // Go to workout view imitateButtonPress(forButton: workoutsButton) } // Acts like the workout button was pressed. public func imitateButtonPress(forButton button: PrettyButton) { buttonPress(sender: button) } // MARK: Event functions // Called by the event handlers to send a call to the main view controller to display view @objc private func buttonPress(sender: PrettyButton) { if selectedView != sender { selectedView?.backgroundColor = nil sender.backgroundColor = .niceYellow var viewType: SectionView.ContentViews? = nil switch(sender) { case sessionButton: viewType = .session case workoutsButton: viewType = .workouts case exercisesButton: viewType = .exercises default: fatalError("User requested view that isn't set up.") } mainViewController?.showContentView(viewType: viewType!) } // Set the newly selected view equal to this button selectedView = sender } // Mark: Constraint functions func createAndActivateButtonConstraints(buttons: [UIButton]) { var prevView: UIView = self // Remove and re-add to remove any assigned constraints. for button in buttons { button.removeFromSuperview() addSubview(button) } // Add constraints for button in buttons { button.translatesAutoresizingMaskIntoConstraints = false // If prevView = self, we need to use the left side of the view instead. NSLayoutConstraint(item: prevView, attribute: prevView == self ? .left : .right, relatedBy: .equal, toItem: button, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: button, withCopyView: self, attribute: .top).isActive = true NSLayoutConstraint.createViewAttributeCopyConstraint(view: button, withCopyView: self, attribute: .bottom).isActive = true // The session button is treated differently. // At the start, it should not be visible. // This means that the session button is always there, but not clickable. // It should only be visible when there is an active session. if button == sessionButton { let constraint = NSLayoutConstraint.createWidthConstraintForView(view: button, width: 0) constraint.isActive = true noSessionWidthConstraints.append(constraint) } else { let constraint = NSLayoutConstraint.createViewAttributeCopyConstraint( view: button, withCopyView: self, attribute: .width, multiplier: 1/CGFloat(buttons.count - 1) ) constraint.isActive = true noSessionWidthConstraints.append(constraint) } sessionWidthConstraints.append(NSLayoutConstraint.createViewAttributeCopyConstraint( view: button, withCopyView: self, attribute: .width, multiplier: 1/CGFloat(buttons.count) ) ) prevView = button } } }
36.62605
101
0.549386
26e620643df7d48fb9ac2c126aa52b39e410f5f9
3,242
// // GoogleAnalytics.swift // BlindWays // // Created by Nicholas Bonatsakis on 6/10/16. // Copyright© 2016 Perkins School for the Blind // // All "Perkins Bus Stop App" Software is licensed under Apache Version 2.0. // 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 class GoogleAnalytics { static let shared = GoogleAnalytics() var tracker: GAITracker { return GAI.sharedInstance().defaultTracker } fileprivate func configure() { if let trackerID = AppConstants.Analytics.trackerID { let gai = GAI.sharedInstance() gai?.trackUncaughtExceptions = false _ = gai?.tracker(withTrackingId: trackerID) if BuildType.debug.active { gai?.logger.logLevel = GAILogLevel.verbose } } } } extension GoogleAnalytics: AppLifecycleConfigurable { var enabledBuildTypes: [BuildType] { return [.internal, .release] } func onDidLaunch(_ application: UIApplication, launchOptions: [UIApplicationLaunchOptionsKey: Any]?) { configure() guard AppConstants.Analytics.trackerID != nil else { return } UIViewController.globalBehaviors.append(GoogleTrackPageViewBehavior()) } } extension GoogleAnalytics: AnalyticsService { private enum CustomDimensions { enum VoiceOver { static let id: UInt = 1 static var value: String { let voiceOverState: String if UIAccessibilityIsVoiceOverRunning() { voiceOverState = "VOICE_OVER_ENABLED" } else { voiceOverState = "VOICE_OVER_DISABLED" } return voiceOverState } } } func trackPageView(_ page: String) { guard AppConstants.Analytics.trackerID != nil else { return } tracker.set(kGAIScreenName, value: page) tracker.set(GAIFields.customDimension(for: CustomDimensions.VoiceOver.id), value: CustomDimensions.VoiceOver.value) if let built = GAIDictionaryBuilder.createScreenView().build() as NSDictionary as? [AnyHashable: Any] { tracker.send(built) } } } public class GoogleTrackPageViewBehavior: ViewControllerLifecycleBehavior { public init() {} public func afterAppearing(_ viewController: UIViewController, animated: Bool) { guard AppConstants.Analytics.trackerID != nil else { return } if let pageRepresentation = viewController as? AnalyticsPageRepresentation { GoogleAnalytics.shared.trackPageRepresentation(pageRepresentation) } } }
30.87619
111
0.648982
ff2f634e5983414c224e72aba8762bcfefbcaf2e
744
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "PIPKit", platforms: [ .iOS(.v8) ], products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library(name: "PIPKit", targets: ["PIPKit"]), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target(name: "PIPKit", path: "PIPKit/Classes") ] )
37.2
122
0.670699
62e8772ad99796f1cc44b266416c68a968947aaf
1,680
import Foundation import JsonFileManager class RequestReviewRepository { private let fileURL: URL private typealias RequestReviewRecordsCache = Dictionary<UUID, RequestReviewRecord> private let fileManager: JsonFileManager<RequestReviewRecordsCache> private var requestedReviewRecords: RequestReviewRecordsCache = [:] public var all: Dictionary<UUID, RequestReviewRecord> { get { return self.requestedReviewRecords } } public init(dirURL: URL) throws { self.fileURL = dirURL.appendingPathComponent("patch-stack-review-requests.json") self.fileManager = JsonFileManager<RequestReviewRecordsCache>(fileURL: self.fileURL) do { try fileManager.read { [weak self] (records) in self?.requestedReviewRecords.merge(records, uniquingKeysWith: { (origRecord, newRecord) -> RequestReviewRecord in return newRecord }) } } catch JsonFileManagerError.fileMissing { try self.fileManager.save(data: self.requestedReviewRecords) } } public func record(_ requestReviewRecord: RequestReviewRecord) throws { self.requestedReviewRecords[requestReviewRecord.patchStackID] = requestReviewRecord try self.fileManager.save(data: self.requestedReviewRecords) } public func removeRecord(withPatchStackID: UUID) throws { self.requestedReviewRecords.removeValue(forKey: withPatchStackID) try self.fileManager.save(data: self.requestedReviewRecords) } public func fetch(_ patchStackID: UUID) -> RequestReviewRecord? { return self.requestedReviewRecords[patchStackID] } }
39.069767
129
0.71369
6777a02284597f979f80c30ab8f7a65ab918ef49
407
import Foundation public struct AssetFolderContents: Codable, Hashable { // MARK: - Instance Properties public var info: AssetInfo? public var properties: AssetFolderProperties? // MARK: - Initializers public init( info: AssetInfo? = AssetInfo(), properties: AssetFolderProperties? = nil ) { self.info = info self.properties = properties } }
20.35
54
0.648649
ab05de668518775dbe3d7c7214c3ec3a3c8c1fe3
2,153
// The MIT License // // Copyright (c) 2018-2019 Alejandro Barros Cuetos. [email protected] // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation final public class MockURLProtocol: URLProtocol { static public var requestHandler: ((URLRequest) throws -> (HTTPURLResponse, Data))? override public class func canInit(with request: URLRequest) -> Bool { return true } override public class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override public func startLoading() { guard let handler = MockURLProtocol.requestHandler else { fatalError("Received unexpected request with not handler") } do { let (response, data) = try handler(request) client?.urlProtocol(self, didLoad: data) client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client?.urlProtocolDidFinishLoading(self) } catch { client?.urlProtocol(self, didFailWithError: error) } } override public func stopLoading() { } }
40.622642
92
0.714817
618d6d55b5d79abfd11bdf1c51b690a892830ebf
664
// Created by Geoff Pado on 6/25/19. // Copyright © 2019 Geoff Pado. All rights reserved. import UIKit @available(iOS 12.0, *) struct PetObservation: Equatable { init(_ petObservation: RecognizedObjectObservation, in image: UIImage) { let boundingBox = petObservation.boundingBox let imageSize = image.size * image.scale self.bounds = CGRect.flippedRect(from: boundingBox, scaledTo: imageSize) let observationUUID = petObservation.uuid self.uuid = observationUUID } init(bounds: CGRect, uuid: UUID) { self.bounds = bounds self.uuid = uuid } let bounds: CGRect let uuid: UUID }
26.56
80
0.670181
3953045b1265ee738e0608d40552b5548e9a52cc
1,595
import XCTest import Quick import Nimble import Fleet @testable import Zendo class CommunityViewControllerTest: QuickSpec { override func spec() { describe("CommunityViewController") { var subject: CommunityViewController! var healthKitViewController: HealthKitViewController! beforeEach { let storyboard = UIStoryboard(name: "Main", bundle: nil) healthKitViewController = try! storyboard.mockIdentifier( "HealthKitViewController", usingMockFor: HealthKitViewController.self) subject = (storyboard.instantiateViewController( withIdentifier: "CommunityViewController") as! CommunityViewController) let navigationController = UINavigationController(rootViewController: subject) Fleet.setAsAppWindowRoot(navigationController) } describe("When hitting the 'Skip' button") { beforeEach { subject.skipButton.tap() } it("presents the HealthKitViewController") { expect(Fleet.getApplicationScreen()?.topmostViewController).toEventually(beIdenticalTo(healthKitViewController)) } it("registers in settings that the user skipped community setup") { expect(Settings.didFinishCommunitySignup).toEventually(beFalse()) expect(Settings.skippedCommunitySignup).toEventually(beTrue()) } } } } }
37.97619
132
0.613166
ffcc0a2e2706ff8e3d6da9c2a2bc093e61ed4955
480
import UIKit extension UIStackView { func addArrangedSubviews(views: [UIView]) { for view in views { view.translatesAutoresizingMaskIntoConstraints = false self.addArrangedSubview(view) } } func addBackground(color: UIColor) { let subView = UIView(frame: bounds) subView.backgroundColor = color subView.autoresizingMask = [.flexibleWidth, .flexibleHeight] insertSubview(subView, at: 0) } }
26.666667
68
0.647917
cc4e87df5f70a0c76313af0e0845289e85680fe8
979
// // AppCoordinator.swift // ReachabilityUIDemo // // Created by Andrei Hogea on 03/10/2018. // Copyright © 2018 Nodes. All rights reserved. // import UIKit class AppCoordinator: NSObject, Coordinator { let window: UIWindow var children: [Coordinator] = [] var dependencies: FullDependencies var launchOptions: [UIApplication.LaunchOptionsKey: Any]? var application: UIApplication! private var mainCoordinator: TabBarCoordinator! init(window: UIWindow, dependencies: FullDependencies = Dependencies.shared) { self.window = window self.dependencies = dependencies } func start() { showMain() window.makeKeyAndVisible() } // MARK: - Flows - func showMain() { let coordinator = TabBarCoordinator(window: window, dependencies: dependencies) mainCoordinator = coordinator coordinator.start() children = [coordinator] } }
23.309524
87
0.648621
611c9de5a63920d728551c053ccb0bedd704ea26
5,726
// // Copyright © 2018 Frollo. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import FrolloSDK class TransactionTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testUpdatingTransactionCompleteData() { let database = Database(path: tempFolderPath()) let managedObjectContext = database.newBackgroundContext() managedObjectContext.performAndWait { let transactionResponse = APITransactionResponse.testCompleteData() let transaction = Transaction(context: managedObjectContext) transaction.update(response: transactionResponse, context: managedObjectContext) XCTAssertEqual(transaction.transactionID, transactionResponse.id) XCTAssertEqual(transaction.accountID, transactionResponse.accountID) XCTAssertEqual(transaction.amount, NSDecimalNumber(string: transactionResponse.amount.amount)) XCTAssertEqual(transaction.baseType, transactionResponse.baseType) XCTAssertEqual(transaction.budgetCategory, transactionResponse.budgetCategory) XCTAssertEqual(transaction.currency, transactionResponse.amount.currency) XCTAssertEqual(transaction.included, transactionResponse.included) XCTAssertEqual(transaction.memo, transactionResponse.memo) XCTAssertEqual(transaction.merchantID, transactionResponse.merchant.id) XCTAssertEqual(transaction.originalDescription, transactionResponse.description.original) XCTAssertEqual(transaction.postDate, Transaction.transactionDateFormatter.date(from: transactionResponse.postDate!)) XCTAssertEqual(transaction.simpleDescription, transactionResponse.description.simple) XCTAssertEqual(transaction.status, transactionResponse.status) XCTAssertEqual(transaction.transactionDate, Transaction.transactionDateFormatter.date(from: transactionResponse.transactionDate)) XCTAssertEqual(transaction.userDescription, transactionResponse.description.user) XCTAssertEqual(transaction.userTags, transactionResponse.userTags) } } func testUpdatingTransactionIncompleteData() { let database = Database(path: tempFolderPath()) let managedObjectContext = database.newBackgroundContext() managedObjectContext.performAndWait { let transactionResponse = APITransactionResponse.testIncompleteData() let transaction = Transaction(context: managedObjectContext) transaction.update(response: transactionResponse, context: managedObjectContext) XCTAssertEqual(transaction.transactionID, transactionResponse.id) XCTAssertEqual(transaction.accountID, transactionResponse.accountID) XCTAssertEqual(transaction.amount, NSDecimalNumber(string: transactionResponse.amount.amount)) XCTAssertEqual(transaction.baseType, transactionResponse.baseType) XCTAssertEqual(transaction.budgetCategory, transactionResponse.budgetCategory) XCTAssertEqual(transaction.currency, transactionResponse.amount.currency) XCTAssertEqual(transaction.included, transactionResponse.included) XCTAssertEqual(transaction.merchantID, transactionResponse.merchant.id) XCTAssertEqual(transaction.originalDescription, transactionResponse.description.original) XCTAssertEqual(transaction.status, transactionResponse.status) XCTAssertEqual(transaction.transactionDate, Transaction.transactionDateFormatter.date(from: transactionResponse.transactionDate)) XCTAssertNil(transaction.memo) XCTAssertNil(transaction.postDate) XCTAssertNil(transaction.simpleDescription) XCTAssertNil(transaction.userDescription) XCTAssertEqual(transaction.userTags, transactionResponse.userTags) } } func testUpdateTransactionRequest() { let database = Database(path: tempFolderPath()) let managedObjectContext = database.newBackgroundContext() managedObjectContext.performAndWait { let transaction = Transaction(context: managedObjectContext) transaction.populateTestData() let updateRequest = transaction.updateRequest() XCTAssertEqual(transaction.budgetCategory, updateRequest.budgetCategory) XCTAssertEqual(transaction.transactionCategoryID, updateRequest.categoryID) XCTAssertEqual(transaction.included, updateRequest.included) XCTAssertEqual(transaction.memo, updateRequest.memo) XCTAssertEqual(transaction.userDescription, updateRequest.userDescription) } } }
51.125
141
0.721446
0ec866cd52fdda64ed707db2026192dbc1c7f3e1
75
/// Namespace for the Smart Card implementations. public enum SmartCard {}
25
49
0.773333
d97fabb482f99ab91f7c38e9f30dca96400e31ac
2,105
// // TidepoolServiceSetupViewController.swift // TidepoolServiceKitUI // // Created by Darin Krauss on 7/24/19. // Copyright © 2019 Tidepool Project. All rights reserved. // import LoopKitUI import TidepoolKit import TidepoolKitUI import TidepoolServiceKit final class TidepoolServiceSetupViewController: UIViewController { private let service: TidepoolService init(service: TidepoolService) { self.service = service super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationController?.setNavigationBarHidden(true, animated: false) var loginSignupViewController = service.tapi.loginSignupViewController() loginSignupViewController.loginSignupDelegate = self loginSignupViewController.view.frame = CGRect(origin: CGPoint(), size: view.frame.size) addChild(loginSignupViewController) view.addSubview(loginSignupViewController.view) loginSignupViewController.didMove(toParent: self) } } extension TidepoolServiceSetupViewController: TLoginSignupDelegate { func loginSignupDidComplete(completion: @escaping (Error?) -> Void) { service.completeCreate { error in guard error == nil else { completion(error) return } DispatchQueue.main.async { if let serviceNavigationController = self.navigationController as? ServiceNavigationController { serviceNavigationController.notifyServiceCreatedAndOnboarded(self.service) serviceNavigationController.notifyComplete() } completion(nil) } } } func loginSignupCancelled() { DispatchQueue.main.async { if let serviceNavigationController = self.navigationController as? ServiceNavigationController { serviceNavigationController.notifyComplete() } } } }
30.507246
112
0.674109
cc3f359df01811cedd8dce7d649291780fae2e1a
40
import UIKit import SDBaseClassLib
5
21
0.775
f4092cdf8d6c36f897c7ee25f905dd8730c1e173
5,615
// // ZPlayerView.swift // DouyinSwift // // Created by 赵福成 on 2019/5/26. // Copyright © 2019 zhaofucheng. All rights reserved. // import UIKit import AVFoundation import RxSwift import RxCocoa private let STATUS_KEYPATH = "status" private var PlayerItemStatusContent: Void? protocol ZPlayerViewDelegate: AnyObject { func onItemStatusChange(status: AVPlayerItem.Status) func onItemCurrentTimeChange(current: Float64, duration: Float64) } class ZPlayerView: UIView { var viewModel: VideoCellViewModel? private var playerItem: AVPlayerItem! private var player: AVPlayer! var videoGravity: AVLayerVideoGravity { set { playerLayer.videoGravity = newValue } get { return playerLayer.videoGravity } } var assetUrl: URL? { didSet { prepareToPlay() } } var shouldAutorepeat: Bool = true weak var delegate: ZPlayerViewDelegate? private var timeObserverToken: Any? private var playToEndObserverToken: NSObjectProtocol? override class var layerClass: AnyClass { return AVPlayerLayer.self } private var playerLayer: AVPlayerLayer { return layer as! AVPlayerLayer } init(assetUrl: URL) { self.assetUrl = assetUrl super.init(frame: CGRect.zero) backgroundColor = UIColor.black autoresizingMask = [.flexibleHeight, .flexibleWidth] prepareToPlay() } init() { super.init(frame: CGRect.zero) backgroundColor = UIColor.black autoresizingMask = [.flexibleHeight, .flexibleWidth] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func prepareToPlay() { guard let assetUrl = assetUrl else { return } // let asset = AVAsset(url: assetUrl) playerItem = AVPlayerItem(url: assetUrl) if let player = player { ZPlayerManager.shared.remove(owner: self.viewController() ?? self, player: player) } player = AVPlayer(playerItem: playerItem) playerLayer.player = player playerItem.addObserver(self, forKeyPath: STATUS_KEYPATH, options: .new, context: &PlayerItemStatusContent) addTapControlGesture() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { DispatchQueue.main.async { guard let playerItem = self.playerItem, context == &PlayerItemStatusContent else { return } playerItem.removeObserver(self, forKeyPath: STATUS_KEYPATH) self.addPlayerTimeObserver() self.addPlayerItemEndObserver() self.delegate?.onItemStatusChange(status: playerItem.status) } } private func addPlayerTimeObserver() { let interval = CMTimeMakeWithSeconds(0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC)) timeObserverToken = self.player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [weak self] (time) in let currentTime = CMTimeGetSeconds(time) guard let itemDuration = self?.playerItem.duration else { return } let duration = CMTimeGetSeconds(itemDuration) self?.delegate?.onItemCurrentTimeChange(current: currentTime, duration: duration) } } private func addPlayerItemEndObserver() { if let playToEndObserverToken = playToEndObserverToken { NotificationCenter.default.removeObserver(playToEndObserverToken) } playToEndObserverToken = NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.playerItem, queue: OperationQueue.main) { [weak self] _ in self?.player.seek(to: CMTime.zero, completionHandler: { if $0, self?.shouldAutorepeat ?? false { self?.player.play() } }) } } private func addTapControlGesture() { let tap = UITapGestureRecognizer(target: self, action: #selector(tapGestureEvent(gesture:))) self.addGestureRecognizer(tap) } @objc private func tapGestureEvent(gesture: UITapGestureRecognizer) { //当前暂停状态 if player.rate == 0 { play() viewModel?.status.accept(.playing) } else if (player?.rate ?? 0) > 0 { pause() viewModel?.status.accept(.pause) } } public func play() { ZPlayerManager.shared.play(owner: self.viewController() ?? self, player: player) } public func pause() { ZPlayerManager.shared.pasueAll() } deinit { ZPlayerManager.shared.pause(player: player) ZPlayerManager.shared.remove(owner: self.viewController() ?? self) if let playToEndObserverToken = playToEndObserverToken { NotificationCenter.default.removeObserver(playToEndObserverToken, name: .AVPlayerItemDidPlayToEndTime, object: self.playerItem) self.playToEndObserverToken = nil } } } extension Reactive where Base: ZPlayerView { var playUrl: Binder<URL?> { return Binder(base) { playerView, url in playerView.assetUrl = url } } }
33.825301
151
0.618344
e611df3689698a163cdfc32a7f22cad7d5995dfa
1,620
// // Copyright (c) 2017 Ahmed Mohamed <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if !os(watchOS) @testable import Robin @testable import UserNotifications @available(iOS 10.0, macOS 10.14, *) struct SystemNotificationResponseMock: SystemNotificationResponse { var robinNotification: RobinNotification var actionIdentifier: String } @available(iOS 10.0, macOS 10.14, *) struct SystemNotificationTextResponseMock: SystemNotificationTextResponse { var robinNotification: RobinNotification var actionIdentifier: String var userText: String } #endif
40.5
80
0.770988
031e743e39f574bd8827e7f86f279440c23e2b1a
376
// // URL.swift // TySimulator // // Created by ty0x2333 on 2016/11/13. // Copyright © 2016年 ty0x2333. All rights reserved. // import Foundation extension URL { var removeTrailingSlash: URL? { guard absoluteString.hasSuffix("/") else { return self } var urlString = absoluteString urlString.removeLast() return URL(string: urlString) } }
17.904762
52
0.662234
9becabc992376fc14f78663f92812e8c8f9c1c90
9,032
// // 🦠 Corona-Warn-App // import Foundation import XCTest @testable import ENA import OpenCombine class DiaryOverviewViewModelTest: XCTestCase { var subscriptions = [AnyCancellable]() override func setUp() { super.setUp() subscriptions.forEach({ $0.cancel() }) subscriptions.removeAll() } /** riksupdate on homeState must trigger refrashTableview*/ func testGIVEN_ViewModel_WHEN_ChangeRiskLevel_THEN_Refresh() { // GIVEN let diaryStore = makeMockStore() let store = MockTestStore() let homeState = HomeState( store: store, riskProvider: MockRiskProvider(), exposureManagerState: ExposureManagerState(authorized: true, enabled: true, status: .active), enState: .enabled, statisticsProvider: StatisticsProvider( client: CachingHTTPClientMock(), store: store ) ) homeState.updateDetectionMode(.automatic) let viewModel = DiaryOverviewViewModel( diaryStore: diaryStore, store: store, eventStore: MockEventStore(), homeState: homeState ) let expectationRefreshTableView = expectation(description: "Refresh Tableview") /*** why 3 times: 1 - initial value days + 1 - initial value homeState + 1 update HomeState */ expectationRefreshTableView.expectedFulfillmentCount = 3 viewModel.$days .sink { _ in expectationRefreshTableView.fulfill() } .store(in: &subscriptions) viewModel.homeState?.$riskState .sink { _ in expectationRefreshTableView.fulfill() } .store(in: &subscriptions) // WHEN homeState.riskState = .risk(.mocked) // THEN wait(for: [expectationRefreshTableView], timeout: .medium) } func testDaysAreUpdatedWhenStoreChanges() throws { let diaryStore = makeMockStore() let store = MockTestStore() let viewModel = DiaryOverviewViewModel( diaryStore: diaryStore, store: store, eventStore: MockEventStore() ) let daysPublisherExpectation = expectation(description: "Days publisher called") /*** why 2 times: 1 - initial value days + 1 updata Diary days */ daysPublisherExpectation.expectedFulfillmentCount = 2 viewModel.$days .sink { _ in daysPublisherExpectation.fulfill() } .store(in: &subscriptions) diaryStore.addContactPerson(name: "Martin Augst") waitForExpectations(timeout: .medium) } func testNumberOfSections() throws { let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: MockTestStore(), eventStore: MockEventStore() ) XCTAssertEqual(viewModel.numberOfSections, 2) } func testNumberOfRows() throws { let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: MockTestStore(), eventStore: MockEventStore() ) XCTAssertEqual(viewModel.numberOfRows(in: 0), 1) XCTAssertEqual(viewModel.numberOfRows(in: 1), 15) } func testGIVEN_DiaryOverviewViewModel_WHEN_noneHistoryExposureIsInStore_THEN_NoneHistoryExposureIsReturned() { // GIVEN let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: MockTestStore(), eventStore: MockEventStore() ) // WHEN let diaryOverviewDayCellModel = viewModel.cellModel(for: IndexPath(row: 4, section: 0)) // THEN XCTAssertEqual(diaryOverviewDayCellModel.historyExposure, .none) } func testGIVEN_DiaryOverviewViewModel_WHEN_noneCheckinsWithRiskInStore_THEN_EmptyCheckinWithRiskIsReturned() { // GIVEN let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: MockTestStore(), eventStore: MockEventStore() ) // WHEN let diaryOverviewDayCellModel = viewModel.cellModel(for: IndexPath(row: 4, section: 0)) // THEN XCTAssertTrue(diaryOverviewDayCellModel.checkinsWithRisk.isEmpty) } func testGIVEN_DiaryOverviewViewModel_WHEN_lowHistoryExposureIsInStore_THEN_LowHistoryExposureIsReturned() throws { // GIVEN let dateFormatter = ISO8601DateFormatter.contactDiaryUTCFormatter let todayString = dateFormatter.string(from: Date()) let today = try XCTUnwrap(dateFormatter.date(from: todayString)) let wrongFormattedTodayMinus5Days = try XCTUnwrap(Calendar.current.date(byAdding: .day, value: -5, to: today)) let todayMinus5DaysString = dateFormatter.string(from: wrongFormattedTodayMinus5Days) let todayMinus5Days = try XCTUnwrap(dateFormatter.date(from: todayMinus5DaysString)) let store = MockTestStore() store.enfRiskCalculationResult = ENFRiskCalculationResult( riskLevel: .low, minimumDistinctEncountersWithLowRisk: 1, minimumDistinctEncountersWithHighRisk: 1, mostRecentDateWithLowRisk: nil, mostRecentDateWithHighRisk: nil, numberOfDaysWithLowRisk: 1, numberOfDaysWithHighRisk: 1, calculationDate: today, riskLevelPerDate: [todayMinus5Days: .low], minimumDistinctEncountersWithHighRiskPerDate: [:] ) let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: store, eventStore: MockEventStore() ) // WHEN let diaryOverviewDayCellModel = viewModel.cellModel(for: IndexPath(row: 5, section: 0)) // THEN XCTAssertEqual(diaryOverviewDayCellModel.historyExposure, .encounter(.low)) } func testGIVEN_DiaryOverviewViewModel_WHEN_highHistoryExposureIsInStore_THEN_HighHistoryExposureIsReturned() throws { // GIVEN let dateFormatter = ISO8601DateFormatter.contactDiaryUTCFormatter let todayString = dateFormatter.string(from: Date()) let today = try XCTUnwrap(dateFormatter.date(from: todayString)) let wrongFormattedTodayMinus5Days = try XCTUnwrap(Calendar.current.date(byAdding: .day, value: -7, to: today)) let todayMinus7DaysString = dateFormatter.string(from: wrongFormattedTodayMinus5Days) let todayMinus7Days = try XCTUnwrap(dateFormatter.date(from: todayMinus7DaysString)) let store = MockTestStore() store.enfRiskCalculationResult = ENFRiskCalculationResult( riskLevel: .low, minimumDistinctEncountersWithLowRisk: 1, minimumDistinctEncountersWithHighRisk: 1, mostRecentDateWithLowRisk: nil, mostRecentDateWithHighRisk: nil, numberOfDaysWithLowRisk: 1, numberOfDaysWithHighRisk: 1, calculationDate: today, riskLevelPerDate: [todayMinus7Days: .high], minimumDistinctEncountersWithHighRiskPerDate: [Date(): 1] ) let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: store, eventStore: MockEventStore() ) // WHEN let diaryOverviewDayCellModel = viewModel.cellModel(for: IndexPath(row: 7, section: 0)) let diaryOverviewDayCellModelNone = viewModel.cellModel(for: IndexPath(row: 5, section: 0)) // THEN XCTAssertEqual(diaryOverviewDayCellModel.historyExposure, .encounter(.high)) XCTAssertEqual(diaryOverviewDayCellModelNone.historyExposure, .none) } func testGIVEN_DiaryOverviewViewModel_WHEN_someCheckinsWithRiskAreInStore_THEN_CheckinsWithRiskAreReturned() throws { // GIVEN let dateFormatter = ISO8601DateFormatter.contactDiaryUTCFormatter let todayString = dateFormatter.string(from: Date()) let today = try XCTUnwrap(dateFormatter.date(from: todayString)) let wrongFormattedTodayMinus5Days = try XCTUnwrap(Calendar.current.date(byAdding: .day, value: -5, to: today)) let todayMinus5DaysString = dateFormatter.string(from: wrongFormattedTodayMinus5Days) let todayMinus5Days = try XCTUnwrap(dateFormatter.date(from: todayMinus5DaysString)) let eventStore = MockEventStore() guard case .success(let checkinId1) = eventStore.createCheckin(Checkin.mock()) else { XCTFail("Success result expected.") return } guard case .success(let checkinId2) = eventStore.createCheckin(Checkin.mock()) else { XCTFail("Success result expected.") return } let store = MockTestStore() let checkinOne = CheckinIdWithRisk(checkinId: checkinId1, riskLevel: .low) let checkinTwo = CheckinIdWithRisk(checkinId: checkinId2, riskLevel: .high) let checkinRiskCalculation = CheckinRiskCalculationResult( calculationDate: today, checkinIdsWithRiskPerDate: [todayMinus5Days: [checkinOne, checkinTwo]], riskLevelPerDate: [:] ) store.checkinRiskCalculationResult = checkinRiskCalculation let viewModel = DiaryOverviewViewModel( diaryStore: makeMockStore(), store: store, eventStore: eventStore ) // WHEN let diaryOverviewDayCellModel = viewModel.cellModel(for: IndexPath(row: 5, section: 0)) // THEN XCTAssertEqual(diaryOverviewDayCellModel.checkinsWithRisk.count, 2) } // MARK: - Private Helpers func makeMockStore() -> MockDiaryStore { let store = MockDiaryStore() store.addContactPerson(name: "Nick Gündling") store.addContactPerson(name: "Marcus Scherer") store.addContactPerson(name: "Artur Friesen") store.addContactPerson(name: "Pascal Brause") store.addContactPerson(name: "Kai Teuber") store.addContactPerson(name: "Karsten Gahn") store.addContactPerson(name: "Carsten Knoblich") store.addContactPerson(name: "Andreas Vogel") store.addContactPerson(name: "Puneet Mahali") store.addContactPerson(name: "Omar Ahmed") store.addLocation(name: "Supermarket") store.addLocation(name: "Bakery") return store } }
31.470383
118
0.762179
e2b465b5bc0d2371c2215a07827b3ab9be99ed4f
12,166
// // LotteryViewController.swift // Bank // // Created by yang on 16/6/28. // Copyright © 2016年 ChangHongCloudTechService. All rights reserved. // // swiftlint:disable force_unwrapping import UIKit import URLNavigator import PromiseKit import MBProgressHUD class LotteryViewController: BaseViewController { @IBOutlet fileprivate var lotteryView: UIView! @IBOutlet weak fileprivate var scrollView: UIScrollView! @IBOutlet weak fileprivate var winInfoView: UIView! @IBOutlet weak fileprivate var prizeView: UIView! @IBOutlet weak fileprivate var stackView: UIStackView! lazy fileprivate var winInfoPageViewController: CyclePageViewController = { return CyclePageViewController(frame: self.winInfoView.bounds) }() lazy fileprivate var prizeGoodsPageViewController: CyclePageViewController = { return CyclePageViewController(frame: self.prizeView.bounds) }() fileprivate var winInfoList: [WinInfo] = [] fileprivate var poolList: [Prize] = [] fileprivate var thePoolList: [[Prize]] = [] fileprivate var selectedPrizeID: String? fileprivate var getPrize: Prize? fileprivate var selectedImageView: UIImageView? override func viewDidLoad() { super.viewDidLoad() tabBarController?.tabBar.isHidden = true requestLotteryHomeData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? PrizeDetailViewController { vc.giftID = self.selectedPrizeID } } fileprivate func setScrollView() { scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: lotteryView.frame.height) lotteryView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: lotteryView.frame.height) scrollView.addSubview(lotteryView) title = R.string.localizable.controller_title_lottery() let shareBarButtonItem = UIBarButtonItem(title: R.string.localizable.barButtonItem_title_share(), style: .plain, target: self, action: #selector(shareAction(_:))) navigationItem.rightBarButtonItem = shareBarButtonItem } //设置活动未开始的信息 fileprivate func setNoneEventView() { let noneEventView = UIImageView(image: R.image.icon_noneEvent()) view.addSubview(noneEventView) title = R.string.localizable.controller_title_not_star() noneEventView.snp.makeConstraints { (make) in make.top.equalTo(view).offset(100) make.centerX.equalTo(view.snp.centerX) } } //设置奖品信息 fileprivate func setPrizeView() { setList() var viewControllers: [UIViewController] = [] var addViews: [UIView] = [] for prizes in thePoolList { let viewController = UIViewController() viewControllers.append(viewController) guard let addView = R.nib.prizePoolView.firstView(owner: nil) else { return } addView.prizeDetailHandleBlock = { (prizeID, segueID) in self.selectedPrizeID = prizeID self.performSegue(withIdentifier: segueID, sender: nil) } addView.configInfo(prizes) addViews.append(addView) } prizeGoodsPageViewController.postion = .vertical prizeGoodsPageViewController.timeInterval = 4 prizeGoodsPageViewController.view.backgroundColor = UIColor.clear prizeGoodsPageViewController.hiddenPageControl = true prizeGoodsPageViewController.configDataSource(viewControllers: viewControllers, addViews: addViews) prizeView.addSubview(prizeGoodsPageViewController.view) prizeGoodsPageViewController.view.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(0) make.right.equalToSuperview().offset(0) make.top.equalToSuperview().offset(0) make.bottom.equalToSuperview().offset(0) } self.addChildViewController(prizeGoodsPageViewController) } //设置获奖信息 fileprivate func setWinInfoView() { var viewControllers: [UIViewController] = [] var addViews: [UIView] = [] for winInfo in winInfoList { let viewController = UIViewController() viewControllers.append(viewController) guard let addView = R.nib.winInfoView.firstView(owner: nil) else { return } addView.configInfo(winInfo) addViews.append(addView) } winInfoPageViewController.postion = .vertical winInfoPageViewController.timeInterval = 3 winInfoPageViewController.view.isUserInteractionEnabled = false winInfoPageViewController.hiddenPageControl = true winInfoPageViewController.configDataSource(viewControllers: viewControllers, addViews: addViews) winInfoView.addSubview(winInfoPageViewController.view) winInfoPageViewController.view.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(0) make.right.equalToSuperview().offset(0) make.top.equalToSuperview().offset(0) make.bottom.equalToSuperview().offset(0) } self.addChildViewController(winInfoPageViewController) } fileprivate func setList() { let group = poolList.count%3 == 0 ? poolList.count/3 : poolList.count/3 + 1 for i in 0..<group { var prizeList: [Prize] = [] var j = i * 3 while j < 3*(i+1) && j < poolList.count { prizeList.append(poolList[j]) j += 1 } thePoolList.append(prizeList) } // for (index, prize) in poolList.enumerate() { // prizeList.append(prize) // if index % 3 == 2 { // thePoolList.append(prizeList) // prizeList.removeAll() // } // // } } //砸金蛋的提示框 fileprivate func showAlertView(_ isShareGetTime: Bool = false, isStart: Bool = true) { guard let alertView = R.nib.lotteryResultView.firstView(owner: nil) else { return } alertView.configUI(isStart, isShareGetTime: isShareGetTime) // alertView.configUsedOut() if let prize = self.getPrize { alertView.configInfo(prize) } alertView.cancelHandleBlock = { alertView.removeFromSuperview() } alertView.shareHandleBlock = { [weak self] in alertView.removeFromSuperview() self?.shareAction(nil) } alertView.backHandleBlock = { [weak self] in _ = self?.navigationController?.popViewController(animated: true) } alertView.frame = UIScreen.main.bounds view.addSubview(alertView) } //弹框 fileprivate func showAlertWithoutAction(_ title: String = "", message: String?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: R.string.localizable.alertTitle_okay(), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } //砸金蛋 @IBAction func eggTapAction(_ sender: UITapGestureRecognizer) { view.isUserInteractionEnabled = false guard let imageView = sender.view as? UIImageView else { return } selectedImageView = imageView requestLotteryData() } /// 开始动画 fileprivate func startAnimation() { selectedImageView?.animationImages = [R.image.animation_01()!, R.image.animation_02()!, R.image.animation_03()!, R.image.animation_04()!] selectedImageView?.animationRepeatCount = 1 selectedImageView?.animationDuration = 0.5 * 4 selectedImageView?.startAnimating() self.perform(#selector(animationDone), with: nil, afterDelay: 2) } /// 动画结束 @objc func animationDone() { view.isUserInteractionEnabled = true selectedImageView?.image = R.image.animation_04() self.showAlertView() } //分享 func shareAction(_ sender: UIBarButtonItem?) { guard let vc = R.storyboard.main.shareViewController() else {return} vc.sharePage = .lottery vc.completeHandle = { [weak self] result in self?.dim(.out) vc.dismiss(animated: true, completion: nil) if result { self?.requestShareData() } } dim(.in) present(vc, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: Request extension LotteryViewController { /** 请求首页数据 */ func requestLotteryHomeData() { MBProgressHUD.loading(view: self.view) let req: Promise<LotteryHomeData> = handleRequest(Router.endpoint(GiftPath.index, param: nil)) req.then { value -> Void in if value.isValid { self.setScrollView() if let winList = value.data?.winList { self.winInfoList = winList self.setWinInfoView() } if let pools = value.data?.poolList { self.poolList = pools self.setPrizeView() } } }.always { MBProgressHUD.hide(for: self.view, animated: true) }.catch { (error) in if let err = error as? AppError { // 没有正在进行的活动 if err.errorCode.errorCode() == RequestErrorCode.noneLottery.errorCode() { self.setNoneEventView() // self.getPrize = nil // self.showAlertView(isStart: false) } else { MBProgressHUD.errorMessage(view: self.view, message: err.toError().localizedDescription) } } } } /** 砸金蛋 */ func requestLotteryData() { MBProgressHUD.loading(view: self.view) let req: Promise<PrizeDetailData> = handleRequest(Router.endpoint(GiftPath.lottery, param: nil)) req.then { value -> Void in if value.isValid { self.getPrize = value.data self.startAnimation() } }.always { self.view.isUserInteractionEnabled = true MBProgressHUD.hide(for: self.view, animated: true) }.catch { (error) in if let err = error as? AppError { if err.errorCode.errorCode() == RequestErrorCode.countsRunOut.errorCode() { // 抽奖次数已用完 self.getPrize = nil self.showAlertView(false) } else if err.errorCode.errorCode() == RequestErrorCode.runOutShare.errorCode() { //抽奖次数已用完,但是分享可以再抽一次 self.getPrize = nil self.showAlertView(true) } else { MBProgressHUD.errorMessage(view: self.view, message: err.toError().localizedDescription) } } } } /** 分享 */ fileprivate func requestShareData() { MBProgressHUD.loading(view: self.view) let req: Promise<NullDataResponse> = handleRequest(Router.endpoint(GiftPath.share, param: nil)) req.then { value -> Void in self.showAlertWithoutAction(message: R.string.localizable.alertTitle_share_success()) }.always { MBProgressHUD.hide(for: self.view, animated: true) }.catch { (error) in if let err = error as? AppError { MBProgressHUD.errorMessage(view: self.view, message: err.toError().localizedDescription) } } } }
37.900312
170
0.602006
21f74b16a0ced94ebb667064317243b785daa71f
421
// // PumpAckMessageBody.swift // RileyLink // // Created by Pete Schwamb on 3/14/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class PumpAckMessageBody: MessageBody { public static let length = 1 let rxData: Data public required init?(rxData: Data) { self.rxData = rxData } public var txData: Data { return rxData } }
17.541667
55
0.631829
28e313e5b4e68ac075799f71fc7df7283516a796
3,425
// // MLCardFormAddCardService.swift // MLCardForm // // Created by Esteban Adrian Boffa on 15/11/2019. // import Foundation import MLCardDrawer final class MLCardFormAddCardService: MLCardFormAddCardServiceBase { func addCardToken(tokenizationData: MLCardFormAddCardService.TokenizationBody, completion: ((Result<MLCardFormTokenizationCardData, Error>) -> ())? = nil) { if publicKey == nil && privateKey == nil { completion?(.failure(MLCardFormAddCardServiceError.missingKeys)) return } if let internetConnection = delegate?.hasInternetConnection(), !internetConnection { completion?(.failure(NetworkLayerError.noInternetConnection)) return } let queryParams = MLCardFormAddCardService.KeyParam(publicKey: publicKey, accessToken: privateKey) let headers = MLCardFormAddCardService.Headers(contentType: "application/json") NetworkLayer.request(router: MLCardFormApiRouter.postCardTokenData(queryParams, headers, buildTokenizationBody(tokenizationData))) { (result: Result<MLCardFormTokenizationCardData, Error>) in completion?(result) } } func saveCard(tokenId: String, addCardData: MLCardFormAddCardService.AddCardBody, completion: ((Result<MLCardFormAddCardData, Error>) -> ())? = nil) { guard let privateKey = privateKey else { completion?(.failure(MLCardFormAddCardServiceError.missingPrivateKey)) return } let accessTokenParam = MLCardFormAddCardService.AccessTokenParam(accessToken: privateKey) let headers = MLCardFormAddCardService.Headers(contentType: "application/json") NetworkLayer.request(router: MLCardFormApiRouter.postCardData(accessTokenParam, headers, buildAddCardBody(tokenId, addCardData: addCardData))) { (result: Result<MLCardFormAddCardData, Error>) in completion?(result) } } } // MARK: HTTP Bodies & Headers extension MLCardFormAddCardService { enum HeadersKeys { case contentType var getKey: String { switch self { case .contentType: return "content-type" } } } struct Headers { let contentType: String } struct TokenizationBody { let cardNumber: String let securityCode: String let expirationMonth: Int let expirationYear: Int let cardholder: MLCardFormCardHolder let device: MLCardFormDevice } struct AddCardBody { let paymentMethod: MLCardFormAddCardPaymentMethod let issuer: MLCardFormAddCardIssuer } } // MARK: Privates private extension MLCardFormAddCardService { func buildTokenizationBody(_ tokenizationData: MLCardFormAddCardService.TokenizationBody) -> MLCardFormTokenizationBody { return MLCardFormTokenizationBody(cardNumber: tokenizationData.cardNumber, securityCode: tokenizationData.securityCode, expirationMonth: tokenizationData.expirationMonth, expirationYear: tokenizationData.expirationYear, cardholder: tokenizationData.cardholder, device: tokenizationData.device) } func buildAddCardBody(_ tokenId: String, addCardData: MLCardFormAddCardService.AddCardBody) -> MLCardFormAddCardBody { return MLCardFormAddCardBody(cardTokenId: tokenId, paymentMethod: addCardData.paymentMethod, issuer: addCardData.issuer) } }
40.294118
301
0.716204
906ced96aeb22106112c4aa2e986475c70d5db65
1,706
// // Nano33BLESenseColorIlluminanceSensor.swift // ScienceJournal // // Created by Sebastian Romero on 1/09/2020. // Copyright © 2020 Arduino. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreBluetooth struct Nano33BLESenseColorIlluminanceSensor: BLEArduinoSensor { static var uuid: CBUUID { CBUUID(string: "555a0002-0018-467a-9538-01f0652c74e8") } static var identifier: String { "\(uuid.uuidString)_1" } var name: String { String.ambientLight } var iconName: String { "ic_sensor_light" } var animatingIconName: String { "mkrsci_light" } var unitDescription: String? { String.ambientLightUnits } var textDescription: String { String.sensorDescShortMkrsciColorIlluminance } var learnMoreInformation: Sensor.LearnMore { Sensor.LearnMore(firstParagraph: "", secondParagraph: "", imageName: "") } var config: BLEArduinoSensorConfig? func point(for data: Data) -> Double { guard data.count == 16 else { return 0 } let illuminance = data.withUnsafeBytes { $0.load(fromByteOffset: 3 * 4, as: Int16.self) } return (Double(illuminance) / 4097.0) * 2.8 * 1000.0 } }
32.807692
93
0.710434
c193c8aa401d776368482f1bee89be37decd5070
971
// // ViewController.swift // LYGradientView // // Created by ButtFly on 12/25/2019. // Copyright (c) 2019 ButtFly. All rights reserved. // import UIKit import LYGradientView class ViewController: UIViewController { let gView = LYGradientView(frame: .zero) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.addSubview(gView) gView.frame = view.bounds gView.colors = [.green, .red] gView.locations = [0, 1] gView.startPoint = CGPoint(x: 0.5, y: 0.2) gView.endPoint = CGPoint(x: 0.5, y: 0.8) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() gView.frame = view.bounds } }
22.581395
80
0.61792
f7bdb264893bd958d88700b659733208e862a777
446
//Challenge 2: Step-by-step Diagrams //Given the following queue: // [S, W, I, F, T] //Provide step-by-step diagrams showing how the following series of commands affects the queue: //enqueue("R") //enqueue("O") //dequeue() //enqueue("C") //dequeue() //dequeue() //enqueue("K") //Assume that the array and ring buffer have an initial size of 5. //Array //배열(Array)이 가득찼을때 새 요소를 추가하려 하면, 기존의 요소가 복사된 두 배 용량의 새 배열을 생성한다. //p.118 부터 참고
15.37931
95
0.661435
e2abaa75b5ef6a17bd5cc15db69e93759fc153b1
491
// // Alert+TKAlert.swift // TripKit // // Created by Adrian Schönig on 12.06.18. // Copyright © 2018 SkedGo Pty Ltd. All rights reserved. // import Foundation import TripKit extension Alert: TKAlert { public var infoURL: URL? { url.flatMap(URL.init) } public var icon: TKImage? { TKInfoIcon.image(for: infoIconType, usage: .normal) } public var iconURL: URL? { imageURL } public var lastUpdated: Date? { nil } public func isCritical() -> Bool { alertSeverity == .alert } }
24.55
83
0.690428
39384c5a311fbc08975ade10942f41647ad33298
45
struct DomainModelOne { let name: String }
11.25
23
0.733333
8f8018b99d53c275412a499c16f56108567acbbb
8,221
// // MainTopCell.swift // Weathy // // Created by inae Lee on 2021/01/04. // import UIKit class MainTopCVC: UICollectionViewCell { //MARK: - Custom Variables var closetTop: [String] = ["기모 맨투맨", "히트텍", "폴로니트", "메종 마르지엘라"] var closetOuter: [String] = ["청바지", "청바지","청바지","청바지","청바지"] var closetBottom: [String] = ["롱패딩","루리스"] var closetEtc: [String] = ["목도리","장갑","귀마개","수면양말", "어쩌라","마마무"] var defaultLocationFlag: Bool = true { didSet { // 값이 바뀔 때 if (defaultLocationFlag) { // 위치정보로 } else { // } } } //MARK: - IBOutlets @IBOutlet weak var todayWeathyNicknameTextLabel: SpacedLabel! @IBOutlet weak var todayWeathyView: UIView! @IBOutlet weak var currTempLabel: SpacedLabel! @IBOutlet weak var maxTempLabel: SpacedLabel! @IBOutlet weak var minTempLabel: SpacedLabel! @IBOutlet weak var climateLabel: SpacedLabel! @IBOutlet weak var locationLabel: SpacedLabel! @IBOutlet weak var weathyDateLabel: SpacedLabel! @IBOutlet weak var weathyClimateImage: UIImageView! @IBOutlet weak var weathyClimateLabel: SpacedLabel! @IBOutlet weak var weathyMaxTempLabel: SpacedLabel! @IBOutlet weak var weathyMinTempLabel: SpacedLabel! @IBOutlet weak var weathyStampImage: UIImageView! @IBOutlet weak var weathyStampLabel: SpacedLabel! @IBOutlet weak var closetTopLabel: SpacedLabel! @IBOutlet weak var closetBottomLabel: SpacedLabel! @IBOutlet weak var closetOuterLabel: SpacedLabel! @IBOutlet weak var closetEtcLabel: SpacedLabel! @IBOutlet weak var helpButton: UIButton! @IBOutlet weak var emptyImage: UIImageView! @IBOutlet weak var downImage: UIImageView! @IBOutlet weak var hourlyClimateImage: UIImageView! @IBOutlet weak var gpsButton: UIButton! //MARK: - Custom Methods func changeWeatherViewData(data: LocationWeatherData!) { locationLabel.text = "\(data.overviewWeather.region.name)" currTempLabel.text = "\(data.overviewWeather.hourlyWeather.temperature!)°" maxTempLabel.text = "\(data.overviewWeather.dailyWeather.temperature.maxTemp)°" minTempLabel.text = "\(data.overviewWeather.dailyWeather.temperature.minTemp)°" hourlyClimateImage.image = UIImage(named: ClimateImage.getClimateMainIllust(data.overviewWeather.hourlyWeather.climate.iconId)) if let desc = data.overviewWeather.hourlyWeather.climate.description { climateLabel.text = "\(desc)" } } func changeWeatherViewBySearchData(data: OverviewWeather) { locationLabel.text = "\(data.region.name)" currTempLabel.text = "\(data.hourlyWeather.temperature)°" maxTempLabel.text = "\(data.dailyWeather.temperature.maxTemp)°" minTempLabel.text = "\(data.dailyWeather.temperature.minTemp)°" hourlyClimateImage.image = UIImage(named: ClimateImage.getClimateMainIllust(data.hourlyWeather.climate.iconId)) climateLabel.text = "\(data.hourlyWeather.climate.description)" } func changeWeathyViewData(data: RecommendedWeathyData) { // print(data.weathy) if (data.weathy == nil) { showEmptyView() return } if let nickname = UserDefaults.standard.string(forKey: "nickname") { todayWeathyNicknameTextLabel.text = "\(nickname)님이 기억하는" } // closetTopLabel.text = insertSeparatorInArray(data.weathy.closet.top.clothes) // closetOuterLabel.text = insertSeparatorInArray(data.weathy.closet.outer.clothes) // closetBottomLabel.text = insertSeparatorInArray(data.weathy.closet.bottom.clothes) // closetEtcLabel.text = insertSeparatorInArray(data.weathy.closet.etc.clothes) if let year: Int = data.weathy.dailyWeather.date.year { let month: Int = data.weathy.dailyWeather.date.month let day: Int = data.weathy.dailyWeather.date.day weathyDateLabel.text = "\(year)년 \(month)월 \(day)일" } weathyClimateImage.image = UIImage(named: ClimateImage.getClimateIconName(data.weathy.hourlyWeather.climate.iconId)) if let climateDesc = data.weathy.hourlyWeather.climate.description { weathyClimateLabel.text = "\(climateDesc)" } weathyMaxTempLabel.text = "\(data.weathy.dailyWeather.temperature.maxTemp)°" weathyMinTempLabel.text = "\(data.weathy.dailyWeather.temperature.minTemp)°" weathyStampImage.image = UIImage(named: Emoji.getEmojiImageAsset(stampId: data.weathy.stampId)) weathyStampLabel.text = Emoji.getEmojiText(stampId: data.weathy.stampId) weathyStampLabel.textColor = Emoji.getEmojiTextColor(stampId: data.weathy.stampId) } func blankDownImage() { UIView.animate(withDuration: 1.0, delay: 0, options: [.autoreverse, .repeat], animations: { self.downImage.alpha = 0 self.downImage.alpha = 1 }, completion: nil) } func showEmptyView() { emptyImage.image = UIImage(named: "main_img_empty") emptyImage.alpha = 1 } func setCell() { blankDownImage() closetTopLabel.font = UIFont.SDGothicRegular13 closetTopLabel.textColor = UIColor.black closetTopLabel.characterSpacing = -0.65 closetOuterLabel.font = UIFont.SDGothicRegular13 closetOuterLabel.textColor = UIColor.black closetOuterLabel.characterSpacing = -0.65 closetBottomLabel.font = UIFont.SDGothicRegular13 closetBottomLabel.textColor = UIColor.black closetBottomLabel.characterSpacing = -0.65 closetEtcLabel.font = UIFont.SDGothicRegular13 closetEtcLabel.textColor = UIColor.black closetEtcLabel.characterSpacing = -0.65 todayWeathyNicknameTextLabel.font = UIFont.SDGothicRegular16 todayWeathyNicknameTextLabel.characterSpacing = -0.8 todayWeathyView.makeRounded(cornerRadius: 35) todayWeathyView.dropShadow(color: UIColor(red: 44/255, green: 82/255, blue: 128/255, alpha: 1), offSet: CGSize(width: 0, height: 10), opacity: 0.21, radius: 50) locationLabel.font = UIFont.SDGothicSemiBold20 locationLabel.textColor = UIColor.mainGrey locationLabel.characterSpacing = -1.0 currTempLabel.font = UIFont.RobotoLight50 currTempLabel.textColor = UIColor.subGrey1 currTempLabel.characterSpacing = -2.5 maxTempLabel.font = UIFont.RobotoLight23 maxTempLabel.textColor = UIColor.redTemp maxTempLabel.characterSpacing = -1.15 minTempLabel.font = UIFont.RobotoLight23 minTempLabel.textColor = UIColor.blueTemp minTempLabel.characterSpacing = -1.15 climateLabel.font = UIFont.SDGothicRegular16 climateLabel.textColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.58) climateLabel.characterSpacing = -0.8 weathyDateLabel.font = UIFont.SDGothicRegular13 weathyDateLabel.textColor = UIColor.subGrey6 weathyDateLabel.characterSpacing = -0.65 weathyClimateLabel.font = UIFont.SDGothicMedium15 weathyClimateLabel.textColor = UIColor.subGrey1 weathyClimateLabel.characterSpacing = -0.75 weathyMaxTempLabel.textColor = UIColor.redTemp weathyMaxTempLabel.font = UIFont.RobotoLight30 weathyMaxTempLabel.characterSpacing = -1.5 weathyMinTempLabel.textColor = UIColor.blueTemp weathyMinTempLabel.font = UIFont.RobotoLight30 weathyMinTempLabel.characterSpacing = -1.5 weathyStampLabel.font = UIFont.SDGothicSemiBold23 weathyStampLabel.textColor = UIColor.imojiColdText weathyStampLabel.characterSpacing = -1.15 gpsButton.contentMode = .scaleAspectFit } //MARK: - IBActions @IBAction func touchUpGpsButton(_ sender: Any) { print("gps") if (self.defaultLocationFlag) { print("default true") } else { print("default false ") } } }
40.102439
168
0.671208
ccbda4c5f81d712040aa0205f002b2122e213ae0
1,523
// // ViewAnimation.swift // sampleAnmation // // Created by 永田大祐 on 2017/02/25. // Copyright © 2017年 永田大祐. All rights reserved. // import UIKit class ViewAnimation: UIView { static let viewAnimation = ViewAnimation() override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func animateImage(target: UIView)-> UIView { target.frame = CGRect(x:UIScreen.main.bounds.size.width/2-30,y:-UIScreen.main.bounds.size.height/9,width:60,height:60) desginModel(target: target) return target } func animateSet(target: UIView, point: CGPoint)-> UIView { target.frame = CGRect(x:point.x,y:point.y,width:60,height:60) desginModel(target: target) return target } func desginModel(target: UIView) { target.layer.cornerRadius = 20 target.layer.masksToBounds = true let angle: CGFloat = CGFloat(Double.pi) UIView.animate( withDuration: 5.0, animations: {() -> Void in target.transform = CGAffineTransform(rotationAngle: angle) target.transform = CGAffineTransform.identity target.layer.cornerRadius = -target.frame.width * 2 }, completion: { (Bool) -> Void in _ = self.animateImage(target: target) }) } }
28.203704
126
0.590282
1afb7187d888bd918679567bd0b675c6112dc80e
445
import Foundation import xcodeproj import XCTest final class PBXResourcesBuildPhaseSpec: XCTestCase { func test_isa_returnsTheCorrectValue() { XCTAssertEqual(PBXResourcesBuildPhase.isa, "PBXResourcesBuildPhase") } private func testDictionary() -> [String: Any] { return [ "files": ["file1"], "buildActionMask": "333", "runOnlyForDeploymentPostprocessing": "3", ] } }
24.722222
76
0.647191
03a0e4055e395af044610e2303abea9b23886d34
1,148
// // BlueProxUITests.swift // BlueProxUITests // // Copyright © 2020 Massachusetts Institute of Technology. All rights reserved. // import XCTest class BlueProxUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.764706
182
0.695993
4bffac51e656377ad93a5a1dea6ec4ae0d07fadc
971
// // FritzStyleModelFilter.swift // FritzVision // // Created by Steven Yeung on 10/29/19. // Copyright © 2019 Fritz Labs Incorporated. All rights reserved. // import Foundation /// Stylizes the input image. @available(iOS 11.0, *) public class FritzVisionStylizeImageCompoundFilter: FritzVisionImageFilter { public let compositionMode = FilterCompositionMode.compoundWithPreviousOutput public let model: FritzVisionStylePredictor public let options: FritzVisionStyleModelOptions public init( model: FritzVisionStylePredictor, options: FritzVisionStyleModelOptions = .init() ) { self.model = model self.options = options } public func process(_ image: FritzVisionImage) -> FritzVisionFilterResult { do { let styleBuffer = try self.model.predict(image, options: options) return .success(FritzVisionImage(ciImage: CIImage(cvPixelBuffer: styleBuffer))) } catch let error { return .failure(error) } } }
26.972222
85
0.738414
dbe85b8b190640311a9e326eca29c3f030e87cf7
1,395
import Foundation import UIKit import SoraFoundation extension UIAlertController { static func phishingWarningAlert(onConfirm: @escaping () -> Void, onCancel: @escaping () -> Void, locale: Locale, displayName paramValue: String) -> UIAlertController { let title = R.string.localizable .walletSendPhishingWarningTitle(preferredLanguages: locale.rLanguages) let message = R.string.localizable .walletSendPhishingWarningText(paramValue, preferredLanguages: locale.rLanguages) let cancelTitle = R.string.localizable .commonCancel(preferredLanguages: locale.rLanguages) let proceedTitle = R.string.localizable .commonContinue(preferredLanguages: locale.rLanguages) let proceedAction = UIAlertAction(title: proceedTitle, style: .default) { _ in onConfirm() } let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel) { _ in onCancel() } let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(proceedAction) alertController.addAction(cancelAction) return alertController } }
42.272727
100
0.615054
d61d5fa2906c8add0fc3d0824db950a580f89560
322
// // Weather.swift // Weather // // Created by Aleksey Bardin on 31.10.2020. // import Foundation struct WeatherModel: Codable { var actualWeather: ActualWeather var coordinate: Coordinate enum CodingKeys: String, CodingKey { case actualWeather = "fact" case coordinate = "info" } }
16.947368
44
0.658385
eb12762a923add48329e35c02c4969ed3f481945
382
// // String+Reverse.swift // BitcoinSwift // // Created by Kevin Greene on 12/25/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation extension String { public var reversedString: String { var reversedString = String() for char in Array(self.characters.reverse()) { reversedString.append(char) } return reversedString } }
18.190476
54
0.680628