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
|
---|---|---|---|---|---|
e29780c20033b210a738c89dec25cddc4deaa4dc | 6,076 | /*****************************************************************************************************************************//**
* PROJECT: Gettysburg
* FILENAME: ExperimentTests.swift
* IDE: AppCode
* AUTHOR: Galen Rhodes
* DATE: July 15, 2021
*
* Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided
* that the above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*//*****************************************************************************************************************************/
import XCTest
import Foundation
import CoreFoundation
import Rubicon
@testable import Gettysburg
public class ExperimentTests: XCTestCase {
public override func setUpWithError() throws {}
public override func tearDownWithError() throws {}
func testURLs_2() throws {
let strURL = "http://goober/Test_UTF-8.xml"
guard let url = URL(string: strURL) else { throw URLErrors.MalformedURL(description: strURL) }
guard let fil = try? InputStream.getInputStream(url: url, authenticate: { _ in .UseDefault }) else { throw StreamError.FileNotFound(description: strURL) }
guard let str = String(fromInputStream: fil, encoding: .utf8) else { throw StreamError.UnknownError() }
print(" Cookies: \(fil.property(forKey: .httpCookiesKey) ?? "")")
print(" Headers: \(fil.property(forKey: .httpHeadersKey) ?? "")")
print(" Status Code: \(fil.property(forKey: .httpStatusCodeKey) ?? "")")
print(" Status Text: \(fil.property(forKey: .httpStatusTextKey) ?? "")")
print(" MIME Type: \(fil.property(forKey: .mimeTypeKey) ?? "")")
print("Text Encoding: \(fil.property(forKey: .textEncodingNameKey) ?? "")")
print("")
print(str)
}
func testURLs_1() throws {
let urls: [String] = [
"galen.html",
"./galen.html",
"../galen.html",
"http://foo.com/Projects/galen.html",
"http://foo.com/Projects/galen.html?bar=foo",
"http://foo.com/Projects/galen.html#bar",
"http://foo.com/Projects/galen.html?bar=foo#bar",
"http://foo.com:8080/Projects/galen.html",
"http://foo.com:8080/Projects/galen.html?bar=foo",
"http://foo.com:8080/Projects/galen.html#bar",
"http://foo.com:8080/Projects/galen.html?bar=foo#bar",
"http://foo.com/Projects/./galen.html",
"http://foo.com/Projects/../galen.html",
"file:///Users/grhodes/Projects/test.swift",
"file:///Users/grhodes/Projects/./test.swift",
"file:///Users/grhodes/Projects/../test.swift",
"file://Users/grhodes/Projects/test.swift",
"file://Users/grhodes/Projects/./test.swift",
"file://Users/grhodes/Projects/../test.swift",
"jdbc://bossman:8080",
"/galen.html",
"~/galen.html",
"~galen.html",
]
for urlString in urls {
if let url = URL(string: urlString)?.standardized {
print("-------------------------------------------------------")
print(" String: \"\(urlString)\"")
print(" URL: \"\(url)\"")
print(" BaseURL: \"\(url.baseURL?.absoluteString ?? "")\"")
print(" Scheme: \"\(url.scheme ?? "")\"")
print(" Host: \"\(url.host ?? "")\"")
print(" Port: \"\(url.port ?? 80)\"")
print(" Path: \"\(url.path)\"")
print(" Query: \"\(url.query ?? "")\"")
print("Fragment: \"\(url.fragment ?? "")\"")
print(" Is File: \(url.isFileURL)")
print(" : \"\(url.absoluteString)\"")
print(" : \"\(url.relativeString)\"")
print(" : \"\(url.standardizedFileURL)\"")
}
else {
print("Malformed URL: \"\(urlString)\"")
}
}
print("============================================================================================")
// let bu = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
// let bu = URL(fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true)
let bu = URL(fileURLWithPath: "/Users/grhodes", isDirectory: true)
for urlString in urls {
if let url = URL(string: urlString, relativeTo: bu)?.standardized {
print("-------------------------------------------------------")
print(" String: \"\(urlString)\"")
print(" URL: \"\(url)\"")
print(" BaseURL: \"\(url.baseURL?.absoluteString ?? "")\"")
print(" Scheme: \"\(url.scheme ?? "")\"")
print(" Host: \"\(url.host ?? "")\"")
print(" Port: \"\(url.port ?? 80)\"")
print(" Path: \"\(url.path)\"")
print(" Query: \"\(url.query ?? "")\"")
print("Fragment: \"\(url.fragment ?? "")\"")
print(" Is File: \(url.isFileURL)")
print(" : \"\(url.absoluteString)\"")
print(" : \"\(url.relativeString)\"")
print(" : \"\(url.standardizedFileURL)\"")
}
else {
print("Malformed URL: \"\(urlString)\"")
}
}
}
}
| 49 | 162 | 0.499342 |
ff8b991147b0e2c44cf137613dbe710fce5bc4b2 | 3,110 | //
// ClientManager.swift
// SocketClient
//
// Created by GongsiWang on 2022/3/24.
//
import Cocoa
import WelfareLibrary
protocol ClientManagerDelegate: AnyObject {
func sendMessageToClient(_ msg: Data)
func clientLog(_ msg: String)
func remove(client: ClientManager)
}
class ClientManager: NSObject {
var client: TCPClient
weak var delegate: ClientManagerDelegate?
fileprivate var isClientConnect = false
// 是否收到心跳包
fileprivate var isReciveHeartBeat = false
init(client: TCPClient) {
self.client = client
}
}
extension ClientManager {
func startReadMessage() {
isClientConnect = true
// 开启检查心跳
// 这里timer 会直接开始 去检查会导致当前客户端直接被移除,所以给后推十秒在开始
let timer = Timer(fireAt: Date(timeIntervalSinceNow: 10), interval: 10, target: self, selector: #selector(heartBeatAction), userInfo: nil, repeats: true)
// 添加到当前线程的 RunLoop
RunLoop.current.add(timer, forMode: .default)
timer.fire()
while isClientConnect {
// [UInt8] 相当于[char]
if let msg = client.read(4) {
// 获取到头部信息
let headData = Data(bytes: msg, count: 4)
var msgLength: Int = 0
(headData as NSData).getBytes(&msgLength, length: 4)
/// 获取类型
guard let t = client.read(2) else {
return
}
var type: Int = 0
let typeData = Data(bytes: t, count: 2)
(typeData as NSData).getBytes(&type, length: 2)
if let option = MessageOption(rawValue: type) {
if option == .leaveRoom {
// 如果消息类型是离开房间
delegate?.remove(client: self)
// 关闭客户端
client.close()
}
if option == .heartbeat {
isReciveHeartBeat = true
// 直接开始下一次消息的接收
continue
}
}
// 获取真实的消息
guard let m = client.read(msgLength) else {
return
}
let msgData = Data(bytes: m, count: msgLength)
// 组装信息
let totalData = headData + typeData + msgData
delegate?.sendMessageToClient(totalData)
}else{
// 一般是系统的消息 空字符 断开连接
isClientConnect = false
DispatchQueue.main.sync {
self.delegate?.clientLog("客户端断开了连接")
self.delegate?.remove(client: self)
}
client.close()
}
}
}
@objc func heartBeatAction() {
if !isReciveHeartBeat {
client.close()
delegate?.remove(client: self)
}else{
isReciveHeartBeat = false
}
}
}
| 29.339623 | 161 | 0.476527 |
01ec04abb988cc75327b79736f51a425da84ddd5 | 490 | //
// ViewController.swift
// McBlog
//
// Created by Theshy on 16/4/14.
// Copyright © 2016年 郭月辉. 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.
}
}
| 18.846154 | 80 | 0.661224 |
560dcaf11194f0d4649c77692dec195ab12eb8a8 | 216 | //
// RxTests.swift
// Rx
//
// Created by Krunoslav Zaher on 12/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Virtual time type.
*/
public typealias TestTime = Int
| 13.5 | 58 | 0.675926 |
0aaa91027a583a9fe8c80fbef4f6b3c2eb59ade5 | 1,971 | // Created by Keith Harrison https://useyourloaf.com
// Copyright © 2020 Keith Harrison. 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.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE 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 UIKit
enum Theme: Int {
case device
case light
case dark
}
extension Theme {
var userInterfaceStyle: UIUserInterfaceStyle {
switch self {
case .device:
return .unspecified
case .light:
return .light
case .dark:
return .dark
}
}
}
| 39.42 | 79 | 0.727549 |
c158a6d4d425d6d74150b98226893d328f959c2f | 654 | import Foundation
import IrohaCrypto
final class AccountCreateWireframe: AccountCreateWireframeProtocol {
func confirm(
from view: AccountCreateViewProtocol?,
request: MetaAccountCreationRequest,
metadata: MetaAccountCreationMetadata
) {
guard let accountConfirmation = AccountConfirmViewFactory
.createViewForOnboarding(request: request, metadata: metadata)?.controller
else {
return
}
if let navigationController = view?.controller.navigationController {
navigationController.pushViewController(accountConfirmation, animated: true)
}
}
}
| 31.142857 | 88 | 0.703364 |
ff3d9ea549af1419679030369d105ed837b84333 | 2,289 | //
// URL+Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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
extension URL {
func append(queryString: String) -> URL {
guard !queryString.utf16.isEmpty else {
return self
}
var absoluteURLString = self.absoluteString
if absoluteURLString.hasSuffix("?") {
absoluteURLString = String(absoluteURLString[0..<absoluteURLString.utf16.count])
}
let urlString = absoluteURLString + (absoluteURLString.range(of: "?") != nil ? "&" : "?") + queryString
return URL(string: urlString)!
}
func hasSameUrlScheme(as otherUrl: URL) -> Bool {
guard let scheme = self.scheme, let otherScheme = otherUrl.scheme else { return false }
return scheme.caseInsensitiveCompare(otherScheme) == .orderedSame
}
var queryParamsForSSO: [String : String] {
guard let host = self.host else { return [:] }
return host.split(separator: "&").reduce(into: [:]) { (result, parameter) in
let keyValue = parameter.split(separator: "=")
result[String(keyValue[0])] = String(keyValue[1])
}
}
}
| 39.465517 | 111 | 0.673657 |
abab21ee6ca99b1fc8484db331f0dde2433dea40 | 2,932 | //
// ImageAttachment+.swift
// FSNotes iOS
//
// Created by Oleksandr Glushchenko on 1/19/19.
// Copyright © 2019 Oleksandr Glushchenko. All rights reserved.
//
import UIKit
import MobileCoreServices
import AVKit
extension NoteAttachment {
public func load() -> NSTextAttachment? {
let imageSize = getSize(url: self.url)
guard let size = getImageSize(imageSize: imageSize) else { return nil }
let attachment = NSTextAttachment()
attachment.bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
attachment.image = UIImage.emptyImage(with: size)
return attachment
}
private func getEditorView() -> EditTextView? {
guard let pc = UIApplication.shared.windows[0].rootViewController as? BasicViewController,
let nav = pc.containerController.viewControllers[1] as? UINavigationController,
let evc = nav.viewControllers.first as? EditorViewController else { return nil }
return evc.editArea
}
private func getImageSize(imageSize: CGSize) -> CGSize? {
let controller = UIApplication.getVC()
let maxWidth = controller.view.frame.width - 15
guard imageSize.width > maxWidth else {
return imageSize
}
let scale = maxWidth / imageSize.width
let newHeight = imageSize.height * scale
return CGSize(width: maxWidth, height: newHeight)
}
public static func resize(image: UIImage, size: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(size)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public static func getImage(url: URL, size: CGSize) -> UIImage? {
let imageData = try? Data(contentsOf: url)
var finalImage: UIImage?
if url.isVideo {
let asset = AVURLAsset(url: url, options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
if let cgImage = try? imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil) {
finalImage = UIImage(cgImage: cgImage)
}
} else if let imageData = imageData {
finalImage = UIImage(data: imageData)
}
guard let image = finalImage else { return nil }
var thumbImage: UIImage?
if let cacheURL = self.getCacheUrl(from: url, prefix: "ThumbnailsBigInline"), FileManager.default.fileExists(atPath: cacheURL.path) {
thumbImage = UIImage(contentsOfFile: cacheURL.path)
} else if
let resizedImage = self.resize(image: image, size: size) {
thumbImage = resizedImage
self.savePreviewImage(url: url, image: resizedImage, prefix: "ThumbnailsBigInline")
}
return thumbImage
}
}
| 34.494118 | 141 | 0.648704 |
e4b5328aeaf06f3605e12a6a3211f167c1d5e9a5 | 165 | public extension Enums {
enum CurrentFanState: UInt8, CharacteristicValueType {
case inactive = 0
case idle = 1
case blowing = 2
}
}
| 20.625 | 58 | 0.612121 |
ab4e8d524b936d227971018bc666bebabb575c2b | 5,899 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE 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 UIKit
open class View: UIView {
open override var intrinsicContentSize: CGSize {
return bounds.size
}
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable
open var image: UIImage? {
get {
guard let v = visualLayer.contents else {
return nil
}
return UIImage(cgImage: v as! CGImage)
}
set(value) {
visualLayer.contents = value?.cgImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
@IBInspectable
open var contentsRect: CGRect {
get {
return visualLayer.contentsRect
}
set(value) {
visualLayer.contentsRect = value
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
@IBInspectable
open var contentsCenter: CGRect {
get {
return visualLayer.contentsCenter
}
set(value) {
visualLayer.contentsCenter = value
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the view. By default, this value is set to the Screen.scale.
*/
@IBInspectable
open var contentsScale: CGFloat {
get {
return visualLayer.contentsScale
}
set(value) {
visualLayer.contentsScale = value
}
}
/// A Preset for the contentsGravity property.
@IBInspectable
open var contentsGravityPreset: Gravity {
didSet {
contentsGravity = GravityToValue(gravity: contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable
open var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.cgColor
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentsGravityPreset = .resizeAspectFill
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
contentsGravityPreset = .resizeAspectFill
super.init(frame: frame)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
contentScaleFactor = Screen.scale
backgroundColor = .white
prepareVisualLayer()
}
}
extension View {
/// Prepares the visualLayer property.
fileprivate func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
}
extension View {
/// Manages the layout for the visualLayer property.
fileprivate func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = layer.cornerRadius
}
}
| 30.096939 | 88 | 0.714358 |
7ad0ea04369a3540dac915d90bf504fe325fb7a1 | 310 | //
// File.swift
//
//
// Created by Everaldlee Johnson on 11/29/20.
//
import Foundation
public class FormRequest:Codable{
public var form:Form?
public var forms:[Form]?
public init(form: Form? = nil, forms: [Form]? = nil) {
self.form = form
self.forms = forms
}
}
| 15.5 | 58 | 0.587097 |
14dd9d926ad7f10a9d96dfda0d1ff197af3d90e6 | 1,029 | //
// PhotoDetailsViewController.swift
// Tumblr
//
// Created by Sneha Pimpalkar on 10/16/16.
// Copyright © 2016 Sneha Pimpalkar. All rights reserved.
//
import UIKit
class PhotoDetailsViewController: UIViewController {
@IBOutlet weak var imgViewSetPhoto: UIImageView!
var photoURL : URL!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imgViewSetPhoto.setImageWith(photoURL)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.5 | 106 | 0.671526 |
08f00b70400b35e8390b8def4f2a04aee96561d5 | 291 | //
// MovieListRoute.swift
// TMDB
//
// Created by Ridoan Wibisono on 02/10/21.
//
import SwiftUI
final class MovieListRouter{
public static func destinationForTappedMovie(movieId : Int) -> some View {
return MovieDetailViewConfigurator.configureMovieDetailView(with: movieId)
}
}
| 19.4 | 76 | 0.752577 |
9b49ef5deaf01a81c3df5af510f9264e1b33add8 | 971 | import Foundation
import Vapor
struct CSRFVerifier: CSRF {
func setCSRF(key: String, request: Request) throws -> String {
let string = "\(try generateRandom())-\(try generateRandom())-\(try generateRandom())-\(try generateRandom())"
try request.session()[key] = string
return string
}
func verifyCSRF(submittedToken: String?, key: String, request: Request) throws {
guard let requiredToken: String = try request.session()[key] else { throw Abort(.forbidden) }
if let token = submittedToken {
guard token == requiredToken else { throw Abort(.forbidden) }
} else {
let _ = try request.content.decode([String: String].self).map(to: Void.self) { form in
guard let submittedToken: String = form[key] else { throw Abort(.forbidden) }
guard requiredToken == submittedToken else { throw Abort(.forbidden) }
}
}
}
}
| 38.84 | 118 | 0.609681 |
d684267e084f946a23c2bea595d460547bcb5cda | 6,553 | //
// 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 UIKit
@objcMembers
class PlainRoomTimelineCellDecorator: RoomTimelineCellDecorator {
func addTimestampLabelIfNeeded(toCell cell: MXKRoomBubbleTableViewCell, cellData: RoomBubbleCellData) {
guard cellData.containsLastMessage && cellData.isCollapsableAndCollapsed == false else {
return
}
// Display timestamp of the last message
self.addTimestampLabel(toCell: cell, cellData: cellData)
}
func addTimestampLabel(toCell cell: MXKRoomBubbleTableViewCell, cellData: RoomBubbleCellData) {
cell.addTimestampLabel(forComponent: UInt(cellData.mostRecentComponentIndex))
}
func addURLPreviewView(_ urlPreviewView: URLPreviewView,
toCell cell: MXKRoomBubbleTableViewCell,
cellData: RoomBubbleCellData,
contentViewPositionY: CGFloat) {
cell.addTemporarySubview(urlPreviewView)
let cellContentView = cell.contentView
urlPreviewView.translatesAutoresizingMaskIntoConstraints = false
urlPreviewView.availableWidth = cellData.maxTextViewWidth
cellContentView.addSubview(urlPreviewView)
var leftMargin = RoomBubbleCellLayout.reactionsViewLeftMargin
if cellData.containsBubbleComponentWithEncryptionBadge {
leftMargin += RoomBubbleCellLayout.encryptedContentLeftMargin
}
let topMargin = contentViewPositionY + RoomBubbleCellLayout.urlPreviewViewTopMargin + RoomBubbleCellLayout.reactionsViewTopMargin
// Set the preview view's origin
NSLayoutConstraint.activate([
urlPreviewView.leadingAnchor.constraint(equalTo: cellContentView.leadingAnchor, constant: leftMargin),
urlPreviewView.topAnchor.constraint(equalTo: cellContentView.topAnchor, constant: topMargin)
])
}
func addReactionView(_ reactionsView: BubbleReactionsView,
toCell cell: MXKRoomBubbleTableViewCell,
cellData: RoomBubbleCellData,
contentViewPositionY: CGFloat,
upperDecorationView: UIView?) {
cell.addTemporarySubview(reactionsView)
if let reactionsDisplayable = cell as? BubbleCellReactionsDisplayable {
reactionsDisplayable.addReactionsView(reactionsView)
} else {
reactionsView.translatesAutoresizingMaskIntoConstraints = false
let cellContentView = cell.contentView
cellContentView.addSubview(reactionsView)
var leftMargin = RoomBubbleCellLayout.reactionsViewLeftMargin
if cellData.containsBubbleComponentWithEncryptionBadge {
leftMargin += RoomBubbleCellLayout.encryptedContentLeftMargin
}
let rightMargin = RoomBubbleCellLayout.reactionsViewRightMargin
let topMargin = RoomBubbleCellLayout.reactionsViewTopMargin
// The top constraint may need to include the URL preview view
let topConstraint: NSLayoutConstraint
if let upperDecorationView = upperDecorationView {
topConstraint = reactionsView.topAnchor.constraint(equalTo: upperDecorationView.bottomAnchor, constant: topMargin)
} else {
topConstraint = reactionsView.topAnchor.constraint(equalTo: cellContentView.topAnchor, constant: contentViewPositionY + topMargin)
}
NSLayoutConstraint.activate([
reactionsView.leadingAnchor.constraint(equalTo: cellContentView.leadingAnchor, constant: leftMargin),
reactionsView.trailingAnchor.constraint(equalTo: cellContentView.trailingAnchor, constant: -rightMargin),
topConstraint
])
}
}
func addReadReceiptsView(_ readReceiptsView: MXKReceiptSendersContainer,
toCell cell: MXKRoomBubbleTableViewCell,
cellData: RoomBubbleCellData,
contentViewPositionY: CGFloat,
upperDecorationView: UIView?) {
cell.addTemporarySubview(readReceiptsView)
if let readReceiptsDisplayable = cell as? BubbleCellReadReceiptsDisplayable {
readReceiptsDisplayable.addReadReceiptsView(readReceiptsView)
} else {
let cellContentView = cell.contentView
cellContentView.addSubview(readReceiptsView)
// Force receipts container size
let widthConstraint = readReceiptsView.widthAnchor.constraint(equalToConstant: RoomBubbleCellLayout.readReceiptsViewWidth)
let heightConstraint = readReceiptsView.heightAnchor.constraint(equalToConstant: RoomBubbleCellLayout.readReceiptsViewHeight)
// Force receipts container position
let trailingConstraint = readReceiptsView.trailingAnchor.constraint(equalTo: cellContentView.trailingAnchor, constant: -RoomBubbleCellLayout.readReceiptsViewRightMargin)
let topMargin = RoomBubbleCellLayout.readReceiptsViewTopMargin
let topConstraint: NSLayoutConstraint
if let upperDecorationView = upperDecorationView {
topConstraint = readReceiptsView.topAnchor.constraint(equalTo: upperDecorationView.bottomAnchor, constant: topMargin)
} else {
topConstraint = readReceiptsView.topAnchor.constraint(equalTo: cellContentView.topAnchor, constant: contentViewPositionY + topMargin)
}
NSLayoutConstraint.activate([
widthConstraint,
heightConstraint,
trailingConstraint,
topConstraint
])
}
}
func addSendStatusView(toCell cell: MXKRoomBubbleTableViewCell, withFailedEventIds failedEventIds: Set<AnyHashable>) {
cell.updateTickView(withFailedEventIds: failedEventIds)
}
}
| 43.979866 | 181 | 0.690523 |
5683fd2e8e1016930f69889938ae39119e88ed21 | 2,275 | //
// FTPCSegementCell.swift
// FTPageController
//
// Created by liufengting on 2018/8/8.
//
import UIKit
open class FTPCSegementCell: UICollectionViewCell {
@objc static let identifier = "\(FTPCSegementCell.classForCoder())"
@objc public lazy var titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = NSTextAlignment.center
return label
}()
@objc public weak var titleModel: FTPCTitleModel!
@objc public weak var segementConfig: FTPCSegementConfig!
@objc public var indexPath: IndexPath!
@objc public override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.titleLabel)
}
@objc public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addSubview(self.titleLabel)
}
@objc open override func layoutSubviews() {
super.layoutSubviews()
self.titleLabel.frame = self.bounds
}
@objc func setupWith(titleModel: FTPCTitleModel, segementConfig: FTPCSegementConfig, indexPath: IndexPath, selected: Bool) {
self.titleModel = titleModel
self.titleLabel.text = titleModel.title
self.segementConfig = segementConfig
self.indexPath = indexPath
self.setSelected(selected: selected)
}
@objc func setSelected(selected: Bool) {
let font = selected ? self.titleModel.selectedFont : self.titleModel.defaultFont
let textColor = selected ? self.titleModel.selectedColor : self.titleModel.defaultColor
UIView.animate(withDuration: 0.3) {
self.titleLabel.font = font
self.titleLabel.textColor = textColor
}
}
@objc func handleTransition(percent: CGFloat) {
let fontSize = self.titleModel.selectedFont.pointSize - ((self.titleModel.selectedFont.pointSize - self.titleModel.defaultFont.pointSize) * percent)
let color = UIColor.transition(fromColor: self.titleModel.selectedColor, toColor: self.titleModel.defaultColor, percent: percent)
let font = UIFont(name: self.titleModel.defaultFont.fontName, size: fontSize)
self.titleLabel.font = font
self.titleLabel.textColor = color
self.titleLabel.setNeedsLayout()
}
}
| 34.469697 | 156 | 0.681758 |
296d4b3460b9e3915d745e708f7b1286cea47945 | 4,660 | /// The protocol for SQLite virtual table modules. It lets you define a DSL for
/// the `Database.create(virtualTable:using:)` method:
///
/// let module = ...
/// try db.create(virtualTable: "items", using: module) { t in
/// ...
/// }
///
/// GRDB ships with three concrete classes that implement this protocol: FTS3,
/// FTS4 and FTS5.
public protocol VirtualTableModule {
/// The type of the closure argument in the
/// `Database.create(virtualTable:using:)` method:
///
/// try db.create(virtualTable: "items", using: module) { t in
/// // t is TableDefinition
/// }
associatedtype TableDefinition
/// The name of the module.
var moduleName: String { get }
/// Returns a table definition that is passed as the closure argument in the
/// `Database.create(virtualTable:using:)` method:
///
/// try db.create(virtualTable: "items", using: module) { t in
/// // t is the result of makeTableDefinition()
/// }
func makeTableDefinition() -> TableDefinition
/// Returns the module arguments for the `CREATE VIRTUAL TABLE` query.
func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
/// Execute any relevant database statement after the virtual table has
/// been created.
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
}
extension Database {
// MARK: - Database Schema: Virtual Table
/// Creates a virtual database table.
///
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
///
/// See https://www.sqlite.org/lang_createtable.html
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - module: The name of an SQLite virtual table module.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("USING")
chunks.append(module)
let sql = chunks.joined(separator: " ")
try execute(sql)
}
/// Creates a virtual database table.
///
/// let module = ...
/// try db.create(virtualTable: "pointOfInterests", using: module) { t in
/// ...
/// }
///
/// The type of the closure argument `t` depends on the type of the module
/// argument: refer to this module's documentation.
///
/// Use this method to create full-text tables using the FTS3, FTS4, or
/// FTS5 modules:
///
/// try db.create(virtualTable: "books", using: FTS4()) { t in
/// t.column("title")
/// t.column("author")
/// t.column("body")
/// }
///
/// See https://www.sqlite.org/lang_createtable.html
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false, no error is thrown if table already exists.
/// - module: a VirtualTableModule
/// - body: An optional closure that defines the virtual table.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create<Module: VirtualTableModule>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws {
// Define virtual table
let definition = module.makeTableDefinition()
if let body = body {
body(definition)
}
// Create virtual table
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
chunks.append("IF NOT EXISTS")
}
chunks.append(tableName.quotedDatabaseIdentifier)
chunks.append("USING")
let arguments = try module.moduleArguments(for: definition, in: self)
if arguments.isEmpty {
chunks.append(module.moduleName)
} else {
chunks.append(module.moduleName + "(" + arguments.joined(separator: ", ") + ")")
}
let sql = chunks.joined(separator: " ")
try inSavepoint {
try execute(sql)
try module.database(self, didCreate: tableName, using: definition)
return .commit
}
}
}
| 37.28 | 191 | 0.595279 |
f8d48fe9977d5e9fa929809aa8c3352eda32aad9 | 1,429 | //
// TipCalculatorUITests.swift
// TipCalculatorUITests
//
// Created by Mason Hughes on 1/25/21.
//
import XCTest
class TipCalculatorUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.232558 | 182 | 0.659202 |
5b35ae977be7002667c208897fdbfed2daa719af | 1,427 | //
// AppDelegate.swift
// Project1
//
// Created by Denis Sheikherev on 18.02.2020.
// Copyright © 2020 Denis Sheikherev. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.552632 | 179 | 0.749124 |
ebb173abebf8c183844fd16ded78a159e8d554c3 | 12,627 | //
// Copyright 2011 - 2018 Schibsted Products & Technology AS.
// Licensed under the terms of the MIT license. See LICENSE in the project root.
//
import UIKit
private enum ViewIndex: Int {
case input = 1
case error = 2
}
class RequiredFieldsViewController: IdentityUIViewController {
enum Action {
case update(fields: [SupportedRequiredField: String])
case cancel
case open(url: URL)
}
var didRequestAction: ((Action) -> Void)?
@IBOutlet var subtext: TextView! {
didSet {
self.subtext.isEditable = false
self.subtext.delegate = self
self.subtext.attributedText = self.viewModel.subtext
}
}
fileprivate var errorLabels: [ErrorLabel] = []
@IBOutlet var requiredFieldsStackView: UIStackView! {
didSet {
let toolbar = UIToolbar.forKeyboard(
target: self,
doneString: self.viewModel.done,
doneSelector: #selector(self.didTapDone),
previousSelector: #selector(self.didTapPrevious),
nextSelector: #selector(self.didTapNext),
leftChevronImage: self.theme.icons.chevronLeft
)
self.requiredFieldsStackView.spacing = 24
let count = self.fieldsCount
for index in 0..<count {
//
// These views are arranged in a way that matches the indices in ViewIndex enum above.
// If you change order make sure to change those as well
//
let field = self.viewModel.supportedRequiredFields[index]
let title = NormalLabel()
title.text = self.viewModel.titleForField(field)
let input = TextField()
input.placeholder = self.viewModel.placeholderForField(field)
input.enableCursorMotion = field.allowsCursorMotion
input.keyboardType = field.keyboardType
input.clearButtonMode = .whileEditing
input.returnKeyType = .default
input.autocorrectionType = .no
input.inputAccessoryView = toolbar
// Mark this so that when it becomes active we can set the currentInputIndex on view model
input.tag = index
assert(input.tag >= 0)
input.delegate = self
let error = ErrorLabel()
error.isHidden = true
self.errorLabels.append(error)
let subStack = UIStackView(arrangedSubviews: [title, input, error])
subStack.axis = .vertical
subStack.spacing = self.theme.geometry.titleViewSpacing
self.requiredFieldsStackView.addArrangedSubview(subStack)
}
}
}
@IBOutlet var continueButton: PrimaryButton! {
didSet {
self.continueButton.setTitle(self.viewModel.proceed, for: .normal)
}
}
@IBOutlet var continueButtonLayoutGuide: NSLayoutConstraint!
var currentInputIndex: UInt = 0
private var values: [String?]
let viewModel: RequiredFieldsViewModel
private var overrideScrollViewBottomContentInset: CGFloat?
init(configuration: IdentityUIConfiguration, navigationSettings: NavigationSettings, viewModel: RequiredFieldsViewModel) {
self.viewModel = viewModel
self.values = [String?](repeating: nil, count: self.viewModel.supportedRequiredFields.count)
super.init(configuration: configuration, navigationSettings: navigationSettings, trackerScreenID: .requiredFieldsForm)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func didTapDone() {
self.view.endEditing(true)
}
@objc func didTapNext() {
self.gotoInput(at: (self.currentInputIndex.addingReportingOverflow(1).partialValue) % UInt(self.viewModel.supportedRequiredFields.count))
}
@objc func didTapPrevious() {
self.gotoInput(at: (self.currentInputIndex.subtractingReportingOverflow(1).partialValue) % UInt(self.viewModel.supportedRequiredFields.count))
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.updateScrollViewContentInset()
}
private func updateScrollViewContentInset() {
let bottom: CGFloat
if let override = self.overrideScrollViewBottomContentInset {
bottom = override
} else {
let padding: CGFloat = 8
let buttonY = self.view.convert(self.continueButton.frame, from: self.continueButton.superview).minY
let buttonAreaHeight = self.view.bounds.height - buttonY + padding
bottom = max(buttonAreaHeight, 0)
}
self.scrollView.contentInset.bottom = bottom
self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset
}
override func viewDidAppear(_: Bool) {
NotificationCenter.default.addObserver(
self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil
)
NotificationCenter.default.addObserver(
self, selector: #selector(self.keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil
)
}
override func viewDidDisappear(_: Bool) {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
override var navigationTitle: String {
return self.viewModel.title
}
@IBAction func didClickContinue(_: Any) {
self.configuration.tracker?.interaction(.submit, with: self.trackerScreenID)
guard let valuesToUpdate = self.valuesToUpdate() else {
return
}
self.didRequestAction?(.update(fields: valuesToUpdate))
}
private func valuesToUpdate() -> [SupportedRequiredField: String]? {
var invalidIndices: [(Int, String)] = []
for (index, field) in self.viewModel.supportedRequiredFields.enumerated() {
guard let value = self.values[index] else {
invalidIndices.append((index, self.viewModel.string(for: .missing)))
continue
}
if let error = field.validate(value: value) {
invalidIndices.append((index, self.viewModel.string(for: error)))
}
}
guard invalidIndices.count == 0 else {
self.handleUnfilledFields(ascendingIndices: invalidIndices)
return nil
}
var valuesToUpdate: [SupportedRequiredField: String] = [:]
for (index, field) in self.viewModel.supportedRequiredFields.enumerated() {
guard let value = self.values[index] else {
continue
}
valuesToUpdate[field] = value
}
return valuesToUpdate
}
private func getActiveInput() -> UIView? {
guard let subStack = self.requiredFieldsStackView.arrangedSubviews[Int(self.currentInputIndex)] as? UIStackView else {
return nil
}
return subStack.arrangedSubviews[ViewIndex.input.rawValue]
}
@objc func keyboardWillShow(notification: NSNotification) {
guard let userInfo = notification.userInfo,
let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size,
let activeInput = self.getActiveInput() else {
return
}
self.overrideScrollViewBottomContentInset = keyboardSize.height
self.updateScrollViewContentInset()
var visibleFrame = self.view.frame
visibleFrame.size.height -= keyboardSize.height
if !visibleFrame.contains(activeInput.frame.origin) {
self.scrollView.scrollRectToVisible(activeInput.frame, animated: true)
}
}
@objc func keyboardWillHide(notification _: NSNotification) {
self.overrideScrollViewBottomContentInset = nil
self.updateScrollViewContentInset()
}
override func startLoading() {
super.startLoading()
self.continueButton.isAnimating = true
}
override func endLoading() {
super.endLoading()
self.continueButton.isAnimating = false
}
}
extension RequiredFieldsViewController: UITextViewDelegate {
func textView(_: UITextView, shouldInteractWith url: URL, in _: NSRange) -> Bool {
if self.viewModel.controlYouPrivacyURL == url {
self.configuration.tracker?.engagement(.click(on: .adjustPrivacyChoices), in: self.trackerScreenID)
} else if self.viewModel.dataAndYouURL == url {
self.configuration.tracker?.engagement(.click(on: .learnMoreAboutSchibsted), in: self.trackerScreenID)
}
self.didRequestAction?(.open(url: url))
return false
}
}
extension RequiredFieldsViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.currentInputIndex = UInt(textField.tag)
return true
}
func textFieldShouldReturn(_: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = (textField.text ?? "") as NSString
let newText = oldText.replacingCharacters(in: range, with: string)
guard let processedText = self.processValueForField(at: textField.tag, from: oldText as String, to: newText),
processedText.count != newText.count else {
return true
}
let beginning = textField.beginningOfDocument
let cursorOffset: Int?
if let start = textField.position(from: beginning, offset: range.location + range.length) {
cursorOffset = textField.offset(from: beginning, to: start)
} else {
cursorOffset = nil
}
textField.text = processedText
let newBeginning = textField.beginningOfDocument
if let cursorOffset = cursorOffset,
let newPosition = textField.position(from: newBeginning, offset: cursorOffset + (processedText.count - (oldText as String).count)) {
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
return false
}
return true
}
private func processValueForField(at index: Int, from oldValue: String, to newValue: String) -> String? {
guard index < self.viewModel.supportedRequiredFields.count else {
return nil
}
guard let formattedString = self.viewModel.supportedRequiredFields[index].format(oldValue: oldValue, with: newValue) else {
self.values[index] = newValue
return nil
}
self.values[index] = formattedString
return formattedString
}
}
extension RequiredFieldsViewController {
var fieldsCount: Int {
return self.viewModel.supportedRequiredFields.count
}
func gotoInput(at index: UInt) {
guard let subStack = self.requiredFieldsStackView.arrangedSubviews[Int(index)] as? UIStackView else {
return
}
subStack.arrangedSubviews[ViewIndex.input.rawValue].becomeFirstResponder()
}
func handleUnfilledFields(ascendingIndices: [(index: Int, message: String)]) {
// This loop sets the indices inbetween the values of ascendingIndices
// to be hidden (since they are not the ones that were invalid)
var currentIndex = 0
for (invalidIndex, message) in ascendingIndices {
while currentIndex < invalidIndex {
self.errorLabels[currentIndex].isHidden = true
currentIndex += 1
}
self.errorLabels[invalidIndex].isHidden = false
self.errorLabels[invalidIndex].text = message
currentIndex += 1
}
// And if there're any indices that we haven't gone through then
// set those to hidden as well
for index in currentIndex..<self.fieldsCount {
self.errorLabels[index].isHidden = true
}
let errorMessages = ascendingIndices.map { self.viewModel.requiredFieldID(at: $0.index) }
self.configuration.tracker?.error(.validation(.requiredField(errorMessages)), in: self.trackerScreenID)
}
}
| 37.468843 | 150 | 0.649481 |
64632cf7fe063785f671bc8e216c7f02a3d92909 | 886 | import XCTest
@testable import Mechanica
#if os(macOS)
final class NSImageUtilsTests: XCTestCase {
func testImageNamed() {
let bundle = Bundle(for: NSImageUtilsTests.self)
let image = NSImage.imageNamed(name: "glasses", in: bundle)
let notExistingImage = NSImage.imageNamed(name: "not-existing-glasses", in: bundle)
if !ProcessInfo.isRunningSwiftPackageTests {
// TODO: - see https://bugs.swift.org/browse/SR-2866
XCTAssertNotNil(image)
XCTAssertNil(notExistingImage)
XCTAssertEqual(image!.name(), NSImage.Name("glasses"))
}
}
func testCGImage() throws {
let data = Resource.glasses.data
let image = NSImage(data: data)
let cgImage = image?.cgImage
XCTAssertNotNil(cgImage)
XCTAssertEqual(cgImage!.width, 483)
XCTAssertEqual(cgImage!.height, 221)
}
}
#endif
| 24.611111 | 89 | 0.665914 |
89107ed5f5e854477e48ae92eb3502f85d6dfcad | 46 | import Foundation
protocol Model: Codable {}
| 11.5 | 26 | 0.782609 |
69af7c7cc68f7654ec4cb4656279870f74e2bddb | 2,513 | @testable import Envoy
import XCTest
private let kRetryPolicy = RetryPolicy(maxRetryCount: 123,
retryOn: [.connectFailure, .status5xx],
perRetryTimeoutMS: 9000)
final class HeadersBuilderTests: XCTestCase {
func testAddingNewHeaderAddsToListOfHeaderKeys() {
let headers = HeadersBuilder(headers: [:])
.add(name: "x-foo", value: "1")
.add(name: "x-foo", value: "2")
.headers
XCTAssertEqual(["1", "2"], headers["x-foo"])
}
func testRemovingSpecificHeaderKeyRemovesAllOfItsValues() {
let headers = HeadersBuilder(headers: [:])
.add(name: "x-foo", value: "1")
.add(name: "x-foo", value: "2")
.remove(name: "x-foo")
.headers
XCTAssertNil(headers["x-foo"])
}
func testRemovingSpecificHeaderKeyDoesNotRemoveOtherKeys() {
let headers = HeadersBuilder(headers: [:])
.add(name: "x-foo", value: "123")
.add(name: "x-bar", value: "abc")
.remove(name: "x-foo")
.headers
XCTAssertEqual(["x-bar": ["abc"]], headers)
}
func testSettingHeaderReplacesExistingHeadersWithMatchingName() {
let headers = HeadersBuilder(headers: [:])
.add(name: "x-foo", value: "123")
.set(name: "x-foo", value: ["abc"])
.headers
XCTAssertEqual(["x-foo": ["abc"]], headers)
}
func testBuildersAreEqualIfUnderlyingHeadersAreEqual() {
let builder1 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]])
let builder2 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]])
XCTAssertEqual(builder1, builder2)
}
func testHeadersAreEqualIfUnderlyingHeadersAreEqual() {
let headers1 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]]).build()
let headers2 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]]).build()
XCTAssertEqual(headers1, headers2)
}
func testBuilderPointersAreNotEqualWhenInstancesAreDifferent() {
let builder1 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]])
let builder2 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]])
XCTAssert(builder1 !== builder2)
}
func testHeadersPointersAreNotEqualWhenInstancesAreDifferent() {
let headers1 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]]).build()
let headers2 = RequestHeadersBuilder(headers: ["x-foo": ["123"], "x-bar": ["abc"]]).build()
XCTAssert(headers1 !== headers2)
}
}
| 37.507463 | 95 | 0.631516 |
7695d2d36907d6ade9fbfc4826feacd3831ceedc | 440 | //
// AppDelegate.swift
// BlurVIewTest
//
// Created by hanwe on 2020/12/15.
//
import UIKit
@main
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
}
}
| 19.130435 | 145 | 0.706818 |
5ddb1f2c46ed3098e2ff97ea55507cd8e2aca578 | 5,582 | //
// UIImage+RunModel.swift
// waifu2x-ios
//
// Created by xieyi on 2017/9/14.
// Copyright © 2017年 xieyi. All rights reserved.
//
import Foundation
import AppKit
import CoreML
/// The output block size.
/// It is dependent on the model.
/// Do not modify it until you are sure your model has a different number.
var block_size = 128
/// The difference of output and input block size
let shrink_size = 7
extension CGImage {
public func run(model: Model, scale: CGFloat = 1) -> CGImage? {
let startTime = Date.timeIntervalSinceReferenceDate
let width = Int(self.width)
let height = Int(self.height)
switch model {
case .anime_noise0, .anime_noise1, .anime_noise2, .anime_noise3, .photo_noise0, .photo_noise1, .photo_noise2, .photo_noise3:
block_size = 128
default:
block_size = 142
}
let rects = getCropRects()
// Prepare for output pipeline
// Merge arrays into one array
let normalize = { (input: Double) -> Double in
let output = input * 255
if output > 255 {
return 255
}
if output < 0 {
return 0
}
return output
}
let out_block_size = block_size * Int(scale)
let out_width = width * Int(scale)
let out_height = height * Int(scale)
let bufferSize = out_block_size * out_block_size * 3
var imgData = [UInt8].init(repeating: 0, count: out_width * out_height * 3)
let out_pipeline = BackgroundPipeline<MLMultiArray>("out_pipeline", count: rects.count) { (index, array) in
let startTime = Date.timeIntervalSinceReferenceDate
let rect = rects[index]
let origin_x = Int(rect.origin.x * scale)
let origin_y = Int(rect.origin.y * scale)
let dataPointer = UnsafeMutableBufferPointer(start: array.dataPointer.assumingMemoryBound(to: Double.self),
count: bufferSize)
var dest_x: Int
var dest_y: Int
var src_index: Int
var dest_index: Int
for channel in 0..<3 {
for src_y in 0..<out_block_size {
for src_x in 0..<out_block_size {
dest_x = origin_x + src_x
dest_y = origin_y + src_y
src_index = src_y * out_block_size + src_x + out_block_size * out_block_size * channel
dest_index = (dest_y * out_width + dest_x) * 3 + channel
imgData[dest_index] = UInt8(normalize(dataPointer[src_index]))
}
}
}
let endTime = Date.timeIntervalSinceReferenceDate
print("pipeline-normalize-data: ",endTime - startTime)
}
// Prepare for model pipeline
// Run prediction on each block
let mlmodel = model.getMLModel()
let model_pipeline = BackgroundPipeline<MLMultiArray>("model_pipeline", count: rects.count) { (index, array) in
let startTime = Date.timeIntervalSinceReferenceDate
let result = try! mlmodel.prediction(input: array)
let endTime = Date.timeIntervalSinceReferenceDate
print("pipeline-prediction: ",endTime - startTime)
out_pipeline.appendObject(result)
}
// Start running model
let expwidth = Int(self.width) + 2 * shrink_size
let expheight = Int(self.height) + 2 * shrink_size
let expanded = expand()
for rect in rects {
let x = Int(rect.origin.x)
let y = Int(rect.origin.y)
let multi = try! MLMultiArray(shape: [3, NSNumber(value: block_size + 2 * shrink_size), NSNumber(value: block_size + 2 * shrink_size)], dataType: .float32)
var x_new: Int
var y_new: Int
for y_exp in y..<(y + block_size + 2 * shrink_size) {
for x_exp in x..<(x + block_size + 2 * shrink_size) {
x_new = x_exp - x
y_new = y_exp - y
multi[y_new * (block_size + 2 * shrink_size) + x_new] = NSNumber(value: expanded[y_exp * expwidth + x_exp])
multi[y_new * (block_size + 2 * shrink_size) + x_new + (block_size + 2 * shrink_size) * (block_size + 2 * shrink_size)] = NSNumber(value: expanded[y_exp * expwidth + x_exp + expwidth * expheight])
multi[y_new * (block_size + 2 * shrink_size) + x_new + (block_size + 2 * shrink_size) * (block_size + 2 * shrink_size) * 2] = NSNumber(value: expanded[y_exp * expwidth + x_exp + expwidth * expheight * 2])
}
}
model_pipeline.appendObject(multi)
}
model_pipeline.wait()
out_pipeline.wait()
let cfbuffer = CFDataCreate(nil, &imgData, out_width * out_height * 3)!
let dataProvider = CGDataProvider(data: cfbuffer)!
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo.byteOrder32Big
let cgImage = CGImage(width: out_width, height: out_height, bitsPerComponent: 8, bitsPerPixel: 24, bytesPerRow: out_width * 3, space: colorSpace, bitmapInfo: bitmapInfo, provider: dataProvider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
let endTime = Date.timeIntervalSinceReferenceDate
print("run-model: ",endTime - startTime)
return cgImage
}
}
| 44.301587 | 285 | 0.589036 |
bb199a0e1cfe6f534d0026a2f0b029557392870b | 1,948 | //
// EditorConfigurations.swift
// VPN Manager
//
// Created by Sergey Umarov on 24.11.16.
// Copyright © 2016 Sergey Umarov. All rights reserved.
//
import UIKit
/**
*
* Конфигурация модуля при редактировании подключения
*
*/
class EditingConfiguration: ModuleConfiguration {
var delegateProvider: EditorDelegateProvider?
var connectionDataManager: DataManager<Connection>! = nil //di
public func configure(controller: UIViewController, with parameter: AnyObject?) -> Bool {
guard let presenter = controller as? EditorPresenter else {
return false
}
guard let ID = parameter as? String else {
return false
}
let interactor = EditorInteractor()
interactor.output = presenter
interactor.connectionDataManager = connectionDataManager
presenter.interactor = interactor
presenter.delegate = delegateProvider?.editorDelegate
presenter.prepareFormForEditing(connectionID: ID)
return true
}
}
/**
*
* Конфигурация модуля при создании подключения
*
*/
class CreationConfiguration: ModuleConfiguration {
var delegateProvider: EditorDelegateProvider?
var connectionDataManager: DataManager<Connection>! = nil //di
public func configure(controller: UIViewController, with parameter: AnyObject?) -> Bool {
guard let presenter = controller as? EditorPresenter else {
return false
}
guard parameter == nil else {
return false
}
let interactor = EditorInteractor()
interactor.output = presenter
interactor.connectionDataManager = connectionDataManager
presenter.interactor = interactor
presenter.delegate = delegateProvider?.editorDelegate
presenter.prepareFormForCreation()
return true
}
}
| 25.631579 | 93 | 0.650411 |
1c97f556cf0b99c9a29f05f648380dc6feb535b8 | 991 | //
// PostMediaCollectionController.swift
// beam
//
// Created by Robin Speijer on 07-10-15.
// Copyright © 2015 Awkward. All rights reserved.
//
import UIKit
import Snoo
class PostMediaCollectionController: NSObject {
typealias MediaCollectionItem = Snoo.MediaObject
var collection: [MediaCollectionItem]?
var post: Post? {
didSet {
self.collection = self.post?.mediaObjects?.array as? [MediaCollectionItem]
}
}
var count: Int {
return self.collection?.count ?? 0
}
func itemAtIndexPath(_ indexPath: IndexPath) -> MediaCollectionItem? {
return self.collection?[indexPath.item]
}
func indexPathForCollectionItem(_ item: MediaCollectionItem) -> IndexPath? {
guard let index = collection?.index(where: { (object) -> Bool in
return object == item
}) else {
return nil
}
return IndexPath(item: index, section: 0)
}
}
| 23.595238 | 86 | 0.620585 |
ac9162a29cfcd58957458b202c1f7a9d6cd4db35 | 520 | //
// ViewController.swift
// CoinConverterReceipt
//
// Created by rnnsilveira on 12/04/2019.
// Copyright (c) 2019 rnnsilveira. 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.8 | 80 | 0.680769 |
e0f0516460d1796e6e784824aa966b618ce58164 | 2,837 | //
// HTTPResponseError.swift
// ARCampaign
//
// Created by Magnus Tviberg on 08/03/2019.
//
import Foundation
enum HTTPResponseError: Error {
case noInternet
case cannotParse
case connectionFailure(ConnectionFailureReason)
case responseErrorWith(message: String)
case serverError(ErrorModel)
case serverErrorWith(statusCode: Int)
case unauthorized
case generic(error: Error)
}
enum ConnectionFailureReason: String {
case emptyResponse = "Fikk ingenting tilbake fra serveren"
case generic = "Får en ukjent feilmelding fra serveren"
}
extension HTTPResponseError: LocalizedError {
var errorDescription: String? {
switch self {
case .noInternet:
return "Ingen internettforbindelse"
case .connectionFailure(let errorMessage):
return errorMessage.rawValue
case .cannotParse:
return "Kunne ikke dekode responsen"
case .unauthorized:
return "Autentisering feilet 😧"
case .generic:
return "Det skjedde en feil"
case .serverError(let errorModel):
return errorModel.error
case .serverErrorWith(let statusCode):
return description(of: statusCode)
case .responseErrorWith(let message):
return message
}
}
var recoverySuggestion: String? {
switch self {
case .noInternet:
return "Sjekk om du er tilkoblet et Wi-Fi nettverk eller om du har mobildekning"
case .serverError:
return "Kontakt Telenor dersom problemet vedvarer"
case .connectionFailure:
return "Prøv igjen"
case .cannotParse:
return nil
case .unauthorized:
return "Prøv å logge ut og inn"
default:
return "Vennligst prøv på nytt"
}
}
}
extension HTTPResponseError {
private func description(of httpStatusCode: Int?) -> String {
guard let statusCode = httpStatusCode else {
return ""
}
switch statusCode {
case 400:
return "(400) Ugyldig etterspørsel"
case 401:
return "(401) Ikke autorisert"
case 403:
return "(403) Mangler tillatelse"
case 404:
return "(404) Ikke funnet"
case 500:
return "(500) Det skjedde en intern tjenerfeil"
case 501:
return "(501) Tjeneren kunne ikke innfri etterspørselen"
case 502:
return "(502) Ugyldig svar fra oppstrømstjeneren"
case 503:
return "(503) Tjeneren er nede grunnet stor pågang eller vedlikehold"
case 504:
return "(504) Tidsavbrudd"
default:
return "(\(statusCode)) Det skjedde en nettverksfeil"
}
}
}
| 29.247423 | 92 | 0.609094 |
90bf410703ebeee45eb54a1b6b943678081cd507 | 2,443 | //
// BasisFuncListViewController.swift
// XXTouchApp
//
// Created by 教主 on 16/7/28.
// Copyright © 2016年 mcy. All rights reserved.
//
import UIKit
class BasisFuncListViewController: UIViewController {
var funcCompletionHandler = FuncCompletionHandler()
weak var delegate: ExtensionFuncListViewControllerDelegate?
private let tableView = UITableView(frame: CGRectZero, style: .Plain)
private var list = [JSON]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
makeConstriants()
setupAction()
bind()
}
private func setupUI() {
navigationItem.title = "代码片段"
view.backgroundColor = UIColor.whiteColor()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(dismiss))
tableView.delegate = self
tableView.dataSource = self
tableView.showsVerticalScrollIndicator = false
tableView.registerClass(CustomOneLabelCell.self, forCellReuseIdentifier: NSStringFromClass(CustomOneLabelCell))
view.addSubview(tableView)
}
private func makeConstriants() {
tableView.snp_makeConstraints { (make) in
make.edges.equalTo(view)
}
}
private func setupAction() {
}
private func bind() {
self.list = JsManager.sharedManager.getSnippetList()
}
@objc private func dismiss() {
delegate?.becomeFirstResponderToTextView()
dismissViewControllerAnimated(true, completion: nil)
}
}
extension BasisFuncListViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(NSStringFromClass(CustomOneLabelCell), forIndexPath: indexPath) as! CustomOneLabelCell
cell.bind(self.list[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let code = self.list[indexPath.row]["content"].stringValue
self.funcCompletionHandler.completionHandler?(code)
self.dismissViewControllerAnimated(true, completion: nil)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return Sizer.valueForDevice(phone: 45, pad: 55)
}
}
| 29.792683 | 145 | 0.739255 |
ef3a065cbb4b27349583e07d286079cb8ef17a21 | 1,242 | //
// ContentView.swift
// simplygrade
//
// Created by Lukas Hecke on 15.10.20.
//
import SwiftUI
struct ContentView: View {
var gradeItemManager = GradeItemManager()
var schoolYearsManager = SchoolYearsManager()
var body: some View {
TabView {
GradeItemsListNavigationView()
.environmentObject(gradeItemManager)
.tabItem {
Text("Noten")
Image(systemName: "doc.plaintext") // TODO: was passendes suchen
} // .listStyle(InsetGroupedListStyle())
SchoolYearsListNavigationView()
.environmentObject(schoolYearsManager)
.tabItem {
Text("Schuljahre")
Image(systemName: "calendar") // TODO: was passendes suchen
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(
gradeItemManager: GradeItemManager(usePreview: true),
schoolYearsManager: SchoolYearsManager(usePreview: true)
)
.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}
| 29.571429 | 105 | 0.58132 |
f519656476f422bb98f3ec4cad41d0cc3f76c5ed | 2,023 | //
// ViewController.swift
// VTMNameCheck-Example
//
// Created by Andrew J Clark on 18/04/2015.
// Copyright (c) 2015 Andrew J Clark. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Example Usage
let nameChecker = VTMNameCheck.sharedInstance
NSLog("Loading shallow index");
nameChecker.loadShallowGenderLists()
NSLog("Loading deep index");
nameChecker.loadDeepNamesList()
NSLog("Finished loading nameChecker");
let nameExamples = ["steve jobs", "alan turing", "some random computer", "chris", "123345", "apple inc", "frances allen", "ada lovelace"]
var malePeople = Set<String>()
var femalePeople = Set<String>()
var eitherPeople = Set<String>()
var unknownPeople = Set<String>()
var nonPeople = Set<String>()
for name in nameExamples {
let result = nameChecker.isPerson(name)
if result.isPerson == true {
if result.gender == .Male {
malePeople.insert(name)
} else if result.gender == .Female {
femalePeople.insert(name)
} else if result.gender == .Either {
eitherPeople.insert(name)
} else if result.gender == .Unknown {
unknownPeople.insert(name)
}
} else {
nonPeople.insert(name)
}
}
println("\n\nMales:\n\(malePeople)\n")
println("Females:\n\(femalePeople)\n")
println("Either Gender:\n\(eitherPeople)\n")
println("Unknown Gender:\n\(unknownPeople)\n")
println("Non People:\n\(nonPeople)\n")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 30.19403 | 145 | 0.554128 |
ffc3006006f2c1ed99fb0b47e28f46f366d57b23 | 1,886 | //
// StructData.swift
// TestDomino
//
// Created by 황정덕 on 2020/01/29.
// Copyright © 2020 Gitbot. All rights reserved.
//
import Foundation
struct Menu {
let category: String
let products: [Product]
}
struct Product {
let name: String
let price: Int
}
let menuData: [Menu] = [
Menu(category: "슈퍼시드", products: [
Product(name: "글램핑 바비큐", price: 35900),
Product(name: "알로하 하와이안", price: 25900),
Product(name: "우리 고구마", price: 31900),
Product(name: "콰트로 치즈 퐁듀", price: 25900)
]
),
Menu(category: "프리미엄", products: [
Product(name: "더블크러스트 이베리코", price: 34900),
Product(name: "블랙앵거스 스테이크", price: 25900),
Product(name: "블랙타이거 슈림프", price: 31900),
Product(name: "와규 앤 비스테카", price: 25900),
Product(name: "직화 스테이크", price: 25900)
]
),
Menu(category: "클래식", products: [
Product(name: "포테이토", price: 25900),
Product(name: "슈퍼디럭스", price: 25900),
Product(name: "슈퍼슈프림", price: 25900),
Product(name: "베이컨체더치즈", price: 25900),
Product(name: "불고기", price: 24900),
Product(name: "페퍼로니", price: 22900)
]
),
Menu(category: "사이드디시", products: [
Product(name: "딸기 슈크림", price: 4800),
Product(name: "슈퍼곡물 치킨", price: 7800),
Product(name: "애플 크러스트 디저트", price: 3800),
Product(name: "치킨퐁듀 그라탕", price: 8800),
Product(name: "퀴노아 치킨 샐러드", price: 7800),
Product(name: "포테이토 순살치킨", price: 7800)
]
),
Menu(category: "음료", products: [
Product(name: "미닛메이드 스파클링 청포도", price: 2300),
Product(name: "스프라이트", price: 2100),
Product(name: "코카콜라", price: 2000),
Product(name: "코카콜라 제로", price: 2100)
]
),
Menu(category: "피클소스", products: [
Product(name: "갈릭 디핑 소스", price: 200),
Product(name: "스위트 칠리소스", price: 300),
Product(name: "우리 피클 L", price: 800),
Product(name: "우리 피클 M", price: 500),
Product(name: "핫소스", price: 100)
]
)
]
| 26.194444 | 49 | 0.602863 |
bb4d98c30be8dc469fda0a15e6ba2fc059dfd32b | 2,050 | import Foundation
protocol StatusItemPresentationLogic {
func presentLoadingIndicator()
func presentSync(_ response: StatusItem.Sync.Response)
func presentError(_ response: StatusItem.Error.Response)
func presentData(_ response: StatusItem.Fetch.Response)
}
final class StatusItemPresenter: StatusItemPresentationLogic {
private weak var controller: StatusItemDisplayLogic?
private let numberFormatter: NumberFormatter
private let locale: Locale
init(controller: StatusItemDisplayLogic,
numberFormatter: NumberFormatter = NumberFormatter(),
locale: Locale = Locale.current) {
self.controller = controller
self.numberFormatter = numberFormatter
self.locale = locale
}
func presentLoadingIndicator() {
controller?.displayData(StatusItem.Fetch.ViewModel(buttonTitle: "status_item_loading".ls))
}
func presentSync(_ response: StatusItem.Sync.Response) {
controller?.displaySync(StatusItem.Sync.ViewModel())
}
func presentError(_ response: StatusItem.Error.Response) {
controller?.displayData(StatusItem.Fetch.ViewModel(buttonTitle: "status_item_error".ls))
}
func presentData(_ response: StatusItem.Fetch.Response) {
let value = response.portfolio.balance.valueForMetricType(response.displayMetricType)
numberFormatter.locale = locale
numberFormatter.numberStyle = .currency
if response.displayMetricType.isBTCValue {
numberFormatter.currencySymbol = "₿"
} else {
numberFormatter.currencySymbol = nil
}
let title: String
if response.displayMetricType.isPercentage {
title = String(format: "%.2f%@", value, "%")
} else if let numberTitle = numberFormatter.string(from: value as NSNumber) {
title = numberTitle
} else {
title = "status_item_unknown".ls
}
controller?.displayData(StatusItem.Fetch.ViewModel(buttonTitle: title))
}
}
| 35.964912 | 98 | 0.687317 |
8a5b262ccec49c7be9237e7d7f892bd2a6d42882 | 576 | //
// List.swift
// duotone
//
// Created by Carlo Eugster on 05.07.21.
//
import AppKit
import ArgumentParser
import Files
extension Duotone {
struct List: ParsableCommand {
static var configuration = CommandConfiguration(abstract: "List all presets.")
mutating func run() throws {
let presets = try Duotone.loadPresets()
for preset in presets {
print("Name: \(preset.name) - Light: \(preset.light), Dark: \(preset.dark), Contrast: \(preset.contrast), Blend: \(preset.blend)")
}
}
}
}
| 24 | 146 | 0.607639 |
f41abce5ed3274d9aa4d750609081fb7219d793c | 1,409 | import SwiftUI
import Foundation
//UIHostingController为SwiftUI视图ContentView创建一个视图控制器
// 当您要将SwiftUI视图集成到UIKit视图层次结构中时,创建一个对象。在创建时,指定要用作此视图控制器的根视图的SwiftUI视图;您可以稍后使用属性更改该视图。通过将其呈现或作为子视图控制器嵌入到界面中,可以像使用其他任何视图控制器一样使用托管控制器
//
class GameViewController: UIHostingController<GameView> {
//数据类
private let viewModel: GameViewModel?
//初始化函数
init(viewModel: GameViewModel) {
//设置viewmodel
self.viewModel = viewModel
//如果所有属性均已初始化,则在实例化类的时候会自动调用init()或super.init()
super.init(rootView: GameView(viewModel: viewModel))
//设置手势
setupGestures()
//开始新游戏
viewModel.start()
}
//设置手势函数
private func setupGestures() {
view.addGestureRecognizer(Swipe(.left) { [weak self] in
self?.viewModel?.push(.left)
//重点是weak用法,弱引用。被标记了weak的对象,能让ARC在正确的时间将其合理的销毁。内存管理方面的一种方式。
})
view.addGestureRecognizer(Swipe(.right) { [weak self] in
self?.viewModel?.push(.right)
})
view.addGestureRecognizer(Swipe(.up) { [weak self] in
self?.viewModel?.push(.up)
})
view.addGestureRecognizer(Swipe(.down) { [weak self] in
self?.viewModel?.push(.down)
})
}
//日志函数报错
@objc required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 28.755102 | 131 | 0.633073 |
67ce471e9772c372eead7aa02d355a6d6726a884 | 722 | class Solution {
func constructMaximumBinaryTree(_ nums: [Int]) -> TreeNode? {
if nums.isEmpty {
return nil
}
if nums.count == 1 {
return TreeNode(nums[0])
}
var maxInt = 0
var maxIndex = 0
for i in 0..<nums.count {
let value = nums[i]
if maxInt < value {
maxInt = value
maxIndex = i
}
}
var root = TreeNode(maxInt)
let left = Array<Int>(nums[..<maxIndex])
let right = Array<Int>(nums[(maxIndex+1)...])
root.left = constructMaximumBinaryTree(left)
root.right = constructMaximumBinaryTree(right)
return root
}
} | 28.88 | 65 | 0.5 |
26917df80e117de68cfd4c7295a7732891997140 | 489 | import Foundation
public struct EnumType {
public init(
file: URL? = nil,
name: String,
genericsArguments: [SType] = [],
caseElements: [CaseElement] = []
) {
self.file = file
self.name = name
self.genericsArguments = genericsArguments
self.caseElements = caseElements
}
public var file: URL?
public var name: String
public var genericsArguments: [SType]
public var caseElements: [CaseElement]
}
| 23.285714 | 50 | 0.611452 |
dd8c8a50acfca299a81d9d0d618d649a27bca257 | 1,381 | //
// PlanSelected.swift
// SwiftUIJam
//
// Created by Armen Mkrtchyan on 2021-02-20.
//
import SwiftUI
struct PlanSelected: View {
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 6) {
Text("Individual")
.font(.system(size: 26,
weight: .bold,
design: .default))
Text("$9.99/month")
.font(.callout)
}
Spacer()
Image(systemName: "checkmark.circle.fill")
.font(.title)
}
.padding(.all, 20)
.background(LinearGradient(
gradient: Gradient(
colors: [.gradientSelectedStart,
.gradientSelectedEnd]),
startPoint: .leading,
endPoint: .trailing),
alignment: .center)
.mask(RoundedRectangle(cornerRadius: 16,
style: .continuous))
.foregroundColor(.white)
}
}
struct PlanSelected_Previews: PreviewProvider {
static var previews: some View {
Group {
PlanSelected()
PlanSelected()
.preferredColorScheme(.dark)
}
.padding()
}
}
| 28.183673 | 60 | 0.443881 |
11dae4943729f6cb19da2be0336723ceca46bd7d | 230 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B{
struct g{var _=a<c
let a{let _=B<a
class B
struct B
| 23 | 87 | 0.752174 |
0a3f137434738f550c0a18d047a5f3b498dd5243 | 17,520 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import Foundation
/*
A collection of mocks for different `Foundation` types. The convention we use is to extend
types with static factory function prefixed with "mock". For example:
```
extension URL {
static func mockAny() -> URL {
// ...
}
}
extension URLSession {
static func mockDeliverySuccess(data: Data, response: HTTPURLResponse) -> URLSessionMock {
// ...
}
}
```
Other conventions to follow:
* Use the name `mockAny()` to name functions that return any value of given type.
* Use descriptive function and parameter names for functions that configure the object for particular scenario.
* Always use the minimal set of parameters which is required by given mock scenario.
*/
// MARK: - Basic types
protocol AnyMockable {
static func mockAny() -> Self
}
protocol RandomMockable {
static func mockRandom() -> Self
}
extension Data: AnyMockable {
static func mockAny() -> Data {
return Data()
}
static func mockRepeating(byte: UInt8, times count: Int) -> Data {
return Data(repeating: byte, count: count)
}
static func mock(ofSize size: UInt64) -> Data {
return mockRepeating(byte: 0x41, times: Int(size))
}
}
extension Array where Element == Data {
/// Returns chunks of mocked data. Accumulative size of all chunks equals `totalSize`.
static func mockChunksOf(totalSize: UInt64, maxChunkSize: UInt64) -> [Data] {
var chunks: [Data] = []
var bytesWritten: UInt64 = 0
while bytesWritten < totalSize {
let bytesLeft = totalSize - bytesWritten
var nextChunkSize: UInt64 = bytesLeft > Int.max ? UInt64(Int.max) : bytesLeft // prevents `Int` overflow
nextChunkSize = nextChunkSize > maxChunkSize ? maxChunkSize : nextChunkSize // caps the next chunk to its max size
chunks.append(.mockRepeating(byte: 0x1, times: Int(nextChunkSize)))
bytesWritten += UInt64(nextChunkSize)
}
return chunks
}
}
extension Array {
func randomElements() -> [Element] {
return compactMap { Bool.random() ? $0 : nil }
}
}
extension Dictionary: AnyMockable where Key: AnyMockable, Value: AnyMockable {
static func mockAny() -> Dictionary {
return [Key.mockAny(): Value.mockAny()]
}
}
extension Date: AnyMockable {
static func mockAny() -> Date {
return Date(timeIntervalSinceReferenceDate: 1)
}
static func mockRandomInThePast() -> Date {
return Date(timeIntervalSinceReferenceDate: TimeInterval.random(in: 0..<Date().timeIntervalSinceReferenceDate))
}
static func mockSpecificUTCGregorianDate(year: Int, month: Int, day: Int, hour: Int, minute: Int = 0, second: Int = 0) -> Date {
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
dateComponents.timeZone = .UTC
dateComponents.calendar = .gregorian
return dateComponents.date!
}
static func mockDecember15th2019At10AMUTC(addingTimeInterval timeInterval: TimeInterval = 0) -> Date {
return mockSpecificUTCGregorianDate(year: 2_019, month: 12, day: 15, hour: 10)
.addingTimeInterval(timeInterval)
}
}
extension TimeZone: AnyMockable {
static var UTC: TimeZone { TimeZone(abbreviation: "UTC")! }
static var EET: TimeZone { TimeZone(abbreviation: "EET")! }
static func mockAny() -> TimeZone { .EET }
}
extension Calendar {
static var gregorian: Calendar {
return Calendar(identifier: .gregorian)
}
}
extension URL: AnyMockable, RandomMockable {
static func mockAny() -> URL {
return URL(string: "https://www.datadoghq.com")!
}
static func mockWith(pathComponent: String) -> URL {
return URL(string: "https://www.foo.com/")!.appendingPathComponent(pathComponent)
}
static func mockRandom() -> URL {
return URL(string: "https://www.foo.com/")!
.appendingPathComponent(
.mockRandom(
among: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
length: 32
)
)
}
}
extension String: AnyMockable {
static func mockAny() -> String {
return "abc"
}
static func mockRandom(length: Int = 10) -> String {
return mockRandom(
among: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",
length: length
)
}
static func mockRandom(among characters: String, length: Int = 10) -> String {
return String((0..<length).map { _ in characters.randomElement()! })
}
static func mockRepeating(character: Character, times: Int) -> String {
let characters = (0..<times).map { _ in character }
return String(characters)
}
}
extension Int: AnyMockable {
static func mockAny() -> Int {
return 0
}
}
extension Int64: AnyMockable, RandomMockable {
static func mockAny() -> Int64 { 0 }
static func mockRandom() -> Int64 { Int64.random(in: Int64.min..<Int64.max) }
}
extension UInt64: AnyMockable {
static func mockAny() -> UInt64 {
return 0
}
}
extension Bool: AnyMockable {
static func mockAny() -> Bool {
return false
}
}
extension Float: AnyMockable {
static func mockAny() -> Float {
return 0
}
}
extension Double: AnyMockable, RandomMockable {
static func mockAny() -> Float {
return 0
}
static func mockRandom() -> Double {
return Double.random(in: 0..<Double.greatestFiniteMagnitude)
}
}
extension TimeInterval {
static func mockAny() -> TimeInterval {
return 0
}
static let distantFuture = TimeInterval(integerLiteral: .max)
}
struct ErrorMock: Error, CustomStringConvertible {
let description: String
init(_ description: String = "") {
self.description = description
}
}
struct FailingEncodableMock: Encodable {
let errorMessage: String
func encode(to encoder: Encoder) throws {
throw ErrorMock(errorMessage)
}
}
class BundleMock: Bundle {
// swiftlint:disable identifier_name
fileprivate var _bundlePath: String = .mockAny()
fileprivate var _bundleIdentifier: String? = nil
fileprivate var _CFBundleVersion: String? = nil
fileprivate var _CFBundleShortVersionString: String? = nil
fileprivate var _CFBundleExecutable: String? = nil
// swiftlint:enable identifier_name
override var bundlePath: String { _bundlePath }
override var bundleIdentifier: String? { _bundleIdentifier }
override func object(forInfoDictionaryKey key: String) -> Any? {
switch key {
case "CFBundleVersion": return _CFBundleVersion
case "CFBundleShortVersionString": return _CFBundleShortVersionString
case "CFBundleExecutable": return _CFBundleExecutable
default: return super.object(forInfoDictionaryKey: key)
}
}
}
extension Bundle {
static func mockAny() -> Bundle {
return mockWith()
}
static func mockWith(
bundlePath: String = .mockAny(),
bundleIdentifier: String? = .mockAny(),
CFBundleVersion: String? = .mockAny(),
CFBundleShortVersionString: String? = .mockAny(),
CFBundleExecutable: String? = .mockAny()
) -> Bundle {
let mock = BundleMock()
mock._bundlePath = bundlePath
mock._bundleIdentifier = bundleIdentifier
mock._CFBundleVersion = CFBundleVersion
mock._CFBundleShortVersionString = CFBundleShortVersionString
mock._CFBundleExecutable = CFBundleExecutable
return mock
}
}
// MARK: - HTTP
extension URLResponse {
static func mockAny() -> HTTPURLResponse {
return .mockResponseWith(statusCode: 200)
}
static func mockResponseWith(statusCode: Int) -> HTTPURLResponse {
return HTTPURLResponse(url: .mockAny(), statusCode: statusCode, httpVersion: nil, headerFields: nil)!
}
static func mockWith(
statusCode: Int = 200,
mimeType: String = "application/json"
) -> HTTPURLResponse {
return HTTPURLResponse(
url: .mockAny(),
statusCode: statusCode,
httpVersion: nil,
headerFields: ["Content-Type": "\(mimeType)"]
)!
}
}
extension URLRequest: AnyMockable {
static func mockAny() -> URLRequest {
return URLRequest(url: .mockAny())
}
static func mockWith(httpMethod: String) -> URLRequest {
var request = URLRequest(url: .mockAny())
request.httpMethod = httpMethod
return request
}
}
// MARK: - Process
class ProcessInfoMock: ProcessInfo {
private var _isLowPowerModeEnabled: Bool
init(isLowPowerModeEnabled: Bool = .mockAny()) {
_isLowPowerModeEnabled = isLowPowerModeEnabled
}
override var isLowPowerModeEnabled: Bool { _isLowPowerModeEnabled }
}
// MARK: - URLSession
extension URLSession {
static func mockAny() -> URLSession {
return .shared
}
}
extension URLSessionTask {
static func mockWith(request: URLRequest, response: HTTPURLResponse) -> URLSessionTask {
return URLSessionTaskMock(request: request, response: response)
}
}
extension URLSessionTaskMetrics {
static func mockAny() -> URLSessionTaskMetrics {
return URLSessionTaskMetrics()
}
@available(iOS 13, *)
static func mockWith(
taskInterval: DateInterval = .init(start: Date(), duration: 1),
transactionMetrics: [URLSessionTaskTransactionMetrics] = []
) -> URLSessionTaskMetrics {
return URLSessionTaskMetricsMock(
taskInterval: taskInterval,
transactionMetrics: transactionMetrics
)
}
}
extension URLSessionTaskTransactionMetrics {
static func mockAny() -> URLSessionTaskTransactionMetrics {
return URLSessionTaskTransactionMetrics()
}
/// Mocks `URLSessionTaskTransactionMetrics` by spreading out detailed values between `start` and `end`.
@available(iOS 13, *)
static func mockBySpreadingDetailsBetween(
start: Date,
end: Date,
resourceFetchType: URLSessionTaskMetrics.ResourceFetchType = .networkLoad
) -> URLSessionTaskTransactionMetrics {
let spread = end.timeIntervalSince(start)
let fetchStartDate = start
let domainLookupStartDate = start.addingTimeInterval(spread * 0.05) // 5%
let domainLookupEndDate = start.addingTimeInterval(spread * 0.15) // 15%
let connectStartDate = start.addingTimeInterval(spread * 0.15) // 15%
let secureConnectionStartDate = start.addingTimeInterval(spread * 0.20) // 20%
let secureConnectionEndDate = start.addingTimeInterval(spread * 0.35) // 35%
let connectEndDate = secureConnectionEndDate
let requestStartDate = start.addingTimeInterval(spread * 0.40) // 40%
let responseStartDate = start.addingTimeInterval(spread * 0.50) // 50%
let responseEndDate = end
let countOfResponseBodyBytesAfterDecoding: Int64 = .random(in: 512..<1_024)
return URLSessionTaskTransactionMetricsMock(
resourceFetchType: resourceFetchType,
fetchStartDate: fetchStartDate,
domainLookupStartDate: domainLookupStartDate,
domainLookupEndDate: domainLookupEndDate,
connectStartDate: connectStartDate,
connectEndDate: connectEndDate,
secureConnectionStartDate: secureConnectionStartDate,
secureConnectionEndDate: secureConnectionEndDate,
requestStartDate: requestStartDate,
responseStartDate: responseStartDate,
responseEndDate: responseEndDate,
countOfResponseBodyBytesAfterDecoding: countOfResponseBodyBytesAfterDecoding
)
}
@available(iOS 13, *)
static func mockWith(
resourceFetchType: URLSessionTaskMetrics.ResourceFetchType = .networkLoad,
fetchStartDate: Date? = nil,
domainLookupStartDate: Date? = nil,
domainLookupEndDate: Date? = nil,
connectStartDate: Date? = nil,
connectEndDate: Date? = nil,
secureConnectionStartDate: Date? = nil,
secureConnectionEndDate: Date? = nil,
requestStartDate: Date? = nil,
responseStartDate: Date? = nil,
responseEndDate: Date? = nil,
countOfResponseBodyBytesAfterDecoding: Int64 = 0
) -> URLSessionTaskTransactionMetrics {
return URLSessionTaskTransactionMetricsMock(
resourceFetchType: resourceFetchType,
fetchStartDate: fetchStartDate,
domainLookupStartDate: domainLookupStartDate,
domainLookupEndDate: domainLookupEndDate,
connectStartDate: connectStartDate,
connectEndDate: connectEndDate,
secureConnectionStartDate: secureConnectionStartDate,
secureConnectionEndDate: secureConnectionEndDate,
requestStartDate: requestStartDate,
responseStartDate: responseStartDate,
responseEndDate: responseEndDate,
countOfResponseBodyBytesAfterDecoding: countOfResponseBodyBytesAfterDecoding
)
}
}
private class URLSessionTaskMock: URLSessionTask {
private let _originalRequest: URLRequest
override var originalRequest: URLRequest? { _originalRequest }
private let _response: URLResponse
override var response: URLResponse? { _response }
init(request: URLRequest, response: HTTPURLResponse) {
self._originalRequest = request
self._response = response
}
}
@available(iOS 13, *) // We can't rely on subclassing the `URLSessionTaskMetrics` prior to iOS 13.0
private class URLSessionTaskMetricsMock: URLSessionTaskMetrics {
private let _taskInterval: DateInterval
override var taskInterval: DateInterval { _taskInterval }
private let _transactionMetrics: [URLSessionTaskTransactionMetrics]
override var transactionMetrics: [URLSessionTaskTransactionMetrics] { _transactionMetrics }
init(taskInterval: DateInterval, transactionMetrics: [URLSessionTaskTransactionMetrics]) {
self._taskInterval = taskInterval
self._transactionMetrics = transactionMetrics
}
}
@available(iOS 13, *) // We can't rely on subclassing the `URLSessionTaskTransactionMetrics` prior to iOS 13.0
private class URLSessionTaskTransactionMetricsMock: URLSessionTaskTransactionMetrics {
private let _resourceFetchType: URLSessionTaskMetrics.ResourceFetchType
override var resourceFetchType: URLSessionTaskMetrics.ResourceFetchType { _resourceFetchType }
private let _fetchStartDate: Date?
override var fetchStartDate: Date? { _fetchStartDate }
private let _domainLookupStartDate: Date?
override var domainLookupStartDate: Date? { _domainLookupStartDate }
private let _domainLookupEndDate: Date?
override var domainLookupEndDate: Date? { _domainLookupEndDate }
private let _connectStartDate: Date?
override var connectStartDate: Date? { _connectStartDate }
private let _connectEndDate: Date?
override var connectEndDate: Date? { _connectEndDate }
private let _secureConnectionStartDate: Date?
override var secureConnectionStartDate: Date? { _secureConnectionStartDate }
private let _secureConnectionEndDate: Date?
override var secureConnectionEndDate: Date? { _secureConnectionEndDate }
private let _requestStartDate: Date?
override var requestStartDate: Date? { _requestStartDate }
private let _responseStartDate: Date?
override var responseStartDate: Date? { _responseStartDate }
private let _responseEndDate: Date?
override var responseEndDate: Date? { _responseEndDate }
private let _countOfResponseBodyBytesAfterDecoding: Int64
override var countOfResponseBodyBytesAfterDecoding: Int64 { _countOfResponseBodyBytesAfterDecoding }
init(
resourceFetchType: URLSessionTaskMetrics.ResourceFetchType,
fetchStartDate: Date?,
domainLookupStartDate: Date?,
domainLookupEndDate: Date?,
connectStartDate: Date?,
connectEndDate: Date?,
secureConnectionStartDate: Date?,
secureConnectionEndDate: Date?,
requestStartDate: Date?,
responseStartDate: Date?,
responseEndDate: Date?,
countOfResponseBodyBytesAfterDecoding: Int64
) {
self._resourceFetchType = resourceFetchType
self._fetchStartDate = fetchStartDate
self._domainLookupStartDate = domainLookupStartDate
self._domainLookupEndDate = domainLookupEndDate
self._connectStartDate = connectStartDate
self._connectEndDate = connectEndDate
self._secureConnectionStartDate = secureConnectionStartDate
self._secureConnectionEndDate = secureConnectionEndDate
self._requestStartDate = requestStartDate
self._responseStartDate = responseStartDate
self._responseEndDate = responseEndDate
self._countOfResponseBodyBytesAfterDecoding = countOfResponseBodyBytesAfterDecoding
}
}
| 33.499044 | 132 | 0.687443 |
38980d343946d5d13749daaa7b06b1d540c006b8 | 2,482 | //
// PostListCell.swift
// BBS-iOS
//
// Created by peng on 2017/11/24.
// Copyright © 2017年 swift520. All rights reserved.
//
import UIKit
class PostListCell: PPTableViewCell {
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var timeLabel: UILabel!
@IBOutlet fileprivate weak var bgImageView: UIImageView!
@IBOutlet fileprivate weak var adjustViewHeightConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var userIconIV: UIImageView!
@IBOutlet fileprivate weak var userNameLabel: UILabel!
@IBOutlet fileprivate weak var collectionBtn: UIButton!
@IBOutlet fileprivate weak var coverView: UIView!
@IBOutlet weak var bgView: UIView!
var postListModel: PostModel? {
didSet {
titleLabel.text = postListModel?.postTitle
if let time = postListModel?.postCreateTime {
timeLabel.text = Date.date(String(describing: time))
} else {
timeLabel.text = "加载中..."
}
userNameLabel.text = postListModel?.user?.userNickName
userIconIV.kf.setImage(with: URL(string: postListModel?.user?.userIcon ?? String()))
if postListModel?.postContentPics?.isEmpty != true {
if let pics = postListModel?.postContentPics {
let strArr = pics.components(separatedBy: ",")
if !strArr.isEmpty && strArr.first?.isEmpty == false {
bgImageView.kf.setImage(with: URL(string: strArr.first!))
bgImageView.isHidden = false
coverView.isHidden = false
adjustViewHeightConstraint.constant = 140
}
}
} else {
bgImageView.isHidden = true
coverView.isHidden = true
adjustViewHeightConstraint.constant = 0
}
// printLog(bgImageViewTopConstraint.constant)
}
}
override func awakeFromNib() {
super.awakeFromNib()
bgView.layer.cornerRadius = 8
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 33.093333 | 96 | 0.586624 |
79015bfa0618436e4d4ff2b3169085b9a8eaaeb4 | 5,287 | import Foundation
import RxSwift
class UserSettingsViewModel: ObservableObject {
private let kvStore: ObservableKeyValueStore
@Published var settingsViewData: [IdentifiableUserSettingViewData] = []
private let disposeBag = DisposeBag()
private let email: Email
private let notificationShower: NotificationShower
init(kvStore: ObservableKeyValueStore, alertFilterSettings: AlertFilterSettings,
envInfos: EnvInfos, email: Email, unitsProvider: UnitsProvider, lengthFormatter: LengthFormatter,
notificationShower: NotificationShower) {
self.kvStore = kvStore
self.email = email
self.notificationShower = notificationShower
Observable.combineLatest(kvStore.filterAlertsWithSymptoms,
kvStore.filterAlertsWithLongDuration,
kvStore.reminderNotificationsEnabled)
.map { filterAlertsWithSymptoms, filterAlertsWithLongDuration, reminderNotificationsEnabled in
buildSettings(filterAlertsWithSymptoms: filterAlertsWithSymptoms,
filterAlertsWithLongDuration: filterAlertsWithLongDuration,
reminderNotificationsEnabled: reminderNotificationsEnabled,
alertFilterSettings: alertFilterSettings,
appVersionString: "\(envInfos.appVersionName)(\(envInfos.appVersionCode))",
lengthFormatter: lengthFormatter)
}
.subscribe(onNext: { [weak self] viewData in
self?.settingsViewData = viewData
})
.disposed(by: disposeBag)
}
func onToggle(id: UserSettingToggleId, value: Bool) {
switch id {
case .filterAlertsWithSymptoms:
// The text says "show all reports" -> negate for filter
kvStore.setFilterAlertsWithSymptoms(value: !value)
case .reminderNotificationsEnabled:
kvStore.setReminderNotificationsEnabled(value: value)
log.d("Toggling reminder", tags: .ui)
if value {
notificationShower.scheduleReminderNotificationsForNext(days: 14)
} else {
//clear scheduled reminder notifiations
notificationShower.clearScheduledNotifications()
}
case .filterAlertsWithLongDuration:
kvStore.setFilterAlertsWithLongDuration(value: value)
}
// sleep(1)
// notificationShower.listScheduledNotifications()
}
func onAction(id: UserSettingActionId) {
switch id {
case .reportProblem: email.openEmail(address: "[email protected]", subject: "Problem with CoEpi")
}
}
func onReminderSave(hours: String, minutes: String) {
kvStore.setReminderHours(value: hours)
kvStore.setReminderMinutes(value: minutes)
}
}
struct IdentifiableUserSettingViewData: Identifiable {
let id: Int
let data: UserSettingViewData
}
enum UserSettingViewData {
case sectionHeader(title: String, description: String)
case toggle(text: String, value: Bool, id: UserSettingToggleId, hasBottomLine: Bool)
case link(text: String, url: URL)
case textAction(text: String, id: UserSettingActionId)
case text(String)
}
enum UserSettingToggleId {
case filterAlertsWithSymptoms
case filterAlertsWithLongDuration
case reminderNotificationsEnabled
}
enum UserSettingActionId {
case reportProblem
}
private func buildSettings(
filterAlertsWithSymptoms: Bool,
filterAlertsWithLongDuration: Bool,
reminderNotificationsEnabled: Bool,
alertFilterSettings: AlertFilterSettings,
appVersionString: String,
lengthFormatter: LengthFormatter
) -> [IdentifiableUserSettingViewData] {
[
UserSettingViewData.sectionHeader(
title: L10n.Settings.Header.Alerts.title,
description: L10n.Settings.Header.Alerts.descr
),
UserSettingViewData.toggle(
text: L10n.Settings.Item.allReports,
value: !filterAlertsWithSymptoms,
id: .filterAlertsWithSymptoms,
hasBottomLine: true
),
UserSettingViewData.toggle(
text: L10n.Settings.Item.durationLongerThanMins(
Int(alertFilterSettings.durationSecondsLargerThan / 60)),
value: filterAlertsWithLongDuration,
id: .filterAlertsWithLongDuration,
hasBottomLine: true
),
UserSettingViewData.toggle(text: L10n.Settings.Item.reminderNotificationsEnabled,
value: reminderNotificationsEnabled,
id: .reminderNotificationsEnabled,
hasBottomLine: false),
UserSettingViewData.link(text: L10n.Settings.Item.privacyStatement,
url: URL(string: "https://www.coepi.org/privacy/")!),
UserSettingViewData.textAction(text: L10n.Settings.Item.reportProblem,
id: .reportProblem),
UserSettingViewData.text(L10n.Settings.Item.version(appVersionString)),
// Note: index as id assumes hardcoded settings list, as above
].enumerated().map { index, data in IdentifiableUserSettingViewData(id: index, data: data) }
}
| 38.035971 | 106 | 0.666351 |
2f5ea45c549e8bf18daa7e08499cd1d2827b542d | 4,785 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -parse-as-library -enable-library-evolution -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift
// RUN: %target-swift-emit-silgen -I %t -enable-library-evolution -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-emit-sil -I %t -O -enable-library-evolution -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s
import resilient_global
public struct MyEmptyStruct {}
// CHECK-LABEL: sil_global private @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvp : $MyEmptyStruct
// CHECK-OPT-LABEL: sil_global private @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvp : $MyEmptyStruct = {
// CHECK-OPT-LABEL: %initval = struct $MyEmptyStruct ()
// CHECK-OPT-LABEL: }
public var myEmptyGlobal = MyEmptyStruct()
// CHECK-LABEL: sil_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp : $MyEmptyStruct
@_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct()
// Mutable addressor for resilient global
// CHECK-LABEL: sil hidden [global_init] [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: global_addr @$s17global_resilience13myEmptyGlobalAA02MyD6StructVv
// CHECK: return
// Synthesized accessors for our resilient global variable
// CHECK-LABEL: sil [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvg
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvs
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvM
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: begin_access [modify] [dynamic]
// CHECK: yield
// CHECK: end_access
// Mutable addressor for fixed-layout global
// CHECK-LABEL: sil private [global_init_once_fn] [ossa] @{{.*}}WZ
// CHECK: alloc_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-LABEL: sil [global_init] [ossa] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK: function_ref @{{.*}}WZ
// CHECK: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-OPT-LABEL: sil private [global_init_once_fn] @{{.*}}WZ
// CHECK-OPT: alloc_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: return
// CHECK-OPT-LABEL: sil [global_init] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK-OPT: function_ref @{{.*}}WZ
// CHECK-OPT: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp
// CHECK-OPT: return
// Accessing resilient global from our resilience domain --
// call the addressor directly
// CHECK-LABEL: sil [ossa] @$s17global_resilience16getMyEmptyGlobalAA0dE6StructVyF
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
public func getMyEmptyGlobal() -> MyEmptyStruct {
return myEmptyGlobal
}
// Accessing resilient global from a different resilience domain --
// access it with accessors
// CHECK-LABEL: sil [ossa] @$s17global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF
// CHECK: function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvg
// CHECK: return
public func getEmptyGlobal() -> EmptyResilientStruct {
return emptyGlobal
}
// CHECK-LABEL: sil [ossa] @$s17global_resilience17modifyEmptyGlobalyyF
// CHECK: [[MODIFY:%.*]] = function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvM
// CHECK-NEXT: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]()
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$s16resilient_global20EmptyResilientStructV6mutateyyF
// CHECK-NEXT: apply [[FN]]([[ADDR]])
// CHECK-NEXT: end_apply [[TOKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
public func modifyEmptyGlobal() {
emptyGlobal.mutate()
}
// Accessing fixed-layout global from a different resilience domain --
// call the addressor directly
// CHECK-LABEL: sil [ossa] @$s17global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF
// CHECK: function_ref @$s16resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVvau
// CHECK: return
public func getFixedLayoutGlobal() -> EmptyResilientStruct {
return fixedLayoutGlobal
}
| 45.141509 | 203 | 0.756949 |
289ad26f36ba188f21ca09446c455cc5694c4f7c | 2,822 | //
// WeatherListRequestTests.swift
// WeatherListTests
//
// Created by TienPham on 6/28/20.
// Copyright © 2020 Tien Pham. All rights reserved.
//
import XCTest
@testable import WeatherList
class WeatherListRequestTests: XCTestCase {
private var weatherListRequest: WeatherListRequest?
override func setUp() {
}
override func tearDown() {
weatherListRequest = nil
super.tearDown()
}
func testInitWithFullData() {
weatherListRequest = WeatherListRequestTests.fullWeatherListRequest
XCTAssertNotNil(weatherListRequest)
XCTAssertNotNil(weatherListRequest!.cityName)
XCTAssertNotNil(weatherListRequest!.numberOfDays)
XCTAssertNotNil(weatherListRequest!.unit)
XCTAssertTrue(weatherListRequest!.cityName == "Ho CHi Minh")
XCTAssertTrue(weatherListRequest!.numberOfDays == "7")
XCTAssertTrue(weatherListRequest!.unit == .default)
}
func testInitWithFullDataQuery() {
weatherListRequest = WeatherListRequestTests.fullWeatherListRequest
XCTAssertNotNil(weatherListRequest)
XCTAssertNotNil(weatherListRequest!.cityName)
XCTAssertNotNil(weatherListRequest!.numberOfDays)
XCTAssertNotNil(weatherListRequest!.unit)
XCTAssertTrue(weatherListRequest!.query == "appId=60c6fbeb4b93ac653c492ba806fc346d&q=Ho CHi Minh&cnt=7")
XCTAssertTrue(weatherListRequest!.storeQuery == "q=Ho CHi Minh")
}
func testInitWithMissingData() {
weatherListRequest = WeatherListRequestTests.missingWeatherListRequest
XCTAssertNotNil(weatherListRequest)
XCTAssertNotNil(weatherListRequest!.cityName)
XCTAssertNil(weatherListRequest!.numberOfDays)
XCTAssertNotNil(weatherListRequest!.unit)
XCTAssertTrue(weatherListRequest!.cityName == "Ha Noi")
XCTAssertTrue(weatherListRequest!.unit == .imperial)
}
func testInitWithMissingDataQuery() {
weatherListRequest = WeatherListRequestTests.missingWeatherListRequest
XCTAssertNotNil(weatherListRequest)
XCTAssertNotNil(weatherListRequest!.cityName)
XCTAssertNil(weatherListRequest!.numberOfDays)
XCTAssertNotNil(weatherListRequest!.unit)
XCTAssertTrue(weatherListRequest!.query == "appId=60c6fbeb4b93ac653c492ba806fc346d&q=Ha Noi&units=imperial")
XCTAssertTrue(weatherListRequest!.storeQuery == "q=Ha Noi&units=imperial")
}
}
extension WeatherListRequestTests {
static let fullWeatherListRequest: WeatherListRequest = WeatherListRequest(cityName: "Ho CHi Minh", numberOfDays: "7", unit: .default)
static let missingWeatherListRequest: WeatherListRequest = WeatherListRequest(cityName: "Ha Noi", numberOfDays: nil, unit: .imperial)
}
| 37.626667 | 138 | 0.725372 |
480972d2aa6d3c98e1ddf460a57664bd492efe32 | 2,372 | //
// SceneDelegate.swift
// ShadowPlayDemo
//
// Created by HonQi on 2019/10/27.
// Copyright © 2019 HonQi Indie. All rights reserved.
//
import UIKit
@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.127273 | 147 | 0.712901 |
64bc831a41acb6eeb0ca5b697798de4f72363bca | 5,618 | //
// Generated by SwagGen
// https://github.com/yonaskolb/SwagGen
//
import Foundation
extension Rocket.Account {
/** Create a new profile under the active account. */
public enum CreateProfile {
public static let service = APIService<Response>(id: "createProfile", tag: "account", method: "POST", path: "/account/profiles", hasBody: true, securityRequirement: SecurityRequirement(type: "accountAuth", scopes: ["Catalog"]))
public final class Request: APIRequest<Response> {
public var body: ProfileCreationRequest
public init(body: ProfileCreationRequest) {
self.body = body
super.init(service: CreateProfile.service) {
let jsonEncoder = JSONEncoder()
return try jsonEncoder.encode(body)
}
}
}
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = ProfileDetail
/** Details of the created profile. */
case status201(ProfileDetail)
/** Bad request. */
case status400(ServiceError)
/** Invalid access token. */
case status401(ServiceError)
/** Forbidden. */
case status403(ServiceError)
/** Not found. */
case status404(ServiceError)
/** Internal server error. */
case status500(ServiceError)
/** Service error. */
case defaultResponse(statusCode: Int, ServiceError)
public var success: ProfileDetail? {
switch self {
case .status201(let response): return response
default: return nil
}
}
public var failure: ServiceError? {
switch self {
case .status400(let response): return response
case .status401(let response): return response
case .status403(let response): return response
case .status404(let response): return response
case .status500(let response): return response
case .defaultResponse(_, let response): return response
default: return nil
}
}
/// either success or failure value. Success is anything in the 200..<300 status code range
public var responseResult: APIResponseResult<ProfileDetail, ServiceError> {
if let successValue = success {
return .success(successValue)
} else if let failureValue = failure {
return .failure(failureValue)
} else {
fatalError("Response does not have success or failure response")
}
}
public var response: Any {
switch self {
case .status201(let response): return response
case .status400(let response): return response
case .status401(let response): return response
case .status403(let response): return response
case .status404(let response): return response
case .status500(let response): return response
case .defaultResponse(_, let response): return response
}
}
public var statusCode: Int {
switch self {
case .status201: return 201
case .status400: return 400
case .status401: return 401
case .status403: return 403
case .status404: return 404
case .status500: return 500
case .defaultResponse(let statusCode, _): return statusCode
}
}
public var successful: Bool {
switch self {
case .status201: return true
case .status400: return false
case .status401: return false
case .status403: return false
case .status404: return false
case .status500: return false
case .defaultResponse: return false
}
}
public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws {
switch statusCode {
case 201: self = try .status201(decoder.decode(ProfileDetail.self, from: data))
case 400: self = try .status400(decoder.decode(ServiceError.self, from: data))
case 401: self = try .status401(decoder.decode(ServiceError.self, from: data))
case 403: self = try .status403(decoder.decode(ServiceError.self, from: data))
case 404: self = try .status404(decoder.decode(ServiceError.self, from: data))
case 500: self = try .status500(decoder.decode(ServiceError.self, from: data))
default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(ServiceError.self, from: data))
}
}
public var description: String {
return "\(statusCode) \(successful ? "success" : "failure")"
}
public var debugDescription: String {
var string = description
let responseString = "\(response)"
if responseString != "()" {
string += "\n\(responseString)"
}
return string
}
}
}
}
| 38.744828 | 235 | 0.545568 |
f8c9727e7491222297ac5cd080a7eb59191ec24e | 68,143 | //
// FeeDelegatedChainDataAnchoringTest.swift
// CaverSwiftTests
//
// Created by won on 2021/07/16.
//
import XCTest
@testable import CaverSwift
class FeeDelegatedChainDataAnchoringTest: XCTestCase {
static let caver = Caver(Caver.DEFAULT_URL)
static let senderPrivateKey = "0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"
static let feePayerPrivateKey = "0xb9d5558443585bca6f225b935950e3f6e69f9da8a5809a83f51c3365dff53936"
static let from = "0xa94f5374Fce5edBC8E2a8697C15331677e6EbF0B"
static let account = Account.createWithAccountKeyLegacy(from)
static let to = "0x7b65b75d204abed71587c9e519a89277766ee1d0"
static let gas = "0x174876e800"
static let gasPrice = "0x5d21dba00"
static let nonce = "0x11"
static let chainID = "0x1"
static let value = "0xa"
static let input = "f8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006"
static let humanReadable = false
static let codeFormat = CodeFormat.EVM.hexa
static let senderSignatureData = SignatureData(
"0x26",
"0xafe41edc9cce1185ab9065ca7dbfb89ab5c7bde3602a659aa258324124644142",
"0x317848698248ba7cc057b8f0dd19a27b52ef904d29cb72823100f1ed18ba2bb3"
)
static let feePayer = "0x33f524631e573329a550296F595c820D6c65213f"
static let feePayerSignatureData = SignatureData(
"0x25",
"0x309e46db21a1bf7bfdae24d9192aca69516d6a341ecce8971fc69cff481cee76",
"0x4b939bf7384c4f919880307323a5e36d4d6e029bae1887a43332710cdd48f174"
)
static let expectedRLPEncoding = "0x49f90176118505d21dba0085174876e80094a94f5374fce5edbc8e2a8697c15331677e6ebf0bb8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f845f84326a0afe41edc9cce1185ab9065ca7dbfb89ab5c7bde3602a659aa258324124644142a0317848698248ba7cc057b8f0dd19a27b52ef904d29cb72823100f1ed18ba2bb39433f524631e573329a550296f595c820d6c65213ff845f84325a0309e46db21a1bf7bfdae24d9192aca69516d6a341ecce8971fc69cff481cee76a04b939bf7384c4f919880307323a5e36d4d6e029bae1887a43332710cdd48f174"
static let expectedTransactionHash = "0xecf1ec12937065617f9b3cd07570452bfdb75dc36404c4f37f78995c6dc462af"
static let expectedSenderTransactionHash = "0x4f5c00ea8f6346baa7d4400dfefd72efa5ec219561ebcebed7be8a2b79d52bcd"
static let expectedRLPEncodingForFeePayerSigning = "0xf8f0b8d6f8d449118505d21dba0085174876e80094a94f5374fce5edbc8e2a8697c15331677e6ebf0bb8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a000000000000000000000000000000000000000000000000000000000000000040580069433f524631e573329a550296f595c820d6c65213f018080"
public static func generateRoleBaseKeyring(_ numArr: [Int], _ address: String) throws -> AbstractKeyring {
let keyArr = KeyringFactory.generateRoleBasedKeys(numArr, "entropy")
return try KeyringFactory.createWithRoleBasedKey(address, keyArr)
}
}
class FeeDelegatedChainDataAnchoringTest_createInstanceBuilder: XCTestCase {
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
public func test_BuilderTest() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertNotNil(txObj)
}
public func test_BuilderWithRPCTest() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setKlaytnCall(FeeDelegatedChainDataAnchoringTest.caver.rpc.klay)
.setGas(gas)
.setFrom(from)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
try txObj.fillTransaction()
XCTAssertFalse(txObj.nonce.isEmpty)
XCTAssertFalse(txObj.gasPrice.isEmpty)
XCTAssertFalse(txObj.chainId.isEmpty)
}
public func test_BuilderTestWithBigInteger() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(BigInt(hex: nonce)!)
.setGas(BigInt(hex: gas)!)
.setGasPrice(BigInt(hex: gasPrice)!)
.setChainId(BigInt(hex: chainID)!)
.setFrom(from)
.setInput(input)
.setFeePayer(feePayer)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertNotNil(txObj)
XCTAssertEqual(gas, txObj.gas)
XCTAssertEqual(gasPrice, txObj.gasPrice)
XCTAssertEqual(chainID, txObj.chainId)
}
public func test_throwException_invalidFrom() throws {
let from = "invalid Address"
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid address. : \(from)"))
}
}
public func test_throwException_missingFrom() throws {
let from = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("from is missing."))
}
}
public func test_throwException_invalidGas() throws {
let gas = "invalid gas"
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid gas. : \(gas)"))
}
}
public func test_throwException_missingGas() throws {
let gas = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("gas is missing."))
}
}
public func test_throwException_invalidInput() throws {
let input = "invalid input"
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid input. : \(input)"))
}
}
public func test_throwException_missingInput() throws {
let input = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("input is missing."))
}
}
public func test_throwException_setFeePayerSignatures_missingFeePayer() throws {
let feePayer = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("feePayer is missing: feePayer must be defined with feePayerSignatures."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_createInstance: XCTestCase {
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
public func test_createInstance() throws {
let txObj = try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)
XCTAssertNotNil(txObj)
}
public func test_throwException_invalidFrom() throws {
let from = "invalid Address"
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid address. : \(from)"))
}
}
public func test_throwException_missingFrom() throws {
let from = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("from is missing."))
}
}
public func test_throwException_invalidGas() throws {
let gas = "invalid gas"
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid gas. : \(gas)"))
}
}
public func test_throwException_missingGas() throws {
let gas = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("gas is missing."))
}
}
public func test_throwException_invalidInput() throws {
let input = "invalid input"
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid input. : \(input)"))
}
}
public func test_throwException_missingInput() throws {
let input = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("input is missing."))
}
}
public func test_throwException_setFeePayerSignatures_missingFeePayer() throws {
let feePayer = ""
XCTAssertThrowsError(try FeeDelegatedChainDataAnchoring(
nil,
from,
nonce,
gas,
gasPrice,
chainID,
[senderSignatureData],
feePayer,
[feePayerSignatureData],
input
)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("feePayer is missing: feePayer must be defined with feePayerSignatures."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_getRLPEncodingTest: XCTestCase {
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
public func test_getRLPEncoding() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertEqual(expectedRLPEncoding, try txObj.getRLPEncoding())
}
public func test_throwException_NoNonce() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try txObj.getRLPEncoding()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("nonce is undefined. Define nonce in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
public func test_throwException_NoGasPrice() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try txObj.getRLPEncoding()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("gasPrice is undefined. Define gasPrice in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_signAsFeePayer_OneKeyTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var keyring: AbstractKeyring?
var feePayerAddress: String?
let privateKey = PrivateKey.generate().privateKey
let feePayerPrivateKey = PrivateKey.generate().privateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
override func setUpWithError() throws {
keyring = try KeyringFactory.createFromPrivateKey(feePayerPrivateKey)
klaytnWalletKey = try keyring?.getKlaytnWalletKey()
feePayerAddress = keyring?.address
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayerAddress!)
.setInput(input)
.setSignatures(senderSignatureData)
.build()
}
public func test_signAsFeePayer_String() throws {
_ = try mTxObj!.signAsFeePayer(feePayerPrivateKey)
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_signAsFeePayer_KlaytnWalletKey() throws {
_ = try mTxObj!.signAsFeePayer(klaytnWalletKey!)
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_signAsFeePayer_Keyring() throws {
_ = try mTxObj!.signAsFeePayer(keyring!, 0, TransactionHasher.getHashForFeePayerSignature(_:))
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_signAsFeePayer_Keyring_NoSigner() throws {
_ = try mTxObj!.signAsFeePayer(keyring!, 0)
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_signAsFeePayer_multipleKey() throws {
let keyArr = [
PrivateKey.generate().privateKey,
feePayerPrivateKey,
PrivateKey.generate().privateKey
]
let keyring = try KeyringFactory.createWithMultipleKey(feePayerAddress!, keyArr)
_ = try mTxObj!.signAsFeePayer(keyring, 1)
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_signAsFeePayer_roleBasedKey() throws {
let keyArr = [
[
PrivateKey.generate().privateKey,
PrivateKey.generate().privateKey
],
[
PrivateKey.generate().privateKey
],
[
PrivateKey.generate().privateKey,
feePayerPrivateKey
]
]
let roleBasedKeyring = try KeyringFactory.createWithRoleBasedKey(feePayerAddress!, keyArr)
_ = try mTxObj!.signAsFeePayer(roleBasedKeyring, 1)
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_throwException_NotMatchAddress() throws {
let keyring = try KeyringFactory.createWithSingleKey(feePayerPrivateKey, PrivateKey.generate().privateKey)
XCTAssertThrowsError(try mTxObj!.signAsFeePayer(keyring, 0)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("The feePayer address of the transaction is different with the address of the keyring to use."))
}
}
public func test_throwException_InvalidIndex() throws {
let role = try AccountUpdateTest.generateRoleBaseKeyring([3,3,3], feePayerAddress!)
XCTAssertThrowsError(try mTxObj!.signAsFeePayer(role, 4)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("Invalid index : index must be less than the length of the key."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_signAsFeePayer_AllKeyTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var singleKeyring, multipleKeyring, roleBasedKeyring: AbstractKeyring?
let privateKey = PrivateKey.generate().privateKey
let feePayerPrivateKey = FeeDelegatedChainDataAnchoringTest.feePayerPrivateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
override func setUpWithError() throws {
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.build()
singleKeyring = try KeyringFactory.createWithSingleKey(feePayer, feePayerPrivateKey)
multipleKeyring = try KeyringFactory.createWithMultipleKey(feePayer, KeyringFactory.generateMultipleKeys(8))
roleBasedKeyring = try KeyringFactory.createWithRoleBasedKey(feePayer, KeyringFactory.generateRoleBasedKeys([3,4,5]))
}
public func test_signWithKeys_singleKeyring() throws {
_ = try mTxObj!.signAsFeePayer(singleKeyring!, TransactionHasher.getHashForFeePayerSignature(_:))
XCTAssertEqual(1, mTxObj?.signatures.count)
}
public func test_signWithKeys_singleKeyring_NoSigner() throws {
_ = try mTxObj!.signAsFeePayer(singleKeyring!)
XCTAssertEqual(1, mTxObj?.feePayerSignatures.count)
}
public func test_signWithKeys_multipleKeyring() throws {
_ = try mTxObj!.signAsFeePayer(multipleKeyring!)
XCTAssertEqual(8, mTxObj?.feePayerSignatures.count)
}
public func test_signWithKeys_roleBasedKeyring() throws {
_ = try mTxObj!.signAsFeePayer(roleBasedKeyring!)
XCTAssertEqual(5, mTxObj?.feePayerSignatures.count)
}
public func test_throwException_NotMatchAddress() throws {
let keyring = try KeyringFactory.createFromPrivateKey(PrivateKey.generate().privateKey)
XCTAssertThrowsError(try mTxObj!.signAsFeePayer(keyring)) {
XCTAssertEqual($0 as? CaverError, CaverError.IllegalArgumentException("The feePayer address of the transaction is different with the address of the keyring to use."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_appendFeePayerSignaturesTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var coupledKeyring: AbstractKeyring?
var deCoupledKeyring: AbstractKeyring?
let privateKey = FeeDelegatedChainDataAnchoringTest.senderPrivateKey
let feePayerPrivateKey = FeeDelegatedChainDataAnchoringTest.feePayerPrivateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
override func setUpWithError() throws {
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.build()
coupledKeyring = try KeyringFactory.createFromPrivateKey(privateKey)
deCoupledKeyring = try KeyringFactory.createWithSingleKey(PrivateKey.generate().getDerivedAddress(), privateKey)
klaytnWalletKey = try coupledKeyring?.getKlaytnWalletKey()
}
public func test_appendFeePayerSignature() throws {
let signatureData = SignatureData(
"0x0fea",
"0xade9480f584fe481bf070ab758ecc010afa15debc33e1bd75af637d834073a6e",
"0x38160105d78cef4529d765941ad6637d8dcf6bd99310e165fee1c39fff2aa27e"
)
try mTxObj!.appendFeePayerSignatures(signatureData)
XCTAssertEqual(signatureData, mTxObj?.feePayerSignatures[0])
}
public func test_appendFeePayerSignatureList() throws {
let signatureData = SignatureData(
"0x0fea",
"0xade9480f584fe481bf070ab758ecc010afa15debc33e1bd75af637d834073a6e",
"0x38160105d78cef4529d765941ad6637d8dcf6bd99310e165fee1c39fff2aa27e"
)
try mTxObj!.appendFeePayerSignatures([signatureData])
XCTAssertEqual(signatureData, mTxObj?.feePayerSignatures[0])
}
public func test_appendFeePayerSignatureList_EmptySig() throws {
let emptySignature = SignatureData.getEmptySignature()
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(emptySignature)
.build()
let signatureData = SignatureData(
"0x0fea",
"0xade9480f584fe481bf070ab758ecc010afa15debc33e1bd75af637d834073a6e",
"0x38160105d78cef4529d765941ad6637d8dcf6bd99310e165fee1c39fff2aa27e"
)
try mTxObj!.appendFeePayerSignatures([signatureData])
XCTAssertEqual(signatureData, mTxObj?.feePayerSignatures[0])
}
public func test_appendFeePayerSignature_ExistedSignature() throws {
let signatureData = SignatureData(
"0x0fea",
"0xade9480f584fe481bf070ab758ecc010afa15debc33e1bd75af637d834073a6e",
"0x38160105d78cef4529d765941ad6637d8dcf6bd99310e165fee1c39fff2aa27e"
)
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(signatureData)
.build()
let signatureData1 = SignatureData(
"0x0fea",
"0x7a5011b41cfcb6270af1b5f8aeac8aeabb1edb436f028261b5add564de694700",
"0x23ac51660b8b421bf732ef8148d0d4f19d5e29cb97be6bccb5ae505ebe89eb4a"
)
try mTxObj!.appendFeePayerSignatures([signatureData1])
XCTAssertEqual(2, mTxObj?.feePayerSignatures.count)
XCTAssertEqual(signatureData, mTxObj?.feePayerSignatures[0])
XCTAssertEqual(signatureData1, mTxObj?.feePayerSignatures[1])
}
public func test_appendSignatureList_ExistedSignature() throws {
let signatureData = SignatureData(
"0x0fea",
"0xade9480f584fe481bf070ab758ecc010afa15debc33e1bd75af637d834073a6e",
"0x38160105d78cef4529d765941ad6637d8dcf6bd99310e165fee1c39fff2aa27e"
)
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(signatureData)
.build()
let signatureData1 = SignatureData(
"0x0fea",
"0x7a5011b41cfcb6270af1b5f8aeac8aeabb1edb436f028261b5add564de694700",
"0x23ac51660b8b421bf732ef8148d0d4f19d5e29cb97be6bccb5ae505ebe89eb4a"
)
let signatureData2 = SignatureData(
"0x0fea",
"0x9a5011b41cfcb6270af1b5f8aeac8aeabb1edb436f028261b5add564de694700",
"0xa3ac51660b8b421bf732ef8148d0d4f19d5e29cb97be6bccb5ae505ebe89eb4a"
)
try mTxObj!.appendFeePayerSignatures([signatureData1, signatureData2])
XCTAssertEqual(3, mTxObj?.feePayerSignatures.count)
XCTAssertEqual(signatureData, mTxObj?.feePayerSignatures[0])
XCTAssertEqual(signatureData1, mTxObj?.feePayerSignatures[1])
XCTAssertEqual(signatureData2, mTxObj?.feePayerSignatures[2])
}
}
class FeeDelegatedChainDataAnchoringTest_combineSignatureTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var coupledKeyring: AbstractKeyring?
var deCoupledKeyring: AbstractKeyring?
let privateKey = FeeDelegatedChainDataAnchoringTest.senderPrivateKey
let from = "0xf1f766ded1aae1e06e2ed6c85127dd69891f7b28"
var account: Account?
let to = "0x8723590d5D60e35f7cE0Db5C09D3938b26fF80Ae"
let gas = "0x174876e800"
let nonce = "0x1"
let gasPrice = "0x5d21dba00"
let chainID = "0x7e3"
let value = BigInt(1)
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
override func setUpWithError() throws {
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setGasPrice(gasPrice)
.setFrom(from)
.setInput(input)
.setChainId(chainID)
.build()
}
public func test_combineSignature() throws {
let expectedRLPEncoded = "0x49f90136018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f847f845820feaa0042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9a03ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be940000000000000000000000000000000000000000c4c3018080"
let expectedSignature = SignatureData(
"0x0fea",
"0x042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9",
"0x3ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be"
)
let rlpEncoded = "0x49f90136018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f847f845820feaa0042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9a03ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be940000000000000000000000000000000000000000c4c3018080"
let combined = try mTxObj!.combineSignedRawTransactions([rlpEncoded])
XCTAssertEqual(expectedRLPEncoded, combined)
XCTAssertEqual(expectedSignature, mTxObj?.signatures[0])
}
public func test_combine_multipleSignature() throws {
let expectedRLPEncoded = "0x49f901c4018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f8d5f845820feaa0042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9a03ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974bef845820feaa0a45210f00ff64784e0aac0597b7eb19ea0890144100fd8dc8bb0b2fe003cbe84a07ff706e9a3825be7767f389789927a5633cf4995790a8bfe26d9332300de5db0f845820feaa076a91becce2c632980731d97a319216030de7b1b94b04c8a568236547d42d263a061c3c3456cda8eb7c440c700a168204b054d45d7bf2652c04171a0a1f76eff73940000000000000000000000000000000000000000c4c3018080"
let expectedSignature = [
SignatureData(
"0x0fea",
"0x042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9",
"0x3ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be"
),
SignatureData(
"0x0fea",
"0xa45210f00ff64784e0aac0597b7eb19ea0890144100fd8dc8bb0b2fe003cbe84",
"0x7ff706e9a3825be7767f389789927a5633cf4995790a8bfe26d9332300de5db0"
),
SignatureData(
"0x0fea",
"0x76a91becce2c632980731d97a319216030de7b1b94b04c8a568236547d42d263",
"0x61c3c3456cda8eb7c440c700a168204b054d45d7bf2652c04171a0a1f76eff73"
)
]
let rlpEncodedString = [
"0x49f90122018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f847f845820feaa0a45210f00ff64784e0aac0597b7eb19ea0890144100fd8dc8bb0b2fe003cbe84a07ff706e9a3825be7767f389789927a5633cf4995790a8bfe26d9332300de5db080c4c3018080",
"0x49f90122018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f847f845820feaa076a91becce2c632980731d97a319216030de7b1b94b04c8a568236547d42d263a061c3c3456cda8eb7c440c700a168204b054d45d7bf2652c04171a0a1f76eff7380c4c3018080"
]
let senderSignatureData = SignatureData(
"0x0fea",
"0x042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9",
"0x3ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be"
)
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setGasPrice(gasPrice)
.setFrom(from)
.setInput(input)
.setChainId(chainID)
.setSignatures(senderSignatureData)
.build()
let combined = try mTxObj!.combineSignedRawTransactions(rlpEncodedString)
XCTAssertEqual(expectedRLPEncoded, combined)
XCTAssertEqual(expectedSignature[0], mTxObj?.signatures[0])
XCTAssertEqual(expectedSignature[1], mTxObj?.signatures[1])
XCTAssertEqual(expectedSignature[2], mTxObj?.signatures[2])
}
public func test_combineSignature_feePayerSignature() throws {
let expectedRLPEncoded = "0x49f90136018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006c4c301808094ee43ecbed54e4862ed98c11d2e71b8bd04c1667ef847f845820fe9a0f8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356fa0346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16"
let expectedSignature = SignatureData(
"0x0fe9",
"0xf8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356f",
"0x346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16"
)
let rlpEncoded = "0x49f90136018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006c4c301808094ee43ecbed54e4862ed98c11d2e71b8bd04c1667ef847f845820fe9a0f8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356fa0346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16"
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setGasPrice(gasPrice)
.setFrom(from)
.setInput(input)
.setChainId(chainID)
.build()
let combined = try mTxObj!.combineSignedRawTransactions([rlpEncoded])
XCTAssertEqual(expectedRLPEncoded, combined)
XCTAssertEqual(expectedSignature, mTxObj?.feePayerSignatures[0])
}
public func test_combineSignature_multipleFeePayerSignature() throws {
let expectedRLPEncoded = "0x49f901c4018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006c4c301808094ee43ecbed54e4862ed98c11d2e71b8bd04c1667ef8d5f845820fe9a0f8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356fa0346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16f845820feaa0baa6a845e8c68ae8bf9acc7e018bceaab506e0818e0dc8db2afe3490a1927317a046bacf69af211302103f8c3841bc3cc6a79e2298ee4bc5d5e73b25f42ca98156f845820fe9a05df342131bfdae8239829e16a4298d711c238d0d4ab679b864878be729362921a07e3a7f484d6eb139c6b652c96aaa8ac8df43a5dfb3adaff46bc552a2c6965cba"
let expectedSignature = [
SignatureData(
"0x0fe9",
"0xf8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356f",
"0x346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16"
),
SignatureData(
"0x0fea",
"0xbaa6a845e8c68ae8bf9acc7e018bceaab506e0818e0dc8db2afe3490a1927317",
"0x46bacf69af211302103f8c3841bc3cc6a79e2298ee4bc5d5e73b25f42ca98156"
),
SignatureData(
"0x0fe9",
"0x5df342131bfdae8239829e16a4298d711c238d0d4ab679b864878be729362921",
"0x7e3a7f484d6eb139c6b652c96aaa8ac8df43a5dfb3adaff46bc552a2c6965cba"
)
]
let rlpEncodedString = [
"0x49f90136018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006c4c301808094ee43ecbed54e4862ed98c11d2e71b8bd04c1667ef847f845820feaa0baa6a845e8c68ae8bf9acc7e018bceaab506e0818e0dc8db2afe3490a1927317a046bacf69af211302103f8c3841bc3cc6a79e2298ee4bc5d5e73b25f42ca98156",
"0x49f90136018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006c4c301808094ee43ecbed54e4862ed98c11d2e71b8bd04c1667ef847f845820fe9a05df342131bfdae8239829e16a4298d711c238d0d4ab679b864878be729362921a07e3a7f484d6eb139c6b652c96aaa8ac8df43a5dfb3adaff46bc552a2c6965cba",
]
let feePayer = "0xee43ecbed54e4862ed98c11d2e71b8bd04c1667e"
let feePayerSignatureData = SignatureData(
"0x0fe9",
"0xf8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356f",
"0x346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16"
)
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setGasPrice(gasPrice)
.setFrom(from)
.setInput(input)
.setFeePayer(feePayer)
.setFeePayerSignatures(feePayerSignatureData)
.setChainId(chainID)
.build()
let combined = try mTxObj!.combineSignedRawTransactions(rlpEncodedString)
XCTAssertEqual(expectedRLPEncoded, combined)
XCTAssertEqual(expectedSignature[0], mTxObj?.feePayerSignatures[0])
XCTAssertEqual(expectedSignature[1], mTxObj?.feePayerSignatures[1])
XCTAssertEqual(expectedSignature[2], mTxObj?.feePayerSignatures[2])
}
public func test_multipleSignature_senderSignatureData_feePayerSignature() throws {
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setGasPrice(gasPrice)
.setFrom(from)
.setInput(input)
.setChainId(chainID)
.build()
let rlpEncodedString = "0x49f901b0018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f8d5f845820feaa0042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9a03ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974bef845820feaa0a45210f00ff64784e0aac0597b7eb19ea0890144100fd8dc8bb0b2fe003cbe84a07ff706e9a3825be7767f389789927a5633cf4995790a8bfe26d9332300de5db0f845820feaa076a91becce2c632980731d97a319216030de7b1b94b04c8a568236547d42d263a061c3c3456cda8eb7c440c700a168204b054d45d7bf2652c04171a0a1f76eff7380c4c3018080"
let expectedSignature = [
SignatureData(
"0x0fea",
"0x042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9",
"0x3ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be"
),
SignatureData(
"0x0fea",
"0xa45210f00ff64784e0aac0597b7eb19ea0890144100fd8dc8bb0b2fe003cbe84",
"0x7ff706e9a3825be7767f389789927a5633cf4995790a8bfe26d9332300de5db0"
),
SignatureData(
"0x0fea",
"0x76a91becce2c632980731d97a319216030de7b1b94b04c8a568236547d42d263",
"0x61c3c3456cda8eb7c440c700a168204b054d45d7bf2652c04171a0a1f76eff73"
)
]
_ = try mTxObj!.combineSignedRawTransactions([rlpEncodedString])
let rlpEncodedStringsWithFeePayerSignatures = "0x49f901c4018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006c4c301808094ee43ecbed54e4862ed98c11d2e71b8bd04c1667ef8d5f845820fe9a0f8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356fa0346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16f845820feaa0baa6a845e8c68ae8bf9acc7e018bceaab506e0818e0dc8db2afe3490a1927317a046bacf69af211302103f8c3841bc3cc6a79e2298ee4bc5d5e73b25f42ca98156f845820fe9a05df342131bfdae8239829e16a4298d711c238d0d4ab679b864878be729362921a07e3a7f484d6eb139c6b652c96aaa8ac8df43a5dfb3adaff46bc552a2c6965cba"
let expectedFeePayerSignatures = [
SignatureData(
"0x0fe9",
"0xf8f21b4d667b139e80818c2b8bfd6117ace4bc11157be3c3ee74c0360565356f",
"0x346828779330f21b7d06be682ec8289f3211c4018a20385cabd0d0ebc2569f16"
),
SignatureData(
"0x0fea",
"0xbaa6a845e8c68ae8bf9acc7e018bceaab506e0818e0dc8db2afe3490a1927317",
"0x46bacf69af211302103f8c3841bc3cc6a79e2298ee4bc5d5e73b25f42ca98156"
),
SignatureData(
"0x0fe9",
"0x5df342131bfdae8239829e16a4298d711c238d0d4ab679b864878be729362921",
"0x7e3a7f484d6eb139c6b652c96aaa8ac8df43a5dfb3adaff46bc552a2c6965cba"
)
]
_ = try mTxObj!.combineSignedRawTransactions([rlpEncodedStringsWithFeePayerSignatures])
XCTAssertEqual(expectedSignature[0], mTxObj?.signatures[0])
XCTAssertEqual(expectedSignature[1], mTxObj?.signatures[1])
XCTAssertEqual(expectedSignature[2], mTxObj?.signatures[2])
XCTAssertEqual(expectedFeePayerSignatures[0], mTxObj?.feePayerSignatures[0])
XCTAssertEqual(expectedFeePayerSignatures[1], mTxObj?.feePayerSignatures[1])
XCTAssertEqual(expectedFeePayerSignatures[2], mTxObj?.feePayerSignatures[2])
}
public func test_throwException_differentField() throws {
let gas = "0x1000"
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGas(gas)
.setGasPrice(gasPrice)
.setFrom(from)
.setInput(input)
.setChainId(chainID)
.build()
let rlpEncoded = "0x49f90122018505d21dba0085174876e80094f1f766ded1aae1e06e2ed6c85127dd69891f7b28b8aff8ad80b8aaf8a8a00000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000002a00000000000000000000000000000000000000000000000000000000000000003a00000000000000000000000000000000000000000000000000000000000000004058006f847f845820feaa0042800bfb7429b6c054fed37b86c473fdea9d4481d5d5b32cc92f34d744983b9a03ce733dfce2efd9f6ffaf70d50a0a211b94d84a8a18f1196e875053896a974be80c4c3018080"
XCTAssertThrowsError(try mTxObj!.combineSignedRawTransactions([rlpEncoded])) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("Transactions containing different information cannot be combined."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_getRawTransactionTest: XCTestCase {
let privateKey = FeeDelegatedChainDataAnchoringTest.senderPrivateKey
let feePayerPrivateKey = FeeDelegatedChainDataAnchoringTest.feePayerPrivateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
public func test_getRawTransaction() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertEqual(expectedRLPEncoding, try txObj.getRawTransaction())
}
}
class FeeDelegatedChainDataAnchoringTest_getTransactionHashTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var coupledKeyring: AbstractKeyring?
var deCoupledKeyring: AbstractKeyring?
let privateKey = FeeDelegatedChainDataAnchoringTest.senderPrivateKey
let feePayerPrivateKey = FeeDelegatedChainDataAnchoringTest.feePayerPrivateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
let expectedTransactionHash = FeeDelegatedChainDataAnchoringTest.expectedTransactionHash
public func test_getTransactionHash() throws {
let txObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertEqual(expectedTransactionHash, try txObj.getTransactionHash())
}
public func test_throwException_NotDefined_Nonce() throws {
let nonce = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getTransactionHash()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("nonce is undefined. Define nonce in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
public func test_throwException_NotDefined_gasPrice() throws {
let gasPrice = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getTransactionHash()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("gasPrice is undefined. Define gasPrice in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_getSenderTxHashTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var coupledKeyring: AbstractKeyring?
var deCoupledKeyring: AbstractKeyring?
let privateKey = FeeDelegatedChainDataAnchoringTest.senderPrivateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
let expectedTransactionHash = FeeDelegatedChainDataAnchoringTest.expectedTransactionHash
let expectedSenderTransactionHash = FeeDelegatedChainDataAnchoringTest.expectedSenderTransactionHash
public func test_getRLPEncodingForSignature() throws {
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertEqual(expectedSenderTransactionHash, try mTxObj!.getSenderTxHash())
}
public func test_throwException_NotDefined_Nonce() throws {
let nonce = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getSenderTxHash()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("nonce is undefined. Define nonce in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
public func test_throwException_NotDefined_gasPrice() throws {
let gasPrice = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getSenderTxHash()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("gasPrice is undefined. Define gasPrice in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
}
class FeeDelegatedChainDataAnchoringTest_getRLPEncodingForFeePayerSignatureTest: XCTestCase {
var mTxObj: FeeDelegatedChainDataAnchoring?
var klaytnWalletKey: String?
var coupledKeyring: AbstractKeyring?
var deCoupledKeyring: AbstractKeyring?
let privateKey = FeeDelegatedChainDataAnchoringTest.senderPrivateKey
let from = FeeDelegatedChainDataAnchoringTest.from
let account = FeeDelegatedChainDataAnchoringTest.account
let to = FeeDelegatedChainDataAnchoringTest.to
let gas = FeeDelegatedChainDataAnchoringTest.gas
let nonce = FeeDelegatedChainDataAnchoringTest.nonce
let gasPrice = FeeDelegatedChainDataAnchoringTest.gasPrice
let chainID = FeeDelegatedChainDataAnchoringTest.chainID
let value = FeeDelegatedChainDataAnchoringTest.value
let input = FeeDelegatedChainDataAnchoringTest.input
let humanReadable = FeeDelegatedChainDataAnchoringTest.humanReadable
let codeFormat = FeeDelegatedChainDataAnchoringTest.codeFormat
let senderSignatureData = FeeDelegatedChainDataAnchoringTest.senderSignatureData
let feePayer = FeeDelegatedChainDataAnchoringTest.feePayer
let feePayerSignatureData = FeeDelegatedChainDataAnchoringTest.feePayerSignatureData
let expectedRLPEncoding = FeeDelegatedChainDataAnchoringTest.expectedRLPEncoding
let expectedTransactionHash = FeeDelegatedChainDataAnchoringTest.expectedTransactionHash
let expectedSenderTransactionHash = FeeDelegatedChainDataAnchoringTest.expectedSenderTransactionHash
let expectedRLPEncodingForFeePayerSigning = FeeDelegatedChainDataAnchoringTest.expectedRLPEncodingForFeePayerSigning
public func test_getRLPEncodingForSignature() throws {
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertEqual(expectedRLPEncodingForFeePayerSigning, try mTxObj!.getRLPEncodingForFeePayerSignature())
}
public func test_throwException_NotDefined_Nonce() throws {
let nonce = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getRLPEncodingForSignature()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("nonce is undefined. Define nonce in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
public func test_throwException_NotDefined_gasPrice() throws {
let gasPrice = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getRLPEncodingForSignature()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("gasPrice is undefined. Define gasPrice in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
public func test_throwException_NotDefined_chainID() throws {
let chainID = ""
mTxObj = try FeeDelegatedChainDataAnchoring.Builder()
.setNonce(nonce)
.setGasPrice(gasPrice)
.setGas(gas)
.setFrom(from)
.setChainId(chainID)
.setFeePayer(feePayer)
.setInput(input)
.setSignatures(senderSignatureData)
.setFeePayerSignatures(feePayerSignatureData)
.build()
XCTAssertThrowsError(try mTxObj!.getRLPEncodingForSignature()) {
XCTAssertEqual($0 as? CaverError, CaverError.RuntimeException("chainId is undefined. Define chainId in transaction or use 'transaction.fillTransaction' to fill values."))
}
}
}
| 49.921612 | 970 | 0.712414 |
e6e6e6cead2f32710bf61130d5bd3219e54d3ab5 | 15,725 | //
// ScanStudentQRCodeViewController.swift
// eCommunicationBook
//
// Created by Ben Tee on 2021/5/29.
// Copyright © 2021 TKY co. All rights reserved.
//
import UIKit
import AVFoundation
import MapKit
import CoreLocation
import SwiftyMenu
import SnapKit
class ScanStudentQRCodeViewController: UIViewController {
var viewModel = ScanStudentQRCodeViewModel()
var hideDropDown = false
@IBOutlet weak var dropDownCourse: SwiftyMenu!
@IBOutlet weak var dropDownLesson: SwiftyMenu!
@IBOutlet weak var middleConstraintTimeIn: NSLayoutConstraint!
@IBOutlet weak var middleConstraintTimeOut: NSLayoutConstraint!
@IBOutlet weak var heightConstraintTimeIn: NSLayoutConstraint!
@IBOutlet weak var heightConstraintTimeOut: NSLayoutConstraint!
@IBOutlet weak var qrCodeView: UIView!
@IBOutlet weak var qrCodeMaskView: UIView!
@IBOutlet weak var labelStudentName: UILabel!
@IBOutlet weak var labelLocaiton: UILabel!
let captureSession = AVCaptureSession()
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var qrCodeFrameView: UIView?
let locationManager = CLLocationManager()
@IBAction func tapLeaveButton(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
viewModel.wroteInSuccess = {
BTProgressHUD.showSuccess(text: "Time In Success")
}
viewModel.wroteOutSuccess = {
BTProgressHUD.showSuccess(text: "Time Out Success")
}
viewModel.courseViewModel.bind { [weak self] _ in
self?.setDropDown()
}
viewModel.lessonListChanged = {
self.dropDownLesson.items = self.viewModel.lessonList
}
if hideDropDown == false {
viewModel.fetchCourse()
}
startDetectingQRCode()
startDetectingCurrentLocation()
addBlurMask()
// prepareWindow()
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
@IBAction func timeInButtonPress(_ sender: Any) {
viewModel.timeIn = true
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.middleConstraintTimeIn.isActive = true
self.middleConstraintTimeOut.isActive = false
self.heightConstraintTimeIn.constant = 200
self.heightConstraintTimeOut.constant = 0
self.view.layoutIfNeeded()
})
}
@IBAction func timeOutButtonPress(_ sender: Any) {
viewModel.timeIn = false
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.middleConstraintTimeIn.isActive = false
self.middleConstraintTimeOut.isActive = true
self.heightConstraintTimeIn.constant = 0
self.heightConstraintTimeOut.constant = 200
self.view.layoutIfNeeded()
})
}
func addBlurMask() {
let distanceToEdge: CGFloat = 50.0
qrCodeMaskView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
let maskLayer = CALayer()
maskLayer.frame = qrCodeMaskView.bounds
maskLayer.addSublayer(midSquareleLayer(distanceToEdge))
let squareInLinePathX = (distanceToEdge + 3) / 2
let squareInLinePathY = (UIScreen.height - 200 - (UIScreen.width - (distanceToEdge + 3))) / 2
let squareInLinePathRect = CGRect(x: squareInLinePathX,
y: squareInLinePathY,
width: UIScreen.width - distanceToEdge - 3,
height: UIScreen.width - distanceToEdge - 3)
let squareInLinePath = UIBezierPath(roundedRect: squareInLinePathRect,
cornerRadius: 15.0)
let shapeLayer = CAShapeLayer()
shapeLayer.path = squareInLinePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.gray.cgColor
shapeLayer.lineWidth = 4.0
let mask = CAShapeLayer()
let maskPath = UIBezierPath()
drawFiveSquares(maskPath)
mask.path = maskPath.cgPath
shapeLayer.mask = mask
qrCodeView.layer.addSublayer(shapeLayer)
qrCodeMaskView.layer.mask = maskLayer
}
func midSquareleLayer(_ distanceToEdge: CGFloat) -> CAShapeLayer {
let midSquareleLayer = CAShapeLayer()
midSquareleLayer.frame = CGRect(x: 0,
y: 0,
width: qrCodeMaskView.frame.size.width,
height: qrCodeMaskView.frame.size.height)
let finalPath = UIBezierPath(roundedRect:
CGRect(x: 0, y: 0,
width: qrCodeMaskView.frame.size.width,
height: qrCodeMaskView.frame.size.height),
cornerRadius: 0)
let squarePath = UIBezierPath(roundedRect:
CGRect(x: distanceToEdge / 2,
y: (UIScreen.height - 200 - (UIScreen.width - distanceToEdge))/2,
width: UIScreen.width - distanceToEdge,
height: UIScreen.width - distanceToEdge),
cornerRadius: 15.0)
finalPath.append(squarePath.reversing())
midSquareleLayer.path = finalPath.cgPath
midSquareleLayer.borderColor = UIColor.white.withAlphaComponent(1).cgColor
midSquareleLayer.borderWidth = 1
return midSquareleLayer
}
func drawFiveSquares(_ path: UIBezierPath) {
let height = UIScreen.height
let width = UIScreen.width
let y1Point = (UIScreen.height + UIScreen.width - 350)/2
let y2Point = (UIScreen.height - UIScreen.width - 50)/2
let pts = [
CGPoint(x: 75, y: 0),
CGPoint(x: 75, y: height),
CGPoint(x: 0, y: height),
CGPoint(x: 0, y: y1Point),
CGPoint(x: width, y: y1Point),
CGPoint(x: width, y: height),
CGPoint(x: width - 75, y: height),
CGPoint(x: width - 75, y: 0),
CGPoint(x: width, y: 0),
CGPoint(x: width, y: y2Point),
CGPoint(x: 0, y: y2Point)]
path.move(to: CGPoint(x: 0, y: 0))
for index in 0 ..< pts.count {
path.addLine(to: pts[index])
}
path.close()
}
func setDropDown() {
if hideDropDown == true {
dropDownCourse.isHidden = true
dropDownLesson.isHidden = true
return
}
// Setup component
dropDownCourse.delegate = self
dropDownLesson.delegate = self
dropDownCourse.items = self.viewModel.courseViewModel.value.map({$0.name})
dropDownLesson.items = self.viewModel.lessonList
if viewModel.studentExistance.courseName == String.empty {
dropDownCourse.placeHolderText = "Select Course"
} else {
dropDownCourse.placeHolderText = self.viewModel.studentExistance.courseName
}
if viewModel.studentExistance.courseLesson == 0 {
dropDownLesson.placeHolderText = "Lesson"
} else {
dropDownLesson.placeHolderText = String(self.viewModel.studentExistance.courseLesson)
}
modDropdow(dropDown: dropDownCourse)
modDropdow(dropDown: dropDownLesson)
}
func modDropdow(dropDown: SwiftyMenu) {
// Custom Behavior
dropDown.scrollingEnabled = true
dropDown.isMultiSelect = false
dropDown.hideOptionsWhenSelect = false
// Custom UI
dropDown.rowHeight = 38
dropDown.listHeight = 340
dropDown.borderWidth = 0.8
// Custom Colors
dropDown.borderColor = .black
dropDown.itemTextColor = .black
dropDown.placeHolderColor = .lightGray
dropDown.borderColor = .black
dropDown.itemTextColor = .black
dropDown.placeHolderColor = .lightGray
// Custom Animation
dropDown.expandingAnimationStyle = .spring(level: .low)
dropDown.expandingDuration = 0.5
dropDown.collapsingAnimationStyle = .linear
dropDown.collapsingDuration = 0.5
}
func startDetectingQRCode() {
labelStudentName.text = "No QR code detected"
guard let captureDevice = AVCaptureDevice
.default(.builtInWideAngleCamera, for: .video, position: .back) else {
print("Failed to get the camera device")
return
}
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession.addInput(input)
// 初始化一個 AVCaptureMetadataOutput 物件並將其設定做為擷取 session 的輸出裝置
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession.addOutput(captureMetadataOutput)
// 設定委派並使用預設的調度佇列來執行回呼(call back)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
// 初始化影片預覽層,並將其作為子層加入 viewPreview 視圖的圖層中
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = qrCodeView.layer.bounds
qrCodeView.layer.addSublayer(videoPreviewLayer!)
// 開始影片的擷取
captureSession.startRunning()
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
qrCodeFrameView.layer.borderWidth = 2
qrCodeView.addSubview(qrCodeFrameView)
qrCodeView.bringSubviewToFront(qrCodeFrameView)
}
} catch {
print(error)
return
}
}
func startDetectingCurrentLocation() {
// Ask for Authorisation from the User.
locationManager.requestAlwaysAuthorization()
// For use in foreground
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.requestLocation()
}
}
}
extension ScanStudentQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection) {
if metadataObjects.isEmpty == true {
qrCodeFrameView?.frame = CGRect.zero
labelStudentName.text = "No QR code detected"
return
}
if let metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
if metadataObj.type == AVMetadataObject.ObjectType.qr {
let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
qrCodeFrameView?.frame = barCodeObject!.bounds
if metadataObj.stringValue != nil {
labelStudentName.text = metadataObj.stringValue
guard let value: String = metadataObj.stringValue else {return}
viewModel.onScanedAQRCode(info: value)
}
}
} else {return}
}
}
extension ScanStudentQRCodeViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print("Found user's location: \(location)")
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
labelLocaiton.text = "locations = \(locValue.latitude) \(locValue.longitude)"
viewModel.onCurrentLocationChanged(latitude: locValue.latitude, longitude: locValue.longitude)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed to find user's location: \(error.localizedDescription)")
labelLocaiton.text = "error"
}
func geocode(latitude: Double,
longitude: Double,
completion: @escaping (CLPlacemark?, Error?) -> Void) {
let location = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(location) { completion($0?.first, $1) }
}
}
// MARK: - SwiftMenuDelegate
extension ScanStudentQRCodeViewController: SwiftyMenuDelegate {
func swiftyMenu(_ swiftyMenu: SwiftyMenu, didSelectItem item: SwiftyMenuDisplayable, atIndex index: Int) {
if swiftyMenu == dropDownCourse {
viewModel.onCourseNameChanged(index: index)
print("Selected item: \(item), at index: \(index)")
} else {
viewModel.onCourseLessonChanged(index: index)
}
}
func swiftyMenu(willExpand swiftyMenu: SwiftyMenu) {
print("SwiftyMenu willExpand.")
}
func swiftyMenu(didExpand swiftyMenu: SwiftyMenu) {
print("SwiftyMenu didExpand.")
}
func swiftyMenu(willCollapse swiftyMenu: SwiftyMenu) {
print("SwiftyMenu willCollapse.")
}
func swiftyMenu(didCollapse swiftyMenu: SwiftyMenu) {
print("SwiftyMenu didCollapse.")
}
}
// String extension to conform SwiftyMenuDisplayable for defult behavior
extension String: SwiftyMenuDisplayable {
public var displayableValue: String {
return self
}
public var retrievableValue: Any {
return self
}
}
| 31.703629 | 112 | 0.565787 |
21a48ee5a65d3080a41bb12456b5a31d626f4f46 | 2,162 | //
// AppDelegate.swift
// MDCalendar
//
// Created by 梁宪松 on 2018/11/1.
// Copyright © 2018 madao. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46 | 285 | 0.754394 |
ef8d79baba395c88f81b7e745263ec36fbf03735 | 20,872 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Effectively an untyped NSString that doesn't require foundation.
@usableFromInline
internal typealias _CocoaString = AnyObject
#if _runtime(_ObjC)
// Swift's String bridges NSString via this protocol and these
// variables, allowing the core stdlib to remain decoupled from
// Foundation.
@objc private protocol _StringSelectorHolder : _NSCopying {
@objc var length: Int { get }
@objc var hash: UInt { get }
@objc(characterAtIndex:)
func character(at offset: Int) -> UInt16
@objc(getCharacters:range:)
func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange
)
@objc(_fastCStringContents:)
func _fastCStringContents(
_ requiresNulTermination: Int8
) -> UnsafePointer<CChar>?
@objc(_fastCharacterContents)
func _fastCharacterContents() -> UnsafePointer<UInt16>?
@objc(getBytes:maxLength:usedLength:encoding:options:range:remainingRange:)
func getBytes(_ buffer: UnsafeMutableRawPointer?,
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>?,
encoding: UInt,
options: UInt,
range: _SwiftNSRange,
remaining leftover: UnsafeMutablePointer<_SwiftNSRange>?) -> Int8
@objc(compare:options:range:locale:)
func compare(_ string: _CocoaString,
options: UInt,
range: _SwiftNSRange,
locale: AnyObject?) -> Int
@objc(newTaggedNSStringWithASCIIBytes_:length_:)
func createTaggedString(bytes: UnsafePointer<UInt8>,
count: Int) -> AnyObject?
}
/*
Passing a _CocoaString through _objc() lets you call ObjC methods that the
compiler doesn't know about, via the protocol above. In order to get good
performance, you need a double indirection like this:
func a -> _objc -> func a'
because any refcounting @_effects on 'a' will be lost when _objc breaks ARC's
knowledge that the _CocoaString and _StringSelectorHolder are the same object.
*/
@inline(__always)
private func _objc(_ str: _CocoaString) -> _StringSelectorHolder {
return unsafeBitCast(str, to: _StringSelectorHolder.self)
}
@_effects(releasenone)
private func _copyNSString(_ str: _StringSelectorHolder) -> _CocoaString {
return str.copy(with: nil)
}
@usableFromInline // @testable
@_effects(releasenone)
internal func _stdlib_binary_CFStringCreateCopy(
_ source: _CocoaString
) -> _CocoaString {
return _copyNSString(_objc(source))
}
@_effects(readonly)
private func _NSStringLen(_ str: _StringSelectorHolder) -> Int {
return str.length
}
@usableFromInline // @testable
@_effects(readonly)
internal func _stdlib_binary_CFStringGetLength(
_ source: _CocoaString
) -> Int {
if let len = getConstantTaggedCocoaContents(source)?.utf16Length {
return len
}
return _NSStringLen(_objc(source))
}
@_effects(readonly)
internal func _isNSString(_ str:AnyObject) -> Bool {
if getConstantTaggedCocoaContents(str) != nil {
return true
}
return _swift_stdlib_isNSString(str) != 0
}
@_effects(readonly)
private func _NSStringCharactersPtr(_ str: _StringSelectorHolder) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return UnsafeMutablePointer(mutating: str._fastCharacterContents())
}
@usableFromInline // @testable
@_effects(readonly)
internal func _stdlib_binary_CFStringGetCharactersPtr(
_ source: _CocoaString
) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return _NSStringCharactersPtr(_objc(source))
}
@_effects(releasenone)
private func _NSStringGetCharacters(
from source: _StringSelectorHolder,
range: Range<Int>,
into destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
source.getCharacters(destination, range: _SwiftNSRange(
location: range.startIndex,
length: range.count)
)
}
/// Copies a slice of a _CocoaString into contiguous storage of sufficient
/// capacity.
@_effects(releasenone)
internal func _cocoaStringCopyCharacters(
from source: _CocoaString,
range: Range<Int>,
into destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_NSStringGetCharacters(from: _objc(source), range: range, into: destination)
}
@_effects(readonly)
private func _NSStringGetCharacter(
_ target: _StringSelectorHolder, _ position: Int
) -> UTF16.CodeUnit {
return target.character(at: position)
}
@_effects(readonly)
internal func _cocoaStringSubscript(
_ target: _CocoaString, _ position: Int
) -> UTF16.CodeUnit {
return _NSStringGetCharacter(_objc(target), position)
}
@_effects(releasenone)
private func _NSStringCopyUTF8(
_ o: _StringSelectorHolder,
into bufPtr: UnsafeMutableBufferPointer<UInt8>
) -> Int? {
let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked
let len = o.length
var remainingRange = _SwiftNSRange(location: 0, length: 0)
var usedLen = 0
let success = 0 != o.getBytes(
ptr,
maxLength: bufPtr.count,
usedLength: &usedLen,
encoding: _cocoaUTF8Encoding,
options: 0,
range: _SwiftNSRange(location: 0, length: len),
remaining: &remainingRange
)
if success && remainingRange.length == 0 {
return usedLen
}
return nil
}
@_effects(releasenone)
internal func _cocoaStringCopyUTF8(
_ target: _CocoaString,
into bufPtr: UnsafeMutableBufferPointer<UInt8>
) -> Int? {
return _NSStringCopyUTF8(_objc(target), into: bufPtr)
}
@_effects(readonly)
private func _NSStringUTF8Count(
_ o: _StringSelectorHolder,
range: Range<Int>
) -> Int? {
var remainingRange = _SwiftNSRange(location: 0, length: 0)
var usedLen = 0
let success = 0 != o.getBytes(
UnsafeMutablePointer<UInt8>(Builtin.inttoptr_Word(0._builtinWordValue)),
maxLength: 0,
usedLength: &usedLen,
encoding: _cocoaUTF8Encoding,
options: 0,
range: _SwiftNSRange(location: range.startIndex, length: range.count),
remaining: &remainingRange
)
if success && remainingRange.length == 0 {
return usedLen
}
return nil
}
@_effects(readonly)
internal func _cocoaStringUTF8Count(
_ target: _CocoaString,
range: Range<Int>
) -> Int? {
if range.isEmpty { return 0 }
return _NSStringUTF8Count(_objc(target), range: range)
}
@_effects(readonly)
private func _NSStringCompare(
_ o: _StringSelectorHolder, _ other: _CocoaString
) -> Int {
let range = _SwiftNSRange(location: 0, length: o.length)
let options = UInt(2) /* NSLiteralSearch*/
return o.compare(other, options: options, range: range, locale: nil)
}
@_effects(readonly)
internal func _cocoaStringCompare(
_ string: _CocoaString, _ other: _CocoaString
) -> Int {
return _NSStringCompare(_objc(string), other)
}
@_effects(readonly)
internal func _cocoaHashString(
_ string: _CocoaString
) -> UInt {
return _swift_stdlib_CFStringHashNSString(string)
}
@_effects(readonly)
internal func _cocoaHashASCIIBytes(
_ bytes: UnsafePointer<UInt8>, length: Int
) -> UInt {
return _swift_stdlib_CFStringHashCString(bytes, length)
}
// These "trampolines" are effectively objc_msgSend_super.
// They bypass our implementations to use NSString's.
@_effects(readonly)
internal func _cocoaCStringUsingEncodingTrampoline(
_ string: _CocoaString, _ encoding: UInt
) -> UnsafePointer<UInt8>? {
return _swift_stdlib_NSStringCStringUsingEncodingTrampoline(string, encoding)
}
@_effects(releasenone)
internal func _cocoaGetCStringTrampoline(
_ string: _CocoaString,
_ buffer: UnsafeMutablePointer<UInt8>,
_ maxLength: Int,
_ encoding: UInt
) -> Int8 {
return Int8(_swift_stdlib_NSStringGetCStringTrampoline(
string, buffer, maxLength, encoding))
}
//
// Conversion from NSString to Swift's native representation.
//
private var kCFStringEncodingASCII: _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x0600 }
}
private var kCFStringEncodingUTF8: _swift_shims_CFStringEncoding {
@inline(__always) get { return 0x8000100 }
}
internal enum _KnownCocoaString {
case storage
case shared
case cocoa
#if !(arch(i386) || arch(arm) || arch(wasm32))
case tagged
#endif
#if arch(arm64)
case constantTagged
#endif
@inline(__always)
init(_ str: _CocoaString) {
#if !(arch(i386) || arch(arm))
if _isObjCTaggedPointer(str) {
#if arch(arm64)
if let _ = getConstantTaggedCocoaContents(str) {
self = .constantTagged
} else {
self = .tagged
}
#else
self = .tagged
#endif
return
}
#endif
switch unsafeBitCast(_swift_classOfObjCHeapObject(str), to: UInt.self) {
case unsafeBitCast(__StringStorage.self, to: UInt.self):
self = .storage
case unsafeBitCast(__SharedStringStorage.self, to: UInt.self):
self = .shared
default:
self = .cocoa
}
}
}
#if !(arch(i386) || arch(arm))
// Resiliently write a tagged _CocoaString's contents into a buffer.
// TODO: move this to the Foundation overlay and reimplement it with
// _NSTaggedPointerStringGetBytes
@_effects(releasenone) // @opaque
internal func _bridgeTagged(
_ cocoa: _CocoaString,
intoUTF8 bufPtr: UnsafeMutableBufferPointer<UInt8>
) -> Int? {
_internalInvariant(_isObjCTaggedPointer(cocoa))
return _cocoaStringCopyUTF8(cocoa, into: bufPtr)
}
#endif
@_effects(readonly)
private func _NSStringASCIIPointer(_ str: _StringSelectorHolder) -> UnsafePointer<UInt8>? {
// TODO(String bridging): Is there a better interface here? Ideally we'd be
// able to ask for UTF8 rather than just ASCII
return str._fastCStringContents(0)?._asUInt8
}
@_effects(readonly) // @opaque
private func _withCocoaASCIIPointer<R>(
_ str: _CocoaString,
requireStableAddress: Bool,
work: (UnsafePointer<UInt8>) -> R?
) -> R? {
#if !(arch(i386) || arch(arm))
if _isObjCTaggedPointer(str) {
if let ptr = getConstantTaggedCocoaContents(str)?.asciiContentsPointer {
return work(ptr)
}
if requireStableAddress {
return nil // tagged pointer strings don't support _fastCStringContents
}
let tmp = _StringGuts(_SmallString(taggedCocoa: str))
return tmp.withFastUTF8 { work($0.baseAddress._unsafelyUnwrappedUnchecked) }
}
#endif
defer { _fixLifetime(str) }
if let ptr = _NSStringASCIIPointer(_objc(str)) {
return work(ptr)
}
return nil
}
@_effects(readonly) // @opaque
internal func withCocoaASCIIPointer<R>(
_ str: _CocoaString,
work: (UnsafePointer<UInt8>) -> R?
) -> R? {
return _withCocoaASCIIPointer(str, requireStableAddress: false, work: work)
}
@_effects(readonly)
internal func stableCocoaASCIIPointer(_ str: _CocoaString)
-> UnsafePointer<UInt8>? {
return _withCocoaASCIIPointer(str, requireStableAddress: true, work: { $0 })
}
private enum CocoaStringPointer {
case ascii(UnsafePointer<UInt8>)
case utf8(UnsafePointer<UInt8>)
case utf16(UnsafePointer<UInt16>)
case none
}
@_effects(readonly)
private func _getCocoaStringPointer(
_ cfImmutableValue: _CocoaString
) -> CocoaStringPointer {
if let ascii = stableCocoaASCIIPointer(cfImmutableValue) {
return .ascii(ascii)
}
if let utf16Ptr = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue) {
return .utf16(utf16Ptr)
}
return .none
}
@inline(__always)
private func getConstantTaggedCocoaContents(_ cocoaString: _CocoaString) ->
(utf16Length: Int, asciiContentsPointer: UnsafePointer<UInt8>?)? {
#if !arch(arm64)
return nil
#else
guard _isObjCTaggedPointer(cocoaString) else {
return nil
}
let taggedValue = unsafeBitCast(cocoaString, to: UInt.self)
//11000000..payload..111
let tagMask:UInt =
0b1111_1111_1000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0111
let expectedValue:UInt =
0b1100_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0111
guard taggedValue & tagMask == expectedValue else {
return nil
}
guard _swift_stdlib_dyld_is_objc_constant_string(
cocoaString as! UnsafeRawPointer
) == 1 else {
return nil
}
let payloadMask = ~tagMask
let payload = taggedValue & payloadMask
let ivarPointer = UnsafePointer<_swift_shims_builtin_CFString>(
bitPattern: payload
)!
let length = ivarPointer.pointee.length
let isUTF16Mask:UInt = 0x0000_0000_0000_0004 //CFStringFlags bit 4: isUnicode
let isASCII = ivarPointer.pointee.flags & isUTF16Mask == 0
let contentsPtr = ivarPointer.pointee.str
return (
utf16Length: Int(length),
asciiContentsPointer: isASCII ? contentsPtr : nil
)
#endif
}
@usableFromInline
@_effects(releasenone) // @opaque
internal func _bridgeCocoaString(_ cocoaString: _CocoaString) -> _StringGuts {
switch _KnownCocoaString(cocoaString) {
case .storage:
return _unsafeUncheckedDowncast(
cocoaString, to: __StringStorage.self).asString._guts
case .shared:
return _unsafeUncheckedDowncast(
cocoaString, to: __SharedStringStorage.self).asString._guts
#if !(arch(i386) || arch(arm))
case .tagged:
return _StringGuts(_SmallString(taggedCocoa: cocoaString))
#if arch(arm64)
case .constantTagged:
let taggedContents = getConstantTaggedCocoaContents(cocoaString)!
return _StringGuts(
cocoa: cocoaString,
providesFastUTF8: false, //TODO: if contentsPtr is UTF8 compatible, use it
isASCII: taggedContents.asciiContentsPointer != nil,
length: taggedContents.utf16Length
)
#endif
#endif
case .cocoa:
// "Copy" it into a value to be sure nobody will modify behind
// our backs. In practice, when value is already immutable, this
// just does a retain.
//
// TODO: Only in certain circumstances should we emit this call:
// 1) If it's immutable, just retain it.
// 2) If it's mutable with no associated information, then a copy must
// happen; might as well eagerly bridge it in.
// 3) If it's mutable with associated information, must make the call
let immutableCopy
= _stdlib_binary_CFStringCreateCopy(cocoaString)
#if !(arch(i386) || arch(arm))
if _isObjCTaggedPointer(immutableCopy) {
return _StringGuts(_SmallString(taggedCocoa: immutableCopy))
}
#endif
let (fastUTF8, isASCII): (Bool, Bool)
switch _getCocoaStringPointer(immutableCopy) {
case .ascii(_): (fastUTF8, isASCII) = (true, true)
case .utf8(_): (fastUTF8, isASCII) = (true, false)
default: (fastUTF8, isASCII) = (false, false)
}
let length = _stdlib_binary_CFStringGetLength(immutableCopy)
return _StringGuts(
cocoa: immutableCopy,
providesFastUTF8: fastUTF8,
isASCII: isASCII,
length: length)
}
}
extension String {
@_spi(Foundation)
public init(_cocoaString: AnyObject) {
self._guts = _bridgeCocoaString(_cocoaString)
}
}
@_effects(releasenone)
private func _createNSString(
_ receiver: _StringSelectorHolder,
_ ptr: UnsafePointer<UInt8>,
_ count: Int,
_ encoding: UInt32
) -> AnyObject? {
return receiver.createTaggedString(bytes: ptr, count: count)
}
@_effects(releasenone)
private func _createCFString(
_ ptr: UnsafePointer<UInt8>,
_ count: Int,
_ encoding: UInt32
) -> AnyObject? {
return _createNSString(
unsafeBitCast(__StringStorage.self as AnyClass, to: _StringSelectorHolder.self),
ptr,
count,
encoding
)
}
extension String {
@_effects(releasenone)
public // SPI(Foundation)
func _bridgeToObjectiveCImpl() -> AnyObject {
_connectOrphanedFoundationSubclassesIfNeeded()
// Smol ASCII a) may bridge to tagged pointers, b) can't contain a BOM
if _guts.isSmallASCII {
let maybeTagged = _guts.asSmall.withUTF8 { bufPtr in
return _createCFString(
bufPtr.baseAddress._unsafelyUnwrappedUnchecked,
bufPtr.count,
kCFStringEncodingUTF8
)
}
if let tagged = maybeTagged { return tagged }
}
if _guts.isSmall {
// We can't form a tagged pointer String, so grow to a non-small String,
// and bridge that instead. Also avoids CF deleting any BOM that may be
// present
var copy = self
// TODO: small capacity minimum is lifted, just need to make native
copy._guts.grow(_SmallString.capacity + 1)
_internalInvariant(!copy._guts.isSmall)
return copy._bridgeToObjectiveCImpl()
}
if _guts._object.isImmortal {
// TODO: We'd rather emit a valid ObjC object statically than create a
// shared string class instance.
let gutsCountAndFlags = _guts._object._countAndFlags
return __SharedStringStorage(
immortal: _guts._object.fastUTF8.baseAddress!,
countAndFlags: _StringObject.CountAndFlags(
sharedCount: _guts.count, isASCII: gutsCountAndFlags.isASCII))
}
_internalInvariant(_guts._object.hasObjCBridgeableObject,
"Unknown non-bridgeable object case")
return _guts._object.objCBridgeableObject
}
}
// Note: This function is not intended to be called from Swift. The
// availability information here is perfunctory; this function isn't considered
// part of the Stdlib's Swift ABI.
@available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *)
@_cdecl("_SwiftCreateBridgedString")
@usableFromInline
internal func _SwiftCreateBridgedString_DoNotCall(
bytes: UnsafePointer<UInt8>,
length: Int,
encoding: _swift_shims_CFStringEncoding
) -> Unmanaged<AnyObject> {
let bufPtr = UnsafeBufferPointer(start: bytes, count: length)
let str:String
switch encoding {
case kCFStringEncodingUTF8:
str = String(decoding: bufPtr, as: Unicode.UTF8.self)
case kCFStringEncodingASCII:
str = String(decoding: bufPtr, as: Unicode.ASCII.self)
default:
fatalError("Unsupported encoding in shim")
}
return Unmanaged<AnyObject>.passRetained(str._bridgeToObjectiveCImpl())
}
// At runtime, this class is derived from `__SwiftNativeNSStringBase`,
// which is derived from `NSString`.
//
// The @_swift_native_objc_runtime_base attribute
// This allows us to subclass an Objective-C class and use the fast Swift
// memory allocator.
@objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase)
class __SwiftNativeNSString {
@objc internal init() {}
deinit {}
}
// Called by the SwiftObject implementation to get the description of a value
// as an NSString.
@_silgen_name("swift_stdlib_getDescription")
public func _getDescription<T>(_ x: T) -> AnyObject {
return String(reflecting: x)._bridgeToObjectiveCImpl()
}
@_silgen_name("swift_stdlib_NSStringFromUTF8")
@usableFromInline //this makes the symbol available to the runtime :(
@available(macOS 10.15.4, iOS 13.4, watchOS 6.2, tvOS 13.4, *)
internal func _NSStringFromUTF8(_ s: UnsafePointer<UInt8>, _ len: Int)
-> AnyObject {
return String(
decoding: UnsafeBufferPointer(start: s, count: len),
as: UTF8.self
)._bridgeToObjectiveCImpl()
}
#else // !_runtime(_ObjC)
internal class __SwiftNativeNSString {
internal init() {}
deinit {}
}
#endif
// Special-case Index <-> Offset converters for bridging and use in accelerating
// the UTF16View in general.
extension StringProtocol {
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Offset(_ idx: Index) -> Int {
return self.utf16.distance(from: self.utf16.startIndex, to: idx)
}
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Index(_ offset: Int) -> Index {
return self.utf16.index(self.utf16.startIndex, offsetBy: offset)
}
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> {
let lowerbound = _toUTF16Offset(indices.lowerBound)
let length = self.utf16.distance(
from: indices.lowerBound, to: indices.upperBound)
return Range(
uncheckedBounds: (lower: lowerbound, upper: lowerbound + length))
}
@_specialize(where Self == String)
@_specialize(where Self == Substring)
public // SPI(Foundation)
func _toUTF16Indices(_ range: Range<Int>) -> Range<Index> {
let lowerbound = _toUTF16Index(range.lowerBound)
let upperbound = _toUTF16Index(range.lowerBound + range.count)
return Range(uncheckedBounds: (lower: lowerbound, upper: upperbound))
}
}
extension String {
public // @testable / @benchmarkable
func _copyUTF16CodeUnits(
into buffer: UnsafeMutableBufferPointer<UInt16>,
range: Range<Int>
) {
_internalInvariant(buffer.count >= range.count)
let indexRange = self._toUTF16Indices(range)
self.utf16._nativeCopy(into: buffer, alignedRange: indexRange)
}
}
| 29.438646 | 108 | 0.726955 |
4b00eb2b708cf44a59104a23729aacfb7e7232c1 | 1,415 | //
// EntryOverviewView.swift
// JournalingApp
//
// Created by Philipp Baldauf on 17.12.19.
// Copyright © 2019 Philipp Baldauf. All rights reserved.
//
import SwiftUI
struct EntryOverviewView: View {
// Access to core data managed object context
@Environment(\.managedObjectContext) var managedObjectContext
@State private var showCreateScreen = false
// Entries as fetched from CoreData
@FetchRequest(fetchRequest: Entry.sortedFetchRequest()) var entries: FetchedResults<Entry>
var body: some View {
NavigationView {
List(entries) { entry in
NavigationLink(destination: EntryDetailView(entry: entry)) {
EntryRow(entry: entry)
}
}
.navigationBarTitle("Entries")
.navigationBarItems(trailing: Button(action: {
self.showCreateScreen.toggle()
}, label: {
Image(systemName: "plus")
}))
.sheet(isPresented: $showCreateScreen) {
NavigationView {
CreateEntryView()
.environment(\.managedObjectContext, self.managedObjectContext)
}
}
}
.padding(.leading, 1.0)
}
}
struct EntryOverviewView_Previews: PreviewProvider {
static var previews: some View {
EntryOverviewView()
}
}
| 28.3 | 94 | 0.585866 |
0a9e75b9a8c2bbbde6f076ec63887797cf7aedf5 | 1,017 | //
// BloomFilterTests.swift
//
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
@testable import Herald
class BloomFilterTests: XCTestCase {
func test() {
let bloomFilter = BloomFilter(1024 * 1024)
// Add even numbers to bloom filter
for i in 0...10000 {
bloomFilter.add(networkByteOrderData(Int32(i * 2)))
}
// Test even numbers are all contained in bloom filter
for i in 0...10000 {
XCTAssertTrue(bloomFilter.contains(networkByteOrderData(Int32(i * 2))))
}
// Confirm odd numbers are not in bloom filter
for i in 0...10000 {
XCTAssertFalse(bloomFilter.contains(networkByteOrderData(Int32(i * 2 + 1))))
}
}
private func networkByteOrderData(_ identifier: Int32) -> Data {
var mutableSelf = identifier.bigEndian // network byte order
return Data(bytes: &mutableSelf, count: MemoryLayout.size(ofValue: mutableSelf))
}
}
| 29.911765 | 88 | 0.633235 |
f7e6b5a5fb881c5d4e9a6f18733d02118127a0ff | 6,500 | // RestoreWalletFromSeedsModel.swift
/*
Package MobileWallet
Created by Adrian Truszczynski on 12/07/2021
Using Swift 5.0
Running on macOS 12.0
Copyright 2019 The Tari Project
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.
3. Neither the name of the copyright holder nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE 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 Combine
struct TokenViewModel: Identifiable, Hashable {
let id: UUID
let title: String
}
final class RestoreWalletFromSeedsModel {
final class ViewModel {
@Published var error: SimpleErrorModel?
@Published var isConfimationEnabled: Bool = false
@Published var isEmptyWalletCreated: Bool = false
@Published var isAutocompletionAvailable: Bool = false
@Published var autocompletionTokens: [TokenViewModel] = []
@Published var autocompletionMessage: String?
}
// MARK: - Properties
@Published var inputText: String = ""
@Published var seedWords: [String] = []
let viewModel: ViewModel = ViewModel()
private var availableAutocompletionTokens: [TokenViewModel] = [] {
didSet { viewModel.isAutocompletionAvailable = !availableAutocompletionTokens.isEmpty }
}
private var cancelables = Set<AnyCancellable>()
// MARK: - Initalizers
init() {
setupFeedbacks()
fetchAvailableSeedWords()
}
// MARK: - Setups
private func setupFeedbacks() {
$seedWords
.map { !$0.isEmpty }
.assign(to: \.isConfimationEnabled, on: viewModel)
.store(in: &cancelables)
$inputText
.map { [unowned self] inputText in self.availableAutocompletionTokens.filter { $0.title.lowercased().hasPrefix(inputText.lowercased()) }}
.map { [unowned self] in $0 != self.availableAutocompletionTokens ? $0 : [] }
.assign(to: \.autocompletionTokens, on: viewModel)
.store(in: &cancelables)
Publishers.CombineLatest($inputText, viewModel.$autocompletionTokens)
.map {
switch ($0.isEmpty, $1.isEmpty) {
case (true, true):
return localized("restore_from_seed_words.autocompletion_toolbar.label.start_typing")
case (false, true):
return localized("restore_from_seed_words.autocompletion_toolbar.label.no_suggestions")
default:
return nil
}
}
.assign(to: \.autocompletionMessage, on: viewModel)
.store(in: &cancelables)
}
// MARK: - Actions
func startRestoringWallet() {
do {
let walletSeedWords = try SeedWords(words: seedWords)
try TariLib.shared.createNewWallet(seedWords: walletSeedWords)
viewModel.isEmptyWalletCreated = true
} catch let error as SeedWords.Error {
handle(seedWordsError: error)
} catch let error as WalletErrors {
handle(walletError: error)
} catch {
handleUnknownError()
}
}
private func fetchAvailableSeedWords() {
availableAutocompletionTokens = (try? SeedWordsMnemonicWordList(language: .english)?.seedWords.map { TokenViewModel(id: UUID(), title: $0) }) ?? []
}
// MARK: - Handlers
private func handle(seedWordsError: SeedWords.Error) {
switch seedWordsError {
case .invalidSeedPhrase, .invalidSeedWord:
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.error.title"),
description: localized("restore_from_seed_words.error.description.invalid_seed_word")
)
case .phraseIsTooShort:
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.error.title"),
description: localized("restore_from_seed_words.error.description.phrase_too_short")
)
case .phraseIsTooLong:
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.error.title"),
description: localized("restore_from_seed_words.error.description.phrase_too_long")
)
case .unexpectedResult:
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.error.title"),
description: localized("restore_from_seed_words.error.description.unknown_error")
)
}
}
private func handle(walletError: WalletErrors) {
guard let description = walletError.errorDescription else {
handleUnknownError()
return
}
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.error.title"),
description: description,
error: walletError
)
}
private func handleUnknownError() {
viewModel.error = SimpleErrorModel(
title: localized("restore_from_seed_words.error.title"),
description: localized("restore_from_seed_words.error.description.unknown_error")
)
}
}
| 36.931818 | 155 | 0.663692 |
e8586feb6cdb16aff95fd4f621bfee03affbbbd5 | 2,236 | /*
Copyright 2018 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
/// `IdentityServersURLGetter` is used to retrieved all the known identity server urls.
final class IdentityServersURLGetter {
// MARK: - Public
// The available identity servers
let identityServerUrls: [String]
/// Prepare the list of the known ISes
///
/// - Parameters:
/// - currentIdentityServerURL: the current identity server if any.
init(currentIdentityServerURL: String?) {
var identityServerUrls: [String] = []
// Consider first the current identity server if any.
if let currentIdentityServerURL = currentIdentityServerURL {
identityServerUrls.append(currentIdentityServerURL)
}
let identityServerPrefixURL = BuildSettings.serverUrlPrefix
var preferredKnownHosts = BuildSettings.preferredIdentityServerNames
// Add randomly the preferred known ISes
while preferredKnownHosts.count > 0 {
let index = Int(arc4random_uniform(UInt32(preferredKnownHosts.count)))
identityServerUrls.append("\(identityServerPrefixURL)\(preferredKnownHosts[index])")
preferredKnownHosts.remove(at: index)
}
var otherKnownHosts = BuildSettings.otherIdentityServerNames
// Add randomly the other known ISes
while otherKnownHosts.count > 0 {
let index = Int(arc4random_uniform(UInt32(otherKnownHosts.count)))
identityServerUrls.append("\(identityServerPrefixURL)\(otherKnownHosts[index])")
otherKnownHosts.remove(at: index)
}
self.identityServerUrls = identityServerUrls
}
}
| 37.266667 | 96 | 0.697674 |
e253e931ac25eb494022e2e8fd237ed0b3a3cb67 | 679 | class Solution {
func partitionDisjoint(_ nums: [Int]) -> Int {
var maxLeft = Array(repeating: 0, count: nums.count)
var minRight = Array(repeating: 0, count: nums.count)
maxLeft[0] = nums[0]
for i in 1..<nums.endIndex {
maxLeft[i] = max(maxLeft[i-1], nums[i])
}
minRight[nums.endIndex-1] = nums[nums.endIndex-1]
for i in stride(from: nums.endIndex-2, through: 0, by: -1) {
minRight[i] = min(minRight[i+1], nums[i])
}
for i in 1..<nums.endIndex {
if maxLeft[i-1] <= minRight[i] {
return i
}
}
return nums.count
}
}
| 27.16 | 68 | 0.511046 |
e50da1b6cb4071da66b5b50d864200ad8555307c | 2,165 | /// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
import UIKit
open class NiblessTableView: UITableView {
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
}
@available(*, unavailable,
message: "Loading this table view from a nib is unsupported in favor of initializer dependency injection."
)
public required init?(coder aDecoder: NSCoder) {
fatalError("Loading this table view from a nib is unsupported in favor of initializer dependency injection.")
}
}
| 48.111111 | 113 | 0.75612 |
1efb0bcb2af04a8231d440cad461badb9422bf76 | 376 | //
// Created by Timofey on 2/20/18.
// Copyright (c) 2018 CocoaPods. All rights reserved.
//
import Foundation
fileprivate class InvalidURLStringError: Swift.Error { }
extension URL {
init(string: String) throws {
if let url = (URL(string: string) as URL?) {
self = url
} else {
throw InvalidURLStringError()
}
}
} | 18.8 | 56 | 0.598404 |
0eb6d11c85a2227e2be52438fcdbc0c9d95d2f2a | 556 | //
// Operators.swift
// GitHubActivityFeed
//
// Created by Piotr Łyczba on 12/05/2019.
// Copyright © 2019 lyzkov. All rights reserved.
//
import Foundation
import Alamofire
func + (url: URL, path: String) -> URL {
return url.appendingPathComponent(path)
}
func + (defaults: Parameters, custom: Parameters) -> Parameters {
return defaults.merging(custom, uniquingKeysWith: { _, new in new })
}
func + (defaults: HTTPHeaders, custom: HTTPHeaders) -> HTTPHeaders {
return defaults.merging(custom, uniquingKeysWith: { _, new in new })
}
| 24.173913 | 72 | 0.701439 |
163c0bac3ed424de1071838b24f86d22f14d0c9b | 8,711 | //
// ResturantDetialViewController.swift
// yemekye
//
// Created by Arsalan Wahid Asghar on 10/22/17.
// Copyright © 2017 Arsalan Wahid Asghar. All rights reserved.
//
import UIKit
/*
TODO-LIST
contains
1. tableview
2. ScrollView
3. Collection View
4. Navigation
5.Resturant Details
6.menu Clickable
WorkFlow
1.This is presented after user selects a resturant from the mainViewControllerafter
2. Fix this view with auto layout
2a. This scene will show all the properties of the resturant object that has been selected
3. Implement scoll view
*/
class ResturantDetialViewController: UITableViewController{
//MARK:- Properties
private let tableCells = 4
private let tableHeaderViewHeight:CGFloat = 300
private let tableViewheaderCutAway : CGFloat = 40
var image: UIImage?
var headerView: ResturantHeaderView!
var headerMaskLayer: CAShapeLayer!
//MARK:- Resturant Cells
struct restuarntDetailCells{
static let infoCell = "infoCell"
static let actionsCell = "actionsCell"
static let amenitiesCell = "amenitiesCell"
}
//MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
headerView = tableView.tableHeaderView as! ResturantHeaderView
headerView.image = image
tableView.tableHeaderView = nil
tableView.addSubview(headerView)
//At this point the table view header is not over the top of rest of the views
//Pushed the tableview down by top CGFloat points
tableView.contentInset = UIEdgeInsets(top: tableHeaderViewHeight, left: 0, bottom: 0, right: 0 )
tableView.contentOffset = CGPoint(x: 0, y: -tableHeaderViewHeight + 64)
//cut Away header View
headerMaskLayer = CAShapeLayer()
headerMaskLayer.fillColor = UIColor.black.cgColor
headerView.layer.mask = headerMaskLayer
let effectiveHeight = tableHeaderViewHeight - tableViewheaderCutAway/2
tableView.contentInset = UIEdgeInsets(top: effectiveHeight, left: 0, bottom: 0, right: 0)
tableView.contentOffset = CGPoint(x: 0, y: -effectiveHeight)
updateheaderView()
//MARK:- NavigationBar
if ResturantsFromAPI.count > 0{
self.navigationItem.title = ResturantsFromAPI[cellIndex].name
}else{
self.navigationItem.title = RData.Rdata.resturants[cellIndex].name
}
navigationItem.backBarButtonItem?.tintColor = .white
}
//MARK:- Helper Method
private func updateheaderView(){
let effectiveheight = tableHeaderViewHeight - tableViewheaderCutAway/2
var headerRect = CGRect(x: 0, y: -effectiveheight, width: tableView.bounds.width, height: tableHeaderViewHeight)
if tableView.contentOffset.y < -effectiveheight {
headerRect.origin.y = tableView.contentOffset.y
headerRect.size.height = -tableView.contentOffset.y + tableViewheaderCutAway / 2
}
headerView.frame = headerRect
//
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: headerRect.width, y: 0))
path.addLine(to: CGPoint(x: headerRect.width, y: headerRect.height))
path.addLine(to: CGPoint(x: 0, y: headerRect.height - tableViewheaderCutAway))
headerMaskLayer?.path = path.cgPath
}
// //MARK:- Navigation
//
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// if segue.identifier == "showMenu"{
// let DVC = segue.destination as! MenuTableViewController
// DVC.menu = RData.Rdata.resturants[cellIndex].menu
// }
// }
}
//MARK:- UITableViewDataSource
extension ResturantDetialViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableCells
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//set info cell
if indexPath.row == 0{
let cell = Bundle.main.loadNibNamed("InfoTableViewCell", owner: self, options: nil)?.first as! InfoTableViewCell
if ResturantsFromAPI.count >= 1{
cell.nameLabel.text = ResturantsFromAPI[cellIndex].name
cell.addressLabel.text = ResturantsFromAPI[cellIndex].location.locality
cell.statusLabel.text = ResturantsFromAPI[cellIndex].user_rating.aggregate_rating
var time = ""
for n in RData.Rdata.resturants[cellIndex].timing
{
let (open,close) = n
time += "\(open)-\(close)\n"
}
cell.timingsLabel.text = time
}else{
cell.nameLabel.text = RData.Rdata.resturants[cellIndex].name
cell.addressLabel.text = RData.Rdata.resturants[cellIndex].address
cell.statusLabel.text = RData.Rdata.resturants[cellIndex].status
var time = ""
for n in RData.Rdata.resturants[cellIndex].timing
{
let (open,close) = n
time += "\(open)-\(close)\n"
}
cell.timingsLabel.text = time
}
return cell
}
//set actions cell
else if indexPath.row == 1{
let cell = Bundle.main.loadNibNamed("ActionsTableViewCell", owner: self, options: nil)?.first as! ActionsTableViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
//Check if any data is Resturants
if ResturantsFromAPI.count >= 1{
cell.phone.titleLabel?.text = "03312226043"
cell.websiteurl.text = ResturantsFromAPI[cellIndex].url
}else{
cell.phone.titleLabel?.text = "03312226034"
cell.website.titleLabel?.text = "https://www.zomato.com/buffalo"
}
return cell
}else if indexPath.row == 2{
let cell = Bundle.main.loadNibNamed("PromotionsTableViewCell", owner: self, options: nil)?.first as! PromotionsTableViewCell
cell.promotionsImage.image = UIImage(named: "menuicon")
cell.promotionsLabel.text = "Menu"
cell.accessoryType = .disclosureIndicator
return cell
}else if indexPath.row == 3{
let cell = Bundle.main.loadNibNamed("AmenitiesTableViewCell", owner: self, options: nil)?.first as! AmenitiesTableViewCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
print(" REstuarnt Phone number \(ResturantsFromAPI[cellIndex].phone_numbers)")
cell.phone.titleLabel?.text = ResturantsFromAPI[cellIndex].phone_numbers
cell.cuisinesLabel.text = ResturantsFromAPI[cellIndex].cusines
cell.avgCostLabel.text = String(ResturantsFromAPI[cellIndex].average_cost_for_two)
cell.currency.text = ResturantsFromAPI[cellIndex].currency
return cell
}else{
fatalError("no cell exists in ResturantDetailViewconteller")
}
//will never run I Guess
return UITableViewCell()
}
//MARK:- UITalbeViewDelegate
//Controls the Custom heights of each cell
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0{
return CGFloat(186.0)
}else if indexPath.row == 1{
return CGFloat(100.0)
}else if indexPath.row == 2{
return CGFloat(80)
}else if indexPath.row == 3{
return CGFloat(330)
}
return CGFloat(44)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 2{
var url: URL!
let menu = ResturantsFromAPI[cellIndex].menu_url
if let menu = menu{
url = URL(string: "\(menu)")!
}else{
print("no menu found")
url = URL(string: "https://www.zomato.com/buffalo")
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
//MARK:- Update Streachy Header
extension ResturantDetialViewController{
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateheaderView()
}
}
| 34.983936 | 136 | 0.615314 |
64a48870e022e64e8bd89e6e31ce16308bfd6f46 | 629 | import Foundation
class Solution {
func asteroidCollision(_ asteroids: [Int]) -> [Int] {
var stack = [Int]()
for item in asteroids {
if item > 0 {
stack.append(item)
} else {
while !stack.isEmpty && stack.last! > 0 && stack.last! < abs(item) {
stack.removeLast()
}
if stack.isEmpty || stack.last! < 0 {
stack.append(item)
} else if stack.last! == -item {
stack.removeLast()
}
}
}
return stack
}
}
| 28.590909 | 84 | 0.418124 |
613c88fdd05528a7823f492d58be4fe9a70581c8 | 2,484 | //
// AppDelegate.swift
// Shinkansen 3D Seat Booking Prototype
//
// Created by Virakri Jinangkul on 5/14/19.
// Copyright © 2019 Virakri Jinangkul. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Interfaces Initializer
window = UIWindow(frame: UIScreen.main.bounds)
let prototypeInitialViewController = PrototypeInitialViewController()
window?.rootViewController = prototypeInitialViewController
window?.makeKeyAndVisible()
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:.
NotificationCenter.default.removeObserver(self)
}
}
| 48.705882 | 285 | 0.750805 |
f84ebbc35fc78ee265248a221424d2346d3da2c7 | 1,004 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "C01S02TimerLEDToggle",
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/madmachineio/SwiftIO.git", .branch("main")),
.package(url: "https://github.com/madmachineio/MadBoards.git", .branch("main")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "C01S02TimerLEDToggle",
dependencies: [
"SwiftIO",
"MadBoards"]),
.testTarget(
name: "C01S02TimerLEDToggleTests",
dependencies: ["C01S02TimerLEDToggle"]),
]
)
| 38.615385 | 116 | 0.640438 |
034977529d3c62eda533edb33376325819ca0ecf | 818 | //
// NetworkingHelper.swift
// WeatherApp
//
// Created by Renzo Crisostomo on 12/08/14.
// Copyright (c) 2014 Renzo Crisóstomo. All rights reserved.
//
import Foundation
class NetworkingHelper {
let URL = "http://api.openweathermap.org/data/2.5/find"
let translatorHelper = TranslatorHelper()
func citiesWithUserLatitude(userLatitude: Double, userLongitude: Double, callback: ([City]?, NSError?)->()) {
let params = ["lat": userLatitude, "lon": userLongitude, "cnt": 100.0]
Alamofire.request(Alamofire.Method.GET, URL, parameters: params, encoding: Alamofire.ParameterEncoding.URL).response { (request, response, data, error) -> Void in
let cities = self.translatorHelper.translateCitiesFromJSON(data)
callback(cities, error)
}
}
} | 34.083333 | 170 | 0.676039 |
286401bba39437362c567d4268eb0fe10e2a9467 | 6,824 |
extension NSNotification.Name {
public static let SkyLabWillRunTestNotification = NSNotification.Name(rawValue: "SwiftSkyLabWillRunTestNotification")
public static let SkyLabDidRunTestNotification = NSNotification.Name(rawValue: "SwiftSkyLabDidRunTestNotification")
public static let SkyLabDidResetTestNotification = NSNotification.Name(rawValue: "SwiftSkyLabDidResetTestNotification")
}
public let SkyLabConditionKey = "com.swiftskylab.condition"
public let SkyLabActiveVariablesKey = "com.swiftskylab.active-variables"
public let SkyLabChoiceKey = SkyLabConditionKey
public class SwiftSkyLab {
public class func abTest(_ name: String,
A: () -> Void,
B: () -> Void) {
splitTest(name, conditions: ["A", "B"]) { (choice) in
if choice == "A" {
A()
} else {
B()
}
}
}
/*
原框架中 conditions 的类型为 NSFastEnumeration
看能否将下面的两种情况合并为一个
*/
public class func splitTest<Item: Hashable & Comparable>(
_ name: String,
conditions: [Item : Double],
block: (Item?) -> Void) {
var condition = UserDefaults.standard.object(forKey: UserDefaultsKey(name: name)) as? Item
if condition == nil || conditions.keys.firstIndex(of: condition!) == nil {
condition = RandomKeyWithWeightedValues(fromDictionary: conditions)
}
splitTest(name, choice: condition, block: block)
}
public class func splitTest<Item: Comparable>(
_ name: String,
conditions: [Item],
block: (Item?) -> Void) {
var condition = UserDefaults.standard.object(forKey: UserDefaultsKey(name: name)) as? Item
if condition == nil || conditions.firstIndex(of: condition!) == nil {
condition = RandomValue(fromArray: conditions)
}
splitTest(name, choice: condition, block: block)
}
class func splitTest<Item: Comparable>(_ name: String,
choice: Item?,
block: (Item?) -> Void) {
let needsSynchronization = choice == (UserDefaults.standard.object(forKey: UserDefaultsKey(name: name)) as? Item)
UserDefaults.standard.set(choice, forKey: UserDefaultsKey(name: name))
if needsSynchronization {
UserDefaults.standard.synchronize()
}
var userInfo = [String : Item]()
userInfo[SkyLabConditionKey] = choice
NotificationCenter.default.post(name: .SkyLabWillRunTestNotification, object: name, userInfo: userInfo)
block(choice)
NotificationCenter.default.post(name: .SkyLabDidRunTestNotification, object: name, userInfo: userInfo)
}
/*
原框架中 conditions 的类型为 NSFastEnumeration
看能否将下面的两种情况合并为一个
*/
public class func multivariateTest<Item: Comparable>(
_ name: String,
variables: [Item : Double],
block: (Set<Item>) -> Void) {
var activeVariables: Set<Item>
if let items = UserDefaults.standard.object(forKey: UserDefaultsKey(name: name)) as? [Item] {
activeVariables = Set(items)
} else {
activeVariables = Set<Item>()
}
if activeVariables.intersection(Array(variables.keys)).count == 0 {
for (key, weightedValues) in variables {
if RandomBinaryChoice(withProbability: weightedValues) {
activeVariables.insert(key)
}
}
}
multivariateTest(name, choice: activeVariables, block: block)
}
public class func multivariateTest<Item: Comparable>(
_ name: String,
variables: [Item],
block: (Set<Item>) -> Void) {
var activeVariables: Set<Item>
if let items = UserDefaults.standard.object(forKey: UserDefaultsKey(name: name)) as? [Item] {
activeVariables = Set(items)
} else {
activeVariables = Set<Item>()
}
if activeVariables.intersection(Array(variables)).count == 0 {
for variable in variables {
if RandomBinaryChoice() {
activeVariables.insert(variable)
}
}
}
multivariateTest(name, choice: activeVariables, block: block)
}
class func multivariateTest<Item: Comparable>(
_ name: String,
choice: Set<Item>,
block: (Set<Item>) -> Void) {
var needsSynchronization = false
if let items = (UserDefaults.standard.object(forKey: UserDefaultsKey(name: name)) as? [Item]) {
needsSynchronization = choice == Set(items)
}
UserDefaults.standard.set(Array(choice), forKey: UserDefaultsKey(name: name))
if needsSynchronization {
UserDefaults.standard.synchronize()
}
var userInfo = [String : Set<Item>]()
userInfo[SkyLabConditionKey] = choice
NotificationCenter.default.post(name: .SkyLabWillRunTestNotification, object: name, userInfo: userInfo)
block(choice)
NotificationCenter.default.post(name: .SkyLabDidRunTestNotification, object: name, userInfo: userInfo)
}
public class func resetTest(_ name: String) {
UserDefaults.standard.removeObject(forKey: UserDefaultsKey(name: name))
UserDefaults.standard.synchronize()
NotificationCenter.default.post(name: .SkyLabDidResetTestNotification, object: name)
}
}
func UserDefaultsKey(name: String) -> String {
let UserDefaultsKeyFormat = "SkyLab-"
return "\(UserDefaultsKeyFormat)\(name)"
}
func RandomValue<Item>(fromArray array: [Item]) -> Item?{
if array.count < 1 {
return nil
}
return array[Int(arc4random_uniform(UInt32(array.count)))]
}
func RandomKeyWithWeightedValues<Key: Hashable>(fromDictionary dictionary: [Key : Double]) -> Key? {
guard dictionary.count > 0 else {
return nil
}
var weightedSums = [Double]()
let keys: [Key] = Array(dictionary.keys)
var total: Double = 0
for key in keys {
total = total + dictionary[key]!
weightedSums.append(total)
}
if !hasSrand {
srand48(Int(Date().timeIntervalSince1970))
hasSrand = true
}
let random = drand48() * total
for (index, item) in weightedSums.enumerated() {
if random < item {
return keys[index]
}
}
return nil
}
func RandomBinaryChoice(withProbability probability: Double = 0.5) -> Bool {
if !hasSrand {
srand48(Int(Date().timeIntervalSince1970))
hasSrand = true
}
return drand48() <= probability
}
var hasSrand: Bool = false
| 34.12 | 123 | 0.610785 |
e57707fb9cea33aa98ced981f21025e395bf156f | 2,499 | //MARK: - Tree
struct Node {
var value: Int
var children: [Node] = []
init(value: Int) {
self.value = value
}
mutating func addNode(with value: Int) {
children.append(Node(value: value))
}
//convenient initialisers to create a dummy tree
init(value: Int, childValues: Int...) {
self.value = value
self.children = childValues.map({ Node(value: $0)})
}
init(value: Int, children: Node...) {
self.value = value
self.children = children
}
}
// MARK: Inside of this extension write two functions
extension Node {
/*1. Write a function that goes through the tree and returns the first element which satisfies the condition. If no element found, return nil;
condition is expressed by closure (Int) -> Bool
*/
func firstSatisfying(condition: (Int) -> Bool) -> Node? {
if condition(value) {
return self
}
for child in children {
if let satisfyingChild = child.firstSatisfying(condition: condition) {
return satisfyingChild
}
}
return nil
}
/*2. Write a filter function that goes through the tree and returns an array of all elements which satisfy the condition. If no element found, return empty array;
condition is expressed by closure (Int) -> Bool
*/
func nodesSatisfying(condition: (Int) -> Bool) -> [Node] {
var nodes: [Node] = []
if condition(value) {
nodes.append(self)
}
children.forEach { nodes += $0.nodesSatisfying(condition: condition) }
return nodes
}
}
//MARK: Test your code
//To test the code, we create a very dummy tree and apply some rules to it.
let middle1 = Node(value: 5, childValues: 13, 16)
let middle2 = Node(value: 7, childValues: 24)
let tree = Node(value: 1, children: middle1, middle2)
//Use the tree to find first object and filter objects that satisfy the conditions:
// element is > 12, > 0, > 50, == 4, == 13, < 15.
extension Node {
func test(condition: (Int) -> Bool) -> Void {
if let elem = firstSatisfying(condition: condition) {
print("first element: ", elem.value)
}
var elems: [Int] = []
nodesSatisfying(condition: condition).forEach {elems.append($0.value)}
print("elements: ", elems)
print()
}
}
print("> 12")
tree.test(condition: {$0 > 12})
print("> 0")
tree.test(condition: {$0 > 0})
print("> 50")
tree.test(condition: {$0 > 50})
print("< 15")
tree.test(condition: {$0 < 15})
print("== 4")
tree.test(condition: {$0 == 4})
print("== 13")
tree.test(condition: {$0 == 13})
| 25.762887 | 164 | 0.645458 |
1e1630245cf852188d102339ab4b1478b40a6bbb | 2,925 | // Copyright (c) 2014 segfault.jp. All rights reserved.
import XCTest
import ReactiveSwift
class SubjectTests: XCTestCase {
func testGenralUse() {
let exec = FakeExecutor()
let subj = Subject(1)
var received1: Packet<Int> = .Done
let chan1 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received1 = $0 }}
XCTAssertEqual(1, subj.subscribers)
XCTAssertTrue(received1.value == nil)
exec.consumeAll()
XCTAssertTrue(received1.value == 1)
var received2: Packet<Int> = .Done
let chan2 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received2 = $0 }}
XCTAssertEqual(2, subj.subscribers)
XCTAssertTrue(received2.value == nil)
exec.consumeAll()
XCTAssertTrue(received2.value == 1)
subj.value = 2
XCTAssertTrue(received1.value == 1)
XCTAssertTrue(received2.value == 1)
exec.consumeAll()
XCTAssertTrue(received1.value == 2)
XCTAssertTrue(received2.value == 2)
chan1.close()
chan2.close()
XCTAssertEqual(0, subj.subscribers)
exec.consumeAll()
XCTAssertEqual(0, subj.subscribers)
}
func testDisposingSubjectCausesCloseAllSubscriptions() {
let exec = FakeExecutor()
var subj = Subject(1)
var received1: Packet<Int>? = nil
var received2: Packet<Int>? = nil
let chan1 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received1 = $0 }}
let chan2 = subj.unwrap.open(exec.newContext()) { $0.subscribe { received2 = $0 }}
exec.consumeAll()
XCTAssertEqual(2, subj.subscribers)
XCTAssertTrue(received1!.value == 1)
XCTAssertTrue(received2!.value == 1)
// overwrite the old `Subject`
subj = Subject(2)
exec.consumeAll()
XCTAssertTrue(received1!.value == nil)
XCTAssertTrue(received2!.value == nil)
}
func testBiMap() {
let exec = FakeExecutor()
let a = Subject(1)
let b = a.bimap({ $0 * 2 }, { $0 / 2 }, exec.newContext())
XCTAssertEqual(1, a.value)
XCTAssertEqual(2, b.value)
a.value = 2
XCTAssertEqual(2, a.value)
XCTAssertEqual(2, b.value)
exec.consumeAll()
XCTAssertEqual(1, a.subscribers)
XCTAssertEqual(1, b.subscribers)
XCTAssertEqual(2, a.value)
XCTAssertEqual(4, b.value)
b.value = 6
XCTAssertEqual(2, a.value)
XCTAssertEqual(6, b.value)
exec.consumeAll()
XCTAssertEqual(3, a.value)
XCTAssertEqual(6, b.value)
}
}
| 26.351351 | 90 | 0.539145 |
1d05cfad363aae3bf694f55a055f45926a36afde | 463 | //
// ImageCaching.swift
// Adequate
//
// Created by Mathew Gacy on 9/27/19.
// Copyright © 2019 Mathew Gacy. All rights reserved.
//
import UIKit
import class MGNetworking.MemoryCache
public protocol ImageCaching {
func insert(_: UIImage, for: URL)
func value(for: URL) -> UIImage?
func removeValue(for: URL)
func removeAll()
}
// MARK: - MemoryCache+ImageCaching
extension MemoryCache: ImageCaching where Key == URL, Value == UIImage {}
| 22.047619 | 73 | 0.699784 |
de4fc0f705f82dc70424b8eaabefd7de12f11af7 | 122 | class PrivateInitializerClass {
private init(a: Int) {}
fileprivate init(b: Int) {}
init(c: Int, d: Int) {}
}
| 20.333333 | 31 | 0.606557 |
d6c9d5421f5aaac554761d68e77e93a6309e95a5 | 924 | //
// Go_trainerTests.swift
// Go trainerTests
//
// Created by Wesley de Groot on 10/08/2018.
// Copyright © 2018 Wesley de Groot. All rights reserved.
//
import XCTest
@testable import Go_trainer
class Go_trainerTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.4 | 111 | 0.658009 |
509b6863bd21ddfcc9178d1373388c307e3caa6c | 11,071 | //
// 3DScnEngine.swift
// VertexKit
//
// Created by Hexagons on 2018-06-30.
// Copyright © 2018 Hexagons. All rights reserved.
//
import SceneKit
import CoreGraphics
import LiveValues
import PixelKit
// MARK: Obj
extension _3DVec {
var scnVec: SCNVector3 {
get {
#if os(iOS)
return SCNVector3(Float(x.cg), Float(y.cg), Float(z.cg))
#elseif os(macOS)
return SCNVector3(x: x.cg, y: y.cg, z: z.cg)
#endif
}
}
}
private extension SCNVector3 {
var vec: _3DVec { get { return _3DVec(x: LiveFloat(x), y: LiveFloat(y), z: LiveFloat(z)) } }
}
class _3DScnObj: _3DObj {
let id = UUID()
let node: SCNNode
var pos: _3DVec { get { return node.position.vec } set { node.position = newValue.scnVec } }
var rot: _3DVec { get { return node.eulerAngles.vec } set { node.eulerAngles = newValue.scnVec } }
var scl: _3DVec { get { return node.scale.vec } set { node.scale = newValue.scnVec } }
var trans: _3DTrans {
get { return _3DTrans(pos: pos, rot: rot, scl: scl) }
set { pos = newValue.pos; rot = newValue.rot; scl = newValue.scl }
}
var color: _Color? {
get { return node.geometry?.firstMaterial?.diffuse.contents as? _Color }
set { node.geometry?.firstMaterial?.diffuse.contents = newValue }
}
init(geometry: SCNGeometry) {
node = SCNNode(geometry: geometry)
}
init(node: SCNNode) {
self.node = node
}
func transform(to _3dTrans: _3DTrans) { trans = _3dTrans }
func transform(by _3dTrans: _3DTrans) { trans +*= _3dTrans }
func position(to _3dCoord: _3DVec) { pos = _3dCoord }
func position(by _3dCoord: _3DVec) { pos += _3dCoord }
func rotate(to _3dCoord: _3DVec) { rot = _3dCoord }
func rotate(by _3dCoord: _3DVec) { rot += _3dCoord }
func scale(to _3dCoord: _3DVec) { scl = _3dCoord }
func scale(by _3dCoord: _3DVec) { scl *= _3dCoord }
func scale(to val: LiveFloat) { scl = _3DVec(x: val, y: val, z: val) }
func scale(by val: LiveFloat) { scl *= _3DVec(x: val, y: val, z: val) }
}
// MARK: Root
class _3DScnRoot: _3DScnObj, _3DRoot {
var worldScale: LiveFloat {
get { return scn.rootNode.scale.vec.x }
set {
#if os(iOS)
scn.rootNode.scale = SCNVector3(x: Float(newValue.cg), y: Float(newValue.cg), z: Float(newValue.cg))
#elseif os(macOS)
scn.rootNode.scale = SCNVector3(x: newValue.cg, y: newValue.cg, z: newValue.cg)
#endif
}
}
let view: _View
let scn = SCNScene()
var snapshot: _Image {
return (view as! SCNView).snapshot()
}
// let cam: SCNCamera
// let camNode: SCNNode
init(ortho: Bool = false, debug: Bool, size: CGSize? = nil) {
let scnView: SCNView
if let size = size {
let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
scnView = SCNView(frame: bounds)
} else {
scnView = SCNView()
}
scnView.backgroundColor = .clear
scnView.autoenablesDefaultLighting = true
// scnView.allowsCameraControl = true
scnView.scene = scn
if debug {
scnView.showsStatistics = true
if #available(iOS 11.0, *) { if #available(OSX 10.13, *) {
scnView.debugOptions.insert(.renderAsWireframe)
} }
// scnView.debugOptions.insert(.showWireframe)
// scnView.debugOptions.insert(.showBoundingBoxes)
// glLineWidth(20)
}
view = scnView
// cam = SCNCamera()
// cam.automaticallyAdjustsZRange = true
// if #available(iOS 11.0, *) {
// cam.fieldOfView = 53.1301023542
// }
// if ortho {
// cam.usesOrthographicProjection = true
//// cam.orthographicScale = 1
// }
// camNode = SCNNode()
// camNode.position = SCNVector3(x: 0, y: 0, z: 1)
// camNode.camera = cam
// scn.rootNode.addChildNode(camNode)
super.init(node: scn.rootNode)
}
func add(_ obj: _3DObj) {
let scnGeo3DObj = obj as! _3DScnObj
scn.rootNode.addChildNode(scnGeo3DObj.node)
}
func add(_ obj: _3DObj, to objParent: _3DObj) {
let scnGeo3DObj = obj as! _3DScnObj
let scnGeo3DObjParent = objParent as! _3DScnObj
scnGeo3DObjParent.node.addChildNode(scnGeo3DObj.node)
}
func remove(_ obj: _3DObj) {
let scnGeo3DObj = obj as! _3DScnObj
scnGeo3DObj.node.removeFromParentNode()
}
}
// MARK: Engine
class _3DScnEngine: _3DEngine {
var debugMode: Bool = false
func debug() { debugMode = true }
var roots: [_3DRoot] = []
var globalWorldScale: LiveFloat = 1 {
didSet {
for root in roots as! [_3DScnRoot] {
root.worldScale = globalWorldScale
}
}
}
func createRoot(at size: CGSize? = nil) -> _3DRoot {
return _3DScnRoot(debug: debugMode, size: size)
}
func create(_ _3dObjKind: _3DObjKind) -> _3DObj {
let scnGeoPrim: _3DScnObj
switch _3dObjKind {
case .node:
scnGeoPrim = _3DScnObj(node: SCNNode())
case .plane:
scnGeoPrim = _3DScnObj(geometry: SCNPlane(width: 1, height: 1))
case .box:
scnGeoPrim = _3DScnObj(geometry: SCNBox(width: 1, height: 1, length: 1, chamferRadius: 0))
case .sphere:
scnGeoPrim = _3DScnObj(geometry: SCNSphere(radius: 0.5)) // .isGeodesic
case .pyramid:
scnGeoPrim = _3DScnObj(geometry: SCNPyramid(width: 1.5, height: 1, length: 1.5)) // 146.5 230.4
case .cone:
scnGeoPrim = _3DScnObj(geometry: SCNCone(topRadius: 0, bottomRadius: 1, height: 1))
case .cylinder:
scnGeoPrim = _3DScnObj(geometry: SCNCylinder(radius: 1, height: 1))
case .capsule:
scnGeoPrim = _3DScnObj(geometry: SCNCapsule(capRadius: 0.5, height: 1))
case .tube:
scnGeoPrim = _3DScnObj(geometry: SCNTube(innerRadius: 0.5, outerRadius: 1, height: 1))
case .torus:
scnGeoPrim = _3DScnObj(geometry: SCNTorus(ringRadius: 1, pipeRadius: 0.5))
}
return scnGeoPrim
}
func create(triangle: _3DTriangle) -> _3DObj {
// var posArr: [_3DVec] = []
// var iArr: [Int] = []
// var i = 0
// for poly in polys {
// for vert in poly.verts {
// posArr.append(vert.pos)
// iArr.append(i)
// i += 1
// }
// }
print(">>>")
let iArr = triangle.verts.enumerated().map { i, _ -> Int in return i }
// let element = SCNGeometryElement(indices: iArr, primitiveType: .triangles)
let dat = Data(bytes: iArr, count: MemoryLayout<Int>.size * iArr.count)
let element = SCNGeometryElement(data: dat, primitiveType: .triangles, primitiveCount: 1, bytesPerIndex: MemoryLayout<Int>.size)
// let posArr = triangle.verts.map { vert -> SCNVector3 in return vert.pos.scnVec }
// let normArr = triangle.verts.map { vert -> SCNVector3 in return vert.norm.scnVec }
// let sourceVerts = SCNGeometrySource(vertices: posArr)
// let sourceNorms = SCNGeometrySource(normals: normArr)
// let sources = [sourceVerts, sourceNorms]
let sources = createSources(from: triangle.verts)
let geo = SCNGeometry(sources: sources, elements: [element])
let obj = _3DScnObj(geometry: geo)
return obj
}
func create(line: _3DLine) -> _3DObj {
// var posArr: [_3DVec] = []
// var iArr: [Int] = []
// var i = 0
// for poly in polys {
// for vert in poly.verts {
// posArr.append(vert.pos)
// iArr.append(i)
// i += 1
// }
// }
// let vertArr = line.verts.map { vert -> SCNVector3 in return vert.pos.scnVec }
// let normArr = line.verts.map { vert -> SCNVector3 in return vert.norm.scnVec }
// let iArr = [0, 1]
//
// let sourceVerts = SCNGeometrySource(vertices: vertArr)
// let sourceNorms = SCNGeometrySource(normals: normArr)
// let element = SCNGeometryElement(indices: iArr, primitiveType: .line)
//
// let geo = SCNGeometry(sources: [sourceVerts, sourceNorms], elements: [element])
let pln = SCNPlane(width: 0.5, height: 2)
pln.heightSegmentCount = 4
let cpy = pln.copy() as! SCNGeometry
print("A", cpy.sources[0])
print("B", cpy.sources[1])
print("C", cpy.elements[0])
let geo = SCNGeometry(sources: [cpy.sources.first!, cpy.sources[1]], elements: [cpy.elements.first!])
let obj = _3DScnObj(geometry: geo)
return obj
}
func createSources(from verts: [_3DVert]) -> [SCNGeometrySource] {
struct FloatVert {
let px, py, pz: Float
let nx, ny, nz: Float
let u, v: Float
}
let floatVerts = verts.map { vert -> FloatVert in
return FloatVert(
px: Float(vert.pos.x.cg),
py: Float(vert.pos.y.cg),
pz: Float(vert.pos.z.cg),
nx: Float(vert.norm.x.cg),
ny: Float(vert.norm.y.cg),
nz: Float(vert.norm.z.cg),
u: Float(vert.uv.u.cg),
v: Float(vert.uv.v.cg)
)
}
let vertSize = MemoryLayout<FloatVert>.size
let valSize = MemoryLayout<Float>.size
let data = Data(bytes: floatVerts, count: floatVerts.count)
let vertexSource = SCNGeometrySource(data: data, semantic: .vertex, vectorCount: floatVerts.count, usesFloatComponents: true, componentsPerVector: 3, bytesPerComponent: valSize, dataOffset: 0, dataStride: vertSize)
let normalSource = SCNGeometrySource(data: data, semantic: .normal, vectorCount: floatVerts.count, usesFloatComponents: true, componentsPerVector: 3, bytesPerComponent: valSize, dataOffset: valSize * 3, dataStride: vertSize)
let tcoordSource = SCNGeometrySource(data: data, semantic: .texcoord, vectorCount: floatVerts.count, usesFloatComponents: true, componentsPerVector: 2, bytesPerComponent: valSize, dataOffset: valSize * 6, dataStride: vertSize)
return [vertexSource, normalSource, tcoordSource]
}
func addRoot(_ root: _3DRoot) {
var root = root
root.worldScale = globalWorldScale
roots.append(root)
}
func removeRoot(_ root: _3DRoot) {
for (i, i_root) in roots.enumerated() {
if i_root.id == root.id {
roots.remove(at: i)
break
}
}
}
}
| 33.650456 | 234 | 0.572487 |
672ec9b233b4e04b97bdc2c02f21afd779acf0dc | 2,704 | //
// SceneDelegate.swift
// ios-app
//
// Created by Nikola Milovic on 14/06/2021.
//
import UIKit
import SwiftUI
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).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
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.
}
}
| 44.327869 | 147 | 0.705991 |
effa9f30c420d6ca87e48aedca041489280ad0e3 | 5,319 | //
// AzkarNotificationsModel.swift
// zikr
//
// Created by Ahmed Ebaid on 6/9/18.
// Copyright © 2018 Ahmed Ebaid. All rights reserved.
//
import UserNotifications
fileprivate let fajrIdentifier = "FajrIdentifier"
fileprivate let asrIdentifier = "AsrIdentifier"
fileprivate let reminderIdentifier = "Reminder"
class AzkarNotificationsModel: NSObject {
let center: UNUserNotificationCenter!
private let zikrContent: UNMutableNotificationContent!
private let sharedModel: AzkarData!
override init() {
center = UNUserNotificationCenter.current()
zikrContent = UNMutableNotificationContent()
sharedModel = AzkarData.sharedInstance
}
private func configureAzkarNotifications() -> [UNNotificationRequest] {
var notificationRequests = [UNNotificationRequest]()
for (i, zikrNotificationTime) in sharedModel.zikrNotificationTimes.enumerated() {
notificationRequests.append(addNotificationRequest(for: zikrNotificationTime,
isFajrNotification: true,
notificationId: i))
notificationRequests.append(addNotificationRequest(for: zikrNotificationTime,
isFajrNotification: false,
notificationId: i))
if (i + 1) == sharedModel.zikrNotificationTimes.count {
notificationRequests.append(addReminderNotificationRequest(for: zikrNotificationTime))
}
}
return notificationRequests
}
private func addNotificationRequest(for zikrNotificationTime: ZikrNotificationTime,
isFajrNotification: Bool,
notificationId: Int) -> UNNotificationRequest {
zikrContent.title = isFajrNotification ? "وقت أذكار الصباح" :
"وقت أذكار المساء"
zikrContent.body = "اللَّهُمَّ إِنِّي أَعُوذُ بِكَ مِنْ زَوَالِ نِعْمَتِكَ، وَتَحَوُّلِ عَافِيَتِكَ، وَفُجَاءَةِ نِقْمَتِكَ، وَجَمِيعِ سَخَطِكَ"
zikrContent.sound = UNNotificationSound.default
var dateComponents = Date.getDateComponents(for: zikrNotificationTime.date)
let zikrTime = isFajrNotification ? getZikrTime(zikrNotificationTime.timings.fajr) : getZikrTime(zikrNotificationTime.timings.asr)
dateComponents.hour = zikrTime.0
dateComponents.minute = zikrTime.1
dateComponents.second = 0
let currentFajrIdentifier = fajrIdentifier + "\(notificationId)"
let currentAsrIdentifier = asrIdentifier + "\(notificationId)"
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
return UNNotificationRequest(identifier: isFajrNotification ? currentFajrIdentifier : currentAsrIdentifier, content: zikrContent, trigger: trigger)
}
private func addReminderNotificationRequest(for zikrNotificationTime: ZikrNotificationTime) -> UNNotificationRequest {
var dateComponents = Date.getDateComponents(for: zikrNotificationTime.date)
let zikrTime = getZikrTime(zikrNotificationTime.timings.asr)
zikrContent.title = "Reminder"
zikrContent.body = "Please open the app to refresh your daily zikr reminder"
zikrContent.sound = UNNotificationSound.default
dateComponents.hour = zikrTime.0
dateComponents.minute = zikrTime.1
dateComponents.second = 55
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
return UNNotificationRequest(identifier: reminderIdentifier, content: zikrContent, trigger: trigger)
}
func toggleNotifications(_ value: Bool) {
if value {
center.delegate = self
let azkarNotificaitionsRequests = configureAzkarNotifications()
for azkarNotification in azkarNotificaitionsRequests {
center.add(azkarNotification) { error in
if error != nil {
print("error \(String(describing: error))")
}
}
}
} else {
removeNotifications()
}
}
func removeNotifications() {
center.removeAllPendingNotificationRequests()
center.removeAllDeliveredNotifications()
}
private func getZikrTime(_ stringTime: String) -> (Int, Int) {
let stringArray = stringTime.split(separator: ":")
guard let hour = Int(stringArray[0]), let minute = Int(stringArray[1].split(separator: " ")[0]) else {
return (0, 0)
}
return (hour, minute)
}
}
extension AzkarNotificationsModel: UNUserNotificationCenterDelegate {
func userNotificationCenter(_: UNUserNotificationCenter, didReceive _: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
}
func userNotificationCenter(_: UNUserNotificationCenter, willPresent _: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge]) // required to show notification when in foreground
}
}
| 45.853448 | 189 | 0.657642 |
f8c7e62ca2a8251dcfc1dfb55fdc0ca9a74b441c | 2,567 | //
// PrefixedTopLevelConstantRule.swift
// SwiftLint
//
// Created by Ornithologist Coder on 1/5/18.
// Copyright © 2018 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct PrefixedTopLevelConstantRule: ASTRule, OptInRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
private let topLevelPrefix = "k"
public init() {}
public static let description = RuleDescription(
identifier: "prefixed_toplevel_constant",
name: "Prefixed Top-Level Constant",
description: "Top-level constants should be prefixed by `k`.",
kind: .style,
nonTriggeringExamples: [
"private let kFoo = 20.0",
"public let kFoo = false",
"internal let kFoo = \"Foo\"",
"let kFoo = true",
"struct Foo {\n" +
" let bar = 20.0\n" +
"}",
"private var foo = 20.0",
"public var foo = false",
"internal var foo = \"Foo\"",
"var foo = true",
"var foo = true, bar = true",
"var foo = true, let kFoo = true",
"let\n" +
" kFoo = true",
"var foo: Int {\n" +
" return a + b\n" +
"}",
"let kFoo = {\n" +
" return a + b\n" +
"}()"
],
triggeringExamples: [
"private let ↓Foo = 20.0",
"public let ↓Foo = false",
"internal let ↓Foo = \"Foo\"",
"let ↓Foo = true",
"let ↓foo = 2, ↓bar = true",
"var foo = true, let ↓Foo = true",
"let\n" +
" ↓foo = true",
"let ↓foo = {\n" +
" return a + b\n" +
"}()"
]
)
public func validate(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard
kind == .varGlobal,
dictionary.setterAccessibility == nil,
dictionary.bodyLength == nil,
dictionary.name?.hasPrefix(topLevelPrefix) == false,
let nameOffset = dictionary.nameOffset
else {
return []
}
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: nameOffset))
]
}
}
| 31.304878 | 92 | 0.490456 |
7617b0feb9d90caa240bd301ffda64eac62df38f | 2,991 | //
// AppDelegate.swift
// GoogleAPIFileUploading
//
// Created by Kahuna on 7/18/17.
// Copyright © 2017 Kahuna. All rights reserved.
//
import UIKit
import Google
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation)
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
}
| 51.568966 | 285 | 0.756937 |
fcccb71cdd665552e9c8dacc51415f975d27d57a | 2,281 | //
// String+TFParsing.swift
// Bender
//
// Created by Mathias Claassen on 5/18/17.
//
//
extension Tensorflow_NodeDef {
var isTFAddOp: Bool { return op == Constants.Ops.Add }
var isTFVariableAssignOp: Bool { return op == Constants.Ops.Assign }
var isTFFusedBatchNorm: Bool { return op == Constants.Ops.FusedBatchNorm }
var isTFBatchNormGlobal: Bool { return op == Constants.Ops.BatchNormGlobal }
var isTFBatchToSpace: Bool { return op == Constants.Ops.BatchToSpace }
var isTFBiasAddOp: Bool { return op == Constants.Ops.BiasAdd }
var isTFConvOp: Bool { return op == Constants.Ops.Conv }
var isTFConstOp: Bool { return op == Constants.Ops.Const }
var isTFDepthwiseConvOp: Bool { return op == Constants.Ops.DepthwiseConv }
var isTFInstanceNormMulOp: Bool { return op == Constants.Ops.InstanceNormMul }
var isTFMatMulOp: Bool { return op == Constants.Ops.MatMul }
var isTFMeanOp: Bool { return op == Constants.Ops.Mean }
var isTFMulOp: Bool { return op == Constants.Ops.Mul }
var isTFPowOp: Bool { return op == Constants.Ops.Pow }
var isTFQReshapeOp: Bool { return op == Constants.Ops.QuantizedReshape }
var isTFRsqrtOp: Bool { return op == Constants.Ops.Rsqrt }
var isTFRealDivOp: Bool { return op == Constants.Ops.RealDiv }
var isTFReshapeOp: Bool { return op == Constants.Ops.Reshape }
var isTFReLuOp: Bool { return op == Constants.Ops.Relu }
var isTFShapeOp: Bool { return op == Constants.Ops.Shape }
var isTFSigmoidOp: Bool { return op == Constants.Ops.Sigmoid }
var isTFSpaceToBatch: Bool { return op == Constants.Ops.SpaceToBatch }
var isTFSubOp: Bool { return op == Constants.Ops.Sub }
var isTFSwitchOp: Bool { return op == Constants.Ops.Switch }
var isTFTanhOp: Bool { return op == Constants.Ops.Tanh }
var isTFVariableV2Op: Bool { return op == Constants.Ops.Variable }
var isTFVariableOrConstOp: Bool { return isTFVariableV2Op || isTFConstOp }
}
// Node Names
extension Tensorflow_NodeDef {
var isTFMovMean: Bool { return name.hasSuffix("/moving_mean") }
var isTFMovVariance: Bool { return name.hasSuffix("/moving_variance") }
var isTFGamma: Bool { return name.hasSuffix("/gamma") }
var isTFBeta: Bool { return name.hasSuffix("/beta") }
}
| 45.62 | 82 | 0.702762 |
d9d535a62e4426697421c7a6120273b233220ae1 | 261 | //
// Idempotent.swift
// WildMath
//
// Created by Dante Broggi on 6/28/17.
// Copyright © 2017 Dante Broggi. All rights reserved.
//
///f(a...) == a
public protocol Idempotent {}
///(a^)^ == a^
public protocol MonoIdempotent: Idempotent, MonoFunctor {}
| 18.642857 | 58 | 0.64751 |
56393bb913ec435a2da71dec9f316a5c0197458a | 7,934 | //
// AddCourseViewController.swift
// Course
//
// Created by Cedric on 2016/12/8.
// Copyright © 2016年 Cedric. All rights reserved.
//
import UIKit
import CourseModel
class AddCourseViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
var editingItem = ""
var courseHeight: CGFloat!
var teacherHeight: CGFloat!
var locationHeight: CGFloat!
var deltaY: CGFloat!
@IBOutlet weak var courseTimePicker: UIPickerView!
@IBOutlet weak var courseName: UITextField!
@IBOutlet weak var teacherName: UITextField!
@IBOutlet weak var location: UITextField!
@IBOutlet weak var toTop: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
courseTimePicker.delegate = self
courseName.delegate = self
location.delegate = self
teacherName.delegate = self
courseTimePicker.selectRow(0, inComponent: 0, animated: true)
courseTimePicker.selectRow(weekNum - 1, inComponent: 1, animated:true)
courseTimePicker.selectRow(0, inComponent: 2, animated: true)
courseTimePicker.selectRow(0, inComponent: 3, animated: true)
courseTimePicker.selectRow(0, inComponent: 4, animated: true)
courseTimePicker.selectRow(1, inComponent: 5, animated: true)
courseHeight = courseName.frame.maxY
teacherHeight = teacherName.frame.maxY
locationHeight = location.frame.maxY
}
override func viewWillAppear(_ animated: Bool) {
// 注册键盘出现和键盘消失的通知
let NC = NotificationCenter.default
NC.addObserver(self,
selector: #selector(AddCourseViewController.keyboardWillChangeFrame(notification:)),
name:NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
NC.addObserver(self,
selector: #selector(AddCourseViewController.keyboardWillHide(notification:)),
name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
// 注销键盘出现和键盘消失的通知
NotificationCenter.default.removeObserver(self)
}
func keyboardWillChangeFrame(notification: NSNotification) {
if let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect {
// 计算可能需要上移的距离
let keyboardHeight = keyboardFrame.origin.y
switch(editingItem) {
case "course":
deltaY = keyboardHeight - courseHeight - 10
case "teacher":
deltaY = keyboardHeight - teacherHeight - 10
case "location":
deltaY = keyboardHeight - locationHeight - 10
default: break
}
// 需要上移时,变化视图位置
if deltaY < 0 {
toTop.constant = deltaY + 16
UIView.animate(withDuration: 0.5, animations: {() -> Void in
self.view.layoutIfNeeded()
})
}
}
}
func keyboardWillHide(notification: NSNotification) {
toTop.constant = 16
UIView.animate(withDuration: 0.5, animations: {() -> Void in
self.view.layoutIfNeeded()
})
}
@IBAction func editCourse(_ sender: UITextField) {
editingItem = "course"
}
@IBAction func editTeacher(_ sender: UITextField) {
editingItem = "teacher"
}
@IBAction func editLocation(_ sender: UITextField) {
editingItem = "location"
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
@IBAction func cancel(_ sender: Any) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 6
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case 0, 1: return weekNum
case 2: return 3
case 3: return weekdayNum
case 4, 5: return courseNum
default: return 0
}
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let title = UILabel()
title.textColor = UIColor.black
title.textAlignment = NSTextAlignment.center
// title.font = UIFont.systemFont(ofSize: 13)
switch component {
case 0, 1: title.text = String(row + 1)
case 2:
switch row {
case 0: title.text = "全"
case 1: title.text = "单"
case 2: title.text = "双"
default: break
}
case 3: title.text = weekdayStrings[row]
case 4, 5: title.text = String(row + 1)
default: break
}
return title
}
func CheckContentIsLegal() -> Bool{
let beginWeek = courseTimePicker.selectedRow(inComponent: 0)
let endWeek = courseTimePicker.selectedRow(inComponent: 1)
let beginLesson = courseTimePicker.selectedRow(inComponent: 4)
let endLesson = courseTimePicker.selectedRow(inComponent: 5)
var hint: String!
if beginWeek > endWeek {
hint = "课程开始周不能晚于结束周!"
} else if beginLesson > endLesson {
hint = "课程开始时间不能晚于结束时间!"
} else if courseName.text == "" {
hint = "未输入课程名!"
} else if teacherName.text == "" {
hint = "未输入老师姓名!"
} else if location.text == "" {
hint = "未输入地点名!"
} else {
return true
}
let alertController = UIAlertController(title: "提示", message: hint, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "确定", style: .default, handler: nil)
alertController.addAction(confirmAction)
self.present(alertController, animated: true, completion: nil)
return false
}
@IBAction func AddCourse(_ sender: UIBarButtonItem) {
if !CheckContentIsLegal() { return }
var alternate = courseTimePicker.selectedRow(inComponent: 2)
if alternate == 0 { alternate = 3 }
let newLesson = Lesson(
course: courseName.text!,
inRoom: location.text!,
fromWeek: courseTimePicker.selectedRow(inComponent: 0) + 1,
toWeek: courseTimePicker.selectedRow(inComponent: 1) + 1,
alternate: alternate,
on: courseTimePicker.selectedRow(inComponent: 3),
fromClass: courseTimePicker.selectedRow(inComponent: 4) + 1,
toClass: courseTimePicker.selectedRow(inComponent: 5) + 1)
let newCourse = Course(course: courseName.text!, teacher: teacherName.text!)
add(course: newCourse)
if add(lesson: newLesson) {
lessonList[newLesson.weekday].sort() { $0.firstClass < $1.firstClass }
let filePath = courseDataFilePath()
NSKeyedArchiver.archiveRootObject(courseList, toFile: filePath)
self.presentingViewController?.dismiss(animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "时间冲突", message: "该课程在相同时间存在其他安排", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
alertController.addAction(confirmAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
| 35.106195 | 132 | 0.606126 |
ded1c17625abdbd2bb14469a3d77af4ec1cd0918 | 413 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "TOCropViewController",
products: [
.library(name: "TOCropViewController", targets: ["TOCropViewController"])
],
dependencies: [],
targets: [
.target(
name: "TOCropViewController",
dependencies: [],
path: "Objective-C/TOCropViewController"
)
]
)
| 22.944444 | 81 | 0.59322 |
ebea12489ab1be450d3e32288afd1b08a2586892 | 7,621 | import UIKit
class SettingVC: UIViewController {
@IBOutlet weak var switchNotification: UISwitch!
@IBOutlet weak var switchTouchID: UISwitch!
@IBOutlet weak var lblLanguague: UILabel!
@IBOutlet weak var lblNotification: UILabel!
@IBOutlet weak var lblTouchIDPasscode: UILabel?
@IBOutlet weak var btnRestoreDefault: UIButton!
var isNotificationOn = false
var isTouchIdOn = false
func setLanguague(lang: Int){
MultiLanguague.languague = lang
MultiLanguague.update()
DispatchQueue.main.async {
self.lblLanguague.text = MultiLanguague.settingLanguague
self.lblNotification.text = MultiLanguague.settingNotification
self.lblTouchIDPasscode?.text = MultiLanguague.settingTouchIDPasscode
self.btnRestoreDefault.setTitle(MultiLanguague.settingRestoreDefaul, for: .normal)
self.navigationItem.title = MultiLanguague.settingTitle
}
//TabVC().setLanguague()
}
@IBAction func btnEn_Tapped(_ sender: Any) {
self.setLanguague(lang: 1)
}
@IBAction func btnVietnamese_Tapped(_ sender: Any) {
self.setLanguague(lang: 2)
}
override func viewWillAppear(_ animated: Bool) {
self.setLanguague(lang: MultiLanguague.languague)
}
@IBAction func btnRestoreDefault_Tapped(_ sender: Any) {
self.setLanguague(lang: 1)
}
override func viewDidLoad() {
super.viewDidLoad()
switchTouchID.setOn(Other.useTouchID, animated: true)
switchNotification.setOn(Other.useNotification, animated: true)
switchTouchID.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)
switchNotification.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)
}
func switchValueDidChange(sender:UISwitch!){
if (sender == switchTouchID) {
if sender.isOn == true {
showInputPasscode(completion: {(ok) in
if ok == true {
Other.useTouchID = true
self.showAlertFail(title: MultiLanguague.success, message: MultiLanguague.pleaseRestart)
}
else {
Other.useTouchID = false
self.showAlertFail(title: MultiLanguague.error, message: MultiLanguague.passDoesNotMatch)
}
self.switchTouchID.setOn(Other.useTouchID, animated: true)
Other.update(completion: {(ok) in
if ok == false {
self.showAlertFail(title: MultiLanguague.error, message: MultiLanguague.tryAgain)
}
})
})
} else {
showConfirmPasscode(completion: {(ok) in
if ok == true {
Other.useTouchID = false
self.showAlertFail(title: MultiLanguague.success, message: MultiLanguague.pleaseRestart)
}
else {
Other.useTouchID = true
self.showAlertFail(title: MultiLanguague.error, message: MultiLanguague.wrongPassword)
}
self.switchTouchID.setOn(Other.useTouchID, animated: true)
Other.update(completion: {(ok) in
if ok == false {
self.showAlertFail(title: MultiLanguague.error, message: MultiLanguague.tryAgain)
}
})
})
}
}
if (sender == switchNotification) {
Other.useNotification = sender.isOn
Other.update(completion: {(ok) in
if ok == false {
self.showAlertFail(title: MultiLanguague.error, message: MultiLanguague.tryAgain)
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: show lock alert
func showInputPasscode(completion: @escaping (Bool) -> Swift.Void){
let alertController = UIAlertController(title: MultiLanguague.passcode, message: MultiLanguague.inputPasscode, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: MultiLanguague.confirm, style: .default) { (_) in
if let field = alertController.textFields![0] as? UITextField {
if let field2 = alertController.textFields![1] as? UITextField {
if field.text == field2.text {
Other.passcode = field.text!
completion(true)
}
else {
completion(false)
}
}
else {
completion(false)
}
} else {
completion(false)
}
}
let cancelAction = UIAlertAction(title: MultiLanguague.cancel, style: .cancel) { (_) in
completion(false)
}
alertController.addTextField { (textField) in
textField.placeholder = MultiLanguague.passcode
textField.isSecureTextEntry = true
textField.keyboardType = .numberPad
}
alertController.addTextField { (textField) in
textField.placeholder = MultiLanguague.confirmPasscode
textField.isSecureTextEntry = true
textField.keyboardType = .numberPad
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
//MARK: show lock alert
func showConfirmPasscode(completion: @escaping (Bool) -> Swift.Void){
let alertController = UIAlertController(title: MultiLanguague.passcode, message: MultiLanguague.inputPasscode, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: MultiLanguague.confirm, style: .default) { (_) in
if let field = alertController.textFields![0] as? UITextField {
if field.text == Other.passcode {
Other.passcode = field.text!
completion(true)
}
else {
completion(false)
}
} else {
completion(false)
}
}
let cancelAction = UIAlertAction(title: MultiLanguague.cancel, style: .cancel) { (_) in
completion(false)
}
alertController.addTextField { (textField) in
textField.placeholder = MultiLanguague.passcode
textField.isSecureTextEntry = true
textField.keyboardType = .numberPad
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func showAlertFail(title: String, message:String) {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertVC.addAction(okAction)
DispatchQueue.main.async() { () -> Void in
self.present(alertVC, animated: true, completion: nil)
}
}
}
| 38.489899 | 142 | 0.566855 |
2f909bd4e64f7118e023a00d5efe12f73842a85c | 2,428 | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
import Foundation
import UIKit
import MultiPlatformLibrary
import MultiPlatformLibraryMvvm
import MultiPlatformLibraryUnits
class NewsViewController: UIViewController {
@IBOutlet private var tableView: UITableView!
@IBOutlet private var activityIndicator: UIActivityIndicatorView!
@IBOutlet private var emptyView: UIView!
@IBOutlet private var errorView: UIView!
@IBOutlet private var errorLabel: UILabel!
private var viewModel: ListViewModel<News>!
private var dataSource: FlatUnitTableViewDataSource!
private var refreshControl: UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = AppComponent.factory.newsFactory.createListViewModel()
// binding methods from https://github.com/icerockdev/moko-mvvm
activityIndicator.bindVisibility(liveData: viewModel.state.isLoadingState())
tableView.bindVisibility(liveData: viewModel.state.isSuccessState())
emptyView.bindVisibility(liveData: viewModel.state.isEmptyState())
errorView.bindVisibility(liveData: viewModel.state.isErrorState())
// in/out generics of Kotlin removed in swift, so we should map to valid class
let errorText: LiveData<StringDesc> = viewModel.state.error().map { $0 as? StringDesc } as! LiveData<StringDesc>
errorLabel.bindText(liveData: errorText)
// datasource from https://github.com/icerockdev/moko-units
dataSource = FlatUnitTableViewDataSource()
dataSource.setup(for: tableView)
// manual bind to livedata, see https://github.com/icerockdev/moko-mvvm
viewModel.state.data().addObserver { [weak self] itemsObject in
guard let items = itemsObject as? [UITableViewCellUnitProtocol] else { return }
self?.dataSource.units = items
self?.tableView.reloadData()
}
refreshControl = UIRefreshControl()
tableView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(onRefresh), for: .valueChanged)
}
@IBAction func onRetryPressed() {
viewModel.onRetryPressed()
}
@objc func onRefresh() {
viewModel.onRefresh { [weak self] in
self?.refreshControl.endRefreshing()
}
}
}
| 37.9375 | 120 | 0.699341 |
d51c185f58b66968114f8a3fcd0614a3419a17c4 | 2,373 | //
// NotificationHandler.swift
// Swift-Samples
//
// Created by luowei on 2016/11/8.
// Copyright © 2016年 wodedata. All rights reserved.
//
import UIKit
import UserNotifications
class NotificationHandler: NSObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let options: UNNotificationPresentationOptions = [.alert, .sound]
completionHandler(options)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let category = response.notification.request.content.categoryIdentifier
switch category {
case let c where c == "saySomething":
let text: String
switch response.actionIdentifier {
case let action where action == "input":
text = (response as? UNTextInputNotificationResponse)?.userText ?? ""
default:
text = ""
}
if !text.isEmpty {
UIAlertController.showConfirmAlertFromTopViewController(message: "你刚才发送了 - \(text)")
}
case let c where c == "customUI":
print(response.actionIdentifier)
default:
break
}
completionHandler()
}
}
extension UIAlertController {
static func showConfirmAlert(message: String, in viewController: UIViewController) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
viewController.present(alert, animated: true)
}
static func showConfirmAlertFromTopViewController(message: String) {
if let vc = UIApplication.shared.keyWindow?.rootViewController {
showConfirmAlert(message: message, in: vc)
}
}
}
func delay(_ timeInterval: TimeInterval, _ block: @escaping ()->Void) {
let after = DispatchTime.now() + timeInterval
DispatchQueue.main.asyncAfter(deadline: after, execute: block)
}
| 32.506849 | 207 | 0.646018 |
e64090e563b78c68c1d77f959ef4e3cfa3623287 | 376 | struct Wallet {
let coin: Coin
let account: Account
let coinSettings: CoinSettings
}
extension Wallet: Hashable {
public static func ==(lhs: Wallet, rhs: Wallet) -> Bool {
lhs.coin == rhs.coin && lhs.account == rhs.account
}
public func hash(into hasher: inout Hasher) {
hasher.combine(coin)
hasher.combine(account)
}
}
| 19.789474 | 61 | 0.62234 |
ff652868abadd1200875478433fd2d7eb4b787aa | 558 | //
// Environment.swift
// TrackFinder
//
// Created by Niels Hoogendoorn on 18/06/2020.
// Copyright © 2020 Nihoo. All rights reserved.
//
import Foundation
enum Environment {
static let spotifyClientId: String = "ad5a0ea0dbd042c080662e6cf9444b5a"
static let spotifyRedirectUri: String = "trackfinder://spotify-login-callback"
static let baseApiUrl: String = "https://api.spotify.com/"
static let baseAccountUrl: String = "https://accounts.spotify.com/"
static let baseAuthUrl: String = "https://trackfinder-auth.herokuapp.com/"
}
| 31 | 82 | 0.729391 |
64af3d400e885b5bcd0c9c670168141c2c5a39a2 | 1,588 | //
// NetworkHelper.swift
// lenddo SDK
//
// Created by iOS dev on 26/03/21.
//
import Foundation
class NetworkHelper: NSObject {
static let shared = NetworkHelper()
func makeApiCall(url : String, parameters:[String:Any], token : String?, method : String, completionHandler: @escaping (Any?) -> Swift.Void) {
var urlString = url
if let token = token{
urlString += "?service_token=\(token)"
}
print(urlString)
let Url = String(format: urlString)
guard let serviceUrl = URL(string: Url) else { return }
var request = URLRequest(url: serviceUrl)
request.httpMethod = method
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
print(parameters)
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
completionHandler(json)
} catch {
print(error)
completionHandler(error)
}
}
}.resume()
}
}
| 27.859649 | 146 | 0.528967 |
2f7dfe3e024c4233ddbe6d1fd70fd7b3ab50e02a | 180 | //
// DebitOrCredit.swift
// LingoClash
//
// Created by Ai Ling Hong on 3/4/22.
//
enum DebitOrCredit: String, Codable {
case debit = "Debit"
case credit = "Credit"
}
| 15 | 38 | 0.627778 |
e4732b59a0c5d1a1c32f0160ff8a051b24dc7173 | 1,208 | //
// APICall.swift
// Core
//
// Created by Dimas Wicaksono on 06/01/22.
//
import Foundation
public struct API {
static let baseUrl = "https://api.themoviedb.org/3/"
public static let imageSource = "https://image.tmdb.org/t/p/original"
static var apiKey: String {
get {
guard let filePath = Bundle.main.path(forResource: "TMDB-Info", ofType: "plist") else {
fatalError("Couldn't find file 'TMDB-Info.plist'.")
}
let plist = NSDictionary(contentsOfFile: filePath)
guard let value = plist?.object(forKey: "API_KEY") as? String else {
fatalError("Couldn't find key 'API_KEY' in 'TMDB-Info.plist'.")
}
return value
}
}
}
protocol Endpoint {
var url: String { get }
}
public enum Endpoints {
public enum Gets: Endpoint {
case movies
case movieDetail(id: Int)
public var url: String {
switch self {
case .movies: return "\(API.baseUrl)movie/now_playing?api_key=\(API.apiKey)"
case .movieDetail(let id): return "\(API.baseUrl)movie/\(id)?api_key=\(API.apiKey)"
}
}
}
}
| 27.454545 | 99 | 0.571192 |
67c47852f83abd5b7a6c6364135405cff2c53ccb | 4,745 | import Foundation
import SourceKittenFramework
final class VariableModel: Model {
var name: String
var type: Type
var offset: Int64
var length: Int64
let accessControlLevelDescription: String
let attributes: [String]?
var canBeInitParam: Bool
let processed: Bool
var data: Data? = nil
var filePath: String = ""
var isStatic = false
var shouldOverride = false
var overrideTypes: [String: String]?
var modelDescription: String? = nil
var modelType: ModelType {
return .variable
}
var staticKind: String {
return isStatic ? .static : ""
}
var fullName: String {
return name + staticKind
}
init(name: String,
typeName: String,
acl: String?,
encloserType: DeclType,
isStatic: Bool,
canBeInitParam: Bool,
offset: Int64,
length: Int64,
overrideTypes: [String: String]?,
modelDescription: String?,
processed: Bool) {
self.name = name.trimmingCharacters(in: .whitespaces)
self.type = Type(typeName.trimmingCharacters(in: .whitespaces))
self.offset = offset
self.length = length
self.isStatic = isStatic
self.shouldOverride = encloserType == .classType
self.canBeInitParam = canBeInitParam
self.processed = processed
self.overrideTypes = overrideTypes
self.accessControlLevelDescription = acl ?? ""
self.attributes = nil
self.modelDescription = modelDescription
}
init(_ ast: Structure, encloserType: DeclType, filepath: String, data: Data, overrideTypes: [String: String]?, processed: Bool) {
name = ast.name
type = Type(ast.typeName)
offset = ast.range.offset
length = ast.range.length
canBeInitParam = ast.canBeInitParam
isStatic = ast.isStaticVariable
shouldOverride = ast.isOverride || encloserType == .classType
accessControlLevelDescription = ast.accessControlLevelDescription
attributes = ast.hasAvailableAttribute ? ast.extractAttributes(data, filterOn: SwiftDeclarationAttributeKind.available.rawValue) : nil
self.processed = processed
self.overrideTypes = overrideTypes
self.data = data
self.filePath = filepath
}
private func isGenerated(_ name: String, type: Type) -> Bool {
return name.hasPrefix(.underlyingVarPrefix) ||
name.hasSuffix(.setCallCountSuffix) ||
name.hasSuffix(.callCountSuffix) ||
name.hasSuffix(.subjectSuffix) ||
name.hasSuffix("SubjectKind") ||
(name.hasSuffix(.handlerSuffix) && type.isOptional)
}
func render(with identifier: String, typeKeys: [String: String]?) -> String? {
if processed {
var prefix = ""
if shouldOverride, !isGenerated(name, type: type) {
prefix = "\(String.override) "
}
if let modelDescription = modelDescription?.trimmingCharacters(in: .whitespacesAndNewlines), !modelDescription.isEmpty {
return prefix + modelDescription
}
if let ret = self.data?.toString(offset: self.offset, length: self.length) {
if !ret.contains(identifier),
let first = ret.components(separatedBy: CharacterSet(arrayLiteral: ":", "=")).first,
let found = first.components(separatedBy: " ").filter({!$0.isEmpty}).last {
let replaced = ret.replacingOccurrences(of: found, with: identifier)
return prefix + replaced
}
return prefix + ret
}
return nil
}
if let rxVar = applyRxVariableTemplate(name: identifier,
type: type,
overrideTypes: overrideTypes,
typeKeys: typeKeys,
staticKind: staticKind,
shouldOverride: shouldOverride,
accessControlLevelDescription: accessControlLevelDescription) {
return rxVar
}
return applyVariableTemplate(name: identifier,
type: type,
typeKeys: typeKeys,
staticKind: staticKind,
shouldOverride: shouldOverride,
accessControlLevelDescription: accessControlLevelDescription)
}
}
| 38.266129 | 142 | 0.56607 |
1d8388a9f1eca40622e2adf8cde0a57003fc0485 | 2,187 | //
// UserCenterHeaderView.swift
// https://github.com/xiaopin/weibo-UserCenter.git
//
// Created by nhope on 2018/2/6.
// Copyright © 2018年 xiaopin. All rights reserved.
//
import UIKit
class UserCenterHeaderView: UIView {
let backgroundImageView = UIImageView()
let avatarImageView = UIImageView()
let usernameLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = .systemFont(ofSize: 15.0)
label.textColor = UIColor(red: 17/255.0, green: 17/255.0, blue: 17/255.0, alpha: 1.0)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .white
([backgroundImageView, avatarImageView, usernameLabel] as! [UIView]).forEach {
self.addSubview($0)
$0.translatesAutoresizingMaskIntoConstraints = false
}
backgroundImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
backgroundImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
backgroundImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
backgroundImageView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
let avatarImageSize: CGFloat = 72.0
avatarImageView.layer.cornerRadius = avatarImageSize * 0.5
avatarImageView.layer.masksToBounds = true
avatarImageView.widthAnchor.constraint(equalToConstant: avatarImageSize).isActive = true
avatarImageView.heightAnchor.constraint(equalToConstant: avatarImageSize).isActive = true
avatarImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
avatarImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
usernameLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
usernameLabel.topAnchor.constraint(equalTo: avatarImageView.bottomAnchor, constant: 20).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 40.5 | 111 | 0.698674 |
e43a241df5930cca8e9330d672d7697c286b141e | 3,447 | //
// KeyboardViewController.swift
// SampleCustomKeyboard
//
// Created by 浅井 岳大 on 2016/03/07.
// Copyright © 2016年 浅井 岳大. All rights reserved.
//
import UIKit
class KeyboardViewController: UIInputViewController {
@IBOutlet var nextKeyboardButton: UIButton!
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
@objc func centerButton(_: AnyObject) {
let text = "🐶"
let proxy = self.textDocumentProxy as UIKeyInput
proxy.insertText(text)
}
@objc func pushButton(_: AnyObject) {
let laugh = ":-))))))))"
let proxy = self.textDocumentProxy as UIKeyInput
proxy.insertText(laugh)
}
override func viewDidLoad() {
super.viewDidLoad()
let viewXib = UINib(nibName: "CustomKeyboard", bundle: nil)
self.view = viewXib.instantiate(withOwner: self, options: nil)[0] as! UIView;
for v in self.view.subviews {
if v.isKind(of: UIButton.self) {
let w = v as! UIButton
if w.currentTitle == "Center" {
w.addTarget(self, action: #selector(KeyboardViewController.centerButton(_:)), for: .touchDown)
} else {
w.addTarget(self, action: #selector(KeyboardViewController.pushButton(_:)), for: .touchDown)
}
}
}
NSLog("NSLog can't be seen in xcode console. See README")
// Perform custom UI setup here
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard?", comment: "Title for 'Next Keyboard' button"), for: UIControlState())
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: #selector(UIInputViewController.advanceToNextInputMode), for: .touchUpInside)
self.view.addSubview(self.nextKeyboardButton)
let nextKeyboardButtonLeftSideConstraint = NSLayoutConstraint(item: self.nextKeyboardButton, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1.0, constant: 0.0)
let nextKeyboardButtonBottomConstraint = NSLayoutConstraint(item: self.nextKeyboardButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1.0, constant: 0.0)
self.view.addConstraints([nextKeyboardButtonLeftSideConstraint, nextKeyboardButtonBottomConstraint])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func textWillChange(_ textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(_ textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.dark {
textColor = UIColor.white
} else {
textColor = UIColor.black
}
self.nextKeyboardButton.setTitleColor(textColor, for: UIControlState())
}
}
| 37.879121 | 208 | 0.659994 |
ed365fa5fc33c8b79cdb662adf1c5fe271b71a0f | 1,417 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialMotion
class TossableExampleViewController: ExampleViewController {
var runtime: MotionRuntime!
override func viewDidLoad() {
super.viewDidLoad()
let square = center(createExampleSquareView(), within: view)
view.addSubview(square)
runtime = MotionRuntime(containerView: view)
let tossable = Tossable()
tossable.spring.destination.value = .init(x: view.bounds.midX, y: view.bounds.midY)
tossable.spring.friction.value /= 2
runtime.add(tossable, to: square)
runtime.whenAllAtRest([tossable]) {
print("Is now at rest")
}
}
override func exampleInformation() -> ExampleInfo {
return .init(title: type(of: self).catalogBreadcrumbs().last!,
instructions: "Use two fingers to rotate the view.")
}
}
| 30.148936 | 87 | 0.733239 |
33256c0919e0b97c2c0ae5448a447aafc7c02a76 | 18,340 | import XCTest
import Apollo
import ApolloTestSupport
@testable import ApolloWebSocket
import StarWarsAPI
import Starscream
class StarWarsSubscriptionTests: XCTestCase {
var concurrentQueue: DispatchQueue!
var client: ApolloClient!
var webSocketTransport: WebSocketTransport!
var connectionStartedExpectation: XCTestExpectation?
var disconnectedExpectation: XCTestExpectation?
var reconnectedExpectation: XCTestExpectation?
override func setUp() {
super.setUp()
concurrentQueue = DispatchQueue(label: "com.apollographql.test.\(self.name)", attributes: .concurrent)
connectionStartedExpectation = self.expectation(description: "Web socket connected")
webSocketTransport = WebSocketTransport(
websocket: DefaultWebSocket(
request: URLRequest(url: TestServerURL.starWarsWebSocket.url)
)
)
webSocketTransport.delegate = self
client = ApolloClient(networkTransport: webSocketTransport, store: ApolloStore())
self.wait(for: [self.connectionStartedExpectation!], timeout: 5)
}
override func tearDownWithError() throws {
client = nil
webSocketTransport = nil
connectionStartedExpectation = nil
disconnectedExpectation = nil
reconnectedExpectation = nil
concurrentQueue = nil
try super.tearDownWithError()
}
private func waitForSubscriptionsToStart(for delay: TimeInterval = 0.1, on queue: DispatchQueue = .main) {
/// This method works around changes to the subscriptions package which mean that subscriptions do not start passing on data the absolute instant they are created.
let waitExpectation = self.expectation(description: "Waited!")
queue.asyncAfter(deadline: .now() + delay) {
waitExpectation.fulfill()
}
self.wait(for: [waitExpectation], timeout: delay + 1)
}
// MARK: Subscriptions
func testSubscribeReviewJediEpisode() {
let expectation = self.expectation(description: "Subscribe single review")
let sub = client.subscribe(subscription: ReviewAddedSubscription(episode: .jedi)) { result in
defer {
expectation.fulfill()
}
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
guard let data = graphQLResult.data else {
XCTFail("No subscription result data")
return
}
XCTAssertEqual(data.reviewAdded?.episode, .jedi)
XCTAssertEqual(data.reviewAdded?.stars, 6)
XCTAssertEqual(data.reviewAdded?.commentary, "This is the greatest movie!")
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
}
self.waitForSubscriptionsToStart()
client.perform(mutation: CreateReviewForEpisodeMutation(
episode: .jedi,
review: ReviewInput(stars: 6, commentary: "This is the greatest movie!")))
waitForExpectations(timeout: 10, handler: nil)
sub.cancel()
}
func testSubscribeReviewAnyEpisode() {
let expectation = self.expectation(description: "Subscribe any episode")
let sub = client.subscribe(subscription: ReviewAddedSubscription()) { result in
defer {
expectation.fulfill()
}
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
guard let data = graphQLResult.data else {
XCTFail("No subscription result data")
return
}
XCTAssertEqual(data.reviewAdded?.stars, 13)
XCTAssertEqual(data.reviewAdded?.commentary, "This is an even greater movie!")
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
}
self.waitForSubscriptionsToStart()
client.perform(mutation: CreateReviewForEpisodeMutation(episode: .empire, review: ReviewInput(stars: 13, commentary: "This is an even greater movie!")))
waitForExpectations(timeout: 2, handler: nil)
sub.cancel()
}
func testSubscribeReviewDifferentEpisode() {
let expectation = self.expectation(description: "Subscription to specific episode - expecting timeout")
expectation.isInverted = true
let sub = client.subscribe(subscription: ReviewAddedSubscription(episode: .jedi)) { result in
defer {
expectation.fulfill()
}
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
guard let data = graphQLResult.data else {
XCTFail("No subscription result data")
return
}
XCTAssertNotEqual(data.reviewAdded?.episode, .jedi)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
}
self.waitForSubscriptionsToStart()
client.perform(mutation: CreateReviewForEpisodeMutation(episode: .empire, review: ReviewInput(stars: 10, commentary: "This is an even greater movie!")))
waitForExpectations(timeout: 3, handler: nil)
sub.cancel()
}
func testSubscribeThenCancel() {
let expectation = self.expectation(description: "Subscription then cancel - expecting timeout")
expectation.isInverted = true
let sub = client.subscribe(subscription: ReviewAddedSubscription(episode: .jedi)) { _ in
XCTFail("Received subscription after cancel")
}
self.waitForSubscriptionsToStart()
sub.cancel()
client.perform(mutation: CreateReviewForEpisodeMutation(episode: .jedi, review: ReviewInput(stars: 10, commentary: "This is an even greater movie!")))
waitForExpectations(timeout: 3, handler: nil)
}
func testSubscribeMultipleReviews() {
let count = 50
let expectation = self.expectation(description: "Multiple reviews")
expectation.expectedFulfillmentCount = count
let sub = client.subscribe(subscription: ReviewAddedSubscription(episode: .empire)) { result in
defer {
expectation.fulfill()
}
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
guard let data = graphQLResult.data else {
XCTFail("No subscription result data")
return
}
XCTAssertEqual(data.reviewAdded?.episode, .empire)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
}
self.waitForSubscriptionsToStart()
for i in 1...count {
let review = ReviewInput(stars: i, commentary: "The greatest movie ever!")
_ = client.perform(mutation: CreateReviewForEpisodeMutation(episode: .empire, review: review))
}
waitForExpectations(timeout: 10, handler: nil)
sub.cancel()
}
func testMultipleSubscriptions() {
// Multiple subscriptions, one for any episode and one for each of the episode
// We send count reviews and expect to receive twice that number of subscriptions
let count = 20
let expectation = self.expectation(description: "Multiple reviews")
expectation.expectedFulfillmentCount = count * 2
var allFulfilledCount = 0
var newHopeFulfilledCount = 0
var empireFulfilledCount = 0
var jediFulfilledCount = 0
let subAll = client.subscribe(subscription: ReviewAddedSubscription()) { result in
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
XCTAssertNotNil(graphQLResult.data)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
allFulfilledCount += 1
}
let subEmpire = client.subscribe(subscription: ReviewAddedSubscription(episode: .empire)) { result in
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
XCTAssertNotNil(graphQLResult.data)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
empireFulfilledCount += 1
}
let subJedi = client.subscribe(subscription: ReviewAddedSubscription(episode: .jedi)) { result in
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
XCTAssertNotNil(graphQLResult.data)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
jediFulfilledCount += 1
}
let subNewHope = client.subscribe(subscription: ReviewAddedSubscription(episode: .newhope)) { result in
switch result {
case .success(let graphQLResult):
XCTAssertNil(graphQLResult.errors)
XCTAssertNotNil(graphQLResult.data)
case .failure(let error):
XCTFail("Unexpected error: \(error)")
}
expectation.fulfill()
newHopeFulfilledCount += 1
}
self.waitForSubscriptionsToStart()
let episodes : [Episode] = [.empire, .jedi, .newhope]
var selectedEpisodes = [Episode]()
for i in 1...count {
let review = ReviewInput(stars: i, commentary: "The greatest movie ever!")
let episode = episodes.randomElement()!
selectedEpisodes.append(episode)
_ = client.perform(mutation: CreateReviewForEpisodeMutation(episode: episode, review: review))
}
waitForExpectations(timeout: 10, handler: nil)
XCTAssertEqual(allFulfilledCount,
count,
"All not fulfilled proper number of times. Expected \(count), got \(allFulfilledCount)")
let expectedNewHope = selectedEpisodes.filter { $0 == .newhope }.count
XCTAssertEqual(newHopeFulfilledCount,
expectedNewHope,
"New Hope not fulfilled proper number of times. Expected \(expectedNewHope), got \(newHopeFulfilledCount)")
let expectedEmpire = selectedEpisodes.filter { $0 == .empire }.count
XCTAssertEqual(empireFulfilledCount,
expectedEmpire,
"Empire not fulfilled proper number of times. Expected \(expectedEmpire), got \(empireFulfilledCount)")
let expectedJedi = selectedEpisodes.filter { $0 == .jedi }.count
XCTAssertEqual(jediFulfilledCount,
expectedJedi,
"Jedi not fulfilled proper number of times. Expected \(expectedJedi), got \(jediFulfilledCount)")
subAll.cancel()
subEmpire.cancel()
subJedi.cancel()
subNewHope.cancel()
}
// MARK: Data races tests
func testConcurrentSubscribing() {
let firstSubscription = ReviewAddedSubscription(episode: .empire)
let secondSubscription = ReviewAddedSubscription(episode: .empire)
let expectation = self.expectation(description: "Subscribers connected and received events")
expectation.expectedFulfillmentCount = 2
var sub1: Cancellable?
var sub2: Cancellable?
concurrentQueue.async {
sub1 = self.client.subscribe(subscription: firstSubscription) { _ in
expectation.fulfill()
}
}
concurrentQueue.async {
sub2 = self.client.subscribe(subscription: secondSubscription) { _ in
expectation.fulfill()
}
}
self.waitForSubscriptionsToStart(on: concurrentQueue)
// dispatched with a barrier flag to make sure
// this is performed after subscription calls
concurrentQueue.sync(flags: .barrier) {
// dispatched on the processing queue to make sure
// this is performed after subscribers are processed
self.webSocketTransport.websocket.callbackQueue.async {
_ = self.client.perform(mutation: CreateReviewForEpisodeMutation(episode: .empire, review: ReviewInput(stars: 5, commentary: "The greatest movie ever!")))
}
}
waitForExpectations(timeout: 10, handler: nil)
sub1?.cancel()
sub2?.cancel()
}
func testConcurrentSubscriptionCancellations() {
let firstSubscription = ReviewAddedSubscription(episode: .empire)
let secondSubscription = ReviewAddedSubscription(episode: .empire)
let expectation = self.expectation(description: "Subscriptions cancelled")
expectation.expectedFulfillmentCount = 2
let invertedExpectation = self.expectation(description: "Subscription received callback - expecting timeout")
invertedExpectation.isInverted = true
let sub1 = client.subscribe(subscription: firstSubscription) { _ in
invertedExpectation.fulfill()
}
let sub2 = client.subscribe(subscription: secondSubscription) { _ in
invertedExpectation.fulfill()
}
self.waitForSubscriptionsToStart(on: concurrentQueue)
concurrentQueue.async {
sub1.cancel()
expectation.fulfill()
}
concurrentQueue.async {
sub2.cancel()
expectation.fulfill()
}
wait(for: [expectation], timeout: 10)
_ = self.client.perform(mutation: CreateReviewForEpisodeMutation(episode: .empire, review: ReviewInput(stars: 5, commentary: "The greatest movie ever!")))
wait(for: [invertedExpectation], timeout: 2)
}
func testConcurrentSubscriptionAndConnectionClose() {
let empireReviewSubscription = ReviewAddedSubscription(episode: .empire)
let expectation = self.expectation(description: "Connection closed")
let invertedExpectation = self.expectation(description: "Subscription received callback - expecting timeout")
invertedExpectation.isInverted = true
let sub = self.client.subscribe(subscription: empireReviewSubscription) { _ in
invertedExpectation.fulfill()
}
self.waitForSubscriptionsToStart(on: concurrentQueue)
concurrentQueue.async {
sub.cancel()
}
concurrentQueue.async {
self.webSocketTransport.closeConnection()
expectation.fulfill()
}
wait(for: [expectation], timeout: 10)
_ = self.client.perform(mutation: CreateReviewForEpisodeMutation(episode: .empire, review: ReviewInput(stars: 5, commentary: "The greatest movie ever!")))
wait(for: [invertedExpectation], timeout: 2)
}
func testConcurrentConnectAndCloseConnection() {
let webSocketTransport = WebSocketTransport(
websocket: MockWebSocket(
request: URLRequest(url: TestServerURL.starWarsWebSocket.url)
)
)
let expectation = self.expectation(description: "Connection closed")
expectation.expectedFulfillmentCount = 2
concurrentQueue.async {
if let websocket = webSocketTransport.websocket as? MockWebSocket {
websocket.reportDidConnect()
expectation.fulfill()
}
}
concurrentQueue.async {
webSocketTransport.closeConnection()
expectation.fulfill()
}
waitForExpectations(timeout: 10, handler: nil)
}
func testPausingAndResumingWebSocketConnection() {
let subscription = ReviewAddedSubscription()
let reviewMutation = CreateAwesomeReviewMutation()
// Send the mutations via a separate transport so they can still be sent when the websocket is disconnected
let store = ApolloStore()
let interceptorProvider = DefaultInterceptorProvider(store: store)
let alternateTransport = RequestChainNetworkTransport(interceptorProvider: interceptorProvider,
endpointURL: TestServerURL.starWarsServer.url)
let alternateClient = ApolloClient(networkTransport: alternateTransport, store: store)
func sendReview() {
let reviewSentExpectation = self.expectation(description: "review sent")
alternateClient.perform(mutation: reviewMutation) { mutationResult in
switch mutationResult {
case .success:
break
case .failure(let error):
XCTFail("Unexpected error sending review: \(error)")
}
reviewSentExpectation.fulfill()
}
self.wait(for: [reviewSentExpectation], timeout: 10)
}
let subscriptionExpectation = self.expectation(description: "Received review")
// This should get hit twice - once before we pause the web socket and once after.
subscriptionExpectation.expectedFulfillmentCount = 2
let reviewAddedSubscription = self.client.subscribe(subscription: subscription) { subscriptionResult in
switch subscriptionResult {
case .success(let graphQLResult):
XCTAssertEqual(graphQLResult.data?.reviewAdded?.episode, .jedi)
subscriptionExpectation.fulfill()
case .failure(let error):
if let wsError = error as? Starscream.WSError {
// This is an expected error on disconnection, ignore it.
XCTAssertEqual(wsError.code, 1000)
} else {
XCTFail("Unexpected error receiving subscription: \(error)")
subscriptionExpectation.fulfill()
}
}
}
self.waitForSubscriptionsToStart()
sendReview()
// TODO: Uncomment this expectation once https://github.com/daltoniam/Starscream/issues/869 is addressed
// and we're actually getting a notification that the socket has disconnected
// self.disconnectedExpectation = self.expectation(description: "Web socket disconnected")
webSocketTransport.pauseWebSocketConnection()
// self.wait(for: [self.disconnectedExpectation!], timeout: 10)
// This should not go through since the socket is paused
sendReview()
self.reconnectedExpectation = self.expectation(description: "Web socket reconnected")
webSocketTransport.resumeWebSocketConnection()
self.wait(for: [self.reconnectedExpectation!], timeout: 10)
self.waitForSubscriptionsToStart()
// Now that we've reconnected, this should go through to the same subscription.
sendReview()
self.wait(for: [subscriptionExpectation], timeout: 10)
// Cancel subscription so it doesn't keep receiving from other tests.
reviewAddedSubscription.cancel()
}
}
extension StarWarsSubscriptionTests: WebSocketTransportDelegate {
func webSocketTransportDidConnect(_ webSocketTransport: WebSocketTransport) {
self.connectionStartedExpectation?.fulfill()
}
func webSocketTransportDidReconnect(_ webSocketTransport: WebSocketTransport) {
self.reconnectedExpectation?.fulfill()
}
func webSocketTransport(_ webSocketTransport: WebSocketTransport, didDisconnectWithError error: Error?) {
self.disconnectedExpectation?.fulfill()
}
}
| 35.201536 | 167 | 0.687732 |
2812a6472dcd43a3e0c39f55b5685abacb111455 | 164 | /// Let `x` conform to `LogStringifyCompatible` to customize the value of `.any(x)`.
public protocol LogStringifyCompatible {
var stringified: String { get }
}
| 32.8 | 84 | 0.72561 |
1eccb37149d6b958b0f4454e5ccb66e7c6c72c37 | 3,629 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence of pairs built out of two underlying sequences, where
/// the elements of the `i`th pair are the `i`th elements of each
/// underlying sequence.
public func zip<Sequence1 : SequenceType, Sequence2 : SequenceType>(
sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
return Zip2Sequence(sequence1, sequence2)
}
/// A generator for `Zip2Sequence`.
public struct Zip2Generator<
Generator1 : GeneratorType, Generator2 : GeneratorType
> : GeneratorType {
/// The type of element returned by `next()`.
public typealias Element = (Generator1.Element, Generator2.Element)
/// Construct around a pair of underlying generators.
public init(_ generator1: Generator1, _ generator2: Generator2) {
_baseStreams = (generator1, generator2)
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> Element? {
// The next() function needs to track if it has reached the end. If we
// didn't, and the first sequence is shorter than the second, then, when we
// have already exhausted the second sequence, on every subsequent call to
// next() we would consume and discard one additional element from the
// first sequence, even though next() return nil.
if _reachedEnd {
return nil
}
guard let e0 = _baseStreams.0.next() else {
_reachedEnd = true
return nil
}
guard let e1 = _baseStreams.1.next() else {
_reachedEnd = true
return nil
}
return .Some((e0, e1))
}
internal var _baseStreams: (Generator1, Generator2)
internal var _reachedEnd: Bool = false
}
/// A sequence of pairs built out of two underlying sequences, where
/// the elements of the `i`th pair are the `i`th elements of each
/// underlying sequence.
public struct Zip2Sequence<Sequence1 : SequenceType, Sequence2 : SequenceType>
: SequenceType {
public typealias Stream1 = Sequence1.Generator
public typealias Stream2 = Sequence2.Generator
/// A type whose instances can produce the elements of this
/// sequence, in order.
public typealias Generator = Zip2Generator<Stream1, Stream2>
/// Construct an instance that makes pairs of elements from `sequence1` and
/// `sequence2`.
public init(_ sequence1: Sequence1, _ sequence2: Sequence2) {
_sequences = (sequence1, sequence2)
}
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> Generator {
return Generator(
_sequences.0.generate(),
_sequences.1.generate())
}
internal let _sequences: (Sequence1, Sequence2)
}
@available(*, unavailable, renamed="Zip2Generator")
public struct ZipGenerator2<
Generator1 : GeneratorType, Generator2 : GeneratorType
> {}
@available(*, unavailable, renamed="Zip2Sequence")
public struct Zip2<
Sequence1 : SequenceType, Sequence2 : SequenceType
> {}
| 33.293578 | 80 | 0.673739 |
ff0c5d7875733e77235c0d8370c62ce202c5382f | 350 | //
// Person.swift
// Example
//
// Created by Matthias Buchetics on 24/11/15.
// Copyright © 2015 aaa - all about apps GmbH. All rights reserved.
//
import Foundation
struct Person: CustomStringConvertible {
let firstName: String
let lastName: String
var description: String {
return "\(firstName) \(lastName)"
}
} | 19.444444 | 68 | 0.657143 |
28c99862fd9cae52e49dd667391720c4d168d6eb | 10,849 | //
// ExtractSourcesOperation.swift
// MockingbirdCli
//
// Created by Andrew Chang on 8/17/19.
// Copyright © 2019 Bird Rides, Inc. All rights reserved.
//
import Foundation
import PathKit
import XcodeProj
import os.log
public struct SourcePath: Hashable, Equatable {
public let path: Path
public let moduleName: String
}
public class ExtractSourcesOperationResult {
fileprivate(set) public var targetPaths = Set<SourcePath>()
fileprivate(set) public var dependencyPaths = Set<SourcePath>()
fileprivate(set) public var supportPaths = Set<SourcePath>() // Mainly used for caching.
fileprivate(set) public var moduleDependencies = [String: Set<String>]()
}
public protocol ExtractSourcesAbstractOperation: BasicOperation {
var result: ExtractSourcesOperationResult { get }
}
public struct ExtractSourcesOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let dependencyPaths = ExtractSourcesOptions(rawValue: 1 << 1)
public static let useMockingbirdIgnore = ExtractSourcesOptions(rawValue: 1 << 2)
public static let all: ExtractSourcesOptions = [.dependencyPaths, .useMockingbirdIgnore]
}
/// Given a target, find all related source files including those compiled by dependencies.
public class ExtractSourcesOperation<T: Target>: BasicOperation, ExtractSourcesAbstractOperation {
public let target: T
let sourceRoot: Path
let supportPath: Path?
let options: ExtractSourcesOptions
let environment: () -> [String: Any]
public let result = ExtractSourcesOperationResult()
public override var description: String { "Extract Sources" }
public init(target: T,
sourceRoot: Path,
supportPath: Path?,
options: ExtractSourcesOptions,
environment: @escaping () -> [String: Any]) {
self.target = target
self.sourceRoot = sourceRoot
self.supportPath = supportPath
self.options = options
self.environment = environment
}
override func run() throws {
try time(.extractSources) {
result.targetPaths = sourceFilePaths(for: target)
if options.contains(.dependencyPaths) {
let supportSourcePaths: Set<SourcePath>
if let supportPath = supportPath {
supportSourcePaths = try findSupportSourcePaths(at: supportPath)
} else {
supportSourcePaths = []
}
result.supportPaths = supportSourcePaths
result.dependencyPaths =
Set(allTargets(for: target).flatMap({ sourceFilePaths(for: $0) }))
.union(supportSourcePaths)
.subtracting(result.targetPaths)
}
}
log("Found \(result.targetPaths.count) source file\(result.targetPaths.count != 1 ? "s" : "") and \(result.dependencyPaths.count) dependency source file\(result.dependencyPaths.count != 1 ? "s" : "") for target \(target.name.singleQuoted)")
}
/// Returns the compiled source file paths for a single given target.
private var memoizedSourceFilePaths = [T: Set<SourcePath>]()
private func sourceFilePaths(for target: T) -> Set<SourcePath> {
if let memoized = memoizedSourceFilePaths[target] { return memoized }
let moduleName = resolveProductModuleName(for: target)
let paths = target.findSourceFilePaths(sourceRoot: sourceRoot)
.map({ SourcePath(path: $0, moduleName: moduleName) })
let includedPaths = includedSourcePaths(for: Set(paths))
memoizedSourceFilePaths[target] = includedPaths
return includedPaths
}
/// Recursively find all targets and its dependency targets.
private var memoizedTargets = [T: Set<T>]()
private func allTargets(for target: T) -> Set<T> {
if let memoized = memoizedTargets[target] { return memoized }
let targets = Set([target]).union(
target.dependencies
.compactMap({ $0.target as? T })
.flatMap({ allTargets(for: $0) }))
let productModuleName = resolveProductModuleName(for: target)
result.moduleDependencies[productModuleName] = Set(targets.map({
resolveProductModuleName(for: $0)
}))
memoizedTargets[target] = targets
return targets
}
/// Recursively find support module sources, taking each directory as the module name. Nested
/// directories are treated as submodules and can be accessed as a source from each parent module.
private func findSupportSourcePaths(at root: Path,
isTopLevel: Bool = true) throws -> Set<SourcePath> {
guard root.isDirectory else { return [] }
let moduleName = root.lastComponent
return try Set(root.children().flatMap({ path throws -> [SourcePath] in
if path.isDirectory {
let childSourcePaths = try findSupportSourcePaths(at: path, isTopLevel: false)
// Parent modules inherit all submodule source paths.
let inheritedSourcePaths = isTopLevel ? [] : childSourcePaths.map({
SourcePath(path: $0.path, moduleName: moduleName)
})
return childSourcePaths + inheritedSourcePaths
} else if !isTopLevel, path.isFile, path.extension == "swift" {
return [SourcePath(path: path, moduleName: moduleName)]
} else {
return []
}
}))
}
/// Only returns non-ignored source file paths based on `.mockingbird-ignore` glob declarations.
private func includedSourcePaths(for sourcePaths: Set<SourcePath>) -> Set<SourcePath> {
guard options.contains(.useMockingbirdIgnore) else { return sourcePaths }
let operations = sourcePaths.map({
retainForever(GlobSearchOperation(sourcePath: $0, sourceRoot: sourceRoot))
})
let queue = OperationQueue.createForActiveProcessors()
queue.addOperations(operations, waitUntilFinished: true)
return Set(operations.compactMap({ $0.result.sourcePath }))
}
private var memoizedProductModuleNames = [T: String]()
private func resolveProductModuleName(for target: T) -> String {
if let memoized = memoizedProductModuleNames[target] { return memoized }
let productModuleName = target.resolveProductModuleName(environment: environment)
memoizedProductModuleNames[target] = productModuleName
return productModuleName
}
}
/// Finds whether a given source path is ignored by a `.mockingbird-ignore` file.
private class GlobSearchOperation: BasicOperation {
class Result {
fileprivate(set) var sourcePath: SourcePath?
}
let result = Result()
let sourcePath: SourcePath
let sourceRoot: Path
init(sourcePath: SourcePath, sourceRoot: Path) {
self.sourcePath = sourcePath
self.sourceRoot = sourceRoot
}
private enum Constants {
static let mockingbirdIgnoreFileName = ".mockingbird-ignore"
static let commentPrefix = "#"
static let negationPrefix = "!"
static let escapingToken = "\\"
}
override var description: String { "Glob Search" }
override func run() throws {
guard shouldInclude(sourcePath: sourcePath.path, in: sourcePath.path.parent()).value else {
log("Ignoring source path at \(sourcePath.path.absolute())")
return
}
result.sourcePath = sourcePath
}
struct Glob {
let pattern: String
let isNegated: Bool
let root: Path
}
/// Recursively checks the source path against any `.mockingbird-ignore` files in the current
/// directory and traversed subdirectories, working from the source path up to the SRCROOT.
private func shouldInclude(sourcePath: Path, in directory: Path) -> (value: Bool, globs: [Glob]) {
guard directory.isDirectory else { return (true, []) }
let matches: (Bool, [Glob]) -> Bool = { (inheritedState, globs) in
return globs.reduce(into: inheritedState) { (result, glob) in
let trailingSlash = glob.pattern.hasPrefix("/") ? "" : "/"
let pattern = "\(glob.root.absolute())" + trailingSlash + glob.pattern
let matches = directory.matches(pattern: pattern, isDirectory: true)
|| sourcePath.matches(pattern: pattern, isDirectory: false)
if glob.isNegated { // Inclusion
result = result || matches
} else { // Exclusion
result = result && !matches
}
}
}
// Recursively find globs if this source is within the project SRCROOT.
guard "\(directory.absolute())".hasPrefix("\(sourceRoot.absolute())") else { return (true, []) }
let (parentShouldInclude, parentGlobs) = shouldInclude(sourcePath: sourcePath,
in: directory.parent())
// Handle non-relative patterns (which can match at any level below the defining ignore level)
// by cumulatively shifting the root to the current directory. This treats each subsequent
// directory like it has an ignore file with all of the patterns from its parents.
let allParentGlobs = parentGlobs + parentGlobs
.filter({ glob in // Only non-relative patterns (no leading slash, single path component).
guard !glob.pattern.hasPrefix("/") else { return false }
return Path(glob.pattern).components.count == 1
})
.map({
Glob(pattern: $0.pattern, isNegated: $0.isNegated, root: directory)
})
// Read in the `.mockingbird-ignore` file contents and find glob declarations.
let ignoreFile = directory + Constants.mockingbirdIgnoreFileName
guard ignoreFile.isFile else {
return (matches(parentShouldInclude, parentGlobs), allParentGlobs)
}
guard let globs = try? ignoreFile.read(.utf8).components(separatedBy: "\n")
.filter({ line -> Bool in
let stripped = line.trimmingCharacters(in: .whitespaces)
return !stripped.isEmpty && !stripped.hasPrefix(Constants.commentPrefix)
})
.map({ rawLine -> Glob in
let isNegated = rawLine.hasPrefix("!")
// Handle filenames that start with an escaped `!` or `#`.
let line: String
if rawLine.hasPrefix(Constants.escapingToken + Constants.negationPrefix)
|| rawLine.hasPrefix(Constants.escapingToken + Constants.commentPrefix) {
line = String(rawLine.dropFirst())
} else {
line = rawLine
}
guard !line.hasPrefix("/") else {
return Glob(pattern: line, isNegated: isNegated, root: directory)
}
let pattern = !isNegated ? line : String(line.dropFirst(Constants.negationPrefix.count))
return Glob(pattern: pattern, isNegated: isNegated, root: directory)
})
else {
logWarning("Unable to read \(Constants.mockingbirdIgnoreFileName.singleQuoted) at \(ignoreFile.absolute())")
return (!matches(parentShouldInclude, parentGlobs), allParentGlobs)
}
let allGlobs = allParentGlobs + globs
return (matches(parentShouldInclude, allGlobs), allGlobs)
}
}
| 39.450909 | 244 | 0.681445 |
22aa95970745945e6b96d7b2efa0482a5b0fffc5 | 2,953 | import UIKit
class TableController: NSObject, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
}
var sections = [TableSectionProtocol]() {
didSet { reload() }
}
func reload() {
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection index: Int) -> Int {
guard let section = section(for: index) else { return 0 }
return section.numberOfRows()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection index: Int) -> String? {
guard self.tableView(tableView, viewForHeaderInSection: index) == nil else { return nil }
guard let section = section(for: index) as? TableSection else { return nil }
return section.name
}
func tableView(_ tableView: UITableView, viewForHeaderInSection index: Int) -> UIView? {
guard let section = section(for: index) else { return nil }
return section.headerView()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection index: Int) -> CGFloat {
guard let sections = section(for: index) else { return 0 }
return sections.headerHeight()
}
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
guard let item = item(for: indexPath) else { return false }
return item.shouldHighlight()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = item(for: indexPath) else { return }
tableView.deselectRow(at: indexPath, animated: true)
item.selectionBlock?()
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let item = item(for: indexPath) {
return item.estimatedCellHeight
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let item = item(for: indexPath) else {
assertionFailure("failed to get item for \(indexPath)")
return UITableViewCell()
}
return item.cell(tableView: tableView, indexPath: indexPath)
}
// MARK: - Utility
func section(for index: Int) -> TableSectionProtocol? {
guard sections.count > index else { return nil }
return sections[index]
}
func item(for indexPath: IndexPath) -> TableItem? {
guard let section = section(for: indexPath.section) as? TableSection else { return nil }
guard section.items.count > indexPath.row else { return nil }
return section.items[indexPath.row]
}
}
| 35.154762 | 103 | 0.662039 |
fe5f8b5c2408fbc8e2656d05b82c77905e9c5d59 | 798 | //
// BaseArticleRequest.swift
// APIManager
//
// Created by Ahmed Moussa on 1/15/20.
// Copyright © 2020 Ahmed Moussa. All rights reserved.
//
import Foundation
public class BaseArticleRequest: Codable, Equatable {
// A comma-seperated string of identifiers for the news sources or blogs you want headlines from.
public var sources: String?
// Keywords or phrases to search for in the article title and body.
public var q: String?
public init(sources: String?, q: String?) {
self.sources = sources
self.q = q
}
public static func == (lhs: BaseArticleRequest, rhs: BaseArticleRequest) -> Bool {
if (lhs.sources == rhs.sources && lhs.q == rhs.q) {
return true
} else {
return false
}
}
}
| 26.6 | 101 | 0.62782 |
de0444917142edee2930ac139f66f4ebca864625 | 602 | import Foundation
extension RubberBand{
typealias Config = (/*This is the RubberBand config Signature*/
friction:CGFloat,
springEasing:CGFloat,
spring:CGFloat,
limit:CGFloat,
epsilon:CGFloat
)
typealias Frame = (/*This is the Frame Signature, basically: (y, height) or (x, width) So that the springsolve can support horizontal and vertical orientation, but what about z?*/
min:CGFloat,/*Basically topMargin when vertical, or leftMargin when horizontal*/
len:CGFloat/*Basically height when vertical or width when horizontal*/
)
}
| 37.625 | 183 | 0.692691 |
f9e8a06f9da7e23b19654761cac9a90f63973e86 | 3,666 | //
// Survey.swift
// Pods
//
// Created by Phillip Connaughton on 12/5/15.
//
//
import Foundation
class Survey: NSObject
{
var surveyId: UUID!
var dismissAction: String?
var userAccountCreation: Date?
var triggerTimestamp : Date?
var event: String?
var comment: String?
var customerUserId: String?
var userType: String?
var completedTimestamp: Date?
var npsRating: Int?
static let triggerTimestampKey = "trigger_timestamp"
static let dismissActionKey = "dismiss_action"
static let completedTimestampKey = "completed_timestamp"
static let npsRatingKey = "nps_rating"
static let commentsKey = "comments"
static let userAccountCreationKey = "user_account_creation"
static let eventKey = "event"
static let customerUserIdKey = "user_id"
static let userTypeKey = "user_type"
static let surveyIdKey = "survey_id"
init(surveyId: UUID){
self.surveyId = surveyId
}
init(map:[String: AnyObject])
{
self.triggerTimestamp = map[Survey.triggerTimestampKey] as? Date
self.dismissAction = map[Survey.dismissActionKey] as? String
self.completedTimestamp = map[Survey.completedTimestampKey] as? Date
self.npsRating = map[Survey.npsRatingKey] as? Int
self.comment = map[Survey.commentsKey] as? String
self.userAccountCreation = map[Survey.userAccountCreationKey] as? Date
self.event = map[Survey.eventKey] as? String
self.customerUserId = map[Survey.customerUserIdKey] as? String
self.userType = map[Survey.userTypeKey] as? String
self.surveyId = UUID(uuidString: map[Survey.surveyIdKey] as! String)
}
func serialize() -> [String: AnyObject]
{
var map = [String: AnyObject]()
map[Survey.triggerTimestampKey] = self.triggerTimestamp as AnyObject?
map[Survey.dismissActionKey] = self.dismissAction as AnyObject?
map[Survey.completedTimestampKey] = self.completedTimestamp as AnyObject?
map[Survey.npsRatingKey] = self.npsRating as AnyObject?
map[Survey.commentsKey] = self.comment as AnyObject?
map[Survey.userAccountCreationKey] = self.userAccountCreation as AnyObject?
map[Survey.eventKey] = self.event as AnyObject?
map[Survey.customerUserIdKey] = self.customerUserId as AnyObject?
map[Survey.userTypeKey] = self.userType as AnyObject?
map[Survey.surveyIdKey] = self.surveyId.uuidString as AnyObject?
return map
}
func serializeForSurvey() -> [String: String]
{
var map = [String: String]()
if(self.triggerTimestamp != nil)
{
map[Survey.triggerTimestampKey] = String(self.triggerTimestamp!.timeIntervalSince1970)
}
map[Survey.dismissActionKey] = self.dismissAction
if(self.completedTimestamp != nil)
{
map[Survey.completedTimestampKey] = String(self.completedTimestamp!.timeIntervalSince1970)
}
if(self.npsRating != nil)
{
map[Survey.npsRatingKey] = String(self.npsRating!)
}
map[Survey.commentsKey] = self.comment
if(self.userAccountCreation == nil)
{
map[Survey.userAccountCreationKey] = String(self.userAccountCreation!.timeIntervalSince1970)
}
map[Survey.eventKey] = self.event
map[Survey.customerUserIdKey] = self.customerUserId
map[Survey.userTypeKey] = self.userType
map[Survey.surveyIdKey] = self.surveyId.uuidString
return map
}
}
| 33.944444 | 104 | 0.654392 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.