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
|
---|---|---|---|---|---|
db15edd623af2290babdb7b19a1d5f468a6ed6b8 | 1,617 | //
// EZFactory.swift
// EZProgressHUD
//
// Created by shndrs on 7/8/19.
// Copyright © 2019 shndrs. All rights reserved.
//
import Foundation
public struct EZProgressHUD {
private init() {}
///A Factory method That returns a EZProgressProtocol to access show() and dismiss() functions
@discardableResult
public static func setProgress(with options:EZProgressOptions) -> EZProgress {
switch options.animationOption {
case .heartBeat:
return HeartBeat(options: options)
case .lineLayer:
return LineLayer(options: options)
case .lordOfTheRings:
return LordOfTheRings(options: options)
case .antColony:
return AntColony(options: options)
default:
return rotationBasedProgress(with: options)
}
}
@discardableResult
private static func rotationBasedProgress(with options:EZProgressOptions)
-> EZProgress {
switch options.animationOption {
case .xRotation:
return XRotation(options: options)
case .xyRotation:
return XYRotation(options: options)
case .yRotation:
return YRotation(options: options)
case .hnk:
return HNK(options: options)
default:
return HeartBeat(options: options)
}
}
}
| 23.1 | 98 | 0.531231 |
87b5384ac42979dbdf53d66122dadf66017ec049 | 784 | //
// ColorView.swift
// UIKitForMacPlayground
//
// Created by Noah Gilmore on 7/15/19.
// Copyright © 2019 Noah Gilmore. All rights reserved.
//
import UIKit
class ColorView: UIView {
var color: UIColor {
didSet {
self.backgroundColor = color
}
}
init(color: UIColor, dimension: CGFloat? = nil) {
self.color = color
super.init(frame: .zero)
self.backgroundColor = color
if let dimension = dimension {
self.widthAnchor.constraint(equalToConstant: dimension).isActive = true
self.heightAnchor.constraint(equalToConstant: dimension).isActive = true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 23.058824 | 84 | 0.622449 |
d55739457f7960e9848d0743f3ec07d871996c2e | 3,923 | /*
Erbele - Based on Fraise 3.7.3 based on Smultron by Peter Borg
Current Maintainer (since 2016):
Andreas Bentele: [email protected] (https://github.com/abentele/Erbele)
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 FRAHelpMenuController : NSObject {
@IBAction func installCommandLineUtilityAction(_ sender: Any) {
if let attachedSheet = FRACurrentWindow()?.attachedSheet {
attachedSheet.close();
}
let alert = NSAlert();
alert.messageText = NSLocalizedString("Are you sure you want to install the command-line utility?", comment: "Ask if they are sure they want to install the command-line utility in Install-command-line-utility sheet");
alert.informativeText = NSLocalizedString("If you choose Install erbele will be installed in /usr/bin and its man page in /usr/share/man/man1 and you can use it directly in the Terminal (you may need to authenticate twice with an administrators username and password). Otherwise you can choose to place all the files you need on the Desktop and install it manually.", comment: "Indicate that if you choose Install erbele will be installed in /usr/bin and its man page in /usr/share/man/man1 and you can use it directly in the Terminal (you may need to authenticate twice with an administrators username and password). Otherwise you can choose to place all the files you need on the desktop and install it manually. in Install-command-line-utility sheet");
alert.addButton(withTitle: NSLocalizedString("Install", comment: "Install-button in Install-command-line-utility sheet"));
alert.addButton(withTitle: NSLocalizedString("Put On Desktop", comment: "Put On Desktop-button in Install-command-line-utility sheet"));
alert.addButton(withTitle: CANCEL_BUTTON());
alert.alertStyle = NSAlert.Style.informational;
alert.beginSheetModal(for: FRACurrentWindow()!) { (response) in
do {
if (response == NSApplication.ModalResponse.alertFirstButtonReturn) {
try FRAAuthenticationController.sharedInstance().installCommandLineUtility()
} else if (response == NSApplication.ModalResponse.alertSecondButtonReturn) {
let fileManager = FileManager.default;
let pathToFolder = URL(fileURLWithPath: NSHomeDirectory())
.appendingPathComponent("Desktop")
.appendingPathComponent("Erbele command-line utility")
try fileManager.createDirectory(at: pathToFolder, withIntermediateDirectories: true, attributes: nil)
try self.copyResource(resource: "erbele", pathToFolder: pathToFolder)
try self.copyResource(resource: "erbele.1", pathToFolder: pathToFolder)
}
} catch {
// TODO error handling
}
}
}
func copyResource(resource: String, pathToFolder: URL) throws {
let fileManager = FileManager.default;
let toURL = pathToFolder.appendingPathComponent(resource)
let item = Bundle.main.url(forResource: resource, withExtension: "")!
try fileManager.copyItem(at: item, to: toURL)
}
@IBAction func erbeleHelp(_ sender: Any) {
NSWorkspace.shared.openFile(Bundle.main.path(forResource: "Erbele-Manual", ofType: "pdf")!)
}
}
| 59.439394 | 763 | 0.698955 |
bfb0fc311d7bbb431abd044ec91f34e60c1f407f | 583 | //
// SRTabBarDelegate.swift
// Example
//
// Created by Stephen Radford on 16/05/2016.
// Copyright © 2016 Stephen Radford. All rights reserved.
//
import Cocoa
public protocol SRTabBarDelegate: NSObjectProtocol {
/**
Called before the index of the active tab will changed
- parameter index: The index the tab changed to
*/
func tabIndexShouldChange(index: Int)
/**
Called when the index of the active tab has changed
- parameter index: The index the tab changed to
*/
func tabIndexChanged(index: Int)
} | 21.592593 | 59 | 0.655232 |
c12db1f2c51af3c96c10a674b1a4475a4270c70b | 1,185 | import Foundation
import XCTest
class RnaTranscriptionTest: XCTestCase {
func test_Rna_complement_of_cytosine_is_guanine(){
XCTAssertEqual("G", Nucleotide("C").complementOfDNA )}
func test_Rna_complement_of_guanine_is_cytosine(){
XCTAssertEqual("C", Nucleotide("G").complementOfDNA )}
func test_Rna_complement_of_thymine_is_adenine(){
XCTAssertEqual("A", Nucleotide("T").complementOfDNA )}
func test_Rna_complement_of_adenine_is_uracil(){
XCTAssertEqual("U", Nucleotide("A").complementOfDNA )}
func test_Rna_complement(){
XCTAssertEqual("UGCACCAGAAUU", Nucleotide("ACGTGGTCTTAA").complementOfDNA )}
func test_Dna_complement_of_cytosine_is_guanine(){
XCTAssertEqual("G", Nucleotide("C").complementOfRNA )}
func test_Dna_complement_of_guanine_is_cytosine(){
XCTAssertEqual("C", Nucleotide("G").complementOfRNA )}
func test_Dna_complement_of_uracil_is_adenine(){
XCTAssertEqual("A", Nucleotide("U").complementOfRNA )}
func test_Dna_complement_of_adenine_is_thymine(){
XCTAssertEqual("T", Nucleotide("A").complementOfRNA )}
func test_Dna_complement(){
XCTAssertEqual("ACTTGGGCTGTAC", Nucleotide("UGAACCCGACAUG").complementOfRNA )}
}
| 32.027027 | 82 | 0.782278 |
8aabd3cd43b4ed848a17137ff0d77c6945bbcdfc | 2,635 | //
// random.swift
// org.SwiftGFX.SwiftMath
//
// Created by Andrey Volodin on 29.09.16.
//
//
// @note copied from SwiftRandom which is MIT Licensed
#if (os(OSX) || os(iOS) || os(tvOS) || os(watchOS))
import Darwin
#else
import Glibc
import SwiftGlibc
internal func arc4random() -> UInt32 {
return UInt32(random())
}
internal func arc4random_uniform(_ val: UInt32) -> UInt32 {
return UInt32(random()) % val
}
#endif
// each type has its own random
public extension Bool {
/// SwiftRandom extension
static func random() -> Bool {
return Int.random() % 2 == 0
}
}
public extension Int {
/// SwiftRandom extension
static func random(range: Range<Int>) -> Int {
return random(range.lowerBound, range.upperBound)
}
/// SwiftRandom extension
static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int {
return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
}
}
public extension Int32 {
/// SwiftRandom extension
static func random(range: Range<Int>) -> Int32 {
return random(range.lowerBound, range.upperBound)
}
/// SwiftRandom extension
///
/// - note: Using `Int` as parameter type as we usually just want to write `Int32.random(13, 37)` and not `Int32.random(Int32(13), Int32(37))`
static func random(_ lower: Int = 0, _ upper: Int = 100) -> Int32 {
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
}
}
public extension Double {
/// SwiftRandom extension
static func random(_ lower: Double = 0, _ upper: Double = 100) -> Double {
return (Double(arc4random()) / 0xFFFFFFFF) * (upper - lower) + lower
}
}
public extension Float {
/// SwiftRandom extension
static func random(_ lower: Float = 0, _ upper: Float = 100) -> Float {
return (Float(arc4random()) / 0xFFFFFF) * (upper - lower) + lower
}
}
public extension Vector2f {
/** Returns a random Vector2f with a length equal to 1.0.
*/
var randomOnUnitCircle: Vector2f {
while true {
let p = p2d(Float.random(-1, 1), Float.random(-1, 1))
let lsq = p.lengthSquared
if 0.1 < lsq && lsq < 1.0 {
return p * Float(1.0 / sqrtf(lsq))
}
}
}
/**Returns a random Vector2f with a length less than 1.0.
*/
var randomInUnitCircle: Vector2f {
while true {
let p = p2d(Float.random(-1, 1), Float.random(-1, 1))
let lsq = p.lengthSquared
if lsq < 1.0 { return p }
}
}
}
| 26.887755 | 146 | 0.596964 |
ef7a01c5ee34b77ac373a2467897a572bda7f63a | 473 | //
// VIPERView.swift
// VIPERBase
//
// Created by Rafael on 27/08/18.
// Copyright © 2018 Rafael Ribeiro da Silva. All rights reserved.
//
import Foundation
/**
Protocol that defines the **View** layer of VIPER architecture.
*/
public protocol VIPERView: VIPERBaseLayer {
/**
Type of the presenter in the view layer.
*/
associatedtype Presenter
/**
Presenter of the module.
*/
var presenter: Presenter! { get set }
}
| 18.192308 | 66 | 0.636364 |
de3bece6fcbaa2744e490b9a23b6296c6d1ec52e | 3,584 | //
// ShimmerAnimation.swift
// ShimmerView
//
// Created by Drouin on 29/07/2019.
// Copyright © 2019 VersusMind. All rights reserved.
//
import UIKit
class ShimmerAnimation {
static func buildAnimation(view: UIView, type: ShimmerOptions.AnimationType) {
switch type {
case .classic: buildClassicAnimation(view: view)
case .fade: buildFadeAnimation(view: view)
}
}
static private func buildFadeAnimation(view: UIView) {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 0.9
animation.toValue = 0.3
let realDuration = ShimmerOptions.instance.animationAutoReserse ? (ShimmerOptions.instance.animationDuration * 2) : ShimmerOptions.instance.animationDuration
animation.duration = CFTimeInterval(realDuration + ShimmerOptions.instance.animationDelay)
animation.repeatCount = HUGE
animation.autoreverses = ShimmerOptions.instance.animationAutoReserse
animation.fillMode = CAMediaTimingFillMode.forwards
animation.isRemovedOnCompletion = false
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
view.layer.add(animation, forKey: "fade")
}
static private func buildClassicAnimation(view: UIView) {
let animation = CABasicAnimation(keyPath: "transform.translation.x")
animation.duration = CFTimeInterval(ShimmerOptions.instance.animationDuration)
var fromValue: CGFloat = 0
var toValue: CGFloat = 0
switch ShimmerOptions.instance.animationDirection {
case .topBottom:
animation.keyPath = "transform.translation.y"
fromValue = -view.frame.size.height
toValue = view.frame.size.height
case .bottomTop:
animation.keyPath = "transform.translation.y"
fromValue = view.frame.size.height
toValue = -view.frame.size.height
case .leftRight:
fromValue = -view.frame.size.width
toValue = view.frame.size.width
case .rightLeft:
fromValue = view.frame.size.width
toValue = -view.frame.size.width
}
animation.fromValue = fromValue
animation.toValue = toValue
animation.fillMode = CAMediaTimingFillMode.forwards
animation.isRemovedOnCompletion = false
animation.autoreverses = ShimmerOptions.instance.animationAutoReserse
let group = CAAnimationGroup()
group.animations = [animation]
let realDuration = ShimmerOptions.instance.animationAutoReserse ? (ShimmerOptions.instance.animationDuration * 2) : ShimmerOptions.instance.animationDuration
group.duration = CFTimeInterval(realDuration + ShimmerOptions.instance.animationDelay)
group.repeatCount = HUGE
let gradientLayer = CAGradientLayer()
gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
gradientLayer.frame = view.bounds
switch ShimmerOptions.instance.animationDirection {
case .topBottom, .bottomTop:
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
case .leftRight, .rightLeft:
gradientLayer.startPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
}
gradientLayer.add(group, forKey: "animationShimmerView")
view.layer.mask = gradientLayer
}
}
| 40.727273 | 165 | 0.665458 |
de8138a4a32da5469e0b5bcf454e64f04b811a72 | 39 | import Foundation
extension Note {
}
| 6.5 | 17 | 0.74359 |
fc939f349a30b3191190437936e5a7f85ae3a21b | 829 | import XCTest
//import ModuleTesthttps://gitlab.extranet.fluxit.com.ar/ios-native-ncuenta/pod-template-module.git
class Tests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 28.586207 | 111 | 0.62123 |
7510581d8ea8b2d2cd10544d0565340dbe2f4245 | 1,763 | //
// DataSourceTest.swift
// MedKit
//
// Created by Ahmed Onawale on 5/28/16.
// Copyright © 2016 Ahmed Onawale. All rights reserved.
//
import UIKit
import XCTest
@testable import MedKit
class Grocery<Element, ListView>: DataSource {
var listView: ListView
var elements: [[Element]]
required init(_ elements: [[Element]], listView: ListView) {
self.elements = elements
self.listView = listView
}
}
class DataSourceTest: MedKitTests {
let dataSource = Grocery([["Butter", "Milk", "Break", "Bacon"], ["Javascript", "Go", "Swift"]], listView: UIView())
func testNumberOfElements() {
XCTAssertEqual(dataSource.countElementsIn(section: 0), 4)
XCTAssertEqual(dataSource.countElementsIn(section: 1), 3)
}
func testNumberOfSections() {
XCTAssertEqual(dataSource.numberOfSections, 2)
}
func testElementAtIndexPath() {
XCTAssertEqual(dataSource[NSIndexPath(forRow: 0, inSection: 0)], "Butter")
XCTAssertEqual(dataSource[NSIndexPath(forRow: 1, inSection: 0)], "Milk")
XCTAssertEqual(dataSource[NSIndexPath(forRow: 2, inSection: 0)], "Break")
XCTAssertEqual(dataSource[NSIndexPath(forRow: 3, inSection: 0)], "Bacon")
XCTAssertEqual(dataSource[NSIndexPath(forRow: 0, inSection: 1)], "Javascript")
XCTAssertEqual(dataSource[NSIndexPath(forRow: 1, inSection: 1)], "Go")
XCTAssertEqual(dataSource[NSIndexPath(forRow: 2, inSection: 1)], "Swift")
}
func testElementsInSection() {
XCTAssertEqual(dataSource.elementsIn(section: 0), ["Butter", "Milk", "Break", "Bacon"])
XCTAssertEqual(dataSource.elementsIn(section: 1), ["Javascript", "Go", "Swift"])
}
} | 32.054545 | 119 | 0.655133 |
08e8b325777acfe9d174d4f8e5f3c842784983d0 | 3,958 | //
// BITTests.swift
// SwiftNesTests
//
// Created by Tibor Bodecs on 2021. 09. 12..
//
import XCTest
@testable import SwiftNes
final class BITTests: XCTestCase {
private func testUnchangedRegisterFlags(_ nes: Nes) {
XCTAssertFalse(nes.cpu.registers.carryFlag)
XCTAssertFalse(nes.cpu.registers.interruptFlag)
XCTAssertFalse(nes.cpu.registers.decimalFlag)
XCTAssertFalse(nes.cpu.registers.breakFlag)
}
func testZeroPage() throws {
let nes = Nes()
nes.cpu.registers.zeroFlag = false
nes.cpu.registers.signFlag = false
nes.cpu.registers.overflowFlag = false
nes.cpu.registers.a = 0xCC
nes.memory.storage[0x00] = nes.cpu.opcode(.bit, .zeroPage)
nes.memory.storage[0x01] = 0x42
nes.memory.storage[0x42] = 0xCC
nes.start(cycles: 3)
XCTAssertTrue(nes.cpu.registers.overflowFlag)
XCTAssertTrue(nes.cpu.registers.signFlag)
XCTAssertTrue(nes.cpu.registers.zeroFlag)
XCTAssertEqual(nes.cpu.registers.a, 0xCC)
testUnchangedRegisterFlags(nes)
XCTAssertEqual(nes.cpu.totalCycles, 3)
}
func testZeroPageFalseFlags() throws {
let nes = Nes()
nes.cpu.registers.zeroFlag = true
nes.cpu.registers.signFlag = true
nes.cpu.registers.overflowFlag = true
nes.cpu.registers.a = 0xCC
nes.memory.storage[0x00] = nes.cpu.opcode(.bit, .zeroPage)
nes.memory.storage[0x01] = 0x42
nes.memory.storage[0x42] = 0x33
nes.start(cycles: 3)
XCTAssertFalse(nes.cpu.registers.overflowFlag)
XCTAssertFalse(nes.cpu.registers.signFlag)
XCTAssertFalse(nes.cpu.registers.zeroFlag)
XCTAssertEqual(nes.cpu.registers.a, 0xCC)
testUnchangedRegisterFlags(nes)
XCTAssertEqual(nes.cpu.totalCycles, 3)
}
func testAbsolute() throws {
let nes = Nes()
nes.cpu.registers.zeroFlag = false
nes.cpu.registers.signFlag = false
nes.cpu.registers.overflowFlag = false
nes.cpu.registers.a = 0xCC
nes.memory.storage[0x00] = nes.cpu.opcode(.bit, .absolute)
nes.memory.storage[0x01] = 0x80
nes.memory.storage[0x02] = 0x01
nes.memory.storage[0x0180] = 0xCC
nes.start(cycles: 4)
XCTAssertTrue(nes.cpu.registers.overflowFlag)
XCTAssertTrue(nes.cpu.registers.signFlag)
XCTAssertTrue(nes.cpu.registers.zeroFlag)
XCTAssertEqual(nes.cpu.registers.a, 0xCC)
testUnchangedRegisterFlags(nes)
XCTAssertEqual(nes.cpu.totalCycles, 4)
}
func testAbsoluteFalseFlags() throws {
let nes = Nes()
nes.cpu.registers.zeroFlag = true
nes.cpu.registers.signFlag = false
nes.cpu.registers.overflowFlag = false
nes.cpu.registers.a = 0x33
nes.memory.storage[0x00] = nes.cpu.opcode(.bit, .absolute)
nes.memory.storage[0x01] = 0x80
nes.memory.storage[0x02] = 0x01
nes.memory.storage[0x0180] = 0xCC
nes.start(cycles: 4)
XCTAssertTrue(nes.cpu.registers.overflowFlag)
XCTAssertTrue(nes.cpu.registers.signFlag)
XCTAssertFalse(nes.cpu.registers.zeroFlag)
XCTAssertEqual(nes.cpu.registers.a, 0x33)
testUnchangedRegisterFlags(nes)
XCTAssertEqual(nes.cpu.totalCycles, 4)
}
func testAbsoluteFalseFlagsMixed() throws {
let nes = Nes()
nes.cpu.registers.signFlag = false
nes.cpu.registers.overflowFlag = true
nes.memory.storage[0x00] = nes.cpu.opcode(.bit, .absolute)
nes.memory.storage[0x01] = 0x80
nes.memory.storage[0x02] = 0x01
nes.memory.storage[0x0180] = 0b10000000
nes.start(cycles: 4)
XCTAssertFalse(nes.cpu.registers.overflowFlag)
XCTAssertTrue(nes.cpu.registers.signFlag)
testUnchangedRegisterFlags(nes)
XCTAssertEqual(nes.cpu.totalCycles, 4)
}
}
| 35.981818 | 66 | 0.652097 |
9019908e906a4adf6067757893e0f8d950a2cbab | 1,016 | //
// sentry_ios_carthageTests.swift
// sentry-ios-carthageTests
//
// Created by Daniel Griesser on 26.09.17.
// Copyright © 2017 Sentry. All rights reserved.
//
import XCTest
@testable import sentry_ios_carthage
class sentry_ios_carthageTests: 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 testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.459459 | 111 | 0.647638 |
5d9ba54125cad2f04ff100067bc0d9fd74c56822 | 241 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S<T where g:C{
var d{
struct S<d{class A
struct A{struct S
let:a
| 24.1 | 87 | 0.755187 |
f79b871a193a7a6697b34f4aed3a747208d98388 | 504 | //
// ViewController.swift
// Bindable
//
// Created by openfryer on 05/05/2017.
// Copyright (c) 2017 openfryer. 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.
}
}
| 20.16 | 80 | 0.670635 |
1e458580a453937f37da4210dd8cd18d205897a1 | 6,746 | //
// TokensAPI.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Alamofire
import PromiseKit
public class TokensAPI: APIBase {
/**
Check Token
- parameter tokenInfo: (body) Token object to be checked
- parameter completion: completion handler to receive the data and the error objects
*/
public class func checkToken(tokenInfo tokenInfo: TokenRequest, completion: ((data: CheckTokenResponse?, error: ErrorType?) -> Void)) {
checkTokenWithRequestBuilder(tokenInfo: tokenInfo).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Check Token
- parameter tokenInfo: (body) Token object to be checked
- returns: Promise<CheckTokenResponse>
*/
public class func checkToken(tokenInfo tokenInfo: TokenRequest) -> Promise<CheckTokenResponse> {
let deferred = Promise<CheckTokenResponse>.pendingPromise()
checkToken(tokenInfo: tokenInfo) { data, error in
if let error = error {
deferred.reject(error)
} else {
deferred.fulfill(data!)
}
}
return deferred.promise
}
/**
Check Token
- POST /accounts/checkToken
- (Deprecated) Check Token. See tokenInfo
- OAuth:
- type: oauth2
- name: artikcloud_oauth
- examples: [{contentType=application/json, example={
"data" : {
"message" : "aeiou"
}
}}]
- parameter tokenInfo: (body) Token object to be checked
- returns: RequestBuilder<CheckTokenResponse>
*/
public class func checkTokenWithRequestBuilder(tokenInfo tokenInfo: TokenRequest) -> RequestBuilder<CheckTokenResponse> {
let path = "/accounts/checkToken"
let URLString = ArtikCloudAPI.basePath + path
let parameters = tokenInfo.encodeToJSON() as? [String:AnyObject]
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<CheckTokenResponse>.Type = ArtikCloudAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true)
}
/**
Refresh Token
- parameter grantType: (form) Grant Type.
- parameter refreshToken: (form) Refresh Token.
- parameter completion: completion handler to receive the data and the error objects
*/
public class func refreshToken(grantType grantType: String, refreshToken: String, completion: ((data: RefreshTokenResponse?, error: ErrorType?) -> Void)) {
refreshTokenWithRequestBuilder(grantType: grantType, refreshToken: refreshToken).execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Refresh Token
- parameter grantType: (form) Grant Type.
- parameter refreshToken: (form) Refresh Token.
- returns: Promise<RefreshTokenResponse>
*/
public class func refreshToken(grantType grantType: String, refreshToken: String) -> Promise<RefreshTokenResponse> {
let deferred = Promise<RefreshTokenResponse>.pendingPromise()
refreshToken(grantType: grantType, refreshToken: refreshToken) { data, error in
if let error = error {
deferred.reject(error)
} else {
deferred.fulfill(data!)
}
}
return deferred.promise
}
/**
Refresh Token
- POST /accounts/token
- Refresh Token
- OAuth:
- type: oauth2
- name: artikcloud_oauth
- examples: [{contentType=application/json, example={
"access_token" : "aeiou",
"refresh_token" : "aeiou",
"token_type" : "aeiou",
"expires_in" : 123456789
}}]
- parameter grantType: (form) Grant Type.
- parameter refreshToken: (form) Refresh Token.
- returns: RequestBuilder<RefreshTokenResponse>
*/
public class func refreshTokenWithRequestBuilder(grantType grantType: String, refreshToken: String) -> RequestBuilder<RefreshTokenResponse> {
let path = "/accounts/token"
let URLString = ArtikCloudAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [
"grant_type": grantType,
"refresh_token": refreshToken
]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<RefreshTokenResponse>.Type = ArtikCloudAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false)
}
/**
Token Info
- parameter completion: completion handler to receive the data and the error objects
*/
public class func tokenInfo(completion: ((data: TokenInfoSuccessResponse?, error: ErrorType?) -> Void)) {
tokenInfoWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
Token Info
- returns: Promise<TokenInfoSuccessResponse>
*/
public class func tokenInfo() -> Promise<TokenInfoSuccessResponse> {
let deferred = Promise<TokenInfoSuccessResponse>.pendingPromise()
tokenInfo() { data, error in
if let error = error {
deferred.reject(error)
} else {
deferred.fulfill(data!)
}
}
return deferred.promise
}
/**
Token Info
- GET /accounts/tokenInfo
- Returns the Token Information
- OAuth:
- type: oauth2
- name: artikcloud_oauth
- examples: [{contentType=application/json, example={
"data" : {
"device_id" : "aeiou",
"user_id" : "aeiou",
"expires_in" : 123,
"client_id" : "aeiou"
}
}}]
- returns: RequestBuilder<TokenInfoSuccessResponse>
*/
public class func tokenInfoWithRequestBuilder() -> RequestBuilder<TokenInfoSuccessResponse> {
let path = "/accounts/tokenInfo"
let URLString = ArtikCloudAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<TokenInfoSuccessResponse>.Type = ArtikCloudAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}
| 33.068627 | 159 | 0.650608 |
1de4dfbc1ff3449c2b19745e033ac2884a896fc6 | 8,182 | //
// ChartGuideLinesLayer.swift
// SwiftCharts
//
// Created by ischuetz on 26/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartGuideLinesLayerSettings {
let linesColor: UIColor
let linesWidth: CGFloat
public init(linesColor: UIColor = UIColor.gray, linesWidth: CGFloat = 0.3) {
self.linesColor = linesColor
self.linesWidth = linesWidth
}
}
open class ChartGuideLinesDottedLayerSettings: ChartGuideLinesLayerSettings {
let dotWidth: CGFloat
let dotSpacing: CGFloat
public init(linesColor: UIColor, linesWidth: CGFloat, dotWidth: CGFloat = 2, dotSpacing: CGFloat = 2) {
self.dotWidth = dotWidth
self.dotSpacing = dotSpacing
super.init(linesColor: linesColor, linesWidth: linesWidth)
}
}
public enum ChartGuideLinesLayerAxis {
case x, y, xAndY
}
open class ChartGuideLinesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer {
fileprivate let settings: T
fileprivate let onlyVisibleX: Bool
fileprivate let onlyVisibleY: Bool
fileprivate let axis: ChartGuideLinesLayerAxis
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .xAndY, settings: T, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
self.settings = settings
self.onlyVisibleX = onlyVisibleX
self.onlyVisibleY = onlyVisibleY
self.axis = axis
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) {
fatalError("override")
}
override open func chartViewDrawing(context: CGContext, chart: Chart) {
let originScreenLoc = self.innerFrame.origin
let xScreenLocs = onlyVisibleX ? self.xAxis.visibleAxisValuesScreenLocs : self.xAxis.axisValuesScreenLocs
let yScreenLocs = onlyVisibleY ? self.yAxis.visibleAxisValuesScreenLocs : self.yAxis.axisValuesScreenLocs
if self.axis == .x || self.axis == .xAndY {
for xScreenLoc in xScreenLocs {
let x1 = xScreenLoc
let y1 = originScreenLoc.y
let x2 = x1
let y2 = originScreenLoc.y + self.innerFrame.height
self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2))
}
}
if self.axis == .y || self.axis == .xAndY {
for yScreenLoc in yScreenLocs {
let x1 = originScreenLoc.x
let y1 = yScreenLoc
let x2 = originScreenLoc.x + self.innerFrame.width
let y2 = y1
self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2))
}
}
}
}
public typealias ChartGuideLinesLayer = ChartGuideLinesLayer_<Any>
open class ChartGuideLinesLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesLayerSettings> {
override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .xAndY, settings: ChartGuideLinesLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY)
}
override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor)
}
}
public typealias ChartGuideLinesDottedLayer = ChartGuideLinesDottedLayer_<Any>
open class ChartGuideLinesDottedLayer_<N>: ChartGuideLinesLayerAbstract<ChartGuideLinesDottedLayerSettings> {
override public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartGuideLinesLayerAxis = .xAndY, settings: ChartGuideLinesDottedLayerSettings, onlyVisibleX: Bool = false, onlyVisibleY: Bool = false) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, axis: axis, settings: settings, onlyVisibleX: onlyVisibleX, onlyVisibleY: onlyVisibleY)
}
override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing)
}
}
open class ChartGuideLinesForValuesLayerAbstract<T: ChartGuideLinesLayerSettings>: ChartCoordsSpaceLayer {
fileprivate let settings: T
fileprivate let axisValuesX: [ChartAxisValue]
fileprivate let axisValuesY: [ChartAxisValue]
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: T, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
self.settings = settings
self.axisValuesX = axisValuesX
self.axisValuesY = axisValuesY
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
fileprivate func drawGuideline(_ context: CGContext, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint, dotWidth: CGFloat, dotSpacing: CGFloat) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: width, color: color, dotWidth: dotWidth, dotSpacing: dotSpacing)
}
fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) {
fatalError("override")
}
override open func chartViewDrawing(context: CGContext, chart: Chart) {
let originScreenLoc = self.innerFrame.origin
for axisValue in self.axisValuesX {
let screenLoc = self.xAxis.screenLocForScalar(axisValue.scalar)
let x1 = screenLoc
let y1 = originScreenLoc.y
let x2 = x1
let y2 = originScreenLoc.y + self.innerFrame.height
self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2))
}
for axisValue in self.axisValuesY {
let screenLoc = self.yAxis.screenLocForScalar(axisValue.scalar)
let x1 = originScreenLoc.x
let y1 = screenLoc
let x2 = originScreenLoc.x + self.innerFrame.width
let y2 = y1
self.drawGuideline(context, p1: CGPoint(x: x1, y: y1), p2: CGPoint(x: x2, y: y2))
}
}
}
public typealias ChartGuideLinesForValuesLayer = ChartGuideLinesForValuesLayer_<Any>
open class ChartGuideLinesForValuesLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesLayerSettings> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY)
}
override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor)
}
}
public typealias ChartGuideLinesForValuesDottedLayer = ChartGuideLinesForValuesDottedLayer_<Any>
open class ChartGuideLinesForValuesDottedLayer_<N>: ChartGuideLinesForValuesLayerAbstract<ChartGuideLinesDottedLayerSettings> {
public override init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, settings: ChartGuideLinesDottedLayerSettings, axisValuesX: [ChartAxisValue], axisValuesY: [ChartAxisValue]) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings, axisValuesX: axisValuesX, axisValuesY: axisValuesY)
}
override fileprivate func drawGuideline(_ context: CGContext, p1: CGPoint, p2: CGPoint) {
ChartDrawDottedLine(context: context, p1: p1, p2: p2, width: self.settings.linesWidth, color: self.settings.linesColor, dotWidth: self.settings.dotWidth, dotSpacing: self.settings.dotSpacing)
}
}
| 45.966292 | 235 | 0.703373 |
9b7b85b791521e706fd965fd9cfd8ed29c2016e7 | 1,975 | //
// ModelDemoController.swift
// FlexColorPickerDemo
//
// Created by Rastislav Mirek on 4/6/18.
//
// MIT License
// Copyright (c) 2018 Rastislav Mirek
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class ModalDemoViewController: DefaultColorPickerViewController {
override func viewDidLoad() {
super.viewDidLoad()
selectedColor = pickedColor
self.delegate = self
self.view.backgroundColor = .black
}
@IBAction func donePressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
extension ModalDemoViewController: ColorPickerDelegate {
func colorPicker(_: ColorPickerController, selectedColor: UIColor, usingControl: ColorControl) {
pickedColor = selectedColor
}
func colorPicker(_: ColorPickerController, confirmedColor: UIColor, usingControl: ColorControl) {
dismiss(animated: true, completion: nil)
}
}
| 36.574074 | 101 | 0.733671 |
bf24dd90a134167f47bc383d9f901eb03ef48d23 | 19 | class Tile {
} | 6.333333 | 12 | 0.473684 |
7a1ac3bac7b9f004812d336091a8a87fba894473 | 1,215 | //
// MainViewController+Table.swift
// ion-swift-client
//
// Created by Ivan Manov on 27.12.2019.
// Copyright © 2019 kxpone. All rights reserved.
//
import IONSwift
import RxSwift
import TableKit
extension MainViewController {
func prepareTable() {
self.tableDirector = TableDirector(tableView: self.tableView)
self.tableDirector?.append(section: self.peersSection())
self.tableDirector?.reload()
}
private func peersSection() -> TableSection {
let section = TableSection()
IONManager.shared.peersSubject
.subscribe(onNext: { peers in
section.clear()
let rows = peers.map { (peer) -> TableRow<PeerTableViewCell> in
let row = TableRow<PeerTableViewCell>(item: peer)
row.on(.click) { _ in
AppRouter.shared.viewController = self
AppRouter.shared.openChat(with: peer.stringIdentifier)
}
return row
}
section.append(rows: rows)
self.tableDirector?.reload()
}).disposed(by: self.disposeBag)
return section
}
}
| 27.613636 | 79 | 0.574486 |
5656af743ffbce980046ad6f71c33087c9e2f301 | 2,019 | // Copyright The swift-UniqueID Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if !NO_FOUNDATION_COMPAT
import Foundation
extension UUID {
/// Losslessly convert a `UniqueID` to a Foundation `UUID`.
///
/// The bytes of the UniqueID are preserved exactly.
/// Both random (v4) and time-ordered (v6) IDs are supported.
///
@inlinable
public init(_ uniqueID: UniqueID) {
self.init(uuid: uniqueID.bytes)
}
}
extension UniqueID {
/// Losslessly convert a Foundation `UUID` to a `UniqueID`.
///
/// The bytes of the Foundation UUID are preserved exactly.
/// By default, Foundation generates random UUIDs (v4).
///
@inlinable
public init(_ uuid: Foundation.UUID) {
self.init(bytes: uuid.uuid)
}
}
// Note: 'Date' might move in to the standard library and increase precision to capture this timestamp exactly.
// https://forums.swift.org/t/pitch-clock-instant-date-and-duration/52451
extension UniqueID.TimeOrdered {
/// The timestamp of the UUID. Note that this has at most 100ns precision.
///
/// ```swift
/// let id = UniqueID("1EC5FE44-E511-6910-BBFA-F7B18FB57436")!
/// id.components(.timeOrdered)?.timestamp
/// // ✅ "2021-12-18 09:24:31 +0000"
/// ```
///
@inlinable
public var timestamp: Date {
Date(timeIntervalSince1970: TimeInterval(_uuid_timestamp_to_unix(timestamp: rawTimestamp)) / 10_000_000)
}
}
#endif // NO_FOUNDATION_COMPAT
| 31.061538 | 113 | 0.68004 |
61f39006afc703cecaeed2f837459d253b7f0ca8 | 11,136 | //
// YepNetworking.swift
// Yep
//
// Created by NIX on 15/3/16.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import Foundation
public enum Method: String, CustomStringConvertible {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
public var description: String {
return self.rawValue
}
}
public struct Resource<A>: CustomStringConvertible {
let path: String
let method: Method
let requestBody: NSData?
let headers: [String: String]
let parse: NSData -> A?
public var description: String {
let decodeRequestBody: [String: AnyObject]
if let requestBody = requestBody {
decodeRequestBody = decodeJSON(requestBody)!
} else {
decodeRequestBody = [:]
}
return "Resource(Method: \(method), path: \(path), headers: \(headers), requestBody: \(decodeRequestBody))"
}
public init(path: String, method: Method, requestBody: NSData?, headers: [String: String], parse: NSData -> A?) {
self.path = path
self.method = method
self.requestBody = requestBody
self.headers = headers
self.parse = parse
}
}
public enum ErrorCode: String {
case BlockedByRecipient = "rejected_your_message"
case NotYetRegistered = "not_yet_registered"
case UserWasBlocked = "user_was_blocked"
}
public enum Reason: CustomStringConvertible {
case CouldNotParseJSON
case NoData
case NoSuccessStatusCode(statusCode: Int, errorCode: ErrorCode?)
case Other(NSError?)
public var description: String {
switch self {
case .CouldNotParseJSON:
return "CouldNotParseJSON"
case .NoData:
return "NoData"
case .NoSuccessStatusCode(let statusCode):
return "NoSuccessStatusCode: \(statusCode)"
case .Other(let error):
return "Other, Error: \(error?.description)"
}
}
}
public typealias FailureHandler = (reason: Reason, errorMessage: String?) -> Void
public let defaultFailureHandler: FailureHandler = { reason, errorMessage in
print("\n***************************** YepNetworking Failure *****************************")
print("Reason: \(reason)")
if let errorMessage = errorMessage {
print("errorMessage: >>>\(errorMessage)<<<\n")
}
}
func queryComponents(key: String, value: AnyObject) -> [(String, String)] {
func escape(string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode)
return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string
}
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value: value)
}
} else {
components.appendContentsOf([(escape(key), escape("\(value)"))])
}
return components
}
var yepNetworkActivityCount = 0 {
didSet {
Manager.networkActivityCountChangedAction?(count: yepNetworkActivityCount)
}
}
private let yepSuccessStatusCodeRange: Range<Int> = 200..<300
public func apiRequest<A>(modifyRequest: NSMutableURLRequest -> (), baseURL: NSURL, resource: Resource<A>?, failure: FailureHandler?, completion: A -> Void) {
guard let resource = resource else {
failure?(reason: .Other(nil), errorMessage: "No resource")
return
}
let session = NSURLSession.sharedSession()
let url = baseURL.URLByAppendingPathComponent(resource.path)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = resource.method.rawValue
func needEncodesParametersForMethod(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in Array(parameters.keys).sort(<) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value: value)
}
return (components.map{"\($0)=\($1)"} as [String]).joinWithSeparator("&")
}
func handleParameters() {
if needEncodesParametersForMethod(resource.method) {
guard let URL = request.URL else {
print("Invalid URL of request: \(request)")
return
}
if let requestBody = resource.requestBody {
if let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(decodeJSON(requestBody)!)
request.URL = URLComponents.URL
}
}
} else {
request.HTTPBody = resource.requestBody
}
}
handleParameters()
modifyRequest(request)
for (key, value) in resource.headers {
request.setValue(value, forHTTPHeaderField: key)
}
#if DEBUG
print(request.cURLCommandLineWithSession(session))
#endif
let _failure: FailureHandler
if let failure = failure {
_failure = failure
} else {
_failure = defaultFailureHandler
}
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if yepSuccessStatusCodeRange.contains(httpResponse.statusCode) {
if let responseData = data {
if let result = resource.parse(responseData) {
completion(result)
} else {
let dataString = NSString(data: responseData, encoding: NSUTF8StringEncoding)
print(dataString)
_failure(reason: .CouldNotParseJSON, errorMessage: errorMessageInData(data))
print("\(resource)\n")
print(request.cURLCommandLine)
}
} else {
_failure(reason: .NoData, errorMessage: errorMessageInData(data))
print("\(resource)\n")
print(request.cURLCommandLine)
}
} else {
let errorCode = errorCodeInData(data)
_failure(reason: .NoSuccessStatusCode(statusCode: httpResponse.statusCode, errorCode: errorCode), errorMessage: errorMessageInData(data))
print("\(resource)\n")
print(request.cURLCommandLine)
// 对于 401: errorMessage: >>>HTTP Token: Access denied<<<
// 用户需要重新登录,所以
if let host = request.URL?.host {
Manager.authFailedAction?(statusCode: httpResponse.statusCode, host: host)
}
}
} else {
_failure(reason: .Other(error), errorMessage: errorMessageInData(data))
print("\(resource)")
print(request.cURLCommandLine)
}
dispatch_async(dispatch_get_main_queue()) {
yepNetworkActivityCount -= 1
}
}
task.resume()
dispatch_async(dispatch_get_main_queue()) {
yepNetworkActivityCount += 1
}
}
func errorMessageInData(data: NSData?) -> String? {
if let data = data {
if let json = decodeJSON(data) {
if let errorMessage = json["error"] as? String {
return errorMessage
}
}
}
return nil
}
func errorCodeInData(data: NSData?) -> ErrorCode? {
if let data = data {
if let json = decodeJSON(data) {
print("error json: \(json)")
if let errorCodeString = json["code"] as? String {
return ErrorCode(rawValue: errorCodeString)
}
}
}
return nil
}
// Here are some convenience functions for dealing with JSON APIs
public typealias JSONDictionary = [String: AnyObject]
public func decodeJSON(data: NSData) -> JSONDictionary? {
if data.length > 0 {
guard let result = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) else {
return JSONDictionary()
}
if let dictionary = result as? JSONDictionary {
return dictionary
} else if let array = result as? [JSONDictionary] {
return ["data": array]
} else {
return JSONDictionary()
}
} else {
return JSONDictionary()
}
}
public func encodeJSON(dict: JSONDictionary) -> NSData? {
return dict.count > 0 ? (try? NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions())) : nil
}
public func jsonResource<A>(path path: String, method: Method, requestParameters: JSONDictionary, parse: JSONDictionary -> A?) -> Resource<A> {
return jsonResource(token: nil, path: path, method: method, requestParameters: requestParameters, parse: parse)
}
public func authJsonResource<A>(path path: String, method: Method, requestParameters: JSONDictionary, parse: JSONDictionary -> A?) -> Resource<A>? {
guard let token = Manager.accessToken?() else {
print("No token for auth")
return nil
}
return jsonResource(token: token, path: path, method: method, requestParameters: requestParameters, parse: parse)
}
public func jsonResource<A>(token token: String?, path: String, method: Method, requestParameters: JSONDictionary, parse: JSONDictionary -> A?) -> Resource<A> {
let jsonParse: NSData -> A? = { data in
if let json = decodeJSON(data) {
return parse(json)
}
return nil
}
let jsonBody = encodeJSON(requestParameters)
var headers = [
"Content-Type": "application/json",
]
if let token = token {
headers["Authorization"] = "Token token=\"\(token)\""
}
let locale = NSLocale.autoupdatingCurrentLocale()
if let
languageCode = locale.objectForKey(NSLocaleLanguageCode) as? String,
countryCode = locale.objectForKey(NSLocaleCountryCode) as? String {
headers["Accept-Language"] = languageCode + "-" + countryCode
}
return Resource(path: path, method: method, requestBody: jsonBody, headers: headers, parse: jsonParse)
}
| 31.908309 | 180 | 0.610722 |
fe117c4c004646a3f298f23b686beb6cd1af3340 | 4,231 | //
// AstroServiceTests.swift
// TadApiTests
//
// Created by Zoltan Tuskes on 30/04/2020.
// Copyright © 2020 Time and Date. All rights reserved.
//
import XCTest
@testable import libtad
class AstroDataServiceTests: XCTestCase {
let request = AstrodataRequest()
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func test_AccessKeyNotSet_ErrorTrue() {
// given
let expectation = self.expectation(description: "Request Completed")
let accessKey: String? = nil
let secretKey = "secret"
let aService = AstrodataService(accessKey: accessKey, secretKey: secretKey)
// when
aService.getAstroDataInfo(request: request, completionHandler: {
(_, error) in
XCTAssertTrue((error != nil), error.debugDescription)
expectation.fulfill()
})
waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func test_SecretKeyNotSet_ErrorTrue() {
// given
let expectation = self.expectation(description: "Request Completed")
let accessKey = "access"
let secretKey: String? = nil
let aService = AstrodataService(accessKey: accessKey, secretKey: secretKey)
// when
aService.getAstroDataInfo(request: request, completionHandler: {
(_, error) in
XCTAssertTrue((error != nil), error.debugDescription)
expectation.fulfill()
})
waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func test_ObjectNotSet_ErrorTrue() {
// given
let expectation = self.expectation(description: "Request Completed")
let accessKey = "access"
let secretKey = "secret"
let aService = AstrodataService(accessKey: accessKey, secretKey: secretKey)
request.placeId = "100"
request.interval = ["timestampgoeshere"]
// when
aService.getAstroDataInfo(request: request, completionHandler: {
(_, error) in
XCTAssertTrue((error != nil), error.debugDescription)
expectation.fulfill()
})
waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func test_PlaceIdNotSet_ErrorTrue() {
// given
let expectation = self.expectation(description: "Request Completed")
let accessKey = "access"
let secretKey = "secret"
let aService = AstrodataService(accessKey: accessKey, secretKey: secretKey)
request.objects = [AstroObjectType.sun]
request.interval = ["timestampgoeshere"]
// when
aService.getAstroDataInfo(request: request, completionHandler: {
(_, error) in
XCTAssertTrue((error != nil), error.debugDescription)
expectation.fulfill()
})
waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
func test_moreThan50_ErrorTrue() {
//given
let expectation = self.expectation(description: "")
let accesskey = "accesskey"
let secretkey = "secrets"
let service = AstrodataService(accessKey: accesskey, secretKey: secretkey)
request.objects = [.sun]
request.placeId = "100"
request.interval = Array( repeatElement("timestampGoesHere", count: 51) )
//when
service.getAstroDataInfo(request: request) { (_, error) in
XCTAssertTrue((error != nil), error.debugDescription)
expectation.fulfill()
}
waitForExpectations(timeout: 5) { (error) in
if let error = error {
XCTFail("waitForExpectationsWithTimeout errored: \(error)")
}
}
}
}
| 30.007092 | 83 | 0.596313 |
efee54bb3b8a9e749a8284bacab6397a11de9ee0 | 13,269 | //
// RxNetworkService.swift
// RxNetworkService
//
// Created by AdlibBeats on 13.03.2021.
// Copyright © 2021 AdlibBeats. All rights reserved.
//
import RxCocoa
import RxSwift
import SWXMLHash
// MARK: RxNetworkService
public enum RxNetworkServiceError: Error {
public enum Status: Int {
case badRequest = 400
case unauthorized = 401
case notFound = 404
case requestTimeout = 408
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case unknown
}
case invalidUrl(String)
case invalidData(Data)
case requestError(Status)
var description: String {
switch self {
case .invalidUrl(let string): return "Invalid url string: \(string)"
case .invalidData(let data): return "Invalid data: \(data)"
case .requestError(let status): return "Error status code: \(status.rawValue > 0 ? "\(status.rawValue)" : "unknown")"
}
}
}
private extension ObserverType {
func onError(_ error: RxNetworkServiceError) {
self.on(.error(error))
}
}
public protocol RxNetworkServiceProtocol: AnyObject {
func fetchUrl(from string: String) -> Observable<URL>
func fetchURLRequest(
from url: String,
contentType: RxNetworkService.ContentType,
charset: RxNetworkService.Charset,
httpMethod: RxNetworkService.HTTPMethod,
body: Data?
) -> Observable<URLRequest>
func fetchURLRequest(
from url: String,
contentType: RxNetworkService.ContentType,
charset: RxNetworkService.Charset,
httpMethod: RxNetworkService.HTTPMethod,
body: String
) -> Observable<URLRequest>
func fetchResponse(from urlRequest: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)>
func fetchDecodableOutput<Output: Decodable>(response: HTTPURLResponse, data: Data) -> Observable<Output>
func fetchStringResponse(response: HTTPURLResponse, data: Data) -> Observable<String>
func fetchXMLOutput<Output: XMLOutput>(from stringResponse: String) -> Observable<Output>
func fetchStatus(response: HTTPURLResponse, data: Data) -> Observable<RxNetworkService.Response>
}
open class RxNetworkService {
public struct Response {
let statusCode: Int
let allHeaderFields: [AnyHashable: Any]
let data: Data
var dataString: String {
String(data: data, encoding: .utf8) ?? ""
}
}
public enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
public enum ContentType: String {
case json
case xml
}
public enum Charset: String {
case utf8 = "utf-8"
}
public enum Logging {
case request
case response
case error
}
public var logging: [Logging] = [.request, .response, .error]
public init() {
}
private func logRequest(request: URLRequest) {
guard
logging.contains(.request),
let httpMethod = request.httpMethod,
let httpBody = request.httpBody
else { return }
#if DEBUG
print("*** 🟡 Request ***\nHTTPMethod: \(httpMethod)\nHTTPBody: \(String(data: httpBody, encoding: .utf8) ?? httpBody.description)")
#endif
}
private func logResponse(response: HTTPURLResponse, data: Data) {
guard logging.contains(.response) else { return }
#if DEBUG
print("*** 🟢 Response ***\nStatus code: \(response.statusCode)\nData: \(String(data: data, encoding: .utf8) ?? data.description)")
#endif
}
private func logError(error: Error) {
guard logging.contains(.error) else { return }
#if DEBUG
print("*** 🔴 Error ***\nValue: \({ ($0 as? RxNetworkServiceError) ?? $0 }(error))")
#endif
}
}
extension RxNetworkService: RxNetworkServiceProtocol {
public func fetchUrl(from string: String) -> Observable<URL> {
Observable.create {
if let url = URL(string: string) { $0.onNext(url) }
else { $0.onError(.invalidUrl(string)) }
return Disposables.create()
}.do(onError: logError)
}
public func fetchURLRequest(
from url: String,
contentType: RxNetworkService.ContentType,
charset: RxNetworkService.Charset,
httpMethod: RxNetworkService.HTTPMethod,
body: Data?
) -> Observable<URLRequest> {
fetchUrl(from: url).map {
var urlRequest = URLRequest(url: $0)
urlRequest.httpMethod = httpMethod.rawValue
urlRequest.addValue(
"text/\(contentType.rawValue); charset=\(charset.rawValue)",
forHTTPHeaderField: "Content-Type"
)
urlRequest.httpBody = body
return urlRequest
}.do(onNext: logRequest)
}
public func fetchURLRequest(
from url: String,
contentType: RxNetworkService.ContentType,
charset: RxNetworkService.Charset,
httpMethod: RxNetworkService.HTTPMethod,
body: String
) -> Observable<URLRequest> {
fetchUrl(from: url).map {
var urlRequest = URLRequest(url: $0)
urlRequest.httpMethod = httpMethod.rawValue
urlRequest.addValue(
"text/\(contentType.rawValue); charset=\(charset.rawValue)",
forHTTPHeaderField: "Content-Type"
)
if !body.isEmpty {
urlRequest.httpBody = body.data(
using: .utf8,
allowLossyConversion: false
)
}
return urlRequest
}.do(onNext: logRequest)
}
public func fetchResponse(from urlRequest: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> {
URLSession.shared.rx.response(request: urlRequest).do(onNext: logResponse, onError: logError)
}
public func fetchDecodableOutput<Output: Decodable>(response: HTTPURLResponse, data: Data) -> Observable<Output> {
Observable.create {
do { $0.onNext(try JSONDecoder().decode(Output.self, from: data)) }
catch { $0.onError(error) }
return Disposables.create()
}.do(onError: logError)
}
public func fetchStringResponse(response: HTTPURLResponse, data: Data) -> Observable<String> {
Observable.create {
if let result = String(
data: data,
encoding: .utf8
) { $0.onNext(result) }
else { $0.onError(.invalidData(data)) }
return Disposables.create()
}.do(onError: logError)
}
public func fetchXMLOutput<Output: XMLOutput>(from stringResponse: String) -> Observable<Output> {
Observable.create {
do { $0.onNext( try RxNetworkService.XML.Mapper.parse(Output.self, from: stringResponse).value()) }
catch { $0.onError(error) }
return Disposables.create()
}.do(onError: logError)
}
public func fetchStatus(response: HTTPURLResponse, data: Data) -> Observable<RxNetworkService.Response> {
Observable.create {
switch response.statusCode {
case 200...299: $0.onNext(.init(statusCode: response.statusCode, allHeaderFields: response.allHeaderFields, data: data))
case let value: $0.onError(.requestError(.init(rawValue: value) ?? .unknown))
}
return Disposables.create()
}.do(onError: logError)
}
}
// MARK: XMLMapper
public typealias XMLModel = XMLIndexer
public typealias XMLOutput = XMLIndexerDeserializable
infix operator <- : DefaultPrecedence
extension String {
public static func <- (name: Self, value: RxNetworkService.XML.Mapper.Property.Value) -> RxNetworkService.XML.Mapper.Property {
.init(name: name, value: value)
}
}
public protocol XMLProtocol {
var xml: String { get }
}
public protocol XMLInput: XMLProtocol {
func mapping() -> RxNetworkService.XML.Mapper.Property
}
extension XMLInput {
public var xml: String {
RxNetworkService.XML.Mapper(value: mapping().xml(mode: .parent)).xml
}
}
public protocol XMLMapperProtocol: XMLProtocol {
func xml(mode: RxNetworkService.XML.Mapper.KindMode) -> String
}
public protocol XMLValueMapperProtocol: XMLMapperProtocol {
var value: String { get }
}
extension RxNetworkService {
public enum XML {
public struct Mapper: XMLValueMapperProtocol {
public enum KindMode {
case parent
case child
case unknown
}
public static func parse<Output: XMLOutput>(_ type: Output.Type, from stringResponse: String) throws -> XMLModel {
try XMLHash.parse(stringResponse)
.byKey("SOAP-ENV:\(String(describing: Envelope.self))")
.byKey("SOAP-ENV:\(String(describing: Body.self))")
.byKey("ns1:\(String(describing: type))")
}
public struct Body: XMLValueMapperProtocol {
public var xml: String { xml(mode: .child) }
public func xml(mode: KindMode) -> String {
"<SOAP-ENV:\(String(describing: Body.self))>\(value)</SOAP-ENV:\(String(describing: Body.self))>"
}
public let value: String
}
public struct Envelope: XMLValueMapperProtocol {
private let env: String
private let enc: String
private let xsi: String
private let xsd: String
public init(
value: String,
env: String = "http://schemas.xmlsoap.org/soap/envelope/",
enc: String = "http://schemas.xmlsoap.org/soap/encoding/",
xsi: String = "http://www.w3.org/2001/XMLSchema-instance",
xsd: String = "http://www.w3.org/2001/XMLSchema"
) {
self.value = value
self.env = env
self.enc = enc
self.xsi = xsi
self.xsd = xsd
}
public var xml: String { xml(mode: .child) }
public func xml(mode: KindMode) -> String {
"<SOAP-ENV:\(String(describing: Envelope.self)) xmlns:SOAP-ENV=\"\(env)\" xmlns:SOAP-ENC=\"\(enc)\" xmlns:xsi=\"\(xsi)\" xmlns:xsd=\"\(xsd)\">\(value)</SOAP-ENV:\(String(describing: Envelope.self))>"
}
public let value: String
}
public struct Header: XMLMapperProtocol {
public enum Encoding: String {
case utf8 = "UTF-8"
}
private let version: Double
private let encoding: Encoding
public init(version: Double = 1.0, encoding: Encoding = .utf8) {
self.version = version
self.encoding = encoding
}
public var xml: String { xml(mode: .child) }
public func xml(mode: KindMode) -> String {
"<?xml version=\"\(String(format: "%.1f", version))\" encoding=\"\(encoding.rawValue)\"?>"
}
}
public struct Property: XMLValueMapperProtocol {
public struct Value {
let value: String
let parentUrl: String
public init(value: String, parentUrl: String) {
self.value = value
self.parentUrl = parentUrl
}
public init(value: String) {
self.init(value: value, parentUrl: "")
}
}
private let name: String
private let parentUrl: String
public init(name: String, value: Value) {
self.name = name
self.value = value.value
self.parentUrl = value.parentUrl
}
public var xml: String { xml(mode: .child) }
public func xml(mode: KindMode) -> String {
switch mode {
case .child: return "<m:\(name)>\(value)</m:\(name)>"
case .parent: return "<m:\(name) xmlns:m=\"\(parentUrl)\">\(value)</m:\(name)>"
case .unknown: return "<\(name)>\(value)</\(name)>"
}
}
public let value: String
}
public let value: String
public var xml: String { xml(mode: .child) }
public func xml(mode: KindMode) -> String {
[Header().xml, Envelope(value: Body(value: value).xml).xml].joined()
}
}
}
}
| 35.103175 | 219 | 0.558671 |
9ccc9d888c216de9f0315ba9b9e598075f4ab947 | 3,956 | // Generated by msgbuilder 2020-05-15 06:20:49 +0000
import StdMsgs
extension sensor_msgs {
/// This is a message to hold data from an IMU (Inertial Measurement Unit)
///
/// Accelerations should be in m/s^2 (not in g's), and rotational velocity should be in rad/sec
///
/// If the covariance of the measurement is known, it should be filled in (if all you know is the
/// variance of each measurement, e.g. from the datasheet, just put those along the diagonal)
/// A covariance matrix of all zeros will be interpreted as "covariance unknown", and to use the
/// data a covariance will have to be assumed or gotten from some other source
///
/// If you have no estimate for one of the data elements (e.g. your IMU doesn't produce an orientation
/// estimate), please set element 0 of the associated covariance matrix to -1
/// If you are interpreting this message, please check for a value of -1 in the first element of each
/// covariance matrix, and disregard the associated estimate.
public struct Imu: MessageWithHeader {
public static let md5sum: String = "6a62c6daae103f4ff57a132d6f95cec2"
public static let datatype = "sensor_msgs/Imu"
public static let definition = """
# This is a message to hold data from an IMU (Inertial Measurement Unit)
#
# Accelerations should be in m/s^2 (not in g's), and rotational velocity should be in rad/sec
#
# If the covariance of the measurement is known, it should be filled in (if all you know is the
# variance of each measurement, e.g. from the datasheet, just put those along the diagonal)
# A covariance matrix of all zeros will be interpreted as "covariance unknown", and to use the
# data a covariance will have to be assumed or gotten from some other source
#
# If you have no estimate for one of the data elements (e.g. your IMU doesn't produce an orientation
# estimate), please set element 0 of the associated covariance matrix to -1
# If you are interpreting this message, please check for a value of -1 in the first element of each
# covariance matrix, and disregard the associated estimate.
Header header
geometry_msgs/Quaternion orientation
float64[9] orientation_covariance # Row major about x, y, z axes
geometry_msgs/Vector3 angular_velocity
float64[9] angular_velocity_covariance # Row major about x, y, z axes
geometry_msgs/Vector3 linear_acceleration
float64[9] linear_acceleration_covariance # Row major x, y z
"""
public var header: std_msgs.Header
public var orientation: geometry_msgs.Quaternion
public var orientation_covariance: FixedLengthFloat64Array9
public var angular_velocity: geometry_msgs.Vector3
public var angular_velocity_covariance: FixedLengthFloat64Array9
public var linear_acceleration: geometry_msgs.Vector3
public var linear_acceleration_covariance: FixedLengthFloat64Array9
public init(header: std_msgs.Header, orientation: geometry_msgs.Quaternion, orientation_covariance: [Float64], angular_velocity: geometry_msgs.Vector3, angular_velocity_covariance: [Float64], linear_acceleration: geometry_msgs.Vector3, linear_acceleration_covariance: [Float64]) {
self.header = header
self.orientation = orientation
self.orientation_covariance = FixedLengthFloat64Array9(orientation_covariance)
self.angular_velocity = angular_velocity
self.angular_velocity_covariance = FixedLengthFloat64Array9(angular_velocity_covariance)
self.linear_acceleration = linear_acceleration
self.linear_acceleration_covariance = FixedLengthFloat64Array9(linear_acceleration_covariance)
}
public init() {
header = std_msgs.Header()
orientation = geometry_msgs.Quaternion()
orientation_covariance = FixedLengthFloat64Array9()
angular_velocity = geometry_msgs.Vector3()
angular_velocity_covariance = FixedLengthFloat64Array9()
linear_acceleration = geometry_msgs.Vector3()
linear_acceleration_covariance = FixedLengthFloat64Array9()
}
}
} | 54.191781 | 282 | 0.775531 |
b9b641573bf47518ab69c5e78e287188011cfb0e | 678 | //
// Client_Configuration.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-02-15.
// Copyright © 2016 George KyeKye. All rights reserved.
//
import Foundation
extension Client{
//http://image.tmdb.org/t/p/w500/8uO0gUM8aNqYLs1OsTBQiXu0fEv.jpg
static func Configuration(_ api_key: String!, completion: @escaping (ClientReturn) -> ()) -> (){
let parameters: [String : AnyObject] = ["api_key": api_key as AnyObject]
let url = "https://api.themoviedb.org/3/configuration"
networkRequest(url: url, parameters: parameters, completion: {
apiReturn in
completion(apiReturn)
})
}
}
| 27.12 | 100 | 0.640118 |
036b0931d43d04193e8884f7a253b4404a99810d | 2,050 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// RouteFilters is the network Client
import Foundation
import azureSwiftRuntime
extension Commands {
public struct RouteFilters {
public static func CreateOrUpdate(resourceGroupName: String, routeFilterName: String, subscriptionId: String, routeFilterParameters: RouteFilterProtocol) -> RouteFiltersCreateOrUpdate {
return CreateOrUpdateCommand(resourceGroupName: resourceGroupName, routeFilterName: routeFilterName, subscriptionId: subscriptionId, routeFilterParameters: routeFilterParameters)
}
public static func Delete(resourceGroupName: String, routeFilterName: String, subscriptionId: String) -> RouteFiltersDelete {
return DeleteCommand(resourceGroupName: resourceGroupName, routeFilterName: routeFilterName, subscriptionId: subscriptionId)
}
public static func Get(resourceGroupName: String, routeFilterName: String, subscriptionId: String) -> RouteFiltersGet {
return GetCommand(resourceGroupName: resourceGroupName, routeFilterName: routeFilterName, subscriptionId: subscriptionId)
}
public static func List(subscriptionId: String) -> RouteFiltersList {
return ListCommand(subscriptionId: subscriptionId)
}
public static func ListByResourceGroup(resourceGroupName: String, subscriptionId: String) -> RouteFiltersListByResourceGroup {
return ListByResourceGroupCommand(resourceGroupName: resourceGroupName, subscriptionId: subscriptionId)
}
public static func Update(resourceGroupName: String, routeFilterName: String, subscriptionId: String, routeFilterParameters: PatchRouteFilterProtocol) -> RouteFiltersUpdate {
return UpdateCommand(resourceGroupName: resourceGroupName, routeFilterName: routeFilterName, subscriptionId: subscriptionId, routeFilterParameters: routeFilterParameters)
}
}
}
| 66.129032 | 190 | 0.793659 |
6a617d13659287b3b79b5e4944a14d3897d60cf4 | 3,168 | //
// CGFloat+BBase.swift
// Fch_Contact
//
// Created by bai on 2018/1/30.
// Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved.
//
import Foundation
import UIKit
extension CGFloat {
/// EZSE: Return the central value of CGFloat.
public var center: CGFloat { return (self / 2) }
@available(*, deprecated: 1.8, renamed: "degreesToRadians")
public func toRadians() -> CGFloat {
return (.pi * self) / 180.0
}
/// EZSwiftExtensions
public func degreesToRadians() -> CGFloat {
return (.pi * self) / 180.0
}
/// EZSwiftExtensions
public mutating func toRadiansInPlace() {
self = (.pi * self) / 180.0
}
/// EZSE: Converts angle degrees to radians.
public static func degreesToRadians(_ angle: CGFloat) -> CGFloat {
return (.pi * angle) / 180.0
}
/// EZSE: Converts radians to degrees.
public func radiansToDegrees() -> CGFloat {
return (180.0 * self) / .pi
}
/// EZSE: Converts angle radians to degrees mutable version.
public mutating func toDegreesInPlace() {
self = (180.0 * self) / .pi
}
/// EZSE : Converts angle radians to degrees static version.
public static func radiansToDegrees(_ angleInDegrees: CGFloat) -> CGFloat {
return (180.0 * angleInDegrees) / .pi
}
/// EZSE: Returns a random floating point number between 0.0 and 1.0, inclusive.
public static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
/// EZSE: Returns a random floating point number in the range min...max, inclusive.
public static func random(within: Range<CGFloat>) -> CGFloat {
return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound
}
/// EZSE: Returns a random floating point number in the range min...max, inclusive.
public static func random(within: ClosedRange<CGFloat>) -> CGFloat {
return CGFloat.random() * (within.upperBound - within.lowerBound) + within.lowerBound
}
/**
EZSE :Returns the shortest angle between two angles. The result is always between
-π and π.
Inspired from : https://github.com/raywenderlich/SKTUtils/blob/master/SKTUtils/CGFloat%2BExtensions.swift
*/
public static func shortestAngleInRadians(from first: CGFloat, to second: CGFloat) -> CGFloat {
let twoPi = CGFloat(.pi * 2.0)
var angle = (second - first).truncatingRemainder(dividingBy: twoPi)
if angle >= .pi {
angle -= twoPi
}
if angle <= -.pi {
angle += twoPi
}
return angle
}
}
extension CGFloat{
public var k:CGFloat{
return self / 1024;
}
public var m:CGFloat{
return self / (1024 * 1024);
}
public func toSizeString() -> String {
if self >= (1024 * 1024) {
return String(format: "%.2fMB", self.m);
}else if self >= 1024 {
return String(format: "%.2fKB", self.k);
}else{
return String(format: "%.2fB", self);
}
}
}
| 29.06422 | 110 | 0.596591 |
18d472591f75234abbdafe0d3b1e56fe2ccb56fb | 969 | //
// Copyright (c) Google 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 FirebaseCore
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication
.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
}
| 31.258065 | 78 | 0.716202 |
ff5cea7a249b233de827581d045388dbf6703938 | 5,761 | //
// ViewController.swift
// QAHelper
//
// Created by Sarath Vijay on 10/11/16.
// Copyright © 2016 QBurst. 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 viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showJiraIssues(_ sender: AnyObject) {
let jiraSB: UIStoryboard = Util.getStoryboard(Constants.Storyboards.jira)
let navJira = jiraSB.instantiateInitialViewController()
if let nav = navJira {
self.present(nav, animated: true, completion: nil)
}
}
}
extension ViewController {
func getIssueStatusTypes() {
GetIssueStatusTypesAPIManager.getIssueStatusTypes(userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (details, error) in
debugPrint("details: \(details)")
if let data = details {
let predicate:NSPredicate = NSPredicate(format:"statusId == \"10001\"")
let subPredicate = [predicate]
let finalPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: subPredicate)
let filteredArray = (data as NSArray).filtered(using: finalPredicate) as! [IssueStatus]
print(filteredArray)
var issue = filteredArray[0] as IssueStatus
print(issue.name)
print(issue.statusId)
}
}
}
func getIssueDetails() {
IssueDetailsApiManager.getIssueDetails(issueId: "QAH1-2", userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (details, error) in
debugPrint("details: \(details)")
debugPrint("error: \(error)")
debugPrint("detailsComment: \(details?.fields?.issueComment?.comments?[1].body)")
}
}
func createIssue() {
CreateIssueAPIManager.createIssue(userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password, issueTypeId: "", summary: "1 Test summary 1", description: "1 Test description 1", assigneeName: "admin") { (details, error) in
debugPrint("details: \(details)")
debugPrint("error: \(error)")
}
}
func getIssueTypes() {
GetIssueTypesAPIManager.getIssueTypes(userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (details, error) in
debugPrint("details: \(details)")
if let data = details {
let predicate:NSPredicate = NSPredicate(format:"issueName == \"Bug\"")
let subPredicate = [predicate]
let finalPredicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: subPredicate)
let filteredArray = (data as NSArray).filtered(using: finalPredicate) as! [IssueType]
print(filteredArray)
var issue = filteredArray[0] as IssueType
print(issue.issueName)
print(issue.issueid)
}
debugPrint("error: \(error)")
}
}
func addCommentToIssue() {
AddCommentApiManager.addComment(comment: "Test Comment chumma", ToIssue: "QAH1-1", userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (comment, error) in
debugPrint("comment: \(comment)")
debugPrint("comment: \(comment?.body)")
}
}
func addAttachmentAndCommentToIssue() {
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
debugPrint("docDir: \(docDir)")
//TODO: - TEST_MODE
let path = docDir! + "/sambu.png" // 'sambu.png' will be the name for image there, so the name should be 'screenshot-2016-11-23 18:14:52.png'[sample name] while saving in our directory
let fileUrl = URL.init(fileURLWithPath: path)
//TODO: - TEST_MODE
AddAttachmentApiManger.addAttachment(fileUrl, issueId: "QAH1-5", userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (response, error) in
if let error = error {
debugPrint("Error: \(error)")
} else {
debugPrint("Attachment and comment succesfully added")
}
}
}
func updateAssignee(){
//TODO: - TEST_MODE
//note: "newAssigneeName" is not "email" or "displayName", its "name"
//TODO: - TEST_MODE
EditIssueApiManager.updateAssignee(newAssigneeName: "sarath", ToIssue: "QAH1-1", userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (editResp, error) in
if let error = error {
debugPrint("error: \(error)")
} else {
debugPrint("response: \(editResp?.isSuccess)")
}
}
}
func getStatusTypes() {
GetStatusTypesApiManager.getStatusTypesForProject(projectId: "10000", userName: JiraAccountDetails.sharedInstance.username, password: JiraAccountDetails.sharedInstance.password) { (resp, error) in
if let err = error {
debugPrint("err: \(err)");
} else {
debugPrint("resp: \(resp)");
}
}
}
}
| 40.006944 | 277 | 0.637042 |
9b8130ec7bbd6d54a856fb8a737b598dbe7ea5b8 | 2,516 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2019 ShopGun. All rights reserved.
import ShopGunSDK
import Incito
import CoreLocation
class PublicationListViewController: UIViewController {
var contentVC: UIViewController? = nil {
didSet {
self.cycleFromViewController(
oldViewController: oldValue,
toViewController: contentVC
)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "ShopGunSDK Demo"
// Show the loading spinner
self.contentVC = LoadingViewController()
// Build the request we wish to send to the coreAPI
let location = CoreAPI.Requests.LocationQuery(coordinate: CLLocationCoordinate2D(latitude:55.631090, longitude: 12.577236), radius: nil)
let publicationReq = CoreAPI.Requests.getPublications(near: location, sortedBy: .newestPublished)
// Perform the request
CoreAPI.shared.request(publicationReq) { [weak self] result in
// Show different contents depending upon the result of the request
switch result {
case let .success(publications):
self?.contentVC = PublicationListContentsViewController(
publications: publications,
shouldOpenIncito: { [weak self] in self?.openIncito(for: $0) },
shouldOpenPagedPub: { [weak self] in self?.openPagedPub(for: $0) }
)
case let .failure(error):
self?.contentVC = ErrorViewController(error: error)
}
}
}
func openIncito(for publication: CoreAPI.PagedPublication) {
// Create an instance of `IncitoLoaderViewController`
let incitoVC = DemoIncitoViewController()
incitoVC.load(publication: publication)
self.navigationController?.pushViewController(incitoVC, animated: true)
}
func openPagedPub(for publication: CoreAPI.PagedPublication) {
// Create a view controller containing a `PagedPublicationView`
let pagedPubVC = DemoPagedPublicationViewController()
pagedPubVC.load(publication: publication)
self.navigationController?.pushViewController(pagedPubVC, animated: true)
}
}
| 34 | 144 | 0.581876 |
fcb70698be636390a1049d66cf27a1c03b3a3f88 | 678 | // Copyright (c) 2018-2020 XMLCoder contributors
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
//
// Created by Vincent Esche on 12/22/18.
//
class SharedBox<Unboxed: Box> {
private(set) var unboxed: Unboxed
init(_ wrapped: Unboxed) {
unboxed = wrapped
}
func withShared<T>(_ body: (inout Unboxed) throws -> T) rethrows -> T {
try body(&unboxed)
}
}
extension SharedBox: Box {
var isNull: Bool {
unboxed.isNull
}
var xmlString: String? {
unboxed.xmlString
}
}
extension SharedBox: SharedBoxProtocol {
func unbox() -> Unboxed {
unboxed
}
}
| 18.833333 | 75 | 0.620944 |
d6ca0c981a1e5e3576c2ef71eec1590e000319ee | 1,320 | //
// Configs.swift
// SwiftMVVMTemplate
//
// Created by m2 on 1/14/21.
//
import UIKit
// All keys are demonstrative and used for the test.
enum Keys {
case github, mixpanel, adMob
var apiKey: String {
switch self {
default: return ""
}
}
var appId: String {
switch self {
default: return ""
}
}
}
struct Configs {
static let bundleIdentifier = "org.m294"
struct App {
static let bundleIdentifier = ""
}
struct BaseDimensions {
static let inset: CGFloat = 8
static let tabBarHeight: CGFloat = 58
static let toolBarHeight: CGFloat = 66
static let navBarWithStatusBarHeight: CGFloat = 64
static let cornerRadius: CGFloat = 5
static let borderWidth: CGFloat = 1
static let buttonHeight: CGFloat = 40
static let textFieldHeight: CGFloat = 40
static let tableRowHeight: CGFloat = 36
static let segmentedControlHeight: CGFloat = 40
}
struct Path {
static let Documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
static let Tmp = NSTemporaryDirectory()
}
struct UserDefaultsKeys {
}
struct Network {
}
}
| 21.639344 | 112 | 0.596212 |
ef2e44f511af3dc05d4ff3f53e6d957364a1afb7 | 2,196 | // Copyright 2020, OpenTelemetry Authors
//
// 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 OpenTelemetryApi
@testable import OpenTelemetrySdk
import XCTest
class CorrelationContextManagerSdkTests: XCTestCase {
let correlationContext = CorrelationContextMock()
let contextManager = CorrelationContextManagerSdk()
func testGetCurrentContext_DefaultContext() {
XCTAssertTrue(contextManager.getCurrentContext() === EmptyCorrelationContext.instance)
}
func testWithCorrelationContext() {
XCTAssertTrue(contextManager.getCurrentContext() === EmptyCorrelationContext.instance)
var wtm = contextManager.withContext(correlationContext: correlationContext)
XCTAssertTrue(contextManager.getCurrentContext() === correlationContext)
wtm.close()
XCTAssertTrue(contextManager.getCurrentContext() === EmptyCorrelationContext.instance)
}
func testWithCorrelationContextUsingWrap() {
let expec = expectation(description: "testWithCorrelationContextUsingWrap")
var wtm = contextManager.withContext(correlationContext: correlationContext)
XCTAssertTrue(contextManager.getCurrentContext() === correlationContext)
let semaphore = DispatchSemaphore(value: 0)
DispatchQueue.global().async {
semaphore.wait()
XCTAssertTrue(self.contextManager.getCurrentContext() === self.correlationContext)
expec.fulfill()
}
wtm.close()
semaphore.signal()
waitForExpectations(timeout: 30) { error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
}
| 39.927273 | 94 | 0.717668 |
4af51aa4105e8ce35a7b764de0dd2eb638a32d06 | 929 | //
// NetMacTests.swift
// BluJTests
//
// Created by Lavergne, Marc on 3/27/20.
// Copyright © 2020 Lavergne, Marc. All rights reserved.
//
import XCTest
@testable import BluJ
class NetMacTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testGetRoutes() {
print(NetworkMac.getRoutes())
}
func testGetLANRoutes() {
print(NetworkMac.getLANRoutes())
}
func testGetDefaultLANRoute() {
print(NetworkMac.getDefaultLANRoute())
}
func testGetDefaultRoute() {
print(NetworkMac.getDefaultRoute())
}
func testGetRoute() {
print(NetworkMac.getRoute("192.168.1.238"))
}
}
| 22.119048 | 111 | 0.642626 |
8f4a7bb198416c8deb2280305ecd8f0e9ca5eb0b | 5,245 | //
// NavigationViewController.swift
// tesla
//
// Created by Rex Sheng on 4/25/16.
// Copyright © 2016 Interactive Labs. All rights reserved.
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
/**
intergration steps:
1. drag a view controller into storyboard set its class to NavigationViewController
2. create your navigationbar class, accept NavigationBarProtocol
3. drag a view into your controller, and set it class to your navigationbar class, connect it to navigationBar outlet
4. create a custom segue to your root view controller, select 'root view controller relationship', name it 'root'
*/
public protocol NavigationBarProtocol {
var titleLabel: UILabel! {get set}
var backButton: UIButton! {get set}
var rightToolbar: UIToolbar! {get set}
var navigationItem: UINavigationItem? {get set}
}
open class RootViewControllerRelationshipSegue: UIStoryboardSegue {
override open func perform() {
guard let source = source as? NavigationViewController else {
return
}
source.childNavigationController?.viewControllers = [destination]
}
}
public protocol NavigationBackProxy {
func navigateBack(_ next: () ->())
}
public protocol Navigation {
var hidesNavigationBarWhenPushed: Bool {get}
}
open class NavigationViewController: UIViewController, UINavigationControllerDelegate {
@IBOutlet weak var navigationBar: UIView! {
didSet {
if let bar = navigationBar as? NavigationBarProtocol {
self.bar = bar
}
}
}
var bar: NavigationBarProtocol?
weak var childNavigationController: UINavigationController?
fileprivate func reattach() {
navigationBar.removeFromSuperview()
view.addSubview(navigationBar)
navigationBar.translatesAutoresizingMaskIntoConstraints = false
}
override open func viewDidLoad() {
super.viewDidLoad()
reattach()
bar?.backButton.addTarget(self, action: #selector(navigateBack(_:)), for: .touchUpInside)
let childNavigationController = UINavigationController()
childNavigationController.isNavigationBarHidden = true
childNavigationController.delegate = self
self.childNavigationController = childNavigationController
addChildViewController(childNavigationController)
let container = childNavigationController.view
container?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(container!)
//H
view.addConstraint(NSLayoutConstraint(item: navigationBar, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: navigationBar, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: container, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: container, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
//V
view.addConstraint(NSLayoutConstraint(item: navigationBar, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: navigationBar, attribute: .bottom, relatedBy: .equal, toItem: container, attribute: .top, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: container, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0))
performSegue(withIdentifier: "root", sender: nil)
}
@IBAction func navigateBack(_ sender: Any) {
if let proxy = childNavigationController?.topViewController as? NavigationBackProxy {
proxy.navigateBack {[weak self] in
let _ = self?.childNavigationController?.popViewController(animated: true)
}
} else {
let _ = childNavigationController?.popViewController(animated: true)
}
}
open func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let showBackButton = childNavigationController?.viewControllers.count > 1
var hides = false
if let customNav = viewController as? Navigation {
hides = customNav.hidesNavigationBarWhenPushed
}
UIView.animate(withDuration: animated ? 0.25 : 0, animations: {
self.navigationBar.alpha = hides ? 0 : 1
self.bar?.navigationItem = viewController.navigationItem
self.bar?.backButton.alpha = showBackButton ? 1 : 0
})
}
}
| 40.346154 | 174 | 0.686749 |
4a4aaad7eba433e84eec8adf6abf11b2a71f2207 | 2,172 | #!/usr/bin/env swift
import Foundation
var program = ""
if CommandLine.argc > 1 {
do {
program = try String(contentsOfFile: CommandLine.arguments[1])
} catch let error as NSError {
let msg = "\(CommandLine.arguments[1]): \(error.localizedDescription)\n"
FileHandle.standardError
.write(msg.data(using: .utf8)!)
exit(1)
}
} else {
while let line = readLine() {
program.append(line)
}
}
program = program.filter("><+-.,[]".contains)
var jumps = Array(repeating: 0, count: program.count)
var stack: [Int] = []
for (i, c) in program.enumerated() {
if c == "[" {
stack.append(i)
} else if c == "]" {
if stack.count == 0 {
FileHandle.standardError
.write("error: extraneous ']'\n".data(using: .utf8)!)
exit(1)
}
let j = stack.removeLast()
jumps[i] = j
jumps[j] = i
}
}
if stack.count > 0 {
FileHandle.standardError
.write("error: expected ']'\n".data(using: .utf8)!)
exit(1)
}
let len = program.count
var i = 0
var line = ""
var ptr = 0
var tape = Array(repeating: 0, count: 65536)
while (i < len) {
let c = program[program.index(program.startIndex, offsetBy: i)]
if c == ">" {
ptr = (ptr + 1) & 65535
} else if c == "<" {
ptr = (ptr - 1) & 65535
} else if c == "+" {
tape[ptr] = (tape[ptr] + 1) & 255
} else if c == "-" {
tape[ptr] = (tape[ptr] - 1) & 255
} else if c == "." {
print(Character(UnicodeScalar(tape[ptr])!), terminator: "")
} else if c == "," {
if line.count == 0 {
let input = readLine(strippingNewline: false)
if input != nil {
line = input!
}
}
if line.count > 0 {
tape[ptr] = Int(UnicodeScalar(String(line
.remove(at: line.startIndex)))!.value)
}
} else if c == "[" {
if tape[ptr] == 0 {
i = jumps[i]
}
} else if c == "]" {
if tape[ptr] != 0 {
i = jumps[i]
}
}
i += 1
}
| 21.939394 | 80 | 0.479282 |
1cb128db2720a185773c8f8a2da18aa94e7d7271 | 673 | import XCTest
@testable import Notes
class NotesTests84: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func NotesUnitTest() {
XCTAssertEqual("/v2/top-picks/rate", "/v2/top-picks/rate")
XCTAssertEqual("super", "super")
XCTAssertEqual("123", "123")
XCTAssertEqual("1", "1")
if false {
XCTAssertEqual("-420", "-420")
} else {
XCTAssertEqual("-480", "-480")
}
XCTAssertEqual("xxx", "xxx")
XCTAssertEqual("xxx", "xxx")
XCTAssertNotNil("xxx")
}
}
| 24.925926 | 67 | 0.514116 |
5055b4a0b565436f82c13fae9bf9efd4efa93114 | 453 | //
// FeedWranglerAuthorizationResult.swift
// Account
//
// Created by Jonathan Bennett on 2019-11-20.
// Copyright © 2019 Ranchero Software, LLC. All rights reserved.
//
import Foundation
struct FeedWranglerAuthorizationResult: Hashable, Codable {
let accessToken: String?
let error: String?
let result: String
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case error = "error"
case result = "result"
}
}
| 18.875 | 65 | 0.726269 |
bf438f7d4593c8347b26c229ee798105d494f1a8 | 3,506 | //
// NumericTypeTests.swift
// SwiftAA
//
// Created by Alexander Vasenin on 03/01/2017.
// Copyright © 2017 onekiloparsec. All rights reserved.
//
import XCTest
@testable import SwiftAA
class NumericTypeTests: XCTestCase {
func testCircularInterval() {
XCTAssertTrue(Degree(15).isWithinCircularInterval(from: 10, to: 20))
XCTAssertFalse(Degree(55).isWithinCircularInterval(from: 10, to: 20))
XCTAssertFalse(Degree(10).isWithinCircularInterval(from: 10, to: 20, isIntervalOpen: true))
XCTAssertTrue(Degree(15).isWithinCircularInterval(from: 10, to: 20, isIntervalOpen: false))
XCTAssertTrue(Degree(10).isWithinCircularInterval(from: 340, to: 20))
XCTAssertTrue(Degree(350).isWithinCircularInterval(from: 340, to: 20))
XCTAssertFalse(Degree(340).isWithinCircularInterval(from: 340, to: 20, isIntervalOpen: true))
XCTAssertTrue(Degree(340).isWithinCircularInterval(from: 340, to: 20, isIntervalOpen: false))
}
func testRoundingToIncrement() {
let accuracy = Second(1e-3).inJulianDays
let jd = JulianDay(year: 2017, month: 1, day: 9, hour: 13, minute: 53, second: 39.87)
AssertEqual(jd.rounded(toIncrement: Minute(1).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 13, minute: 54), accuracy: accuracy)
AssertEqual(jd.rounded(toIncrement: Minute(15).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 14), accuracy: accuracy)
AssertEqual(jd.rounded(toIncrement: Hour(3).inJulianDays), JulianDay(year: 2017, month: 1, day: 9, hour: 15), accuracy: accuracy)
}
func testConstructors() {
// Damn one needs to do to increase UT coverage...
AssertEqual(1.234.degrees, Degree(1.234))
AssertEqual(-1.234.degrees, Degree(-1.234))
AssertEqual(1.234.arcminutes, ArcMinute(1.234))
AssertEqual(-1.234.arcminutes, ArcMinute(-1.234))
AssertEqual(1.234.arcseconds, ArcSecond(1.234))
AssertEqual(-1.234.arcseconds, ArcSecond(-1.234))
AssertEqual(1.234.hours, Hour(1.234))
AssertEqual(-1.234.hours, Hour(-1.234))
AssertEqual(1.234.minutes, Minute(1.234))
AssertEqual(-1.234.minutes, Minute(-1.234))
AssertEqual(1.234.seconds, Second(1.234))
AssertEqual(-1.234.seconds, Second(-1.234))
AssertEqual(1.234.radians, Radian(1.234))
AssertEqual(-1.234.radians, Radian(-1.234))
AssertEqual(1.234.days, Day(1.234))
AssertEqual(-1.234.days, Day(-1.234))
AssertEqual(1.234.julianDays, JulianDay(1.234))
AssertEqual(-1.234.julianDays, JulianDay(-1.234))
let s1 = 1.234.sexagesimal
XCTAssertEqual(s1.sign, .plus)
XCTAssertEqual(s1.radical, 1)
XCTAssertEqual(s1.minute, 14)
XCTAssertEqualWithAccuracy(s1.second, 2.4, accuracy: 0.000000001) // rounding error...
XCTAssertEqual(1.234.sexagesimalShortString, "+01:14:02.4")
// One needs a true sexagesimal library...
// let s2 = -1.234.sexagesimal
// let s3 = -0.123.sexagesimal
// XCTAssertEqual(s2.sign, .minus)
// XCTAssertEqual(s2.radical, -1)
// XCTAssertEqual(s2.minute, 2)
// XCTAssertEqual(s2.second, 3.4)
//
// XCTAssertEqual(s3.sign, .minus)
// XCTAssertEqual(s3.radical, 0)
// XCTAssertEqual(s3.minute, 1)
// XCTAssertEqual(s3.second, 2.3)
// XCTAssertEqual(-1.234.sexagesimalShortString, "")
}
}
| 39.393258 | 151 | 0.654307 |
f803a002dcf19b5e0ea1c62dac6df482af4f07b9 | 3,747 | //
// WeatherDataManager.swift
// Weather++
//
// Created by Rohan Patel on 7/24/19.
// Copyright © 2019 Rohan Patel. All rights reserved.
//
import Foundation
/* A helper class to facilitate parsing of API response and storing data into model object */
class WeatherDataManager {
class func getLatestWeatherData(completion: @escaping () -> ()){
let lat = UserDefaults.standard.double(forKey: "latitude")
let long = UserDefaults.standard.double(forKey: "longitude")
WebServiceManager.fetchWeatherDataForLocation(latitude: lat,
longitude: long,
success: { (response) in
if let value = response as? [String : Any]{
let currentWeather = CurrentWeather()
if let currently = value["currently"] as? [String: Any]{
currentWeather.apparentTemperature = currently["apparentTemperature"] as? Double
currentWeather.currentSummary = currently["summary"] as? String
currentWeather.humidity = currently["humidity"] as? Double
currentWeather.icon = currently["icon"] as? String
currentWeather.temperature = currently["temperature"] as? Double
currentWeather.time = convertTime(time: currently["time"] as? Double)
currentWeather.uvIndex = currently["uvIndex"] as? Double
currentWeather.visibility = currently["visibility"] as? Double
}
if let minutely = value["minutely"] as? [String: Any]{
currentWeather.minutelySummary = minutely["summary"] as? String
}
ResourceManager.sharedManager.currentWeather = currentWeather
completion()
}
}) { (error) in
}
}
/**
* Type fucntion to convert the UNIX time into human readable format.
*
* @param time A double type value containing UNIX time
*
* @return A string representing the time
*/
class func convertTime(time : Double?) -> String {
if let time = time{
let date = Date(timeIntervalSince1970: time)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.short //Set time style
let localDate = dateFormatter.string(from: date)
return localDate
}
else{
return "time not available"
}
}
}
| 49.96 | 144 | 0.396584 |
d56e4249cc54db60dba0a1584104426fd7bfd504 | 1,867 | //
// UserLocation.swift
// morurun
//
// Created by watanabe on 2016/11/08.
// Copyright © 2016年 Crypton Future Media, INC. All rights reserved.
//
import Foundation
import MapKit
import RxSwift
import RxCocoa
class UserLocation: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
let currentLocation = Variable<CLLocation?>(nil)
let isInMuroran = Variable<Bool>(false)
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 10_000 // 10km
}
func startTracking() {
self.locationManager.startUpdatingLocation()
}
// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse:
manager.startUpdatingLocation()
case .denied: break
// TODO:
default: break
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// TODO:
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// manager.stopUpdatingLocation()
self.currentLocation.value = locations.first
CLGeocoder().reverseGeocodeLocation(locations.last!) {placemarks, error in
guard let placemarkLocality = placemarks?.last?.locality as NSString? else { return }
let inMuroran = placemarkLocality.contains("室蘭") || placemarkLocality.lowercased.contains("muroran")
self.isInMuroran.value = inMuroran
}
}
}
| 31.644068 | 112 | 0.670059 |
3a00380a1cc843df5da005a7ab062cf3d2df1425 | 976 | //
// json-functions-swift
//
//
// Copyright (c) 2022 SAP SE or an SAP affiliate company
//
import Foundation
struct ArrayFind: Expression {
let expression: Expression
func eval(with data: inout JSON) throws -> JSON {
guard let array = self.expression as? ArrayOfExpressions,
array.expressions.count >= 2,
case let .Array(dataArray) = try array.expressions[0].eval(with: &data)
else {
return .Null
}
let findOperation = array.expressions[1]
if let elementKey = try array.expressions[safe: 2]?.eval(with: &data).string, data.type == .object {
return try dataArray.first {
data[elementKey] = $0
return try findOperation.eval(with: &data).truthy()
} ?? .Null
} else {
return try dataArray.first {
return try findOperation.eval(with: $0).truthy()
} ?? .Null
}
}
}
| 26.378378 | 108 | 0.5625 |
1cd95b082ae9e4e041bf3015414daf79f7068d37 | 3,108 | //
// ExampleCoachMarksViewController.swift
// DARCoachMarksExample
//
// Created by Apple on 2/16/18.
// Copyright © 2018 DAR. All rights reserved.
//
import UIKit
class ExampleCoachMarksViewController: DARCoachMarksViewController {
override var dimmerGradientColors: [UIColor] {
return [
UIColor(red: 0/255, green: 5/255, blue: 50/255, alpha: 0.85),
UIColor(red: 0/255, green: 123/255, blue: 131/255, alpha: 0.85)
]
}
override var accentColor: UIColor {
return UIColor(red: 52/255, green: 161/255, blue: 242/255, alpha: 1)
}
override func numberOfSteps() -> Int {
return 4
}
override func stepAt(number: Int) -> DARCoachMarkConfig {
let step = DARCoachMarkConfig()
switch number {
case 0:
step.text = "DAR Play — это не обычное развлекательное приложение, это образ жизни."
step.highlightFrame = CGRect(x: view.frame.width/2 - 164, y: 173, width: 110, height: 110)
step.highlightCornerRadius = 15
step.hintBottom = 100
step.arrowStartPoint = CGPoint(x: view.frame.width/2, y: 510)
step.arrowControlPoint = CGPoint(x: view.frame.width/2 + 50, y: 173 + 110/2)
step.arrowEndPoint = CGPoint(x: view.frame.width/2-50, y: 173 + 110/2)
break
case 1:
step.text = "DAR Bazar — новая платформа сделает онлайн-торговлю невообразимо легкой для всех."
step.highlightFrame = CGRect(x: view.frame.width/2 + 60, y: 173, width: 110, height: 110)
step.highlightCornerRadius = 15
step.hintBottom = 100
step.arrowStartPoint = CGPoint(x: view.frame.width/2, y: 510)
step.arrowControlPoint = CGPoint(x: view.frame.width/2 - 50, y: 173 + 110/2)
step.arrowEndPoint = CGPoint(x: view.frame.width/2+50, y: 173 + 110/2)
break
case 2:
step.text = "DAR VIS — это новый взгляд на оплату сервисов и перевод денег."
step.highlightFrame = CGRect(x: view.frame.width/2 - 164, y: 353, width: 110, height: 110)
step.highlightCornerRadius = 15
step.hintBottom = 100
step.arrowStartPoint = CGPoint(x: view.frame.width/2, y: 530)
step.arrowControlPoint = CGPoint(x: view.frame.width/2, y: 353 + 110/2)
step.arrowEndPoint = CGPoint(x: view.frame.width/2-50, y: 353 + 110/2)
break
case 3:
step.text = "DAR Business — инструмент для успешного ведения бизнеса."
step.highlightFrame = CGRect(x: view.frame.width/2 + 60, y: 353, width: 110, height: 110)
step.highlightCornerRadius = 15
step.hintBottom = 100
step.arrowStartPoint = CGPoint(x: view.frame.width/2, y: 530)
step.arrowControlPoint = CGPoint(x: view.frame.width/2, y: 353 + 110/2)
step.arrowEndPoint = CGPoint(x: view.frame.width/2+50, y: 353 + 110/2)
break
default:
return step
}
return step
}
}
| 41.44 | 107 | 0.59556 |
721fa075c243017c8fa2cf9bc87a8479826690cb | 2,982 | //
// UIView+Extension.swift
// Genius
//
// Created by 黄进文 on 2017/1/11.
// Copyright © 2017年 evenCoder. All rights reserved.
//
import UIKit
extension UIView {
public var x: CGFloat{
get{
return self.frame.origin.x
}
set{
var f = self.frame
f.origin.x = newValue
self.frame = f
}
}
public var y: CGFloat{
get{
return self.frame.origin.y
}
set{
var f = self.frame
f.origin.y = newValue
self.frame = f
}
}
public var top: CGFloat{
get {
return self.frame.origin.y
}
set{
var f = self.frame
f.origin.y = newValue
self.frame = f
}
}
public var bottom: CGFloat{
get {
return self.frame.origin.y + self.frame.size.height
}
set{
var f = self.frame
f.origin.y = newValue - self.frame.size.height
self.frame = f
}
}
public var left: CGFloat {
get {
return self.frame.origin.x
}
set {
var f = self.frame
f.origin.x = newValue
self.frame = f
}
}
public var right: CGFloat {
get {
return self.frame.origin.x + self.frame.size.width
}
set {
var f = self.frame
f.origin.x = newValue - self.frame.size.width
self.frame = f
}
}
public var width: CGFloat{
get {
return self.frame.size.width
}
set{
var r = self.frame
r.size.width = newValue
self.frame = r
}
}
public var height: CGFloat{
get {
return self.frame.size.height
}
set{
var r = self.frame
r.size.height = newValue
self.frame = r
}
}
public var centerX: CGFloat {
get {
return self.center.x
}
set {
var center = self.center
center.x = newValue
self.center = center
}
}
public var centerY: CGFloat {
get {
return self.center.y
}
set {
var center = self.center
center.y = newValue
self.center = center
}
}
public var size: CGSize {
get {
return self.frame.size
}
set {
var s = self.frame.size
s = newValue
self.frame.size = s
}
}
}
| 18.182927 | 63 | 0.391683 |
db6a3993793eb3e8a6754d9f6d91bfd2b3e1d217 | 10,852 | import XCTest
@testable import Apollo
import ApolloTestSupport
import StarWarsAPI
class WatchQueryTests: XCTestCase {
func testRefetchWatchedQuery() throws {
let query = HeroNameQuery()
let initialRecords: RecordSet = [
"QUERY_ROOT": ["hero": Reference(key: "hero")],
"hero": [
"name": "R2-D2",
"__typename": "Droid",
]
]
withCache(initialRecords: initialRecords) { (cache) in
let networkTransport = MockNetworkTransport(body: [
"data": [
"hero": [
"name": "Artoo",
"__typename": "Droid"
]
]
])
let store = ApolloStore(cache: cache)
let client = ApolloClient(networkTransport: networkTransport, store: store)
var verifyResult: OperationResultHandler<HeroNameQuery>
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
XCTAssertEqual(result?.data?.hero?.name, "R2-D2")
}
var expectation = self.expectation(description: "Fetching query")
let watcher = client.watch(query: query) { (result, error) in
verifyResult(result, error)
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
XCTAssertEqual(result?.data?.hero?.name, "Artoo")
}
expectation = self.expectation(description: "Refetching query")
watcher.refetch()
waitForExpectations(timeout: 5, handler: nil)
}
}
func testWatchedQueryGetsUpdatedWithResultFromOtherQuery() throws {
let initialRecords: RecordSet = [
"QUERY_ROOT": ["hero": Reference(key: "QUERY_ROOT.hero")],
"QUERY_ROOT.hero": [
"name": "R2-D2",
"__typename": "Droid",
"friends": [
Reference(key: "QUERY_ROOT.hero.friends.0"),
Reference(key: "QUERY_ROOT.hero.friends.1"),
Reference(key: "QUERY_ROOT.hero.friends.2")
]
],
"QUERY_ROOT.hero.friends.0": ["__typename": "Human", "name": "Luke Skywalker"],
"QUERY_ROOT.hero.friends.1": ["__typename": "Human", "name": "Han Solo"],
"QUERY_ROOT.hero.friends.2": ["__typename": "Human", "name": "Leia Organa"],
]
withCache(initialRecords: initialRecords) { (cache) in
let networkTransport = MockNetworkTransport(body: [
"data": [
"hero": [
"name": "Artoo",
"__typename": "Droid"
]
]
])
let store = ApolloStore(cache: cache)
let client = ApolloClient(networkTransport: networkTransport, store: store)
let query = HeroAndFriendsNamesQuery()
var verifyResult: OperationResultHandler<HeroAndFriendsNamesQuery>
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
guard let data = result?.data else { XCTFail(); return }
XCTAssertEqual(data.hero?.name, "R2-D2")
let friendsNames = data.hero?.friends?.flatMap { $0?.name }
XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"])
}
var expectation = self.expectation(description: "Fetching query")
_ = client.watch(query: query) { (result, error) in
verifyResult(result, error)
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
guard let data = result?.data else { XCTFail(); return }
XCTAssertEqual(data.hero?.name, "Artoo")
let friendsNames = data.hero?.friends?.flatMap { $0?.name }
XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"])
}
expectation = self.expectation(description: "Updated after fetching other query")
client.fetch(query: HeroNameQuery(), cachePolicy: .fetchIgnoringCacheData)
waitForExpectations(timeout: 5, handler: nil)
}
}
func testWatchedQueryDoesNotRefetchAfterUnrelatedQuery() throws {
let initialRecords: RecordSet = [
"QUERY_ROOT": ["hero": Reference(key: "QUERY_ROOT.hero")],
"QUERY_ROOT.hero": [
"name": "R2-D2",
"__typename": "Droid",
"friends": [
Reference(key: "QUERY_ROOT.hero.friends.0"),
Reference(key: "QUERY_ROOT.hero.friends.1"),
Reference(key: "QUERY_ROOT.hero.friends.2")
]
],
"QUERY_ROOT.hero.friends.0": ["__typename": "Human", "name": "Luke Skywalker"],
"QUERY_ROOT.hero.friends.1": ["__typename": "Human", "name": "Han Solo"],
"QUERY_ROOT.hero.friends.2": ["__typename": "Human", "name": "Leia Organa"],
]
withCache(initialRecords: initialRecords) { (cache) in
let networkTransport = MockNetworkTransport(body: [
"data": [
"hero": [
"name": "Artoo",
"__typename": "Droid"
]
]
])
let store = ApolloStore(cache: cache)
let client = ApolloClient(networkTransport: networkTransport, store: store)
let query = HeroAndFriendsNamesQuery()
var verifyResult: OperationResultHandler<HeroAndFriendsNamesQuery>
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
guard let data = result?.data else { XCTFail(); return }
XCTAssertEqual(data.hero?.name, "R2-D2")
let friendsNames = data.hero?.friends?.flatMap { $0?.name }
XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"])
}
let expectation = self.expectation(description: "Fetching query")
_ = client.watch(query: query) { (result, error) in
verifyResult(result, error)
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
verifyResult = { (result, error) in
XCTFail()
}
client.fetch(query: HeroNameQuery(episode: .empire), cachePolicy: .fetchIgnoringCacheData)
waitFor(timeInterval: 1.0)
}
}
func testWatchedQueryWithID() throws {
let query = HeroNameWithIdQuery()
let initialRecords: RecordSet = [
"QUERY_ROOT": ["hero": Reference(key: "2001")],
"2001": [
"id": "2001",
"name": "R2-D2",
"__typename": "Droid",
]
]
withCache(initialRecords: initialRecords) { (cache) in
let networkTransport = MockNetworkTransport(body: [
"data": [
"hero": [
"id": "2001",
"name": "Luke Skywalker",
"__typename": "Human"
]
]
])
let store = ApolloStore(cache: cache)
let client = ApolloClient(networkTransport: networkTransport, store: store)
client.store.cacheKeyForObject = { $0["id"] }
var verifyResult: OperationResultHandler<HeroNameWithIdQuery>
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
XCTAssertEqual(result?.data?.hero?.name, "R2-D2")
}
var expectation = self.expectation(description: "Fetching query")
_ = client.watch(query: query) { (result, error) in
verifyResult(result, error)
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
XCTAssertEqual(result?.data?.hero?.name, "Luke Skywalker")
}
expectation = self.expectation(description: "Fetching other query")
client.fetch(query: HeroNameWithIdQuery(), cachePolicy: .fetchIgnoringCacheData)
waitForExpectations(timeout: 5, handler: nil)
}
}
func testWatchedQueryGetsUpdatedWithResultFromReadWriteTransaction() throws {
let initialRecords: RecordSet = [
"QUERY_ROOT": ["hero": Reference(key: "QUERY_ROOT.hero")],
"QUERY_ROOT.hero": [
"name": "R2-D2",
"__typename": "Droid",
"friends": [
Reference(key: "QUERY_ROOT.hero.friends.0"),
Reference(key: "QUERY_ROOT.hero.friends.1"),
Reference(key: "QUERY_ROOT.hero.friends.2")
]
],
"QUERY_ROOT.hero.friends.0": ["__typename": "Human", "name": "Luke Skywalker"],
"QUERY_ROOT.hero.friends.1": ["__typename": "Human", "name": "Han Solo"],
"QUERY_ROOT.hero.friends.2": ["__typename": "Human", "name": "Leia Organa"],
]
try withCache(initialRecords: initialRecords) { (cache) in
let networkTransport = MockNetworkTransport(body: [:])
let store = ApolloStore(cache: cache)
let client = ApolloClient(networkTransport: networkTransport, store: store)
let query = HeroAndFriendsNamesQuery()
var verifyResult: OperationResultHandler<HeroAndFriendsNamesQuery>
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
guard let data = result?.data else { XCTFail(); return }
XCTAssertEqual(data.hero?.name, "R2-D2")
let friendsNames = data.hero?.friends?.flatMap { $0?.name }
XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"])
}
var expectation = self.expectation(description: "Fetching query")
_ = client.watch(query: query) { (result, error) in
verifyResult(result, error)
expectation.fulfill()
}
waitForExpectations(timeout: 5, handler: nil)
let nameQuery = HeroNameQuery()
try await(store.withinReadWriteTransaction { transaction in
try transaction.update(query: nameQuery) { (data: inout HeroNameQuery.Data) in
data.hero?.name = "Artoo"
}
})
verifyResult = { (result, error) in
XCTAssertNil(error)
XCTAssertNil(result?.errors)
guard let data = result?.data else { XCTFail(); return }
XCTAssertEqual(data.hero?.name, "Artoo")
let friendsNames = data.hero?.friends?.flatMap { $0?.name }
XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"])
}
expectation = self.expectation(description: "Updated after fetching other query")
client.fetch(query: HeroNameQuery(), cachePolicy: .fetchIgnoringCacheData)
waitForExpectations(timeout: 5, handler: nil)
}
}
// TODO: Replace with .inverted on XCTestExpectation, which is new in Xcode 8.3
private func waitFor(timeInterval: TimeInterval) {
let untilDate = Date(timeIntervalSinceNow: timeInterval)
while untilDate.timeIntervalSinceNow > 0 {
RunLoop.current.run(mode: .defaultRunLoopMode, before: untilDate)
}
}
}
| 32.785498 | 96 | 0.614818 |
2194b80a06002edf6d23a9c7b6060d914d8df28e | 2,404 | import UIKit
var str = "Hello, playground"
//**************************数组******************************
var someInts = [Int]()
someInts.append(2)
someInts.append(3)
someInts.remove(at:0) // 下标
print(someInts)
// someInts = []// 置空 但是类型依然是 var someInts: [Int]
var repeatArray = Array(repeating:"重要的事情说三遍", count: 3)
print(repeatArray)
var combineArray = someInts + Array(repeating: 5, count: 3) // 数组合并前提类型一致
print(combineArray)
// 数组修改
if someInts.isEmpty {
print("这个数组是空的")
}
// 添加
someInts.append(33)
print(someInts)
someInts += [55] //运算符运算 只能是同种类型
print(someInts)
// 取值
someInts[0]
someInts[1...2]
// 遍历
for index in someInts {
print(index)
}
// enumerated 返回下标和值
for (index,value) in someInts.enumerated() {
print("下标是--\(index) \n value---\(value)")
}
//**************************集合******************************
var letters = Set<Character>() // 初始化 集合是无须的
letters.insert("a")
letters.insert("b")
letters.insert("c")
letters.insert("d")
print(letters)
// 遍历
for item in letters.sorted() { // 排序后遍历
print(item)
}
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 使用 union(_:)方法来创建一个包含两个合集所有值的新合集;
oddDigits.intersection(evenDigits).sorted()
// [] 使用 intersection(_:)方法来创建一个只包含两个合集共有值的新合集;
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9] 使用 subtracting(_:)方法来创建一个两个合集当中不包含某个合集值的新合集。
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9] 使用 symmetricDifference(_:)方法来创建一个只包含两个合集各自有的非共有值的新合集;
let houseAnimals: Set = ["?", "?"]
let farmAnimals: Set = ["?", "?", "?", "?", "?"]
let cityAnimals: Set = ["?", "?"]
houseAnimals.isSubset(of: farmAnimals)
// true 一个合集的所有值是被某合集包含
farmAnimals.isSuperset(of: houseAnimals)
// true 方法来确定一个合集是否包含某个合集的所有值;
farmAnimals.isDisjoint(with: cityAnimals)
// true isStrictSubset(of:) 或者 isStrictSuperset(of:)方法来确定是个合集是否为某一个合集的子集或者超集,但并不相等;
//**************************字典******************************
// 创建字典
var dict = [Int: String]() // key int Value为string
dict[1] = "HI"
print(dict)
// 修改
let oldvalue = dict.updateValue("你好", forKey: 1) // 返回j旧值
let oldvalue1 = dict.updateValue("你好啊", forKey: 2) //没有旧值返回nil
// 遍历
for (key,Value) in dict {
print("key====\(key) \n value======\(Value)")
}
let keys = dict.keys
| 20.201681 | 84 | 0.629784 |
e45e3ed32e3cd77b54267f5fba467ac8407ac144 | 6,445 | // Copyright © 2016 Robots and Pencils, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// Neither the name of the Robots and Pencils, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import Alamofire
/**
A simple logger that listens for NetworkService request/response events and logs the related information in a nicely formatted message for debugging.
*/
open class NetworkServiceLogger: NSObject {
/**
Use this instance for the simplest use case. For example, starting the logger can be as simple as:
```
NetworkServiceLogger.sharedInstance.start()
```
*/
open static let sharedInstance = NetworkServiceLogger()
/**
Set this option to include or exclude the request and response headers in the formatted log message. Defaults to false (forced to true when logging response errors).
*/
open var includeHeaders = false
/**
Set this option to include or exclude the request and response body in the formatted log message. Defaults to true (forced to true when logging response errors).
*/
open var includeBody = true
deinit {
stop()
}
/**
Starts observing and logging network service notifications.
*/
open func start() {
NotificationCenter.default.addObserver(self, selector: #selector(didRequest(_:)), name: NSNotification.Name(rawValue: NetworkService.Notifications.DidRequest), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceive(_:)), name: NSNotification.Name(rawValue: NetworkService.Notifications.DidReceive), object: nil)
}
/**
Stops observing and logging network service notifications.
*/
open func stop() {
NotificationCenter.default.removeObserver(self)
}
/**
Internal method for handling request notifications
*/
func didRequest(_ notification: Notification) {
guard let request = notification.info?.request else { return }
Log.info(request.debugDescription(headers: includeHeaders, body: includeBody))
}
/**
Internal method for handling response notifications
*/
func didReceive(_ notification: Notification) {
guard let response = notification.info?.response else { return }
switch response.result {
case .failure(let error):
Log.error(response.debugDescription(headers: includeHeaders, body: includeBody) + ": \(error)")
case .success:
Log.info(response.debugDescription(headers: includeHeaders, body: includeBody))
}
}
}
private extension Notification {
/**
Private convenience extension to make extracting the network info from the notification simple.
*/
var info: NetworkService.NotificationInfo? {
return userInfo?[NetworkService.NotificationInfoKey] as? NetworkService.NotificationInfo
}
}
private extension URLRequest {
/**
Private extension for formatting a request into a debug string.
- parameter headers: option to include request headers in the output
- parameter body: option to include the request body in the output
- returns: A formatted string representing the request
*/
func debugDescription(headers includeHeaders: Bool = false, body includeBody: Bool = false) -> String {
let method = httpMethod
let absoluteUrlString = url?.absoluteString ?? ""
var result = "\(method) \(absoluteUrlString)"
if includeHeaders {
let headers = allHTTPHeaderFields?.map { "\($0): \($1)" }
if let headers = headers {
result.append(":\n\(headers)\n")
}
}
if includeBody {
if let bodyData = httpBody,
let body = String(data: bodyData, encoding: String.Encoding.utf8) {
result.append("\n")
result.append(body)
}
}
return result
}
}
private extension DataResponse {
/**
Private extension for formatting a response into a debug string.
- parameter headers: option to include response headers in the output
- parameter body: option to include the response body in the output
- returns: A formatted string representing the response
*/
func debugDescription(headers includeHeaders: Bool = false, body includeBody: Bool = false) -> String {
let statusCode = HTTPStatusCode(intValue: response?.statusCode ?? 0)
let durationMillis = Int(timeline.totalDuration * 1000)
let url = request?.url?.absoluteString ?? ""
let status = statusCode.flatMap { "\($0.rawValue)" } ?? ""
var result = "[\(durationMillis)ms] \(status) \(url)"
if includeHeaders || statusCode?.isError == true {
let headers = response?.allHeaderFields.map { "\($0): \($1)" }
if let headers = headers {
result.append(":\n\(headers)\n")
}
}
if includeBody || statusCode?.isError == true {
if let bodyData = self.data,
let body = String(data: bodyData, encoding: String.Encoding.utf8) {
result.append("\n")
result.append(body)
}
}
return result
}
}
| 42.682119 | 464 | 0.670442 |
9b3066762df53b1abafc0665fba4eb2bda52dca9 | 791 | import XCTest
class BTThreeDSecureLookupResult_Tests: XCTestCase {
func testRequiresUserAuthentication_whenAcsUrlIsPresent_returnsTrue() {
let lookup = BTThreeDSecureLookupResult()
lookup.acsURL = URL(string: "http://example.com")
lookup.termURL = URL(string: "http://example.com")
lookup.md = "an-md"
lookup.paReq = "a-PAReq"
XCTAssertTrue(lookup.requiresUserAuthentication())
}
func testRequiresUserAuthentication_whenAcsUrlIsNotPresent_returnsFalse() {
let lookup = BTThreeDSecureLookupResult()
lookup.acsURL = nil
lookup.termURL = URL(string: "http://example.com")
lookup.md = "an-md"
lookup.paReq = "a-PAReq"
XCTAssertFalse(lookup.requiresUserAuthentication())
}
}
| 31.64 | 79 | 0.677623 |
64044c21ab3a0a52cf8f20e3ec6ffe6490a9f767 | 14,891 | //
// Copyright © 2019 Gnosis Ltd. All rights reserved.
//
import Foundation
public protocol ClientDelegate: class {
func client(_ client: Client, didConnect url: WCURL)
func client(_ client: Client, didFailToConnect url: WCURL)
func client(_ client: Client, didConnect session: Session)
func client(_ client: Client, didDisconnect session: Session)
func client(_ client: Client, didUpdate session: Session)
}
public class Client: WalletConnect {
public typealias RequestResponse = (Response) -> Void
private(set) weak var delegate: ClientDelegate?
private let dAppInfo: Session.DAppInfo
private var responses: Responses
public enum ClientError: Error {
case missingWalletInfoInSession
case sessionNotFound
}
public init(delegate: ClientDelegate, dAppInfo: Session.DAppInfo) {
self.delegate = delegate
self.dAppInfo = dAppInfo
responses = Responses(queue: DispatchQueue(label: "org.walletconnect.swift.client.pending"))
super.init()
}
/// Send request to wallet.
///
/// - Parameters:
/// - request: Request object.
/// - completion: RequestResponse completion.
/// - Throws: Client error.
public func send(_ request: Request, completion: RequestResponse?) throws {
guard let session = communicator.session(by: request.url) else {
throw ClientError.sessionNotFound
}
guard let walletInfo = session.walletInfo else {
throw ClientError.missingWalletInfoInSession
}
if let completion = completion, let requestID = request.internalID, requestID != .null {
responses.add(requestID: requestID, response: completion)
}
communicator.send(request, topic: walletInfo.peerId)
}
/// Send response to wallet.
///
/// - Parameter response: Response object.
/// - Throws: Client error.
public func send(_ response: Response) throws {
guard let session = communicator.session(by: response.url) else {
throw ClientError.sessionNotFound
}
guard let walletInfo = session.walletInfo else {
throw ClientError.missingWalletInfoInSession
}
communicator.send(response, topic: walletInfo.peerId)
}
/// Request to sign a message.
///
/// https://docs.walletconnect.org/json-rpc/ethereum#personal_sign
///
/// - Parameters:
/// - url: WalletConnect url object.
/// - message: String representing human readable message to sign.
/// - account: String representing Ethereum address.
/// - completion: Response with string representing signature, or error.
/// - Throws: client error.
public func personal_sign(url: WCURL,
message: String,
account: String,
completion: @escaping RequestResponse) throws {
let messageHex = message.data(using: .utf8)!.map { String(format: "%02x", $0) }.joined()
try sign(url: url, method: "personal_sign", param1: messageHex, param2: account, completion: completion)
}
/// Request to sign a message.
///
/// https://docs.walletconnect.org/json-rpc/ethereum#eth_sign
///
/// - Parameters:
/// - url: WalletConnect url object.
/// - account: String representing Ethereum address.
/// - message: String representin Data to sign.
/// - completion: Response with string representing signature, or error.
/// - Throws: client error.
public func eth_sign(url: WCURL,
account: String,
message: String,
completion: @escaping RequestResponse) throws {
try sign(url: url, method: "eth_sign", param1: account, param2: message, completion: completion)
}
/// Request to sign typed daya.
///
/// https://docs.walletconnect.org/json-rpc/ethereum#eth_signtypeddata
///
/// - Parameters:
/// - url: WalletConnect url object.
/// - account: String representing Ethereum address.
/// - message: String representin Data to sign.
/// - completion: Response with string representing signature, or error.
/// - Throws: client error.
public func eth_signTypedData(url: WCURL,
account: String,
message: String,
completion: @escaping RequestResponse) throws {
try sign(url: url, method: "eth_signTypedData", param1: account, param2: message, completion: completion)
}
private func sign(url: WCURL,
method: String,
param1: String,
param2: String,
completion: @escaping RequestResponse) throws {
let request = try Request(url: url, method: method, params: [param1, param2])
try send(request, completion: completion)
}
/// Request to send a transaction.
///
/// https://docs.walletconnect.org/json-rpc/ethereum#eth_sendtransaction
///
/// - Parameters:
/// - url: WalletConnect url object.
/// - transaction: Transaction object.
/// - completion: Response with string representing transaction hash, or error.
/// - Throws: client error.
public func eth_sendTransaction(url: WCURL,
transaction: Transaction,
completion: @escaping RequestResponse) throws {
try handleTransaction(url: url, method: "eth_sendTransaction", transaction: transaction, completion: completion)
}
/// Request to sign a transaction.
///
/// https://docs.walletconnect.org/json-rpc/ethereum#eth_signtransaction
///
/// - Parameters:
/// - url: WalletConnect url object.
/// - transaction: Transaction object.
/// - completion: Response with string representing transaction signature, or error.
/// - Throws: client error.
public func eth_signTransaction(url: WCURL,
transaction: Transaction,
completion: @escaping RequestResponse) throws {
try handleTransaction(url: url, method: "eth_signTransaction", transaction: transaction, completion: completion)
}
private func handleTransaction(url: WCURL,
method: String,
transaction: Transaction,
completion: @escaping RequestResponse) throws {
let request = try Request(url: url, method: method, params: [transaction])
try send(request, completion: completion)
}
/// Request to send a raw transaction. Creates new message call transaction or
/// a contract creation for signed transactions.
///
/// https://docs.walletconnect.org/json-rpc/ethereum#eth_sendrawtransaction
///
/// - Parameters:
/// - url: WalletConnect url object.
/// - data: Data as String.
/// - completion: Response with the transaction hash, or the zero hash if the transaction is not
/// yet available, or error.
/// - Throws: client error.
public func eth_sendRawTransaction(url: WCURL, data: String, completion: @escaping RequestResponse) throws {
let request = try Request(url: url, method: "eth_sendRawTransaction", params: [data])
try send(request, completion: completion)
}
override func onConnect(to url: WCURL) {
LogService.shared.log("WC: client didConnect url: \(url.bridgeURL.absoluteString)")
delegate?.client(self, didConnect: url)
if let existingSession = communicator.session(by: url) {
communicator.subscribe(on: existingSession.dAppInfo.peerId, url: existingSession.url)
delegate?.client(self, didConnect: existingSession)
} else { // establishing new connection, handshake in process
communicator.subscribe(on: dAppInfo.peerId, url: url)
let request = try! Request(url: url, method: "wc_sessionRequest", params: [dAppInfo], id: UUID().hashValue)
let requestID = request.internalID!
responses.add(requestID: requestID) { [unowned self] response in
self.handleHandshakeResponse(response)
}
communicator.send(request, topic: url.topic)
}
}
private func handleHandshakeResponse(_ response: Response) {
do {
let walletInfo = try response.result(as: Session.WalletInfo.self)
let session = Session(url: response.url, dAppInfo: dAppInfo, walletInfo: walletInfo)
guard walletInfo.approved else {
// TODO: handle Error
delegate?.client(self, didFailToConnect: response.url)
return
}
communicator.addSession(session)
delegate?.client(self, didConnect: session)
} catch {
// TODO: handle error
delegate?.client(self, didFailToConnect: response.url)
}
}
override func onTextReceive(_ text: String, from url: WCURL) {
if let response = try? communicator.response(from: text, url: url) {
log(response)
// Rainbow (at least) application send connect response with random id
// because of that correlated request can't be found by id. Here is crutch
let isConnectResponse = (try? response.result(as: Session.WalletInfo.self)) != nil
let completion = responses.find(requestID: response.internalID, isConnectResponse: isConnectResponse)
completion?(response)
if isConnectResponse {
responses.removeAll()
} else {
responses.remove(requestID: response.internalID)
}
} else if let request = try? communicator.request(from: text, url: url) {
log(request)
expectUpdateSessionRequest(request)
}
}
private func expectUpdateSessionRequest(_ request: Request) {
if request.method == "wc_sessionUpdate" {
guard let info = sessionInfo(from: request) else {
// TODO: error handling
try! send(Response(request: request, error: .invalidJSON))
return
}
guard let session = communicator.session(by: request.url) else { return }
if !info.approved {
do {
try disconnect(from: session)
} catch { // session already disconnected
delegate?.client(self, didDisconnect: session)
}
} else {
if let walletInfo = session.walletInfo {
let updatedInfo = Session.WalletInfo(
approved: info.approved,
accounts: info.accounts ?? [],
chainId: info.chainId,
peerId: walletInfo.peerId,
peerMeta: walletInfo.peerMeta
)
var updatedSesson = session
updatedSesson.walletInfo = updatedInfo
communicator.addSession(updatedSesson)
delegate?.client(self, didUpdate: updatedSesson)
} else {
delegate?.client(self, didUpdate: session)
}
}
} else {
// TODO: error handling
let response = try! Response(request: request, error: .methodNotFound)
try! send(response)
}
}
private func sessionInfo(from request: Request) -> SessionInfo? {
do {
let info = try request.parameter(of: SessionInfo.self, at: 0)
return info
} catch {
LogService.shared.log("WC: incoming approval cannot be parsed: \(error)")
return nil
}
}
override func sendDisconnectSessionRequest(for session: Session) throws {
let dappInfo = session.dAppInfo.with(approved: false)
let request = try Request(url: session.url, method: "wc_sessionUpdate", params: [dappInfo], id: nil)
try send(request, completion: nil)
}
override func failedToConnect(_ url: WCURL) {
delegate?.client(self, didFailToConnect: url)
}
override func didDisconnect(_ session: Session) {
delegate?.client(self, didDisconnect: session)
}
/// Thread-safe collection of client reponses
private class Responses {
private var responses = [JSONRPC_2_0.IDType: RequestResponse]()
private let queue: DispatchQueue
init(queue: DispatchQueue) {
self.queue = queue
}
func add(requestID: JSONRPC_2_0.IDType, response: @escaping RequestResponse) {
dispatchPrecondition(condition: .notOnQueue(queue))
queue.sync { [unowned self] in
self.responses[requestID] = response
}
}
func find(requestID: JSONRPC_2_0.IDType, isConnectResponse: Bool) -> RequestResponse? {
var result: RequestResponse?
dispatchPrecondition(condition: .notOnQueue(queue))
queue.sync { [unowned self] in
if let response = self.responses[requestID] {
result = response
}
if isConnectResponse, responses.count == 1, let response = responses.first {
result = response.value
}
}
return result
}
func remove(requestID: JSONRPC_2_0.IDType) {
dispatchPrecondition(condition: .notOnQueue(queue))
queue.sync { [unowned self] in
_ = self.responses.removeValue(forKey: requestID)
}
}
func removeAll() {
dispatchPrecondition(condition: .notOnQueue(queue))
queue.sync { [unowned self] in
self.responses.removeAll()
}
}
}
/// https://docs.walletconnect.org/json-rpc/ethereum#parameters-3
public struct Transaction: Encodable {
var from: String
var to: String?
var data: String
var gas: String?
var gasPrice: String?
var value: String?
var nonce: String?
public init(from: String,
to: String?,
data: String,
gas: String?,
gasPrice: String?,
value: String?,
nonce: String?) {
self.from = from
self.to = to
self.data = data
self.gas = gas
self.gasPrice = gasPrice
self.value = value
self.nonce = nonce
}
}
}
| 39.922252 | 120 | 0.588275 |
480eb9ebd2a51fa356012c88e41e2b47aad47440 | 19,479 | // File created from ScreenTemplate
// $ createScreen.sh Room Room
/*
Copyright 2021 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
import CommonKit
import MatrixSDK
final class RoomCoordinator: NSObject, RoomCoordinatorProtocol {
// MARK: - Properties
// MARK: Private
private let parameters: RoomCoordinatorParameters
private let roomViewController: RoomViewController
private let userIndicatorStore: UserIndicatorStore
private var selectedEventId: String?
private var loadingCancel: UserIndicatorCancel?
private var roomDataSourceManager: MXKRoomDataSourceManager {
return MXKRoomDataSourceManager.sharedManager(forMatrixSession: self.parameters.session)
}
/// Indicate true if the Coordinator has started once
private var hasStartedOnce: Bool {
return self.roomViewController.delegate != nil
}
private var navigationRouter: NavigationRouterType? {
var finalNavigationRouter: NavigationRouterType?
if let navigationRouter = self.parameters.navigationRouter {
finalNavigationRouter = navigationRouter
} else if let navigationRouterStore = self.parameters.navigationRouterStore, let currentNavigationController = self.roomViewController.navigationController {
// If no navigationRouter has been provided, try to get the navigation router from the current RoomViewController navigation controller if exists
finalNavigationRouter = navigationRouterStore.navigationRouter(for: currentNavigationController)
}
return finalNavigationRouter
}
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: RoomCoordinatorDelegate?
var canReleaseRoomDataSource: Bool {
// If the displayed data is not a preview, let the manager release the room data source
// (except if the view controller has the room data source ownership).
return self.parameters.previewData == nil && self.roomViewController.roomDataSource != nil && self.roomViewController.hasRoomDataSourceOwnership == false
}
// MARK: - Setup
init(parameters: RoomCoordinatorParameters) {
self.parameters = parameters
self.selectedEventId = parameters.eventId
self.userIndicatorStore = UserIndicatorStore(presenter: parameters.userIndicatorPresenter)
if let threadId = parameters.threadId {
self.roomViewController = ThreadViewController.instantiate(withThreadId: threadId,
configuration: parameters.displayConfiguration)
} else {
self.roomViewController = RoomViewController.instantiate(with: parameters.displayConfiguration)
}
self.roomViewController.userIndicatorStore = userIndicatorStore
self.roomViewController.showSettingsInitially = parameters.showSettingsInitially
self.roomViewController.parentSpaceId = parameters.parentSpaceId
if #available(iOS 14, *) {
TimelinePollProvider.shared.session = parameters.session
}
super.init()
}
deinit {
roomViewController.destroy()
}
// MARK: - Public
func start() {
self.start(withCompletion: nil)
}
// NOTE: Completion closure has been added for legacy architecture purpose.
// Remove this completion after LegacyAppDelegate refactor.
func start(withCompletion completion: (() -> Void)?) {
self.roomViewController.delegate = self
// Detect when view controller has been dismissed by gesture when presented modally (not in full screen).
// FIXME: Find a better way to manage modal dismiss. This makes the `roomViewController` to never be released
// self.roomViewController.presentationController?.delegate = self
if let previewData = self.parameters.previewData {
self.loadRoomPreview(withData: previewData, completion: completion)
} else if let threadId = self.parameters.threadId {
self.loadRoom(withId: self.parameters.roomId,
andThreadId: threadId,
eventId: self.parameters.eventId,
completion: completion)
} else if let eventId = self.selectedEventId {
self.loadRoom(withId: self.parameters.roomId, andEventId: eventId, completion: completion)
} else {
self.loadRoom(withId: self.parameters.roomId, completion: completion)
}
// Add `roomViewController` to the NavigationRouter, only if it has been explicitly set as parameter
if let navigationRouter = self.parameters.navigationRouter {
if navigationRouter.modules.isEmpty == false {
navigationRouter.push(self.roomViewController, animated: true, popCompletion: nil)
} else {
navigationRouter.setRootModule(self.roomViewController, popCompletion: nil)
}
}
}
func start(withEventId eventId: String, completion: (() -> Void)?) {
self.selectedEventId = eventId
if self.hasStartedOnce {
self.roomViewController.highlightAndDisplayEvent(eventId, completion: completion)
} else {
self.start(withCompletion: completion)
}
}
func toPresentable() -> UIViewController {
return self.roomViewController
}
// MARK: - Private
private func loadRoom(withId roomId: String, completion: (() -> Void)?) {
// Present activity indicator when retrieving roomDataSource for given room ID
startLoading()
let roomDataSourceManager: MXKRoomDataSourceManager = MXKRoomDataSourceManager.sharedManager(forMatrixSession: self.parameters.session)
// LIVE: Show the room live timeline managed by MXKRoomDataSourceManager
roomDataSourceManager.roomDataSource(forRoom: roomId, create: true, onComplete: { [weak self] (roomDataSource) in
guard let self = self else {
return
}
self.stopLoading()
if let roomDataSource = roomDataSource {
self.roomViewController.displayRoom(roomDataSource)
}
completion?()
})
}
private func loadRoom(withId roomId: String, andEventId eventId: String, completion: (() -> Void)?) {
// Present activity indicator when retrieving roomDataSource for given room ID
startLoading()
// Open the room on the requested event
RoomDataSource.load(withRoomId: roomId,
initialEventId: eventId,
threadId: nil,
andMatrixSession: self.parameters.session) { [weak self] (dataSource) in
guard let self = self else {
return
}
self.stopLoading()
guard let roomDataSource = dataSource as? RoomDataSource else {
return
}
roomDataSource.markTimelineInitialEvent = true
self.roomViewController.displayRoom(roomDataSource)
// Give the data source ownership to the room view controller.
self.roomViewController.hasRoomDataSourceOwnership = true
completion?()
}
}
private func loadRoom(withId roomId: String, andThreadId threadId: String, eventId: String?, completion: (() -> Void)?) {
// Present activity indicator when retrieving roomDataSource for given room ID
startLoading()
// Open the thread on the requested event
ThreadDataSource.load(withRoomId: roomId,
initialEventId: eventId,
threadId: threadId,
andMatrixSession: self.parameters.session) { [weak self] (dataSource) in
guard let self = self else {
return
}
self.stopLoading()
guard let threadDataSource = dataSource as? ThreadDataSource else {
return
}
threadDataSource.markTimelineInitialEvent = false
threadDataSource.highlightedEventId = eventId
self.roomViewController.displayRoom(threadDataSource)
// Give the data source ownership to the room view controller.
self.roomViewController.hasRoomDataSourceOwnership = true
completion?()
}
}
private func loadRoomPreview(withData previewData: RoomPreviewData, completion: (() -> Void)?) {
self.roomViewController.displayRoomPreview(previewData)
completion?()
}
private func startLocationCoordinatorWithEvent(_ event: MXEvent? = nil, bubbleData: MXKRoomBubbleCellDataStoring? = nil) {
guard #available(iOS 14.0, *) else {
return
}
guard let navigationRouter = self.navigationRouter,
let mediaManager = mxSession?.mediaManager,
let user = mxSession?.myUser else {
MXLog.error("[RoomCoordinator] Invalid location sharing coordinator parameters. Returning.")
return
}
var avatarData: AvatarInputProtocol
if event != nil, let bubbleData = bubbleData {
avatarData = AvatarInput(mxContentUri: bubbleData.senderAvatarUrl,
matrixItemId: bubbleData.senderId,
displayName: bubbleData.senderDisplayName)
} else {
avatarData = AvatarInput(mxContentUri: user.avatarUrl,
matrixItemId: user.userId,
displayName: user.displayname)
}
var location: CLLocationCoordinate2D?
var coordinateType: MXEventAssetType = .user
if let locationContent = event?.location {
location = CLLocationCoordinate2D(latitude: locationContent.latitude, longitude: locationContent.longitude)
coordinateType = locationContent.assetType
}
let parameters = LocationSharingCoordinatorParameters(roomDataSource: roomViewController.roomDataSource,
mediaManager: mediaManager,
avatarData: avatarData,
location: location,
coordinateType: coordinateType)
let coordinator = LocationSharingCoordinator(parameters: parameters)
coordinator.completion = { [weak self, weak coordinator] in
guard let self = self, let coordinator = coordinator else {
return
}
self.navigationRouter?.dismissModule(animated: true, completion: nil)
self.remove(childCoordinator: coordinator)
}
add(childCoordinator: coordinator)
navigationRouter.present(coordinator, animated: true)
coordinator.start()
}
private func startEditPollCoordinator(startEvent: MXEvent? = nil) {
guard #available(iOS 14.0, *) else {
return
}
let parameters = PollEditFormCoordinatorParameters(room: roomViewController.roomDataSource.room, pollStartEvent: startEvent)
let coordinator = PollEditFormCoordinator(parameters: parameters)
coordinator.completion = { [weak self, weak coordinator] in
guard let self = self, let coordinator = coordinator else {
return
}
self.navigationRouter?.dismissModule(animated: true, completion: nil)
self.remove(childCoordinator: coordinator)
}
add(childCoordinator: coordinator)
navigationRouter?.present(coordinator, animated: true)
coordinator.start()
}
private func startLoading() {
// The `RoomViewController` does not currently ensure that `startLoading` is matched by corresponding `stopLoading` and may
// thus trigger start of loading multiple times. To solve for this we will hold onto the cancellation reference of the
// last loading request, and if one already exists, we will not present a new indicator.
guard loadingCancel == nil else {
return
}
MXLog.debug("[RoomCoordinator] Present loading indicator in a room: \(roomId ?? "unknown")")
loadingCancel = userIndicatorStore.present(type: .loading(label: VectorL10n.homeSyncing, isInteractionBlocking: false))
}
private func stopLoading() {
MXLog.debug("[RoomCoordinator] Dismiss loading indicator in a room: \(roomId ?? "unknown")")
loadingCancel?()
loadingCancel = nil
}
}
// MARK: - RoomIdentifiable
extension RoomCoordinator: RoomIdentifiable {
var roomId: String? {
return self.parameters.roomId
}
var threadId: String? {
return self.parameters.threadId
}
var mxSession: MXSession? {
self.parameters.session
}
}
// MARK: - UIAdaptivePresentationControllerDelegate
extension RoomCoordinator: UIAdaptivePresentationControllerDelegate {
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
self.delegate?.roomCoordinatorDidDismissInteractively(self)
}
}
// MARK: - RoomViewControllerDelegate
extension RoomCoordinator: RoomViewControllerDelegate {
func roomViewController(_ roomViewController: RoomViewController, showRoomWithId roomID: String, eventId eventID: String?) {
self.delegate?.roomCoordinator(self, didSelectRoomWithId: roomID, eventId: eventID)
}
func roomViewController(_ roomViewController: RoomViewController, didReplaceRoomWithReplacementId roomID: String) {
self.delegate?.roomCoordinator(self, didReplaceRoomWithReplacementId: roomID)
}
func roomViewController(_ roomViewController: RoomViewController, showMemberDetails roomMember: MXRoomMember) {
// TODO:
}
func roomViewControllerShowRoomDetails(_ roomViewController: RoomViewController) {
// TODO:
}
func roomViewControllerDidLeaveRoom(_ roomViewController: RoomViewController) {
self.delegate?.roomCoordinatorDidLeaveRoom(self)
}
func roomViewControllerPreviewDidTapCancel(_ roomViewController: RoomViewController) {
self.delegate?.roomCoordinatorDidCancelRoomPreview(self)
}
func roomViewController(_ roomViewController: RoomViewController, startChatWithUserId userId: String, completion: @escaping () -> Void) {
AppDelegate.theDelegate().createDirectChat(withUserId: userId, completion: completion)
}
func roomViewController(_ roomViewController: RoomViewController, showCompleteSecurityFor session: MXSession) {
AppDelegate.theDelegate().presentCompleteSecurity(for: session)
}
func roomViewController(_ roomViewController: RoomViewController, handleUniversalLinkWith parameters: UniversalLinkParameters) -> Bool {
return AppDelegate.theDelegate().handleUniversalLink(with: parameters)
}
func roomViewControllerDidRequestPollCreationFormPresentation(_ roomViewController: RoomViewController) {
startEditPollCoordinator()
}
func roomViewControllerDidRequestLocationSharingFormPresentation(_ roomViewController: RoomViewController) {
startLocationCoordinatorWithEvent()
}
func roomViewController(_ roomViewController: RoomViewController, didRequestLocationPresentationFor event: MXEvent, bubbleData: MXKRoomBubbleCellDataStoring) {
startLocationCoordinatorWithEvent(event, bubbleData: bubbleData)
}
func roomViewController(_ roomViewController: RoomViewController, locationShareActivityViewControllerFor event: MXEvent) -> UIActivityViewController? {
guard let location = event.location else {
return nil
}
return LocationSharingCoordinator.shareLocationActivityController(CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude))
}
func roomViewController(_ roomViewController: RoomViewController, canEndPollWithEventIdentifier eventIdentifier: String) -> Bool {
guard #available(iOS 14.0, *) else {
return false
}
return TimelinePollProvider.shared.timelinePollCoordinatorForEventIdentifier(eventIdentifier)?.canEndPoll() ?? false
}
func roomViewController(_ roomViewController: RoomViewController, endPollWithEventIdentifier eventIdentifier: String) {
guard #available(iOS 14.0, *) else {
return
}
TimelinePollProvider.shared.timelinePollCoordinatorForEventIdentifier(eventIdentifier)?.endPoll()
}
func roomViewController(_ roomViewController: RoomViewController, canEditPollWithEventIdentifier eventIdentifier: String) -> Bool {
guard #available(iOS 14.0, *) else {
return false
}
return TimelinePollProvider.shared.timelinePollCoordinatorForEventIdentifier(eventIdentifier)?.canEditPoll() ?? false
}
func roomViewController(_ roomViewController: RoomViewController, didRequestEditForPollWithStart startEvent: MXEvent) {
startEditPollCoordinator(startEvent: startEvent)
}
func roomViewControllerDidStartLoading(_ roomViewController: RoomViewController) {
startLoading()
}
func roomViewControllerDidStopLoading(_ roomViewController: RoomViewController) {
stopLoading()
}
func roomViewControllerDidTapLiveLocationSharingBanner(_ roomViewController: RoomViewController) {
// TODO:
}
func roomViewControllerDidStopLiveLocationSharing(_ roomViewController: RoomViewController) {
// TODO:
}
func threadsCoordinator(for roomViewController: RoomViewController, threadId: String?) -> ThreadsCoordinatorBridgePresenter? {
guard let session = mxSession, let roomId = roomId else {
MXLog.error("[RoomCoordinator] Cannot create threads coordinator for room \(roomId ?? "")")
return nil
}
return ThreadsCoordinatorBridgePresenter(
session: session,
roomId: roomId,
threadId: threadId,
userIndicatorPresenter: parameters.userIndicatorPresenter
)
}
}
| 39.997947 | 165 | 0.657837 |
ac52366890789334acaed59fb132619bf8201b06 | 1,416 | //
// AndesTooltipViewLink.swift
// AndesUI
//
// Created by Juan Andres Vasquez Ferrer on 09-02-21.
//
import Foundation
class AndesTooltipViewActions: AndesTooltipAbstractView {
@IBOutlet weak var secondaryAction: AndesButton!
@IBOutlet weak var primaryAction: AndesButton!
override func loadNib() {
let bundle = AndesBundle.bundle()
bundle.loadNibNamed("AndesTooltipViewActions", owner: self, options: nil)
}
override func updateView() {
super.updateView()
self.updatePrimaryAction()
self.updateSecondaryActionIfNeeded()
}
private func updatePrimaryAction() {
if let primaryActionConfig = config.primaryActionConfig {
primaryAction.updateWithCustomConfig(primaryActionConfig)
}
}
private func updateSecondaryActionIfNeeded() {
guard let secondaryActionConfig = config.secondaryActionConfig else {
hideSecondaryButton()
return
}
secondaryAction.updateWithCustomConfig(secondaryActionConfig)
}
private func hideSecondaryButton() {
secondaryAction.removeFromSuperview()
}
@IBAction func primaryActionButtonTapped(_ sender: Any) {
config.primaryActionOnPressed?()
dismiss()
}
@IBAction func secondaryActionButtonTapped(_ sender: Any) {
config.secondaryActionOnPressed?()
dismiss()
}
}
| 26.716981 | 81 | 0.682203 |
fc811a679de1669e72efef9372ba682536752816 | 118 | import XCTest
import RazeCoreTests
var tests = [XCTestCaseEntry]()
tests += RazeCoreTests.allTests()
XCTMain(tests)
| 14.75 | 33 | 0.779661 |
f59f959732ba3c1a109ff5c719c526c558498adb | 1,181 | //
// Created by kojiba on 16.08.2020.
// Copyright (c) 2020 kojiba. All rights reserved.
//
import Foundation
class Network {
private let loadingDelay: UInt32 = 2
static let shared = Network()
func getTags(completion: @escaping (_: [TagModel]) -> Void) {
let models = Mocks.tags.map {
TagModel(tag: $0)
}
simulateNetwork(result: models, completion: completion)
}
func getPosts(tags: [String], completion: @escaping (_: [PostModel]) -> Void) {
let models = Mocks.posts.map { PostModel(content: $0, tags: tags) }
simulateNetwork(result: models, completion: completion)
}
func login(email: String, password: String, completion: @escaping (_: Bool) -> Void) {
simulateNetwork(result: true, completion: completion)
}
private func simulateNetwork<Result>(result: Result, completion: @escaping (_ :Result) -> ()) {
DispatchQueue.global().async {
self.delay()
DispatchQueue.main.async {
completion(result)
}
}
}
private func delay() {
sleep(self.loadingDelay)
}
}
| 25.673913 | 99 | 0.587638 |
46dfa8cc32da971c1e2e1a93c66d97633f6b64e8 | 4,192 | //
// DestinationCollectionCell.swift
// DoorRush
//
// Created by edwin on 03/06/2020.
// Copyright © 2020 edwin. All rights reserved.
//
import UIKit
class RestaurantCollectionCell: BaseCollectionCell {
let restaurants = [
Restuarant(imageName: "pizzas", name: "Eataly", feature: "20 min · Free delivery"),
Restuarant(imageName: "burgers", name: "Sam's Crispy Chicken", feature: "20 min · Free delivery"),
Restuarant(imageName: "Bakery", name: "Dominique Ansel Bakery", feature: "20 min · Free delivery"),
Restuarant(imageName: "sticky-finger", name: "Sticky's Finger Joint", feature: "20 min · Free delivery")
]
let foodLabel: UILabel = {
let label = UILabel()
label.text = "National Favorites"
label.font = UIFont.bold(ofSize: 22)
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
return label
}()
let allButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("See All", for: .normal)
button.tintColor = UIColor(named: "red")
button.contentHorizontalAlignment = .right
button.titleLabel?.font = UIFont.regular(ofSize: 16)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 100).isActive = true
return button
}()
let horizontalStack: UIStackView = {
let stack = UIStackView()
stack.axis = .horizontal
stack.distribution = .fillProportionally
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
override func setupViews() {
super.setupViews()
contentView.backgroundColor = .white
addSubview(horizontalStack)
addSubview(collectionView)
horizontalStack.addArrangedSubview(foodLabel)
horizontalStack.addArrangedSubview(allButton)
topConstraint?.isActive = false
bottomConstraint?.isActive = false
NSLayoutConstraint.activate([
collectionView.widthAnchor.constraint(equalToConstant: frame.width),
horizontalStack.leftAnchor.constraint(equalTo: leftAnchor, constant: 16),
horizontalStack.rightAnchor.constraint(equalTo: rightAnchor, constant: -16),
horizontalStack.topAnchor.constraint(equalTo: topAnchor, constant: 10),
horizontalStack.bottomAnchor.constraint(equalTo: collectionView.topAnchor, constant: 0),
collectionView.leftAnchor.constraint(equalTo: leftAnchor),
collectionView.rightAnchor.constraint(equalTo: rightAnchor),
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
override func registerClass() {
collectionView.register(RestaurantCell.self, forCellWithReuseIdentifier: RestaurantCell.reuseIdentifier)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return restaurants.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RestaurantCell.reuseIdentifier, for: indexPath) as! RestaurantCell
cell.restaurant = restaurants[indexPath.item]
return cell
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: frame.width / 1.4, height: frame.height)
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10
}
}
| 41.098039 | 171 | 0.687261 |
11d78e6256d94bfe869f45f78ad8a155c3603034 | 336 | // DependencyContainer+Backend.swift
//
// - Authors:
// Ben John
//
// - Date: 17.08.18
//
// Copyright © 2018 Ben John. All rights reserved.
import DIKit
public extension DependencyContainer {
static var backend = module {
single { Backend() as BackendProtocol }
single { Network() as NetworkProtocol }
}
}
| 17.684211 | 50 | 0.651786 |
dea39d0787e31423e9c89efc76f85ba466dd38ff | 562 | //
// ChatCell.swift
// ParseChat
//
// Created by Dhriti Chawla on 2/5/18.
// Copyright © 2018 Dhriti Chawla. All rights reserved.
//
import UIKit
class ChatCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myUser: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.071429 | 65 | 0.656584 |
26acdeb8147f685704484a75c21867a177a9a349 | 2,305 | //
// UserSignViewController.swift
// Horoscope
//
// Created by Ruslan Latfulin on 13.01.2019.
// Copyright © 2019 Ruslan Latfulin. All rights reserved.
//
import UIKit
class UserSignViewController: UIViewController {
var selectedItem: Int = 0
@IBOutlet weak var buttonCancel: UIButton!
@IBAction func pushCancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func pushCancelAction(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
if userSign == nil{
buttonCancel.isHidden = true
navigationItem.leftBarButtonItem = nil
} else {
navigationItem.title = "Current sign: \(userSign!)"
}
// Do any additional setup after loading the view.
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
userSign = Model.shared.staticZodiacSigns[indexPath.row]
dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension UserSignViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Model.shared.staticZodiacSigns.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserSignCell", for: indexPath) as! CollectionViewCell
cell.imageZodiacSign.image = UIImage(named: Model.shared.staticZodiacSigns[indexPath.row])
cell.labelName.text = Model.shared.staticZodiacSignsRus[indexPath.row]
return cell
}
}
| 30.733333 | 129 | 0.679393 |
29b9e4659fb2a17184fddcb97138b3c6cb45eb5b | 632 | //
// SyncSensingDelegate.swift
// SensorKit
//
// Created by Andrea Piscitello on 07/11/16.
// Copyright © 2016 Andrea Piscitello. All rights reserved.
//
import Foundation
// TODO: seriously public???
public class SyncSensingDelegate : SensingDelegate {
public var managedSensors = [Sensor]()
public func addSensor(_ sensor: Sensor) {
managedSensors.append(sensor)
}
public func start() {
for s in managedSensors {
s.start()
}
}
public func stop() {
for s in managedSensors {
s.stop()
}
}
public init() {}
}
| 19.151515 | 60 | 0.583861 |
117373c5e0d37a5772f753bf47cb17e83d612ff0 | 4,981 | //
// CITA+TransactionDetails.swift
// Cyton
//
// Created by 晨风 on 2018/11/16.
// Copyright © 2018 Cryptape. All rights reserved.
//
import Foundation
import BigInt
import Alamofire
import CITA
import PromiseKit
class CITATransactionDetails: TransactionDetails {
var gasUsed: BigUInt = 0
var quotaUsed: BigUInt = 0
var chainId: Int = 0
var chainName: String = ""
var errorMessage: String?
enum CITACodingKeys: String, CodingKey {
case content
case gasUsed
case quotaUsed
case chainId
case chainName
case errorMessage
}
override init() {
super.init()
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CITACodingKeys.self)
if let value = try? values.decode(String.self, forKey: .gasUsed) {
gasUsed = BigUInt(string: value) ?? 0
}
if let value = try? values.decode(String.self, forKey: .quotaUsed) {
quotaUsed = BigUInt(string: value) ?? 0
}
chainName = (try? values.decode(String.self, forKey: .chainName)) ?? ""
chainId = (try? values.decode(Int.self, forKey: .chainId)) ?? 0
errorMessage = try? values.decode(String.self, forKey: .errorMessage)
if errorMessage != nil {
status = .failure
}
}
}
private struct CITATransactionsResponse: Decodable {
let result: Result
struct Result: Decodable {
let count: UInt
let transactions: [CITATransactionDetails]
}
}
private struct CITATransactionResponse: Decodable {
let result: Result
struct Result: Decodable {
let transaction: CITATransactionDetails?
}
}
private struct CITAErc20TransactionsResponse: Decodable {
let result: Result
struct Result: Decodable {
let transfers: [CITATransactionDetails]
}
}
extension CITANetwork {
func getTransactionHistory(walletAddress: String, page: UInt, pageSize: UInt) throws -> [CITATransactionDetails] {
let url = host().appendingPathComponent("/api/transactions")
let parameters: [String: Any] = [
"account": walletAddress.lowercased(),
"page": page,
"perPage": pageSize
]
return try Promise<[CITATransactionDetails]>.init { (resolver) in
AF.request(url, method: .get, parameters: parameters).responseJSON { (response) in
do {
guard let responseData = response.data else { throw TransactionHistoryError.networkFailure }
let response = try JSONDecoder().decode(CITATransactionsResponse.self, from: responseData)
let transactions = response.result.transactions
resolver.fulfill(transactions)
} catch {
resolver.reject(error)
}
}
}.wait()
}
func getErc20TransactionHistory(walletAddress: String, tokenAddress: String, page: UInt, pageSize: UInt) throws -> [CITATransactionDetails] {
let url = host().appendingPathComponent("/api/erc20/transfers")
let parameters: [String: Any] = [
"account": walletAddress.lowercased(),
"address": tokenAddress,
"page": page,
"perPage": pageSize
]
return try Promise<[CITATransactionDetails]>.init { (resolver) in
AF.request(url, method: .get, parameters: parameters).responseJSON { (response) in
do {
guard let responseData = response.data else { throw TransactionHistoryError.networkFailure }
let response = try JSONDecoder().decode(CITAErc20TransactionsResponse.self, from: responseData)
let transactions = response.result.transfers
resolver.fulfill(transactions)
} catch {
resolver.reject(error)
}
}
}.wait()
}
func getTransaction(txhash: String) throws -> CITATransactionDetails {
let url = host().appendingPathComponent("/api/transactions/\(txhash)")
return try Promise<CITATransactionDetails>.init { (resolver) in
AF.request(url, method: .get, parameters: nil).responseData(completionHandler: { (response) in
do {
guard let responseData = response.data else { throw TransactionHistoryError.networkFailure }
let response = try JSONDecoder().decode(CITATransactionResponse.self, from: responseData)
if let transaction = response.result.transaction {
resolver.fulfill(transaction)
} else {
throw TransactionHistoryError.networkFailure
}
} catch {
resolver.reject(error)
}
})
}.wait()
}
}
| 36.094203 | 145 | 0.600683 |
db773f84517fb87cbc3c7732d30a20498de24932 | 1,374 | //
// ImageItem.swift
// PhotoLooker
//
// Created by Bohdan Mihiliev on 30.09.17.
// Copyright © 2017 Bohdan Mihiliev. All rights reserved.
//
import UIKit
struct ImageItem: Decodable {
// MARK: - Properties
let id: String
let title: String
var imageURL: URL? {
return URL(string: displaySize.uri)
}
var imageKey: String {
return "\(id).jpg"
}
private var displaySize: DisplaySize
enum CodingKeys: String, CodingKey {
case id, title, displaySizes = "display_sizes"
}
// MARK: - Initializers
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let displaySizes = try container.decode([DisplaySize].self, forKey: .displaySizes)
let id = try container.decode(String.self, forKey: .id)
let title = try container.decode(String.self, forKey: .title)
guard let displaySize = displaySizes.first else {
let errorContext = DecodingError.Context(codingPath: [CodingKeys.displaySizes],
debugDescription: "Display sizes is corruptedß")
throw DecodingError.dataCorrupted(errorContext)
}
self.init(id: id, title: title, displaySize: displaySize)
}
init (id: String, title: String, displaySize: DisplaySize) {
self.id = id
self.title = title
self.displaySize = displaySize
}
}
| 28.040816 | 96 | 0.66885 |
e59e4c1d52a5b657fa4699b476534aa1dad6a7c5 | 2,122 | /*
* Copyright 2018 Tua Rua Ltd.
*
* 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 FreSwift
extension SwiftController: FreSwiftMainController {
@objc public func getFunctions(prefix: String) -> [String] {
functionsToSet["\(prefix)init"] = initController
functionsToSet["\(prefix)createGUID"] = createGUID
functionsToSet["\(prefix)signIn"] = signIn
functionsToSet["\(prefix)signInSilently"] = signInSilently
functionsToSet["\(prefix)signOut"] = signOut
functionsToSet["\(prefix)revokeAccess"] = revokeAccess
functionsToSet["\(prefix)handle"] = handle
var arr: [String] = []
for key in functionsToSet.keys {
arr.append(key)
}
return arr
}
@objc public func dispose() {
NotificationCenter.default.removeObserver(self)
}
// Must have this function. It exposes the methods to our entry ObjC.
@objc public func callSwiftFunction(name: String, ctx: FREContext, argc: FREArgc, argv: FREArgv) -> FREObject? {
if let fm = functionsToSet[name] {
return fm(ctx, argc, argv)
}
return nil
}
@objc public func setFREContext(ctx: FREContext) {
self.context = FreContextSwift.init(freContext: ctx)
}
@objc public func onLoad() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidFinishLaunching),
name: UIApplication.didFinishLaunchingNotification, object: nil)
}
}
| 35.366667 | 116 | 0.652215 |
ddd29c6ce40f138eddbccdecaec79c2672c38405 | 2,545 | //
// SceneDelegate.swift
// stackFoodGame
//
// Created by Michael Hayes on 5/6/20.
// Copyright © 2020 Michael Hayes. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
// Save changes in the application's managed object context when the application transitions to the background.
(UIApplication.shared.delegate as? AppDelegate)?.saveContext()
}
}
| 44.649123 | 147 | 0.716306 |
118a6803ad394b5313e522be90f3ff1a24cd34b3 | 227 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
{
}
struct S<T {
class B<T : B<T> {
}
let c = B
| 18.916667 | 87 | 0.700441 |
d64ce78ca95f4f4cf7e63697abbefa005bc17c7c | 45 | import Foundation
protocol AutoEquatable {}
| 11.25 | 25 | 0.822222 |
5663be8202d12d9be478e4ab8640a71c0160b8bb | 7,785 | //
// HippoActionMessage.swift
// Fugu
//
// Created by Vishal on 04/02/19.
// Copyright © 2019 Socomo Technologies Private Limited. All rights reserved.
//
import Foundation
class HippoActionMessage: HippoMessage {
var selectedBtnId: String = ""
var isUserInteractionEnbled: Bool = false
var buttons: [HippoActionButton]?
var responseMessage: HippoMessage?
var repliedBy: String?
var repliedById: Int?
override init?(dict: [String : Any]) {
super.init(dict: dict)
isActive = Bool.parse(key: "is_active", json: dict)
selectedBtnId = dict["selected_btn_id"] as? String ?? ""
repliedBy = dict["replied_by"] as? String
repliedById = Int.parse(values: dict, key: "replied_by_id")
if let content_value = dict["content_value"] as? [[String: Any]] {
self.contentValues = content_value
let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId
let (buttons, selectedButton) = HippoActionButton.getArray(array: contentValues, selectedId: selectedId)
tryToSetResponseMessage(selectedButton: selectedButton)
self.buttons = buttons
}
setHeight()
isUserInteractionEnbled = isActive
}
func tryToSetResponseMessage(selectedButton: HippoActionButton?) {
guard let parsedSelectedButton = selectedButton else {
return
}
responseMessage = HippoMessage(message: parsedSelectedButton.title, type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType)
responseMessage?.userType = .customer
responseMessage?.creationDateTime = self.creationDateTime
responseMessage?.status = status
cellDetail?.actionHeight = nil
}
func setHeight() {
cellDetail = HippoCellDetail()
cellDetail?.headerHeight = attributtedMessage.messageHeight + attributtedMessage.nameHeight + attributtedMessage.timeHeight
cellDetail?.showSenderName = false
if let attributtedMessage = responseMessage?.attributtedMessage {
let nameHeight: CGFloat = HippoConfig.shared.appUserType == .agent ? attributtedMessage.nameHeight : 0
cellDetail?.responseHeight = attributtedMessage.messageHeight + attributtedMessage.timeHeight + nameHeight + 10
cellDetail?.actionHeight = nil
} else {
let buttonHeight = buttonsHeight() //(buttons?.count ?? 0) * 50
cellDetail?.actionHeight = CGFloat(buttonHeight) + 15 + 10 + 10 //Button Height + (timeLabelHeight + time gap from top) + padding
}
cellDetail?.padding = 1
}
func buttonsHeight() -> CGFloat {
guard let buttons = buttons, !buttons.isEmpty else {
return 0
}
let maxWidth = windowScreenWidth - 27
var buttonCount: Int = 0
var remaningWidth: CGFloat = maxWidth
for each in buttons {
let w: CGFloat = findButtonWidth(each.title) + 40
let widthRemaningAfterInsertion = remaningWidth - w - 5
if remaningWidth == maxWidth {
buttonCount += 1
remaningWidth = widthRemaningAfterInsertion
} else if widthRemaningAfterInsertion <= -5 {
buttonCount += 1
remaningWidth = maxWidth - w - 5
} else {
remaningWidth = widthRemaningAfterInsertion
}
// let message = "===\(each.title)--w=\(w)--widthRemaningAfterInsertion=\(widthRemaningAfterInsertion)--b=\(buttonCount)--remaning=\(remaningWidth) \n"
// HippoConfig.shared.log.debug(message, level: .custom)
}
return CGFloat(buttonCount * 35) + CGFloat(5 * (buttonCount - 1))
}
private func findButtonWidth(_ text: String) -> CGFloat {
let attributedText = NSMutableAttributedString(string: text)
let range = (text as NSString).range(of: text)
attributedText.addAttribute(.font, value: HippoConfig.shared.theme.incomingMsgFont, range: range)
let boxSize: CGSize = CGSize(width: windowScreenWidth - 30, height: CGFloat.greatestFiniteMagnitude)
return sizeOf(attributedString: attributedText, availableBoxSize: boxSize).width
}
private func sizeOf(attributedString: NSMutableAttributedString, availableBoxSize: CGSize) -> CGSize {
return attributedString.boundingRect(with: availableBoxSize, options: .usesLineFragmentOrigin, context: nil).size
}
override func getJsonToSendToFaye() -> [String : Any] {
var json = super.getJsonToSendToFaye()
json["selected_btn_id"] = selectedBtnId
json["is_active"] = isActive.intValue()
json["content_value"] = contentValues
json["user_id"] = currentUserId()
json["replied_by"] = currentUserName()
json["replied_by_id"] = currentUserId()
return json
}
func selectBtnWith(btnId: String) {
selectedBtnId = btnId
isActive = false
isUserInteractionEnbled = false
repliedById = currentUserId()
repliedBy = currentUserName()
let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId
if !contentValues.isEmpty {
contentValues.append(contentsOf: customButtons)
let list = contentValues
let (buttons, selectedButton) = HippoActionButton.getArray(array: list, selectedId: selectedId)
self.tryToSetResponseMessage(selectedButton: selectedButton)
self.buttons = buttons
}
setHeight()
}
func updateObject(with newObject: HippoActionMessage) {
super.updateObject(with: newObject)
self.selectedBtnId = newObject.selectedBtnId
self.isActive = newObject.isActive
self.isUserInteractionEnbled = newObject.isUserInteractionEnbled
self.repliedById = newObject.repliedById
self.repliedBy = newObject.repliedBy
let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId
if !contentValues.isEmpty {
let (buttons, selectedButton) = HippoActionButton.getArray(array: contentValues, selectedId: selectedId)
self.tryToSetResponseMessage(selectedButton: selectedButton)
self.buttons = buttons
}
setHeight()
self.status = .sent
messageRefresed?()
}
func getButtonWithId(id: String) -> HippoActionButton? {
guard let buttons = self.buttons else {
return nil
}
let button = buttons.first { (b) -> Bool in
return b.id == id
}
return button
}
}
let customButtons: [[String: Any]] = [
[
"btn_id": "451",
"btn_color": "#FFFFFF",
"btn_title": "Agent List",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "AGENTS",
"btn_title_selected_color": "#FFFFFF"
],
[
"btn_id": "454",
"btn_color": "#FFFFFF",
"btn_title": "audio call",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "AUDIO_CALL",
"btn_title_selected_color": "#FFFFFF"
],
[
"btn_id": "455",
"btn_color": "#FFFFFF",
"btn_title": "video call",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "VIDEO_CALL",
"btn_title_selected_color": "#FFFFFF"
],
[
"btn_id": "455",
"btn_color": "#FFFFFF",
"btn_title": "Continue chat",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "CONTINUE_CHAT",
"btn_title_selected_color": "#FFFFFF"
]
]
| 36.378505 | 162 | 0.62736 |
8f181223f4cb9bce1e35ff36ff44497cb078a3bc | 2,763 | //
// AppDelegate.swift
// zrmgz
//
// Created by lenbo lan on 2021/4/26.
//
import UIKit
import AppTrackingTransparency
import AdSupport
import BUAdSDK
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
checkTrackingAuthorization()
BUAdSDKManager.setAppID(Constant.appID)
BUAdSDKManager.setLoglevel(.debug)
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.
}
// MARK: BUAdSDK
private func checkTrackingAuthorization() {
if #available(iOS 14, *) {
switch ATTrackingManager.trackingAuthorizationStatus {
case .authorized:
print("Allow Tracking")
print("IDFA: \(ASIdentifierManager.shared().advertisingIdentifier)")
case .denied:
print("denied")
case .restricted:
print("restricted")
case .notDetermined:
showRequestTrackingAuthorizationAlert()
@unknown default:
fatalError()
}
}
}
private func showRequestTrackingAuthorizationAlert() {
if #available(iOS 14, *) {
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
switch status {
case .authorized:
print("IDFA: \(ASIdentifierManager.shared().advertisingIdentifier)")
case .denied, .restricted, .notDetermined:
print("IDFA been denied!!!")
@unknown default:
fatalError()
}
})
}
}
}
| 34.111111 | 179 | 0.639884 |
0118323e6004ac815a8ec2ee1409fe6add374ddd | 5,449 | //
// PPUTests.swift
// NESwftTests
//
// Created by HIROTA Ichiro on 2018/10/25.
// Copyright © 2018 HIROTA Ichiro. All rights reserved.
//
import XCTest
@testable import NESwft
class PPUTests: XCTestCase {
func testStat() {
var stat = PPU.Stat()
stat.rawValue[bit: 7] = 1
XCTAssertTrue(stat.vblank)
stat.rawValue[bit: 7] = 0
XCTAssertFalse(stat.vblank)
stat.rawValue[bit: 6] = 1
XCTAssertTrue(stat.spr0hit)
stat.rawValue[bit: 6] = 0
XCTAssertFalse(stat.spr0hit)
}
func testPPUCtrl() {
var ctrl = PPU.Ctrl()
ctrl.rawValue = 0
XCTAssertEqual(ctrl.baseNameTable, 0)
ctrl.rawValue = 1
XCTAssertEqual(ctrl.baseNameTable, 1)
ctrl.rawValue = 2
XCTAssertEqual(ctrl.baseNameTable, 2)
ctrl.rawValue = 3
XCTAssertEqual(ctrl.baseNameTable, 3)
ctrl.rawValue[bit: 2] = 0
XCTAssertEqual(ctrl.addrIncr, 1)
ctrl.rawValue[bit: 2] = 1
XCTAssertEqual(ctrl.addrIncr, 32)
ctrl.rawValue[bit: 3] = 0
XCTAssertEqual(ctrl.spPatTable, 0x0000)
ctrl.rawValue[bit: 3] = 1
XCTAssertEqual(ctrl.spPatTable, 0x1000)
ctrl.rawValue[bit: 4] = 0
XCTAssertEqual(ctrl.bgPatTable, 0x0000)
ctrl.rawValue[bit: 4] = 1
XCTAssertEqual(ctrl.bgPatTable, 0x1000)
ctrl.rawValue[bit: 5] = 0
XCTAssertEqual(ctrl.spriteHeight, 8)
ctrl.rawValue[bit: 5] = 1
XCTAssertEqual(ctrl.spriteHeight, 16)
ctrl.rawValue[bit: 7] = 0
XCTAssertFalse(ctrl.generateNMI)
ctrl.rawValue[bit: 7] = 1
XCTAssertTrue(ctrl.generateNMI)
}
func testPPUMask() {
var mask = PPU.Mask()
mask.rawValue[bit: 0] = 0
XCTAssertFalse(mask.greyscale)
mask.rawValue[bit: 0] = 1
XCTAssertTrue(mask.greyscale)
mask.rawValue[bit: 1] = 0
XCTAssertFalse(mask.showBgEdge)
mask.rawValue[bit: 1] = 1
XCTAssertTrue(mask.showBgEdge)
mask.rawValue[bit: 2] = 0
XCTAssertFalse(mask.showSpEdge)
mask.rawValue[bit: 2] = 1
XCTAssertTrue(mask.showSpEdge)
mask.rawValue[bit: 3] = 0
XCTAssertFalse(mask.showBg)
mask.rawValue[bit: 3] = 1
XCTAssertTrue(mask.showBg)
mask.rawValue[bit: 4] = 0
XCTAssertFalse(mask.showSp)
mask.rawValue[bit: 4] = 1
XCTAssertTrue(mask.showSp)
mask.rawValue = 0b0000_0000
XCTAssertEqual(mask.emphasis, PPU.Mask.Emphasis(r: false, g: false, b: false))
mask.rawValue = 0b0010_0000
XCTAssertEqual(mask.emphasis, PPU.Mask.Emphasis(r: true, g: false, b: false))
mask.rawValue = 0b0100_0000
XCTAssertEqual(mask.emphasis, PPU.Mask.Emphasis(r: false, g: true, b: false))
mask.rawValue = 0b1000_0000
XCTAssertEqual(mask.emphasis, PPU.Mask.Emphasis(r: false, g: false, b: true))
}
func testPalPix() {
let pp12 = PalPix(palette: 1, pixel: 2)
XCTAssertEqual(pp12.palette, 1)
XCTAssertEqual(pp12.pixel, 2)
let pp30 = PalPix(palette: 3, pixel: 0)
XCTAssertEqual(pp30.palette, 3)
XCTAssertEqual(pp30.pixel, 0)
}
func testPPU() {
let chrmem = DRAM(data: Data(count: 0x1000))
let sprmem = DRAM(data: Data(count: 256))
let ppu = PPU(chrmem: chrmem, vram: BGVM(), sprmem: sprmem)
ppu[0x2000] = 0xAB // write PPUCTRL
XCTAssertEqual(ppu.ctrl.rawValue, 0xAB)
ppu[0x2001] = 0xCD // write PPUMASK
XCTAssertEqual(ppu.mask.rawValue, 0xCD)
ppu.writeLatchW = true
ppu.stat.vblank = true
let stat = ppu[0x2002] // read PPUSTATUS($2002), reset $2006 writing status, clear vblank
XCTAssertEqual(stat, 0x80)
XCTAssertFalse(ppu.writeLatchW)
XCTAssertFalse(ppu.stat.vblank)
ppu[0x2003] = 0x12 // write OAMADDR
XCTAssertEqual(ppu.sprAddr, 0x12)
ppu[0x2004] = 0xAB // write OAMDATA
XCTAssertEqual(ppu.sprAddr, 0x13) // sprite address incremented
ppu[0x2003] = 0x12 // write OAMADDR
let ff = ppu[0x2004] // read OAMDATA
XCTAssertEqual(ff, 0xAB)
XCTAssertEqual(ppu.sprAddr, 0x12) // sprite address unchanged
// $3F10 = Sprite Palette #0:0
ppu[0x2006] = 0x3F // write PPUADDR H
ppu[0x2006] = 0x10 // write PPUADDR L
XCTAssertEqual(ppu.ppuAddr, 0x3F10)
ppu[0x2007] = 0x2C // write PPUDATA
XCTAssertEqual(ppu.ppuAddr, 0x3F11) // address incremented
ppu[0x2006] = 0x3F // write PPUADDR H
ppu[0x2006] = 0x10 // write PPUADDR L
let dd = ppu[0x2007] // read PPUDATA
XCTAssertEqual(dd, 0x2C)
// $3F00 = BG Palette #0:0
ppu[0x2006] = 0x3F // write PPUADDR H
ppu[0x2006] = 0x00 // write PPUADDR L
let ee = ppu[0x2007] // read PPUDATA
XCTAssertEqual(ee, 0x2C) // $3F10 is mirror of $3F00
ppu[0x2005] = 54 // write PPUSCROLL X
ppu[0x2005] = 32 // write PPUSCROLL Y
XCTAssertEqual(ppu.scroll, Point(x: 54, y: 32))
}
}
extension PPU.Mask.Emphasis: Equatable {
public static func == (a: PPU.Mask.Emphasis, b: PPU.Mask.Emphasis) -> Bool {
return a.rawValue == b.rawValue
}
init(r: Bool, g: Bool, b: Bool) {
self.init(rawValue: (b.byte<<2) | (g.byte<<1) | r.byte)
}
}
| 32.052941 | 97 | 0.603046 |
91441b5220d100918c531395cb31e3dc56b85865 | 6,048 | //
// EmojiCell.swift
// Basic Integration
//
// Created by Yuki Tokuhiro on 5/29/19.
// Copyright © 2019 Stripe. All rights reserved.
//
import UIKit
let emojiBackgroundBottomPadding = CGFloat(50)
let emojiContentInset = CGFloat(2)
let defaultPadding = CGFloat(8)
class EmojiCell: UICollectionViewCell {
struct Colors {
let background: UIColor
let price: UIColor
}
let priceLabel: UILabel
let emojiLabel: UILabel
let plusMinusButton: PlusMinusButton
override var isSelected: Bool {
didSet {
if isSelected {
UIView.animate(withDuration: 0.2) {
self.contentView.backgroundColor = .stripeBrightGreen
self.emojiLabel.textColor = .white
self.priceLabel.textColor = .white
self.plusMinusButton.style = .minus
}
} else {
UIView.animate(withDuration: 0.2) {
self.contentView.backgroundColor = UIColor(
red: 231 / 255, green: 235 / 255, blue: 239 / 255, alpha: 1)
self.emojiLabel.textColor = .black
self.priceLabel.textColor = .black
#if canImport(CryptoKit)
if #available(iOS 13.0, *) {
self.contentView.backgroundColor = .systemGray5
self.emojiLabel.textColor = .label
self.priceLabel.textColor = .label
}
#endif
self.plusMinusButton.style = .plus
}
}
}
}
override init(frame: CGRect) {
priceLabel = UILabel()
priceLabel.font = UIFont.boldSystemFont(ofSize: 16)
emojiLabel = UILabel()
emojiLabel.font = UIFont.systemFont(ofSize: 75)
plusMinusButton = PlusMinusButton()
plusMinusButton.backgroundColor = .clear
super.init(frame: frame)
contentView.layer.cornerRadius = 4
installConstraints()
isSelected = false
}
required init(coder: NSCoder) {
fatalError()
}
public func configure(with product: Product, numberFormatter: NumberFormatter) {
priceLabel.text = numberFormatter.string(from: NSNumber(value: Float(product.price) / 100))!
emojiLabel.text = product.emoji
}
// MARK: - Layout
private func installConstraints() {
let emojiContentBackground = UIView()
emojiContentBackground.backgroundColor = .white
#if canImport(CryptoKit)
if #available(iOS 13.0, *) {
emojiContentBackground.backgroundColor = .systemBackground
}
#endif
emojiContentBackground.layer.cornerRadius = 4
for view in [emojiContentBackground, priceLabel, emojiLabel, plusMinusButton] {
view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(view)
}
NSLayoutConstraint.activate([
emojiContentBackground.leadingAnchor.constraint(
equalTo: contentView.leadingAnchor, constant: emojiContentInset),
emojiContentBackground.trailingAnchor.constraint(
equalTo: contentView.trailingAnchor, constant: -emojiContentInset),
emojiContentBackground.topAnchor.constraint(
equalTo: contentView.topAnchor, constant: emojiContentInset),
emojiContentBackground.bottomAnchor.constraint(
equalTo: contentView.bottomAnchor, constant: -emojiBackgroundBottomPadding),
emojiLabel.centerXAnchor.constraint(equalTo: emojiContentBackground.centerXAnchor),
emojiLabel.centerYAnchor.constraint(equalTo: emojiContentBackground.centerYAnchor),
priceLabel.leadingAnchor.constraint(
equalTo: contentView.leadingAnchor, constant: defaultPadding),
priceLabel.centerYAnchor.constraint(
equalTo: contentView.bottomAnchor, constant: -emojiBackgroundBottomPadding / 2),
plusMinusButton.trailingAnchor.constraint(
equalTo: contentView.trailingAnchor, constant: -10),
plusMinusButton.topAnchor.constraint(
equalTo: emojiContentBackground.bottomAnchor, constant: 10),
plusMinusButton.bottomAnchor.constraint(
equalTo: contentView.bottomAnchor, constant: -10),
plusMinusButton.widthAnchor.constraint(equalTo: plusMinusButton.heightAnchor),
])
}
}
class PlusMinusButton: UIView {
enum Style {
case plus
case minus
}
var style: Style = .plus {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
let circle = UIBezierPath(ovalIn: rect)
let backgroundColor: UIColor = {
var color = UIColor.white
#if canImport(CryptoKit)
if #available(iOS 13.0, *) {
color = .systemBackground
}
#endif
return color
}()
let circleColor: UIColor = style == .plus ? .stripeDarkBlue : backgroundColor
circleColor.setFill()
circle.fill()
let width = rect.size.width / 2
let thickness = CGFloat(2)
let horizontalLine = UIBezierPath(
rect: CGRect(
x: width / 2,
y: rect.size.height / 2 - thickness / 2,
width: width,
height: thickness))
let verticalLine = UIBezierPath(
rect: CGRect(
x: rect.size.width / 2 - thickness / 2,
y: rect.size.height / 4,
width: thickness,
height: rect.size.height / 2))
let lineColor: UIColor = style == .minus ? .stripeDarkBlue : backgroundColor
lineColor.setFill()
horizontalLine.fill()
if style == .plus {
verticalLine.fill()
}
}
}
| 35.786982 | 100 | 0.588294 |
166641501dd2a9e70faa285bf2091ed779fd37d4 | 930 | import Cocoa
public protocol TextAnnotationUpdateDelegate {
func textAnnotationUpdated(textAnnotation: TextAnnotation,
modelable: TextAnnotationModelable)
}
public protocol TextAnnotation where Self: NSView {
var delegate: TextAnnotationDelegate? { get set }
var textUpdateDelegate: TextAnnotationUpdateDelegate? { get set }
var text: String { get set }
var textColor: TextColor { get set }
var frame: CGRect { get set }
var state: TextAnnotationState { get set }
func startEditing()
func updateFrame(with modelable: TextAnnotationModelable)
func updateColor(with color: NSColor)
}
extension TextAnnotation {
public func delete() {
removeFromSuperview()
}
public func select() {
state = .active
}
public func deselect() {
state = .inactive
}
public func addTo(canvas: TextAnnotationCanvas) {
canvas.add(textAnnotation: self)
}
}
| 22.682927 | 67 | 0.705376 |
38e198c1c3116f15a80a23dfde5b6af10fc77dc4 | 505 | import Foundation
import UIKit
public protocol EventDescriptor: AnyObject {
var startDate: Date {get set}
var endDate: Date {get set}
var isAllDay: Bool {get}
var text: String {get}
var attributedText: NSAttributedString? {get}
var lineBreakMode: NSLineBreakMode? {get}
var font : UIFont {get}
var color: UIColor {get}
var textColor: UIColor {get}
var backgroundColor: UIColor {get}
var editedEvent: EventDescriptor? {get set}
func makeEditable() -> Self
func commitEditing()
}
| 26.578947 | 47 | 0.730693 |
0936567bcab342b3ab92c534b862ae7d649a7ce4 | 18,145 | //
// RocketChatViewController.swift
// RocketChatViewController Example
//
// Created by Rafael Kellermann Streit on 30/07/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
import DifferenceKit
public extension UICollectionView {
public func dequeueChatCell(withReuseIdentifier reuseIdetifier: String, for indexPath: IndexPath) -> ChatCell {
guard let cell = dequeueReusableCell(withReuseIdentifier: reuseIdetifier, for: indexPath) as? ChatCell else {
fatalError("Trying to dequeue a reusable UICollectionViewCell that doesn't conforms to BindableCell protocol")
}
return cell
}
}
/**
A type-erased ChatCellViewModel that must conform to the Differentiable protocol.
The `AnyChatCellViewModel` type forwards equality comparisons and utilities operations or properties
such as relatedReuseIdentifier to an underlying differentiable value,
hiding its specific underlying type.
*/
public struct AnyChatItem: ChatItem, Differentiable {
public var relatedReuseIdentifier: String {
return base.relatedReuseIdentifier
}
public let base: ChatItem
public let differenceIdentifier: AnyHashable
let isUpdatedFrom: (AnyChatItem) -> Bool
public init<D: Differentiable & ChatItem>(_ base: D) {
self.base = base
self.differenceIdentifier = AnyHashable(base.differenceIdentifier)
self.isUpdatedFrom = { source in
guard let sourceBase = source.base as? D else { return false }
return base.isContentEqual(to: sourceBase)
}
}
public func isContentEqual(to source: AnyChatItem) -> Bool {
return isUpdatedFrom(source)
}
}
/**
A type-erased SectionController.
The `AnySectionController` type forwards equality comparisons and servers as a data source
for RocketChatViewController to build one section, hiding its specific underlying type.
*/
public struct AnyChatSection: ChatSection {
public weak var controllerContext: UIViewController? {
get {
return base.controllerContext
}
set(newControllerContext) {
base.controllerContext = newControllerContext
}
}
public var object: AnyDifferentiable {
return base.object
}
public var base: ChatSection
public init<D: ChatSection>(_ base: D) {
self.base = base
}
public func viewModels() -> [AnyChatItem] {
return base.viewModels()
}
public func cell(for viewModel: AnyChatItem, on collectionView: UICollectionView, at indexPath: IndexPath) -> ChatCell {
return base.cell(for: viewModel, on: collectionView, at: indexPath)
}
}
extension AnyChatSection: Differentiable {
public var differenceIdentifier: AnyHashable {
return AnyHashable(base.object.differenceIdentifier)
}
public func isContentEqual(to source: AnyChatSection) -> Bool {
return base.object.isContentEqual(to: source.object)
}
}
/**
The responsible for implementing the data source of a single section
which represents an object splitted into differentiable view models
each one being binded on a reusable UICollectionViewCell that get updated when there's
something to update on its content.
A SectionController is also responsible for handling the actions
and interactions with the object related to it.
A SectionController's object is meant to be immutable.
*/
public protocol ChatSection {
var object: AnyDifferentiable { get }
var controllerContext: UIViewController? { get set }
func viewModels() -> [AnyChatItem]
func cell(for viewModel: AnyChatItem, on collectionView: UICollectionView, at indexPath: IndexPath) -> ChatCell
}
/**
A single split of an object that binds an UICollectionViewCell and can be differentiated.
A ChatCellViewModel also holds the related UICollectionViewCell's reuseIdentifier.
*/
public protocol ChatItem {
var relatedReuseIdentifier: String { get }
}
public extension ChatItem where Self: Differentiable {
// In order to use a ChatCellViewModel along with a SectionController
// we must use it as a type-erased ChatCellViewModel, which in this case also means
// that it must conform to the Differentiable protocol.
public var wrapped: AnyChatItem {
return AnyChatItem(self)
}
}
/**
A protocol that must be implemented by all cells to padronize the way we bind the data on its view.
*/
public protocol ChatCell {
var messageWidth: CGFloat { get set }
var viewModel: AnyChatItem? { get set }
func configure(completeRendering: Bool)
}
public protocol ChatDataUpdateDelegate: class {
func didUpdateChatData(newData: [AnyChatSection], updatedItems: [AnyHashable])
}
/**
RocketChatViewController is basically a UIViewController that holds
two key components: a list and a message composer.
The whole idea is to keep the list as close as possible to a regular UICollectionView,
but with some features and add-ons to make it more "chat friendly" in the point of view of
performance, modularity and flexibility.
To solve modularity (and help with performance) we've created a set of protocols
and wrappers that ensure that we treat each object as a section of our list
then break it down as much as possible into subobjects that can be differentiated.
Bringing it to the chat concept, each message is a section, each section can have one
or more items, it will depend on the complexity of each message. For example, if it's a simple
text-only message we can represent it using a single reusable cell for this message's section,
on the other hand if the message has attachments or multimedia content, it's better to
split the most basic components of a message (avatar, username and text) into a reusable cell
and the multimedia content (video, image, link preview, etc) into other reusable cells. This
way we will wind up with simpler cells that cost less to reuse.
To solve performance our main efforts are concentrated on updating the views the least
possible. In order to do that we rely on a third-party (awesome) diffing library
called DifferenceKit. Based on the benchmarks provided on its GitHub page it is the most
performatic diffing library available for iOS development now. DifferenceKit also provides a
UICollectionView extension that performs batch updates based on a changeset making sure that
only the items that changed are going to be refreshed. On top of DifferenceKit's reloading
we've implemented a simple operation queue to guarantee that no more than one reload will run
at once.
To solve flexibility we thought a lot on how to do the things above but yet keep it a regular
UICollectionView for those who just want to implement their own list, and we decided that we would
manage the UICollectionViewDataSource through a public `data` property that reflects on a private `internalData`
property. This way on a subclass of RocketChatViewController we just need to process the data and set to the `data`
property that the superclass implementation will handle the data source and will be able to apply the custom reload
method managed by our operation queue. On the other hand, if anyone wants to implement their message list without
having to conform to DifferenceKit and our protocols, he just need to override the UICollectionViewDataSource methods
and provide a custom implementation.
Minor features:
- Inverted mode
- Self-sizing cells support
*/
open class RocketChatViewController: UICollectionViewController {
open var composerHeightConstraint: NSLayoutConstraint!
open var composerView = ComposerView()
open override var inputAccessoryView: UIView? {
guard presentedViewController?.isBeingDismissed != false else {
return nil
}
composerView.layoutMargins = view.layoutMargins
composerView.directionalLayoutMargins = systemMinimumLayoutMargins
return composerView
}
open override var canBecomeFirstResponder: Bool {
return true
}
private var internalData: [ArraySection<AnyChatSection, AnyChatItem>] = []
open weak var dataUpdateDelegate: ChatDataUpdateDelegate?
private let updateDataQueue: OperationQueue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.qualityOfService = .userInteractive
operationQueue.underlyingQueue = DispatchQueue.main
return operationQueue
}()
open var isInverted = true {
didSet {
DispatchQueue.main.async {
if self.isInverted != oldValue {
self.collectionView?.transform = self.isInverted ? self.invertedTransform : self.regularTransform
self.collectionView?.reloadData()
}
}
}
}
open var isSelfSizing = false
fileprivate let kEmptyCellIdentifier = "kEmptyCellIdentifier"
fileprivate var keyboardHeight: CGFloat = 0.0
private let invertedTransform = CGAffineTransform(scaleX: 1, y: -1)
private let regularTransform = CGAffineTransform(scaleX: 1, y: 1)
override open func viewDidLoad() {
super.viewDidLoad()
setupChatViews()
registerObservers()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startObservingKeyboard()
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopObservingKeyboard()
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
adjustContentSizeIfNeeded()
}
func registerObservers() {
view.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
func setupChatViews() {
guard let collectionView = collectionView else {
return
}
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kEmptyCellIdentifier)
collectionView.collectionViewLayout = UICollectionViewFlowLayout()
collectionView.backgroundColor = .white
collectionView.transform = isInverted ? invertedTransform : collectionView.transform
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.keyboardDismissMode = .interactive
collectionView.contentInsetAdjustmentBehavior = isInverted ? .never : .always
collectionView.scrollsToTop = false
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout, isSelfSizing {
flowLayout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
}
}
open func updateData(with target: [ArraySection<AnyChatSection, AnyChatItem>]) {
updateDataQueue.cancelAllOperations()
updateDataQueue.addOperation { [weak self] in
guard
let strongSelf = self,
let collectionView = strongSelf.collectionView
else {
return
}
let source = strongSelf.internalData
UIView.performWithoutAnimation {
let changeset = StagedChangeset(source: source, target: target)
collectionView.reload(using: changeset, interrupt: { $0.changeCount > 100 }) { newData, changes in
strongSelf.internalData = newData
let newSections = newData.map { $0.model }
let updatedItems = strongSelf.updatedItems(from: source, with: changes)
strongSelf.dataUpdateDelegate?.didUpdateChatData(newData: newSections, updatedItems: updatedItems)
assert(newSections.count == newData.count)
}
}
}
}
func updatedItems(from data: [ArraySection<AnyChatSection, AnyChatItem>], with changes: Changeset<[ArraySection<AnyChatSection, AnyChatItem>]>?) -> [AnyHashable] {
guard let changes = changes else {
return []
}
var updatedItems = [AnyHashable]()
changes.elementUpdated.forEach { item in
let section = data[item.section]
let elementId = section.elements[item.element].differenceIdentifier
updatedItems.append(elementId)
}
changes.elementDeleted.forEach { item in
let section = data[item.section]
let elementId = section.elements[item.element].differenceIdentifier
updatedItems.append(elementId)
}
return updatedItems
}
}
// MARK: Content Adjustment
extension RocketChatViewController {
@objc open var topHeight: CGFloat {
if navigationController?.navigationBar.isTranslucent ?? false {
var top = navigationController?.navigationBar.frame.height ?? 0.0
top += UIApplication.shared.statusBarFrame.height
return top
}
return 0.0
}
@objc open var bottomHeight: CGFloat {
var composer = keyboardHeight > 0.0 ? keyboardHeight : composerView.frame.height
composer += view.safeAreaInsets.bottom
return composer
}
fileprivate func adjustContentSizeIfNeeded() {
guard let collectionView = collectionView else { return }
var contentInset = collectionView.contentInset
if isInverted {
contentInset.bottom = topHeight
contentInset.top = bottomHeight
} else {
contentInset.bottom = bottomHeight
}
collectionView.contentInset = contentInset
collectionView.scrollIndicatorInsets = contentInset
}
}
extension RocketChatViewController {
open override func numberOfSections(in collectionView: UICollectionView) -> Int {
return internalData.count
}
open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return internalData[section].elements.count
}
open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let sectionController = internalData[indexPath.section].model
let viewModels = sectionController.viewModels()
if indexPath.row >= viewModels.count {
return collectionView.dequeueReusableCell(withReuseIdentifier: kEmptyCellIdentifier, for: indexPath)
}
let viewModel = viewModels[indexPath.row]
guard let chatCell = sectionController.cell(for: viewModel, on: collectionView, at: indexPath) as? UICollectionViewCell else {
fatalError("The object conforming to BindableCell is not a UICollectionViewCell as it must be")
}
return chatCell
}
open override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
cell.contentView.transform = isInverted ? invertedTransform : regularTransform
}
}
extension RocketChatViewController: UICollectionViewDelegateFlowLayout {}
extension RocketChatViewController {
func startObservingKeyboard() {
NotificationCenter.default.addObserver(
self,
selector: #selector(_onKeyboardFrameWillChangeNotificationReceived(_:)),
name: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil
)
}
func stopObservingKeyboard() {
NotificationCenter.default.removeObserver(
self,
name: NSNotification.Name.UIKeyboardWillChangeFrame,
object: nil
)
}
@objc private func _onKeyboardFrameWillChangeNotificationReceived(_ notification: Notification) {
guard presentedViewController?.isBeingDismissed != false else {
return
}
guard
let userInfo = notification.userInfo,
let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
let collectionView = collectionView
else {
return
}
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let safeAreaFrame = view.safeAreaLayoutGuide.layoutFrame.insetBy(dx: 0, dy: -additionalSafeAreaInsets.top)
let intersection = safeAreaFrame.intersection(keyboardFrameInView)
let animationDuration: TimeInterval = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve = UIViewAnimationOptions(rawValue: animationCurveRaw)
guard intersection.height != self.keyboardHeight else {
return
}
UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: {
self.keyboardHeight = intersection.height
// Update contentOffset with new keyboard size
var contentOffset = collectionView.contentOffset
contentOffset.y -= intersection.height
collectionView.contentOffset = contentOffset
self.view.layoutIfNeeded()
}, completion: { _ in
UIView.performWithoutAnimation {
self.view.layoutIfNeeded()
}
})
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object as AnyObject === view, keyPath == "frame" {
guard let window = UIApplication.shared.keyWindow else {
return
}
composerView.containerViewLeadingConstraint.constant = window.bounds.width - view.bounds.width
}
}
}
| 37.335391 | 167 | 0.69887 |
75392b6cb60501d93a38bac30051d7143713dbc3 | 235 | //
// NERoomDestroyEvent.swift
// NELiveRoom
//
// Created by Wenchao Ding on 2021/5/25.
//
import Foundation
@objc
open class NERoomDestroyEvent: NSObject {
/// 房间信息
@objc
public var roomInfo: NERoomInfo?
}
| 13.055556 | 41 | 0.646809 |
916c1320a1e89199d8731818a3036a153c4e4ceb | 4,374 | //
// GradientView.swift
// GradientView
//
// Created by Lorenzo Oliveto on 09/03/18.
// Copyright © 2018 Mumble. All rights reserved.
//
import UIKit
open class GradientView: UIView {
private var gradientLayer: CAGradientLayer!
open var colors: [Any]? {
didSet {
self.gradientLayer.colors = colors
}
}
/* The start and end points of the gradient when drawn into the layer's
* coordinate space. The start point corresponds to the first gradient
* stop, the end point to the last gradient stop. Both points are
* defined in a unit coordinate space that is then mapped to the
* layer's bounds rectangle when drawn. (I.e. [0,0] is the bottom-left
* corner of the layer, [1,1] is the top-right corner.) The default values
* are [.5,0] and [.5,1] respectively. Both are animatable. */
open var startPoint: CGPoint? {
didSet {
if let startPoint = startPoint {
self.gradientLayer.startPoint = startPoint
} else {
self.gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
}
}
}
open var endPoint: CGPoint? {
didSet {
if let endPoint = endPoint {
self.gradientLayer.endPoint = endPoint
} else {
self.gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
}
}
}
// MARK: - Initializers
/**
Initializes the view with a frame and an array of colors for the gradient.
- Parameter frame: The frame for the view.
- Parameter colors: The colors of the gradient.
*/
convenience init(frame: CGRect, colors: [Any]) {
self.init(frame: frame, colors: colors, startPoint: nil, endPoint: nil)
}
/**
Initializes the view with a frame, an array of colors for the gradient and the start and end point of the gradient.
- Parameter frame: The frame for the view.
- Parameter colors: The colors of the gradient.
- Parameter startPoint: The startPoint of the gradient.
- Parameter endPoint: The endPoint of the gradient.
*/
convenience init(frame: CGRect, colors: [Any], startPoint: CGPoint?, endPoint: CGPoint?) {
self.init(frame: frame)
self.colors = colors
self.startPoint = startPoint
if let endPoint = endPoint {
self.endPoint = endPoint
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initGradientLayer()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initGradientLayer()
}
private func initGradientLayer() {
self.gradientLayer = CAGradientLayer()
self.gradientLayer.frame = self.bounds
if let colors = self.colors {
self.gradientLayer.colors = colors
}
self.layer.masksToBounds = true
self.layer.insertSublayer(self.gradientLayer, at: 0)
}
// MARK: - Layout
override open func layoutSubviews() {
super.layoutSubviews()
if let gradientLayer = self.gradientLayer {
gradientLayer.frame = self.bounds
}
}
/**
Set the start and end point of the gradient.
- Parameter startPoint: start point.
- Parameter endPoint: end point.
*/
open func set(startPoint: CGPoint, endPoint: CGPoint) {
self.gradientLayer.startPoint = startPoint
self.gradientLayer.endPoint = endPoint
}
}
open class VerticalGradientView: GradientView {
override init(frame: CGRect) {
super.init(frame: frame)
set(startPoint: CGPoint(x: 0.5, y: 0), endPoint: CGPoint(x: 0.5, y: 1))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
set(startPoint: CGPoint(x: 0.5, y: 0), endPoint: CGPoint(x: 0.5, y: 1))
}
convenience init(frame: CGRect, colors: [Any], startPoint: CGPoint?, endPoint: CGPoint?) {
self.init(frame: frame)
self.colors = colors
self.startPoint = startPoint ?? CGPoint(x: 0.5, y: 0)
if let endPoint = endPoint {
self.endPoint = endPoint
} else {
self.endPoint = CGPoint(x: 0.5, y: 1)
}
}
}
| 30.802817 | 120 | 0.593964 |
8732af5df6b548224240d73f950962a2561a4dbc | 1,760 | //
// UserMedia.swift
// Instagram
//
// Created by XXY on 16/3/1.
// Copyright © 2016年 XXY. All rights reserved.
//
import UIKit
import Parse
class UserMedia: NSObject {
/**
Method to post user media to Parse by uploading image file
- parameter image: Image that the user wants upload to parse
- parameter caption: Caption text input by the user
- parameter completion: Block to be executed after save operation is complete
*/
class func postUserImage(image: UIImage?, withCaption caption: String?, withCompletion completion: PFBooleanResultBlock?) {
// Create Parse object PFObject
let media = PFObject(className: "UserMedia")
// Add relevant fields to the object
media["media"] = getPFFileFromImage(image) // PFFile column type
media["author"] = PFUser.currentUser() // Pointer column type that points to PFUser
media["caption"] = caption
media["likesCount"] = 0
media["commentsCount"] = 0
// Save object (following function will save the object in Parse asynchronously)
media.saveInBackgroundWithBlock(completion)
}
/**
Method to post user media to Parse by uploading image file
- parameter image: Image that the user wants to upload to parse
- returns: PFFile for the the data in the image
*/
class func getPFFileFromImage(image: UIImage?) -> PFFile? {
// check if image is not nil
if let image = image {
// get image data and check if that is not nil
if let imageData = UIImagePNGRepresentation(image) {
return PFFile(name: "image.png", data: imageData)
}
}
return nil
}
}
| 33.207547 | 127 | 0.634659 |
d9633366a77ec8ffe03ffea1456e6a8d32bc41de | 12,332 | //
// SILThroughputViewController.swift
// BlueGecko
//
// Created by Kamil Czajka on 23.4.2021.
// Copyright © 2021 SiliconLabs. All rights reserved.
//
import Foundation
import SVProgressHUD
class SILThroughputViewController: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var navigationBar: UIView!
@IBOutlet weak var speedGaugeView: SILThroughputGaugeView!
@IBOutlet weak var notificationsTestButton: UIButton!
@IBOutlet weak var indicationsTestButton: UIButton!
private let modeSelectedImage = UIImage(named: "checkBoxActive")
private let unselectedModeImage = UIImage(named: "checkBoxInactive")
private let disabledSelectedImage = UIImage(named: "gray_checkbox")
@IBOutlet weak var optionsView: UIView!
@IBOutlet weak var phyLabel: SILConnectionParameterLabel!
@IBOutlet weak var intervalLabel: SILConnectionParameterLabel!
@IBOutlet weak var latencyLabel: SILConnectionParameterLabel!
@IBOutlet weak var supervisionTimeoutLabel: SILConnectionParameterLabel!
@IBOutlet weak var pduLabel: SILConnectionParameterLabel!
@IBOutlet weak var mtuLabel: SILConnectionParameterLabel!
@IBOutlet weak var buttonsView: UIView!
@IBOutlet weak var startStopTestButton: SILPrimaryButton!
private var viewModel: SILThroughputViewModel!
var peripheralManager: SILThroughputPeripheralManager!
var centralManager: SILCentralManager!
var connectedPeripheral: CBPeripheral!
private var disposeBag = SILObservableTokenBag()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.addShadow()
self.navigationBar.superview?.bringSubviewToFront(self.navigationBar)
self.buttonsView.addShadow()
self.addShadowForOptionsView()
self.setImagesForSelectionModeButtons()
self.showProgressView()
viewModel = SILThroughputViewModel(peripheralManager: peripheralManager, centralManager: centralManager, connectedPeripheral: connectedPeripheral)
viewModel.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
subscribeToConnectionParameters()
subscribeToViewControllerUpdateEvents()
self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
viewModel.viewWillDisappear()
}
private func addShadowForOptionsView() {
optionsView.layer.cornerRadius = CornerRadiusStandardValue
optionsView.layer.shadowColor = UIColor.black.cgColor
optionsView.layer.shadowOpacity = 0.3
optionsView.layer.shadowOffset = CGSize.zero
optionsView.layer.shadowRadius = 2
}
private func setImagesForSelectionModeButtons() {
notificationsTestButton.setImage(modeSelectedImage, for: .selected)
notificationsTestButton.setImage(unselectedModeImage, for: .normal)
notificationsTestButton.setImage(disabledSelectedImage, for: [.disabled, .selected])
indicationsTestButton.setImage(modeSelectedImage, for: .selected)
indicationsTestButton.setImage(unselectedModeImage, for: .normal)
indicationsTestButton.setImage(disabledSelectedImage, for: [.disabled, .selected])
}
// MARK: - Subscriptions
private func subscribeToConnectionParameters() {
weak var weakSelf = self
let phyStatus = viewModel.phyStatus.observe( { phy in
guard let weakSelf = weakSelf else { return }
weakSelf.phyLabel.text = "PHY: \(phy.rawValue)"
})
disposeBag.add(token: phyStatus)
let connectionInterval = viewModel.connectionIntervalStatus.observe( { value in
guard let weakSelf = weakSelf else { return }
if value == -1.0 {
weakSelf.intervalLabel.text = "Interval: N/A"
} else {
weakSelf.intervalLabel.text = "Interval: \(Double(value)) ms"
}
})
disposeBag.add(token: connectionInterval)
let slaveLatency = viewModel.slaveLatencyStatus.observe( { value in
guard let weakSelf = weakSelf else { return }
if value == -1.0 {
weakSelf.latencyLabel.text = "Latency: N/A"
} else {
weakSelf.latencyLabel.text = "Latency: \(Double(value)) ms"
}
})
disposeBag.add(token: slaveLatency)
let supervisionTimeout = viewModel.supervisionTimeoutStatus.observe( { value in
guard let weakSelf = weakSelf else { return }
if value == -1.0 {
weakSelf.supervisionTimeoutLabel.text = "Supervision Timeout: N/A"
} else {
weakSelf.supervisionTimeoutLabel.text = "Supervision Timeout: \(Double(value)) ms"
}
})
disposeBag.add(token: supervisionTimeout)
let pdu = viewModel.pduStatus.observe( { value in
guard let weakSelf = weakSelf else { return }
if value == -1 {
weakSelf.pduLabel.text = "PDU: N/A"
} else {
weakSelf.pduLabel.text = "PDU: \(value) bytes"
}
})
disposeBag.add(token: pdu)
let mtu = viewModel.mtuStatus.observe( { value in
guard let weakSelf = weakSelf else { return }
if value == -1 {
weakSelf.mtuLabel.text = "MTU: N/A"
} else {
weakSelf.mtuLabel.text = "MTU: \(value) bytes"
}
})
disposeBag.add(token: mtu)
let peripheralConnectionStatus = viewModel.peripheralConnectionStatus.observe( { value in
guard let weakSelf = weakSelf else { return }
if !value {
weakSelf.viewModel.viewWillDisappear()
SVProgressHUD.dismiss()
weakSelf.navigationController?.popToRootViewController(animated: true)
}
})
disposeBag.add(token: peripheralConnectionStatus)
}
private func subscribeToViewControllerUpdateEvents() {
weak var weakSelf = self
let bluetoothState = viewModel.bluetoothState.observe( { value in
guard let weakSelf = weakSelf else { return }
if !value {
SVProgressHUD.dismiss()
weakSelf.showBluetoothDisabledAlert()
}
})
disposeBag.add(token: bluetoothState)
let testState = viewModel.testState.observe({ state in
guard let weakSelf = weakSelf else { return }
guard state != .none else { return }
weakSelf.hideProgressView()
switch state {
case .invalidCommunicationWithEFR:
weakSelf.showCharacteristicArentNotyfingErrorDialog()
case .noSubscriber:
weakSelf.showNoSubscriberErrorDialog()
default:
break
}
})
disposeBag.add(token: testState)
let throughputResult = viewModel.testResult.observe({ result in
guard let weakSelf = weakSelf else { return }
weakSelf.speedGaugeView.updateView(throughputResult: result)
})
disposeBag.add(token: throughputResult)
let testButtonState = viewModel.testButtonState.observe( { value in
guard let weakSelf = weakSelf else { return }
switch value {
case .EFRToPhoneTest:
debugPrint("EFR TO PHONE!")
weakSelf.indicationsTestButton.isEnabled = false
weakSelf.notificationsTestButton.isEnabled = false
weakSelf.startStopTestButton.isEnabled = false
weakSelf.startStopTestButton.backgroundColor = .lightGray
weakSelf.startStopTestButton.setTitle("Start", for: .normal)
case .phoneToEFRTest:
debugPrint("PHONE TO EFR!")
weakSelf.indicationsTestButton.isEnabled = false
weakSelf.notificationsTestButton.isEnabled = false
weakSelf.startStopTestButton.isEnabled = true
weakSelf.startStopTestButton.backgroundColor = UIColor.sil_siliconLabsRed()
weakSelf.startStopTestButton.setTitle("Stop", for: .normal)
case .readyForTesting:
debugPrint("READY FOR TESTING!")
weakSelf.indicationsTestButton.isEnabled = true
weakSelf.notificationsTestButton.isEnabled = true
weakSelf.startStopTestButton.isEnabled = true
weakSelf.startStopTestButton.backgroundColor = UIColor.sil_regularBlue()
weakSelf.startStopTestButton.setTitle("Start", for: .normal)
}
})
disposeBag.add(token: testButtonState)
let phoneTestModeSelection = viewModel.phoneTestModeSelected.observe( { selectedMode in
guard let weakSelf = weakSelf else { return }
switch selectedMode {
case .indicationsSelected:
debugPrint("INDICATIONS SELECTED")
weakSelf.indicationsTestButton.isSelected = true
weakSelf.notificationsTestButton.isSelected = false
case .notificationsSelected:
debugPrint("NOTIFICATIONS SELECTED")
weakSelf.indicationsTestButton.isSelected = false
weakSelf.notificationsTestButton.isSelected = true
}
})
disposeBag.add(token: phoneTestModeSelection)
}
// MARK: - User Actions
@IBAction func notificationsButtonWasTapped(_ sender: UIButton) {
debugPrint("NOTIFICATIONS BUTTON WAS TAPPED")
viewModel.changePhoneTestModeSelection(newSelection: .notificationsSelected)
}
@IBAction func indicationsButtonWasTapped(_ sender: UIButton) {
debugPrint("INDICATIONS BUTTON WAS TAPPED")
viewModel.changePhoneTestModeSelection(newSelection: .indicationsSelected)
}
@IBAction func didBackButtonTapped(_ sender: UIButton) {
backToHomeScreenActions()
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
backToHomeScreenActions()
return false
}
private func backToHomeScreenActions() {
centralManager.disconnect(from: connectedPeripheral)
viewModel.viewWillDisappear()
self.navigationController?.popToRootViewController(animated: true)
}
@IBAction func startStopButtonWasTapped(_ sender: UIButton) {
viewModel.changeTestState()
}
private func showBluetoothDisabledAlert() {
let bluetoothDisabledAlert = SILBluetoothDisabledAlert.throughput
self.alertWithOKButton(title: bluetoothDisabledAlert.title, message: bluetoothDisabledAlert.message, completion: { _ in
self.viewModel.viewWillDisappear()
self.navigationController?.popViewController(animated: true)
})
}
private func showProgressView() {
SVProgressHUD.show(withStatus: "Reading device state…")
}
private func hideProgressView() {
SVProgressHUD.dismiss()
}
private func showNoSubscriberErrorDialog() {
self.alertWithOKButton(title: "Error: Failed to find Throughput service. This demo may not work correctly.",
message: "This demo requires Bluetooth - SoC Throughput sample app running on the kit. Please ensure it has been correctly flashed.")
}
private func showCharacteristicArentNotyfingErrorDialog() {
self.alertWithOKButton(title: "Error: Failed to find Throughput service",
message: "This demo requires Bluetooth - SoC Throughput sample app running on the kit. Please ensure it has been correctly flashed",
completion: { alertAction in
self.backToHomeScreenActions()
})
}
}
| 40.9701 | 164 | 0.637853 |
5066d0bf49a90c663b6304ae42c433b704ab26ef | 1,702 | //
// UIView+Frame.swift
// BSBuDeJie
//
// Created by mh on 16/4/21.
// Copyright © 2016年 BS. All rights reserved.
//
import UIKit
extension UIView{
/// x 坐标
var x:CGFloat{
set{
var newFrame = frame
newFrame.origin.x = newValue
frame = newFrame
}
get{ return frame.origin.x }}
/// y 坐标
var y:CGFloat{
set{
var newFrame = frame
newFrame.origin.y = newValue
frame = newFrame
}
get{ return frame.origin.y }}
/// width 宽度
var width:CGFloat{
set{
var newFrame = frame
newFrame.size.width = newValue
frame = newFrame
}
get{ return frame.size.width }}
/// height 高度
var height:CGFloat{
set{
var newFrame = frame
newFrame.size.height = newValue
frame = newFrame
}
get{ return frame.size.height }}
/// centerX 中心点x
var centerX:CGFloat{
set{
var newCenter = center
newCenter.x = newValue
center = newCenter
}
get{ return center.x }}
/// centerY 中心点y
var centerY:CGFloat{
set{
var newCenter = center
newCenter.y = newValue
center = newCenter
}
get{ return center.y }}
/// 宽度一半
var halfWidth:CGFloat{
set{ width = newValue * 2 }
get{ return frame.size.width * 0.5 }}
/// 高度一半
var halfHeight:CGFloat{
set{ height = newValue * 2 }
get{ return frame.size.height * 0.5 }}
}
| 22.103896 | 50 | 0.481199 |
f87ced715bfd59de24ce2214971ef2d38f2b163d | 287 | //
// main.swift
// appFirewall
//
// Created by Sergey Fominov on 10/15/20.
// Copyright © 2020 Doug Leith. All rights reserved.
//
import Cocoa
let delegate = AppDelegate()
NSApplication.shared.delegate = delegate
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
| 19.133333 | 63 | 0.735192 |
38f975e6d55c70c0026c32e33bac54391ad1e1b7 | 4,761 | //
// WalletInformationAndMarketWidget.swift
// WalletInformationAndMarketWidget
//
// Created by Marcos Rodriguez on 10/29/20.
// Copyright © 2020 BlueWallet. All rights reserved.
//
import WidgetKit
import SwiftUI
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), marketData: emptyMarketData)
}
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry: SimpleEntry
if (context.isPreview) {
entry = SimpleEntry(date: Date(), marketData: MarketData(nextBlock: "26", sats: "9 134", price: "$10,000", rate: 10000), allWalletsBalance: WalletData(balance: 1000000, latestTransactionTime: LatestTransaction(isUnconfirmed: false, epochValue: 1568804029000)))
} else {
entry = SimpleEntry(date: Date(), marketData: emptyMarketData)
}
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
var entries: [SimpleEntry] = []
let userPreferredCurrency = WidgetAPI.getUserPreferredCurrency();
let allwalletsBalance = WalletData(balance: UserDefaultsGroup.getAllWalletsBalance(), latestTransactionTime: UserDefaultsGroup.getAllWalletsLatestTransactionTime())
let marketDataEntry = MarketData(nextBlock: "...", sats: "...", price: "...", rate: 0)
WidgetAPI.fetchMarketData(currency: userPreferredCurrency, completion: { (result, error) in
let entry: SimpleEntry
if let result = result {
entry = SimpleEntry(date: Date(), marketData: result, allWalletsBalance: allwalletsBalance)
} else {
entry = SimpleEntry(date: Date(), marketData: marketDataEntry, allWalletsBalance: allwalletsBalance)
}
entries.append(entry)
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
})
}
}
struct SimpleEntry: TimelineEntry {
let date: Date
let marketData: MarketData
var allWalletsBalance: WalletData = WalletData(balance: 0)
}
struct WalletInformationAndMarketWidgetEntryView : View {
@Environment(\.widgetFamily) var family
var entry: Provider.Entry
var WalletBalance: some View {
WalletInformationView(allWalletsBalance: entry.allWalletsBalance, marketData: entry.marketData).background(Color.widgetBackground)
}
var MarketStack: some View {
MarketView(marketData: entry.marketData)
}
var SendReceiveButtonsView: some View {
SendReceiveButtons().padding(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/, /*@START_MENU_TOKEN@*/10/*@END_MENU_TOKEN@*/)
}
var body: some View {
if family == .systemLarge {
HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
VStack(alignment: .leading, spacing: nil, content: {
HStack(content: {
WalletBalance.padding()
}).background(Color.widgetBackground)
HStack(content: {
MarketStack }).padding()
SendReceiveButtonsView }).background(Color(.lightGray).opacity(0.77))
})
} else {
HStack(content: {
WalletBalance.padding()
HStack(content: {
MarketStack.padding()
}).background(Color(.lightGray).opacity(0.77))
}).background(Color.widgetBackground)
}
}
}
@main
struct WalletInformationAndMarketWidget: Widget {
let kind: String = "WalletInformationAndMarketWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: Provider()) { entry in
WalletInformationAndMarketWidgetEntryView(entry: entry)
}
.configurationDisplayName("Wallet and Market")
.description("View your total wallet balance and network prices.").supportedFamilies([.systemMedium, .systemLarge])
}
}
struct WalletInformationAndMarketWidget_Previews: PreviewProvider {
static var previews: some View {
WalletInformationAndMarketWidgetEntryView(entry: SimpleEntry(date: Date(), marketData: MarketData(nextBlock: "26", sats: "9 134", price: "$10,000", rate: 0), allWalletsBalance: WalletData(balance: 10000, latestTransactionTime: LatestTransaction(isUnconfirmed: false, epochValue: 1568804029000))))
.previewContext(WidgetPreviewContext(family: .systemMedium))
WalletInformationAndMarketWidgetEntryView(entry: SimpleEntry(date: Date(), marketData: MarketData(nextBlock: "26", sats: "9 134", price: "$10,000", rate: 0), allWalletsBalance: WalletData(balance: 10000, latestTransactionTime: LatestTransaction(isUnconfirmed: false, epochValue: 1568804029000))))
.previewContext(WidgetPreviewContext(family: .systemLarge))
}
}
| 41.043103 | 300 | 0.704264 |
283fdff3d617713c3b5816e844c50bfdc5e7baa4 | 4,708 | //
// QSFPSLabel.swift
// QFFPS
//
// Created by zhangping on 15/12/5.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
// 关联对象的key,只能放到外面.因为extension里面不能有属性
var fpsViewKey = "fpsViewKey"
// 扩展 UIView, 添加属性(利用runtime关联对象)
public extension UIView {
// 添加属性
var fpsView: QSFPSLabel? {
get {
// 从self中获取 fpsViewKey 关联的对象
if let fps = objc_getAssociatedObject(self, &fpsViewKey) as? QSFPSLabel {
// 获取到关联的对象,直接返回
return fps
} else { // 没有获取到关联的对象
// 创建一个 QSFPSLabel 对象
let fps = QSFPSLabel()
// 添加到当前view里面
self.addSubview(fps)
// 调用set 方法来将 fps 关联到 fpsViewKey 上面
self.fpsView = fps
// 返回 fps
return fps
}
}
set {
// 将 newValue 对象 关联到 fpsViewKey
objc_setAssociatedObject(self, &fpsViewKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func show() {
show(CGPointZero)
}
func show(origin: CGPoint) {
fpsView?.frame.origin = origin
}
}
// 自定义 QSFPSLabel,显示view的帧率
public class QSFPSLabel: UILabel {
// fpsLabel的大小
private var FPSSize = CGSize(width: 65, height: 20)
// 帧数的 Font
private var textFont: UIFont? = UIFont.systemFontOfSize(14)
// FPS文字的 Font
private var subTextFont: UIFont? = UIFont.systemFontOfSize(14)
// CADisplayLink
private var link: CADisplayLink?
// 上一次计算帧数的时间
private var lastTime: NSTimeInterval = 0
// 一秒内调用了多少次
private var count = 0
// FPS 文字
private let FPSText = "FPS"
// 构造方法
override init(var frame: CGRect) {
// 判断外面调用的时候是否有传frame进来
if frame.size.width == 0 && frame.size.height == 0 {
frame.size = FPSSize
}
super.init(frame: frame)
// 设置图层的圆角
layer.cornerRadius = 5
clipsToBounds = true
// 设置文字居中显示
textAlignment = NSTextAlignment.Center
// 设置背景颜色
backgroundColor = UIColor(white: 0, alpha: 0.7)
// 获取字体大小
textFont = UIFont(name: "Menlo", size: 14)
if let _ = textFont {
subTextFont = UIFont(name: "Menlo", size: 12)
} else {
textFont = UIFont(name: "Courier", size: 14)
subTextFont = UIFont(name: "Courier", size: 12)
}
// 创建 CADisplayLink 并加入 NSRunLoop
link = CADisplayLink(target: self, selector: "tick:")
link?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
link?.invalidate()
}
override public func sizeThatFits(size: CGSize) -> CGSize {
return FPSSize
}
// 每帧调用
func tick(link: CADisplayLink) {
// 判断是否是第一次调用,第一次调用,设置 上一次计算帧数的时间
if lastTime == 0 {
lastTime = link.timestamp
return
}
// 调用次数++
count++
// 计算距离上次计算帧数的时间
let delta = link.timestamp - lastTime
// 没有到1秒钟
if delta < 1 {
return
}
// 到一秒钟, 计算帧数
let fps = Double(count) / delta
// 赋值最后一次计算帧数时间
lastTime = link.timestamp
// 清空帧数
count = 0
// 计算比例,显示颜色
let progress = fps / 60.0
// 计算 帧数 颜色
let color = UIColor(hue: CGFloat(0.27 * (progress - 0.2)), saturation: 1, brightness: 0.9, alpha: 1)
let fpsString = String(format: "%.1f", arguments: [fps])
// 设置内容
let content = "\(fpsString) \(FPSText)"
// 创建属性文本
let attr = NSMutableAttributedString(string: "\(content)")
// 添加属性
attr.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: attr.length - FPSText.characters.count))
let range = (content as NSString).rangeOfString(FPSText)
attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: range)
attr.addAttribute(NSFontAttributeName, value: textFont!, range: NSRange(location: 0, length: attr.length))
attr.addAttribute(NSFontAttributeName, value: subTextFont!, range: range)
// 赋值文本
attributedText = attr
}
}
| 26.301676 | 148 | 0.540144 |
c1e5e5316bb6de1c60e8abd4f68857d8ab18fabe | 2,048 | import Darwin
public func **(lhs: Tensor, rhs: Tensor) -> Tensor {
return noncommutativeBinaryOperation(lhs, rhs, operation: powf)
}
public func **(lhs: Tensor, rhs: Tensor.Element) -> Tensor {
return Tensor(shape: lhs.shape, elements: lhs.elements.map { powf($0, rhs) })
}
public func **(lhs: Tensor.Element, rhs: Tensor) -> Tensor {
return Tensor(shape: rhs.shape, elements: rhs.elements.map { powf(lhs, $0) })
}
extension Tensor {
public func sin() -> Tensor {
return Tensor(shape: shape, elements: elements.map(sinf))
}
public func cos() -> Tensor {
return Tensor(shape: shape, elements: elements.map(cosf))
}
public func tan() -> Tensor {
return Tensor(shape: shape, elements: elements.map(tanf))
}
public func asin() -> Tensor {
return Tensor(shape: shape, elements: elements.map(asinf))
}
public func acos() -> Tensor {
return Tensor(shape: shape, elements: elements.map(acosf))
}
public func atan() -> Tensor {
return Tensor(shape: shape, elements: elements.map(atanf))
}
public func sinh() -> Tensor {
return Tensor(shape: shape, elements: elements.map(sinhf))
}
public func cosh() -> Tensor {
return Tensor(shape: shape, elements: elements.map(coshf))
}
public func tanh() -> Tensor {
return Tensor(shape: shape, elements: elements.map(tanhf))
}
public func exp() -> Tensor {
return Tensor(shape: shape, elements: elements.map(expf))
}
public func log() -> Tensor {
return Tensor(shape: shape, elements: elements.map(logf))
}
public func sqrt() -> Tensor {
return Tensor(shape: shape, elements: elements.map(sqrtf))
}
public func cbrt() -> Tensor {
return Tensor(shape: shape, elements: elements.map(cbrtf))
}
}
extension Tensor {
public func sigmoid() -> Tensor {
return Tensor(shape: shape, elements: elements.map { 1.0 / (1.0 + expf(-$0)) })
}
}
| 27.675676 | 87 | 0.606934 |
67316a779ec03043116d9c54c64dd436b97e1a23 | 2,020 | //
// DeviceTokens.swift
// TheGreatGame
//
// Created by Oleg Dreyman on 13.06.17.
// Copyright © 2017 The Great Game. All rights reserved.
//
import Foundation
import Alba
import Shallows
public final class DeviceTokens {
var notifications: ThreadSafe<PushToken?> = ThreadSafe(nil)
var complication: ThreadSafe<PushToken?> = ThreadSafe(nil)
public private(set) var getNotification: Retrieve<PushToken>!
public private(set) var getComplication: Retrieve<PushToken>!
public init() {
self.getNotification = Retrieve<PushToken>(storageName: "retrieve-notif", retrieve: { (_, completion) in
do {
let val = try self.notifications.read().unwrap()
completion(.success(val))
} catch {
completion(.failure(error))
}
})
self.getComplication = Retrieve<PushToken>(storageName: "retrieve-compl", retrieve: { (_, completion) in
do {
let val = try self.complication.read().unwrap()
completion(.success(val))
} catch {
completion(.failure(error))
}
})
}
public func subscribeTo(notifications: Subscribe<PushToken>, complication: Subscribe<PushToken>) {
notifications.subscribe(self, with: DeviceTokens.updateNotificationsToken)
complication.subscribe(self, with: DeviceTokens.updateComplicationToken)
}
public let didUpdateNotificationsToken = Publisher<PushToken>(label: "DeviceTokens.didUpdateNotificationsToken")
public let didUpdateComplicationToken = Publisher<PushToken>(label: "DeviceTokens.didUpdateComplicationToken")
func updateNotificationsToken(_ token: PushToken) {
self.notifications.write(token)
didUpdateNotificationsToken.publish(token)
}
func updateComplicationToken(_ token: PushToken) {
self.complication.write(token)
didUpdateComplicationToken.publish(token)
}
}
| 34.237288 | 116 | 0.656436 |
fc2821296689a9149726b85d12ddbb778a870dfe | 9,376 | //
// Firebase.swift
// FirebaseSwift
//
// Created by Graham Chance on 10/15/16.
//
//
import Foundation
import Just
/// This class models an object that can send requests to Firebase, such as POST, GET PATCH and DELETE.
public final class Firebase {
/// Google OAuth2 access token
public var accessToken: String?
/// Legacy Database auth token. You can use the deprecated Firebase Database Secret.
/// You should use the new accessToken instead.
/// See more details here: https://firebase.google.com/docs/database/rest/auth
@available(*, deprecated) public var auth: String?
/// Base URL (e.g. http://myapp.firebaseio.com)
public let baseURL: String
/// Timeout of http operations
public var timeout: Double = 30.0 // seconds
private let headers = ["Accept": "application/json"]
/// Constructor
///
/// - Parameters:
/// - baseURL: Base URL (e.g. http://myapp.firebaseio.com)
/// - auth: Database auth token
public init(baseURL: String = "", accessToken: String? = nil) {
self.accessToken = accessToken
var url = baseURL
if url.characters.last != Character("/") {
url.append(Character("/"))
}
self.baseURL = url
}
/// Performs a synchronous PUT at base url plus given path.
///
/// - Parameters:
/// - path: path to append to base url
/// - value: data to set
/// - Returns: value of set data if successful
public func setValue(path: String, value: Any) -> [String: Any]? {
return put(path: path, value: value)
}
/// Performs an asynchronous PUT at base url plus given path.
///
/// - Parameters:
/// - path: path to append to base url.
/// - value: data to set
/// - asyncCompletion: called on completion with the value of set data if successful.
public func setValue(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
put(path: path, value: value, asyncCompletion: asyncCompletion)
}
/// Performs a synchronous POST at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to post
/// - Returns: value of posted data if successful
public func post(path: String, value: Any) -> [String: Any]? {
return write(value: value, path: path, method: .post, complete: nil)
}
/// Performs an asynchronous POST at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to post
/// - asyncCompletion: called on completion with the value of posted data if successful.
public func post(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
write(value: value, path: path, method: .post, complete: asyncCompletion)
}
/// Performs an synchronous PUT at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to put
/// - Returns: Value of put data if successful
public func put(path: String, value: Any) -> [String: Any]? {
return write(value: value, path: path, method: .put, complete: nil)
}
/// Performs an asynchronous PUT at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to put
/// - asyncCompletion: called on completion with the value of put data if successful.
public func put(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
write(value: value, path: path, method: .put, complete: asyncCompletion)
}
/// Performs a synchronous PATCH at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: data to patch
/// - Returns: value of patched data if successful
public func patch(path: String, value: Any) -> [String: Any]? {
return write(value: value, path: path, method: .patch, complete: nil)
}
/// Performs an asynchronous PATCH at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - value: value to patch
/// - asyncCompletion: called on completion with the value of patched data if successful.
public func patch(path: String,
value: Any,
asyncCompletion: @escaping ([String: Any]?) -> Void) {
write(value: value, path: path, method: .patch, complete: asyncCompletion)
}
/// Performs a synchronous DELETE at given path from the base url.
///
/// - Parameter path: path to append to the base url
public func delete(path: String) {
let url = completeURLWithPath(path: path)
_ = HTTPMethod.delete.justRequest(url, [:], [:], nil, headers, [:], nil, [:],
false, timeout, nil, nil, nil, nil)
}
/// Performs an asynchronous DELETE at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - asyncCompletion: called on completion
public func delete(path: String,
asyncCompletion: @escaping () -> Void) {
let url = completeURLWithPath(path: path)
_ = HTTPMethod.delete.justRequest(url, [:], [:], nil, headers, [:], nil, [:],
false, timeout, nil, nil, nil) { _ in
asyncCompletion()
}
}
/// Performs a synchronous GET at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - Returns: resulting data if successful
public func get(path: String) -> Any? {
return get(path: path, complete: nil)
}
/// Performs an asynchronous GET at given path from the base url.
///
/// - Parameters:
/// - path: path to append to the base url
/// - asyncCompletion: called on completion with the resulting data if successful.
public func get(path: String,
asyncCompletion: @escaping ((Any?) -> Void)) {
get(path: path, complete: asyncCompletion)
}
@discardableResult
private func get(path: String, complete: ((Any?) -> Void)?) -> Any? {
let url = completeURLWithPath(path: path)
let completionHandler = createCompletionHandler(method: .get, callback: complete)
let httpResult = HTTPMethod.get.justRequest(url, [:], [:], nil, headers, [:], nil, [:],
false, timeout, nil, nil, nil, completionHandler)
guard complete == nil else { return nil }
return process(httpResult: httpResult, method: .get)
}
@discardableResult
private func write(value: Any,
path: String,
method: HTTPMethod,
complete: (([String: Any]?) -> Void)? = nil) -> [String: Any]? {
let url = completeURLWithPath(path: path)
let json: Any? = JSONSerialization.isValidJSONObject(value) ? value : [".value": value]
let callback: ((Any?) -> Void)? = complete == nil ? nil : { result in
complete?(result as? [String: Any])
}
let completionHandler = createCompletionHandler(method: method, callback: callback)
let result = method.justRequest(url, [:], [:], json, headers, [:], nil, [:],
false, timeout, nil, nil, nil, completionHandler)
guard complete == nil else { return nil }
return process(httpResult: result, method: method) as? [String : Any]
}
private func completeURLWithPath(path: String) -> String {
var url = baseURL + path + ".json"
if let accessToken = accessToken {
url += "?access_token=" + accessToken
} else if let auth = auth {
url += "?auth=" + auth
}
return url
}
private func process(httpResult: HTTPResult, method: HTTPMethod) -> Any? {
if let e = httpResult.error {
print("ERROR FirebaseSwift-\(method.rawValue) message: \(e.localizedDescription)")
return nil
}
guard httpResult.content != nil else {
print("ERROR FirebaseSwift-\(method.rawValue) message: No content in http response.")
return nil
}
if let json = httpResult.contentAsJSONMap() {
return json
} else {
print("ERROR FirebaseSwift-\(method.rawValue) message: Failed to parse json response. Status code: \(String(describing: httpResult.statusCode))")
return nil
}
}
private func createCompletionHandler(method: HTTPMethod,
callback: ((Any?) -> Void)?) -> ((HTTPResult) -> Void)? {
if let callback = callback {
let completionHandler: ((HTTPResult) -> Void)? = { result in
callback(self.process(httpResult: result, method: method))
}
return completionHandler
}
return nil
}
}
| 37.654618 | 157 | 0.576685 |
fe400f6d9814b094db015fe62ec170be666bb179 | 812 | //
// Request.swift
// TextureSimply_Example
//
// Created by Di on 2019/2/11.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import Moya
class Request {
static func getResult<T>(_ type: T.Type,
target: Service,
complection:@escaping ((T?) -> Void))
where T: Codable {
MoyaProvider<Service>().request(target) { result in
if let value = result.value {
do {
let model = try value.map(type)
complection(model)
} catch let error as MoyaError {
print(error)
} catch {
}
}
}
}
}
| 26.193548 | 66 | 0.432266 |
8928dcf9ade4a5c02ebc73f67f97d74200e69664 | 2,179 | //
// AppDelegate.swift
// CSPieChart
//
// Created by chansim.youk on 01/04/2017.
// Copyright (c) 2017 chansim.youk. 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 throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.361702 | 285 | 0.754016 |
abec92664a669fc940b65c67ac50beb9742e2146 | 5,710 | // Copyright 2018 Tua Rua Ltd.
//
// 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.
//
// Additional Terms
// No part, or derivative of this Air Native Extensions's code is permitted
// to be sold as the basis of a commercially packaged Air Native Extension which
// undertakes the same purpose as this software. That is, a WebView for Windows,
// OSX and/or iOS and/or Android.
// All Rights Reserved. Tua Rua Ltd.
import Cocoa
import Foundation
import WebKit
class PopupVC: NSViewController, WKUIDelegate, WKNavigationDelegate,
URLSessionTaskDelegate, URLSessionDelegate, URLSessionDownloadDelegate {
var webView: WKWebView?
private var request: URLRequest!
private var width: Int!
private var height: Int!
private var downloadTaskSaveTos = [Int: URL]()
convenience init(request: URLRequest, width: Int, height: Int, configuration: WKWebViewConfiguration) {
self.init()
self.request = request
self.width = width
self.height = height
webView = WKWebView(frame: self.view.frame, configuration: configuration)
if let wv = webView {
wv.translatesAutoresizingMaskIntoConstraints = true
wv.navigationDelegate = self
wv.uiDelegate = self
wv.addObserver(self, forKeyPath: "title", options: .new, context: nil)
wv.load(request)
self.view.addSubview(wv)
}
}
func dispose() {
if let wv = webView {
wv.removeObserver(self, forKeyPath: "title")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
let myRect: NSRect = NSRect(x: 0, y: 0, width: self.width, height: self.height)
self.view = NSView(frame: myRect)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let wv = webView else {
return
}
switch keyPath! {
case "title":
if let val = wv.title {
if val != "" {
self.view.window?.title = val
}
}
default:
break
}
return
}
@available(OSX 10.12, *)
public func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters,
initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) {
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true
openPanel.allowsMultipleSelection = true
openPanel.begin(completionHandler: {(result) in
if result.rawValue == NSFileHandlingPanelOKButton {
completionHandler(openPanel.urls)
} else {
completionHandler([])
}
})
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
guard let destinationURL = downloadTaskSaveTos[downloadTask.taskIdentifier] else { return }
let fileManager = FileManager.default
try? fileManager.removeItem(at: destinationURL)
do {
try fileManager.copyItem(at: location, to: destinationURL)
} catch {}
downloadTaskSaveTos[downloadTask.taskIdentifier] = nil
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
var props = [String: Any]()
props["id"] = downloadTask.taskIdentifier
props["url"] = downloadTask.originalRequest?.url?.absoluteString
props["speed"] = 0
props["percent"] = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)) * 100
props["bytesLoaded"] = Double(totalBytesWritten)
props["bytesTotal"] = Double(totalBytesExpectedToWrite)
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url
else {
decisionHandler(.allow)
return
}
let userAction = (navigationAction.navigationType != .other)
if userAction && UrlRequestHeaderManager.shared.persistRequestHeaders,
let host = navigationAction.request.url?.host,
UrlRequestHeaderManager.shared.persistentRequestHeaders.index(forKey: host) != nil {
var request = URLRequest(url: url)
for header in UrlRequestHeaderManager.shared.persistentRequestHeaders[host] ?? [] {
request.addValue(header.1, forHTTPHeaderField: header.0)
}
decisionHandler(.cancel)
webView.load(request)
}
decisionHandler(.allow)
}
}
| 38.066667 | 109 | 0.622417 |
75ed95e80afce925872317631834c2d3c6c70f9f | 1,254 | //
// Rumors.swift
// D&D Tavern Aid
//
// Created by Rafael on 10/05/19.
// Copyright © 2019 Rafael Plinio. All rights reserved.
//
import Foundation
class RumorsManager {
var rumors: [Rumor]
init() {
let fileURL = Bundle.main.url(forResource: "rumors", withExtension: "json")!
let jsonData = try! Data(contentsOf: fileURL)
let jsonDecoder = JSONDecoder()
rumors = try! jsonDecoder.decode([Rumor].self, from: jsonData)
//rumors = [] put it somewhere else for the cloud data feature
}
var rumorsList: [Rumor] {
return rumors
}
func getRandomRumor() -> String {
let index1 = Int(arc4random_uniform(UInt32(rumors.count)))
return rumors[index1].rumor
}
//receive new info from another json sent by the user??
func loadDataFromURL(url: String, completion: @escaping (String?)->()){
REST.loadRumorData(url:url, onComplete: { (rumors) in
self.rumors = rumors
DispatchQueue.main.async {
completion(nil)
}
}) { (error) in
print(error)
completion("error")
}
}
}
| 22.8 | 84 | 0.551037 |
902c99c5d1c1f40f348290c8d45f37e46989da48 | 6,555 | //
// CraftTableViewController.swift
// PrincessGuide
//
// Created by zzk on 2018/5/3.
// Copyright © 2018 zzk. All rights reserved.
//
import UIKit
import Gestalt
class CraftTableViewController: UITableViewController {
struct CardRequire {
let card: Card
let number: Int
}
struct Row {
enum Model {
case summary(Equipment)
case consume(Craft.Consume)
case properties([Property.Item])
case charas([CardRequire])
case text(String, String)
}
var type: UITableViewCell.Type
var data: Model
}
var equipment: Equipment? {
didSet {
if let _ = equipment {
prepareRows()
registerRows()
tableView.reloadData()
}
}
}
private var rows = [Row]()
private func registerRows() {
rows.forEach {
tableView.register($0.type, forCellReuseIdentifier: $0.type.description())
}
}
private func prepareRows() {
rows.removeAll()
guard let equipment = equipment, let craft = equipment.craft else {
return
}
rows = [Row(type: CraftSummaryTableViewCell.self, data: .summary(equipment))]
rows += craft.consumes.map { Row(type: CraftTableViewCell.self, data: .consume($0)) }
rows += equipment.property.ceiled().noneZeroProperties().map { Row(type: CraftPropertyTableViewCell.self, data: .properties([$0])) }
let craftCost = equipment.recursiveCraft.reduce(0) { $0 + $1.craftedCost }
let enhanceCost = equipment.enhanceCost
rows += [Row(type: CraftTextTableViewCell.self, data: .text(NSLocalizedString("Mana Cost of Crafting", comment: ""), String(craftCost)))]
rows += [Row(type: CraftTextTableViewCell.self, data: .text(NSLocalizedString("Mana Cost of Enhancing", comment: ""), String(enhanceCost)))]
let requires = Preload.default.cards.values
.map { CardRequire(card: $0, number: $0.countOf(equipment)) }
.filter { $0.number > 0 }
.sorted { $0.number > $1.number }
if requires.count > 0 {
rows.append(Row(type: CraftCharaTableViewCell.self, data: .charas(requires)))
}
rows.append(Row(type: CraftTextTableViewCell.self, data: .text(NSLocalizedString("Description", comment: ""), equipment.description)))
}
let backgroundImageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundView = backgroundImageView
ThemeManager.default.apply(theme: Theme.self, to: self) { (themeable, theme) in
themeable.backgroundImageView.image = theme.backgroundImage
themeable.tableView.indicatorStyle = theme.indicatorStyle
}
tableView.cellLayoutMarginsFollowReadableWidth = true
tableView.estimatedRowHeight = 84
tableView.rowHeight = UITableView.automaticDimension
tableView.register(CraftSummaryTableViewCell.self, forCellReuseIdentifier: CraftSummaryTableViewCell.description())
tableView.register(CraftTableViewCell.self, forCellReuseIdentifier: CraftTableViewCell.description())
tableView.register(CraftCharaTableViewCell.self, forCellReuseIdentifier: CraftCharaTableViewCell.description())
tableView.tableFooterView = UIView()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = rows[indexPath.row]
switch row.data {
case .consume(let consume):
if let equipment = consume.equipment {
if equipment.craftFlg == 0 {
DropSummaryTableViewController.configureAsync(equipment: equipment, callback: { [weak self] (vc) in
self?.navigationController?.pushViewController(vc, animated: true)
})
} else {
let vc = CraftTableViewController()
vc.navigationItem.title = equipment.equipmentName
vc.equipment = equipment
vc.hidesBottomBarWhenPushed = true
LoadingHUDManager.default.hide()
self.navigationController?.pushViewController(vc, animated: true)
}
}
default:
break
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = rows[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: model.type.description(), for: indexPath) as! CraftDetailConfigurable
cell.configure(for: model.data)
switch cell {
case let cell as CraftSummaryTableViewCell:
cell.delegate = self
case let cell as CraftCharaTableViewCell:
cell.delegate = self
default:
break
}
return cell as! UITableViewCell
}
}
extension CraftTableViewController: CraftSummaryTableViewCellDelegate {
func craftSummaryTableViewCell(_ craftSummaryTableViewCell: CraftSummaryTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: craftSummaryTableViewCell) {
let model = rows[indexPath.row]
guard case .summary(let equipment) = model.data else {
return
}
DropSummaryTableViewController.configureAsync(equipment: equipment) { [weak self] (vc) in
self?.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
extension CraftTableViewController: CraftCharaTableViewCellDelegate {
func craftCharaTableViewCell(_ craftCharaTableViewCell: CraftCharaTableViewCell, didSelect index: Int) {
if let indexPath = tableView.indexPath(for: craftCharaTableViewCell) {
let model = rows[indexPath.row]
guard case .charas(let requires) = model.data else {
return
}
let vc = CDTabViewController(card: requires[index].card)
navigationController?.pushViewController(vc, animated: true)
}
}
}
| 38.110465 | 148 | 0.624561 |
2921cfce2d6cd8444b0ba1a6e5987eaae89d7b07 | 1,101 | // swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "MonkeyKing",
platforms: [
.iOS(.v8),
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "MonkeyKing",
targets: ["MonkeyKing"]
),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "MonkeyKing",
dependencies: []
),
.testTarget(
name: "MonkeyKingTests",
dependencies: ["MonkeyKing"]
),
]
)
| 31.457143 | 122 | 0.595822 |
8981ea77317b485503be26fbabc3584c66bca7f0 | 11,020 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
case UnableToGetInitialFlags
}
@available(*, unavailable, renamed: "Notification.Name.reachabilityChanged")
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
public extension Notification.Name {
static let reachabilityChanged = Notification.Name("reachabilityChanged")
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
@available(*, unavailable, renamed: "Connection")
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public enum Connection: CustomStringConvertible {
case none, wifi, cellular
public var description: String {
switch self {
case .cellular: return "Cellular"
case .wifi: return "WiFi"
case .none: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
@available(*, deprecated, renamed: "allowsCellularConnection")
public let reachableOnWWAN: Bool = true
/// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`)
public var allowsCellularConnection: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
@available(*, deprecated, renamed: "connection.description")
public var currentReachabilityString: String {
return "\(connection)"
}
@available(*, unavailable, renamed: "connection")
public var currentReachabilityStatus: Connection {
return connection
}
public var connection: Connection {
if flags == nil {
try? setReachabilityFlags()
}
switch flags?.connection {
case .none?, nil: return .none
case .cellular?: return allowsCellularConnection ? .cellular : .none
case .wifi?: return .wifi
}
}
fileprivate var isRunningOnDevice: Bool = {
#if targetEnvironment(simulator)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate let reachabilityRef: SCNetworkReachability
fileprivate let reachabilitySerialQueue: DispatchQueue
fileprivate(set) var flags: SCNetworkReachabilityFlags? {
didSet {
guard flags != oldValue else { return }
reachabilityChanged()
}
}
required public init(reachabilityRef: SCNetworkReachability, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
self.allowsCellularConnection = true
self.reachabilityRef = reachabilityRef
self.reachabilitySerialQueue = DispatchQueue(label: "reachability", qos: queueQoS, target: targetQueue)
}
public convenience init?(hostname: String, queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue)
}
public convenience init?(queueQoS: DispatchQoS = .default, targetQueue: DispatchQueue? = nil) {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil }
self.init(reachabilityRef: ref, queueQoS: queueQoS, targetQueue: targetQueue)
}
deinit {
stopNotifier()
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard !notifierRunning else { return }
let callback: SCNetworkReachabilityCallBack = { (reachability, flags, info) in
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
reachability.flags = flags
}
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an initial check
try setReachabilityFlags()
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
@available(*, deprecated, message: "Please use `connection != .none`")
var isReachable: Bool {
return connection != .none
}
@available(*, deprecated, message: "Please use `connection == .cellular`")
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return connection == .cellular
}
@available(*, deprecated, message: "Please use `connection == .wifi`")
var isReachableViaWiFi: Bool {
return connection == .wifi
}
var description: String {
guard let flags = flags else { return "unavailable flags" }
let W = isRunningOnDevice ? (flags.isOnWWANFlagSet ? "W" : "-") : "X"
let R = flags.isReachableFlagSet ? "R" : "-"
let c = flags.isConnectionRequiredFlagSet ? "c" : "-"
let t = flags.isTransientConnectionFlagSet ? "t" : "-"
let i = flags.isInterventionRequiredFlagSet ? "i" : "-"
let C = flags.isConnectionOnTrafficFlagSet ? "C" : "-"
let D = flags.isConnectionOnDemandFlagSet ? "D" : "-"
let l = flags.isLocalAddressFlagSet ? "l" : "-"
let d = flags.isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func setReachabilityFlags() throws {
try reachabilitySerialQueue.sync { [unowned self] in
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(self.reachabilityRef, &flags) {
self.stopNotifier()
throw ReachabilityError.UnableToGetInitialFlags
}
self.flags = flags
}
}
func reachabilityChanged() {
let block = connection != .none ? whenReachable : whenUnreachable
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else { return }
block?(strongSelf)
strongSelf.notificationCenter.post(name: .reachabilityChanged, object: strongSelf)
}
}
}
extension SCNetworkReachabilityFlags {
typealias Connection = Reachability.Connection
var connection: Connection {
guard isReachableFlagSet else { return .none }
// If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
#if targetEnvironment(simulator)
return .wifi
#else
var connection = Connection.none
if !isConnectionRequiredFlagSet {
connection = .wifi
}
if isConnectionOnTrafficOrDemandFlagSet {
if !isInterventionRequiredFlagSet {
connection = .wifi
}
}
if isOnWWANFlagSet {
connection = .cellular
}
return connection
#endif
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
}
| 34.763407 | 135 | 0.673684 |
d6c38c22d16fdbb0771ec9df9a2ecead9ff6a0b9 | 1,631 | import UIKit
extension Component {
func setupTableView(_ tableView: TableView, with size: CGSize) {
tableView.dataSource = componentDataSource
tableView.delegate = componentDelegate
tableView.rowHeight = UITableView.automaticDimension
tableView.layer.masksToBounds = false
tableView.frame.size = size
tableView.frame.size.width = round(size.width - (tableView.contentInset.left))
tableView.frame.origin.x = round(size.width / 2 - tableView.frame.width / 2)
#if os(tvOS)
tableView.remembersLastFocusedIndexPath = true
tableView.layoutMargins = .zero
#endif
prepareItems()
var height: CGFloat = 0.0
for item in model.items {
height += item.size.height
}
height += headerHeight
height += footerHeight
tableView.contentSize = CGSize(
width: tableView.frame.size.width,
height: height - tableView.contentInset.top - tableView.contentInset.bottom)
/// On iOS 8 and prior, the second cell always receives the same height as the first cell. Setting estimatedRowHeight magically fixes this issue. The value being set is not relevant.
if #available(iOS 9, *) {
// Set `estimatedRowHeight` to `0` to opt-out of using self-sizing cells based on autolayout.
tableView.estimatedRowHeight = 0
return
} else {
tableView.estimatedRowHeight = 10
}
}
func layoutTableView(_ tableView: TableView, with size: CGSize) {
tableView.frame.size.width = round(size.width - CGFloat(model.layout.inset.left + model.layout.inset.right))
tableView.frame.origin.x = CGFloat(model.layout.inset.left)
}
}
| 33.285714 | 186 | 0.709381 |
4858e1a8e28b17c67c05447d77a4e2959bcd815e | 3,481 | //
// AppDelegate.swift
// Instagram
//
// Created by Vivian Pham on 3/11/17.
// Copyright © 2017 Vivian Pham. All rights reserved.
//
import UIKit
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Initialize Parse
// Set applicationId and server based on the values in the Heroku settings.
// clientKey is not used on Parse open source unless explicitly configured
Parse.initialize(
with: ParseClientConfiguration(block: { (configuration:ParseMutableClientConfiguration) -> Void in
configuration.applicationId = "Instagram"
configuration.clientKey = "fboivfndvo;newlfopfhovn;ldnvp'wn"
configuration.server = "https://rocky-refuge-37701.herokuapp.com/parse"
})
)
// check if user is logged in.
if PFUser.current() != nil {
// if there is a logged in user then load the home view controller
print("There is a current user")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "TabBarController")
window?.rootViewController = vc
}
else {
print("There is no current user")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
window?.rootViewController = vc
}
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:.
}
}
| 45.802632 | 285 | 0.696352 |
dbf54f6fff398c005ce2aede8b6c8865c694ccaa | 3,172 | //
// This source file is part of the Web3Swift.io open source project
// Copyright 2018 The Web3Swift Authors
// Licensed under Apache License v2.0
//
// EthTransactionBytesTests.swift
//
// Created by Timofey Solonin on 10/05/2018
//
import CryptoSwift
import Nimble
import Quick
@testable import Web3Swift
final class EthTransactionBytesTests: XCTestCase {
func testStaticParametersAreSignedCorrectly() {
expect{
return try EthTransactionBytes(
networkID: SimpleInteger(
integer: 42
),
transactionsCount: EthNumber(
value: 0
),
gasPrice: EthNumber(
hex: SimpleString(
string: "0x06FC23AC00"
)
),
gasEstimate: EthNumber(
value: 21000
),
senderKey: EthPrivateKey(
bytes: BytesFromHexString(
hex: "0x1636e10756e62baabddd4364010444205f1216bdb1644ff8f776f6e2982aa9f5"
)
),
recipientAddress: BytesFromHexString(
hex: "0xcD8aC90d9cc7e4c03430d58d2f3e87Dae70b807e"
),
weiAmount: EthNumber(
hex: SimpleString(
string: "0xE8D4A51000"
)
),
contractCall: EmptyBytes()
).value().toHexString()
}.to(
equal("f869808506fc23ac0082520894cd8ac90d9cc7e4c03430d58d2f3e87dae70b807e85e8d4a510008078a0be0f8648eb3ac495916ae251dae74c6339ff211dcad7b355280b64b3c2746a91a021ed29b918d61cfda1bb5c9dd0c708643308ec38afe5ae224fe1eb010fed042e"),
description: "The above transaction is expected to be correctly signed"
)
}
func test129thTransactionIsSignedCorrectly() {
expect{
return try EthTransactionBytes(
networkID: SimpleInteger(
integer: 1
),
transactionsCount: EthNumber(
value: 128
),
gasPrice: EthNumber(
hex: SimpleString(
string: "0x04A817C800"
)
),
gasEstimate: EthNumber(
value: 21000
),
senderKey: Tim().privateKey(),
recipientAddress: Alice().address(),
weiAmount: EthNumber(
hex: SimpleString(
string: "0x01"
)
),
contractCall: EmptyBytes()
).value().toHexString()
}.to(
equal(
"f86581808504a817c80082520894cd8ac90d9cc7e4c03430d58d2f3e87dae70b807e018026a00f577abf16807cf9a79e0451c80ba7ee5d847234c3d775ea87a008b587eda933a0518e3b6008ead901fdda1acca7d8f003633c50934f12721d76d6d67558449ab3"
),
description: "The above transaction with a nonce of 128 is expected to be correctly signed"
)
}
}
| 34.857143 | 236 | 0.536255 |
1d1e60ee026f05d1f096b0a3944311db024ae6eb | 2,238 | //
// LengthRule.swift
// Navajo
//
// Copyright (c) 2015-2017 Jason Nam (http://jasonnam.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// LengthRule checks the length of password.
open class LengthRule: PasswordRule {
open var range: NSRange?
/// Initialize with minimum and maximum values.
public convenience init(min: Int, max: Int) {
self.init()
range = NSMakeRange(min, max - min + 1)
}
/// Evaluate password. Return false if it is passed and true if failed.
open func evaluate(_ password: String) -> Bool {
guard let range = range else {
return false
}
return !NSLocationInRange(password.count, range)
}
/// Error description.
/// Localization Key - "NAVAJO_LENGTH_ERROR"
open var localizedErrorDescription: String {
var rangeDescription = "nil"
if let range = range {
rangeDescription = String(range.lowerBound) + " - " + String(range.upperBound - 1)
}
return NSLocalizedString("NAVAJO_LENGTH_ERROR", tableName: nil, bundle: Bundle.main, value: "Must be within range ", comment: "Navajo - Length rule") + rangeDescription
}
}
| 37.3 | 176 | 0.701966 |
d62f2ad2eec8efdaec29b602afdbc5c8df407234 | 3,827 | //
// AnimalRequests.swift
// Wildlife
//
// Created by Felix Eisenmenger on 19.06.18.
// Copyright © 2018 Felix Eisenmenger. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
func getAnimalCount(username: String){
let url = eurekaClientUrl + getAnimalUrl(username: username)
Alamofire.request(url, method: .get).responseJSON { response in
if response.result.isSuccess {
let apiResponse = JSON(response.result.value!)
if apiResponse["status"] == JSON.null {
animalCount = apiResponse.count
} else {
animalCount = -1
}
}
}
}
func getAnimalData(username: String, completion: @escaping (Bool, Any?, Error?) -> Void) {
DispatchQueue.global(qos: .utility).async {
let url = eurekaClientUrl + getAnimalUrl(username: username)
Alamofire.request(url, method: .get).responseJSON { response in
if response.result.isSuccess {
let apiResponse = JSON(response.result.value!)
if apiResponse["status"] == JSON.null {
if apiResponse.count > 0 {
for j in apiResponse.array! {
let tempName: String = j["name"].stringValue
let tempId: String = j["id"].stringValue
let tempCreatedBy = j["createdBy"].stringValue
let tempAge = j["age"].stringValue
let tempSex = j["sex"].stringValue
let tempSpecies = j["species"].stringValue
if !animalArray.contains(tempName) {
animalDataArray.append(Animal.init(id: tempId,
name: tempName,
createdBy: tempCreatedBy,
age: tempAge,
sex: tempSex,
species: tempSpecies))
// animalMap.updateValue(tempId, forKey: tempName)
// animalMap.updateValue(tempName, forKey: tempId)
// animalMap.updateValue(tempName, forKey: "animalName")
// animalMap.updateValue(tempCreatedBy, forKey: "createdBy")
// animalMap.updateValue(tempAge, forKey: "age")
// animalMap.updateValue(tempSex, forKey: "sex")
// animalMap.updateValue(tempSpecies, forKey: "species")
//
// allAnimals.append(animalMap)
animalArray.append(tempName)
}
}
DispatchQueue.main.async {
completion(true, nil, nil)
}
} else {
DispatchQueue.main.async {
completion(true, nil, nil)
}
}
} else {
DispatchQueue.main.async {
completion(false, nil, nil)
}
}
}
}
}
}
| 47.8375 | 123 | 0.402143 |
5daed0b7285cd085ac0db88878d35f7a81fe6e76 | 224 | //
// SizeableCell.swift
// SmartTourist
//
// Created on 21/04/2020
//
import UIKit
import Tempura
public protocol SizeableCell: ModellableView {
static func size(for model: VM, in superview: UIView?) -> CGSize
}
| 14.933333 | 68 | 0.700893 |
622395871a396c1eaf5b88f4f444ee303f9e3895 | 3,822 | import UIKit
import ThemeKit
import SnapKit
class ViewController: ThemeViewController {
private let colors: [Color] = [
Color(name: "Jacob", value: .themeJacob),
Color(name: "Remus", value: .themeRemus),
Color(name: "Lucian", value: .themeLucian),
Color(name: "Oz", value: .themeOz),
Color(name: "Leah", value: .themeLeah),
Color(name: "Jeremy", value: .themeJeremy),
Color(name: "Elena", value: .themeElena),
Color(name: "Lawrence", value: .themeLawrence),
Color(name: "Lawrence Pressed", value: .themeLawrencePressed),
Color(name: "Claude", value: .themeClaude),
Color(name: "Andy", value: .themeAndy),
Color(name: "Tyler", value: .themeTyler),
Color(name: "Nina", value: .themeNina),
Color(name: "Helsing", value: .themeHelsing),
Color(name: "Cassandra", value: .themeCassandra),
Color(name: "Rains", value: .themeRaina),
Color(name: "Bran", value: .themeBran),
]
private let tableView = UITableView()
private var themeModeIterator = 0
private var themeBarButtonItem: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
themeBarButtonItem = UIBarButtonItem(title: ThemeManager.shared.themeMode.rawValue, style: .plain, target: self, action: #selector(onToggleLightMode))
navigationItem.rightBarButtonItem = themeBarButtonItem
navigationItem.largeTitleDisplayMode = .never
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
tableView.delegate = self
tableView.dataSource = self
tableView.register(ColorCell.self, forCellReuseIdentifier: String(describing: ColorCell.self))
tableView.backgroundColor = .clear
tableView.separatorInset = .zero
tableView.separatorColor = .themeSteel20
tableView.allowsSelection = false
tableView.tableFooterView = UIView()
}
@objc func onToggleLightMode() {
themeModeIterator += 1
if themeModeIterator > 2 {
themeModeIterator = 0
}
if themeModeIterator == 0 {
ThemeManager.shared.themeMode = .system
UIApplication.shared.windows.first(where: \.isKeyWindow)?.overrideUserInterfaceStyle = .unspecified
}
if themeModeIterator == 1 {
ThemeManager.shared.themeMode = .dark
UIApplication.shared.windows.first(where: \.isKeyWindow)?.overrideUserInterfaceStyle = .dark
}
if themeModeIterator == 2 {
ThemeManager.shared.themeMode = .light
UIApplication.shared.windows.first(where: \.isKeyWindow)?.overrideUserInterfaceStyle = .light
}
themeBarButtonItem?.title = ThemeManager.shared.themeMode.rawValue
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
colors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: ColorCell.self)) {
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cell = cell as? ColorCell else {
return
}
cell.bind(color: colors[indexPath.row])
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
50
}
}
extension ViewController {
struct Color {
let name: String
let value: UIColor
}
}
| 32.948276 | 158 | 0.652276 |
3352135bcb070da422f37ee1c95cc8a46b4042b6 | 2,175 | //
// AlertMessage.swift
// Petulia
//
// Created by Samuel Folledo on 4/15/21.
// Copyright © 2021 Johandre Delgado . All rights reserved.
//
import SwiftUI
struct AlertError {
var title: String = "Error"
var message: String
}
enum AlertMessage {
/// A message for errors with OK button
case error(title: String = "Error", body: String = "")
case alertError(alertError: AlertError)
/// A message and OK button
case information(body: String)
/// A message and OK button
case warning(body: String)
/// A question with YES and NO buttons
case confirmation(body: String, action: () -> Void)
/// A question about destractive action with `action` and CANCEL buttons
case destruction(body: String, label: String, action: () -> Void)
}
extension AlertMessage: Identifiable {
var id: String { String(reflecting: self) }
}
extension AlertMessage {
/// Builder of an Alert
func show() -> Alert {
switch self {
case let .error(title, body):
return Alert(
title: Text(title),
message: Text(body))
case let .alertError(alertError):
return Alert(
title: Text(alertError.title),
message: Text(alertError.message))
case let .information(body):
return Alert(
title: Text("Information"),
message: Text(body))
case let .warning(body):
return Alert(
title: Text("Warning"),
message: Text(body))
case let .confirmation(body, action):
return Alert(
title: Text("Confirmation"),
message: Text(body),
primaryButton: .default(Text("YES"), action: action),
secondaryButton: .cancel(Text("NO")))
case let .destruction(body, label, action):
return Alert(
title: Text("Confirmation"),
message: Text(body),
primaryButton: .destructive(Text(label), action: action),
secondaryButton: .cancel())
}
}
}
| 29.391892 | 76 | 0.56 |
873be2121d3cd82ba5ddd43686a1750238a20c70 | 550 | import Foundation
@testable import RestlerCore
extension Restler.Request {
func deprecatedOnSuccess(_ handler: @escaping (D) -> Void) -> Self {
self.onSuccess(handler)
}
func deprecatedOnFailure(_ handler: @escaping (Error) -> Void) -> Self {
self.onFailure(handler)
}
func deprecatedOnCompletion(_ handler: @escaping (Result<D, Error>) -> Void) -> Self {
self.onCompletion(handler)
}
@discardableResult
func deprecatedStart() -> RestlerTaskType? {
self.start()
}
}
| 25 | 90 | 0.634545 |
8f82e5cfe1846fc356e6a7689d825d3c53ecde97 | 5,634 | //
// GitController.swift
//
//
// Created by Marek Fořt on 9/9/19.
//
import Foundation
import TSCBasic
import TSCUtility
import protocol TuistSupport.FatalError
import enum TuistSupport.ErrorType
enum GitError: FatalError, Equatable {
case tagExists(Version)
case tagNotExists(Version)
var type: ErrorType { .abort }
var description: String {
switch self {
case let .tagExists(version):
return "Version tag \(version) already exists."
case let .tagNotExists(version):
return "Can not delete tag \(version) that does not exist"
}
}
}
/// Interface for interacting with git
public protocol GitControlling {
/// Initialize git repository
/// - Parameters:
/// - path: Path defining where should the git repository be created
func initGit(path: AbsolutePath) throws
/// Get current git name
/// - Returns: Git name
func currentName() throws -> String
/// Get current git email
/// - Returns: Git email
func currentEmail() throws -> String
/// Creates new commit and adds unstaged files
/// - Parameters:
/// - message: Commit message
/// - path: Path of the git directory
func commit(_ message: String, path: AbsolutePath?) throws
/// Deletes a tag
/// - Parameters:
/// - version: Tag version to delete
/// - path: Path of the git directory
func deleteTagVersion(_ version: Version, path: AbsolutePath?) throws
/// Creates new tag
/// - Parameters:
/// - version: New tag version
/// - path: Path of the git directory
/// - Throws: When `version` already exists
func tagVersion(_ version: Version, path: AbsolutePath?) throws
/// Checks if tag version already exists
/// - Parameters:
/// - version: Version to be checked
/// - path: Path of the git directory
/// - Returns: True if `version` exists
func tagExists(_ version: Version, path: AbsolutePath?) throws -> Bool
/// Stages `files` for commit
/// - Parameters:
/// - files: Files to stage
/// - path: Path of the git directory
func add(files: [AbsolutePath], path: AbsolutePath?) throws
/// Push to the remote repository
/// - Parameters:
/// - path: Path of the git directory
func push(path: AbsolutePath?) throws
/// Push sepcific tag to the remote repository
/// - Parameters:
/// - tag: Tag to push
/// - path: Path of the git directory
func pushTag(
_ tag: String,
path: AbsolutePath?
) throws
/// - Parameters:
/// - path: Path of the git directory
/// - Returns: All tags for directory at `path`
func allTags(path: AbsolutePath?) throws -> [Version]
}
/// Class for interacting with git
public final class GitController: GitControlling {
public static var shared: GitControlling = GitController()
public init() {}
public func initGit(path: AbsolutePath) throws {
try System.shared.run("git", "init", path.pathString)
}
public func currentName() throws -> String {
return try System.shared.capture("git", "config", "user.name").replacingOccurrences(of: "\n", with: "")
}
public func currentEmail() throws -> String {
return try System.shared.capture("git", "config", "user.email").replacingOccurrences(of: "\n", with: "")
}
public func deleteTagVersion(_ version: Version, path: AbsolutePath?) throws {
guard try tagExists(version, path: path) else { throw GitError.tagNotExists(version) }
try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
try System.shared.run("git", "tag", "-d", version.description)
}
}
public func pushTag(
_ tag: String,
path: AbsolutePath?
) throws {
try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
try System.shared.runAndPrint("git", "push", "origin", "refs/tags/\(tag)")
}
}
public func tagVersion(_ version: Version, path: AbsolutePath?) throws {
guard try !tagExists(version, path: path) else { throw GitError.tagExists(version) }
try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
try System.shared.run("git", "tag", version.description)
}
}
public func commit(_ message: String, path: AbsolutePath?) throws {
try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
try System.shared.run("git", "commit", "-m", message)
}
}
public func add(files: [AbsolutePath], path: AbsolutePath?) throws {
try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
files.forEach {
try? System.shared.run("git", "add", $0.pathString)
}
}
}
public func push(path: AbsolutePath?) throws {
try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
try System.shared.runAndPrint("git", "push")
}
}
public func tagExists(_ version: Version, path: AbsolutePath?) throws -> Bool {
return try allTags(path: path).contains(version)
}
public func allTags(path: AbsolutePath?) throws -> [Version] {
return try FileHandler.shared.inDirectory(path ?? FileHandler.shared.currentPath) {
try System.shared.capture("git", "tag", "--list").split(separator: "\n").compactMap { Version(string: String($0)) }
}
}
}
| 35.658228 | 127 | 0.622648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.