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
e6e6514d55518f288f6e9f58a6290271db124a65
1,346
// // Animator.swift // InstagramStory // // Created by Ivan Sapozhnik on 4/30/17. // Copyright © 2017 Ivan Sapozhnik. All rights reserved. // import UIKit final class Animator: NSObject { public var perspective: CGFloat public var totalAngle: CGFloat public init(perspective: CGFloat = -1 / 1500, totalAngle: CGFloat = CGFloat(Double.pi/2)) { self.perspective = perspective self.totalAngle = totalAngle } public func animate(collectionView: UICollectionView, attributes: InstagramStoryLayoutAttributes) { let position = attributes.middleOffset attributes.dimmAlpha = abs(position) - 0.4 if abs(position) >= 1 { attributes.contentView?.layer.transform = CATransform3DIdentity } else if attributes.scrollDirection == .horizontal { let rotateAngle = totalAngle * position var transform = CATransform3DIdentity transform.m34 = perspective transform = CATransform3DRotate(transform, rotateAngle, 0, 1, 0) attributes.contentView?.layer.transform = transform attributes.contentView?.keepCenterAndApplyAnchorPoint(CGPoint(x: position > 0 ? 0 : 1, y: 0.5)) attributes.dimmView?.alpha = attributes.dimmAlpha } } }
32.829268
107
0.642645
11f3a0b7aec8c3eb4184103bad5d9451a3012f2b
4,208
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// #if canImport(Glibc) import Glibc #elseif canImport(Darwin) import Darwin #elseif canImport(CRT) import CRT #elseif canImport(WASILibc) import WASILibc #endif /// A shell for which the parser can generate a completion script. public struct CompletionShell: RawRepresentable, Hashable, CaseIterable { public var rawValue: String /// Creates a new instance from the given string. public init?(rawValue: String) { switch rawValue { case "zsh", "bash", "fish": self.rawValue = rawValue default: return nil } } /// An instance representing `zsh`. public static var zsh: CompletionShell { CompletionShell(rawValue: "zsh")! } /// An instance representing `bash`. public static var bash: CompletionShell { CompletionShell(rawValue: "bash")! } /// An instance representing `fish`. public static var fish: CompletionShell { CompletionShell(rawValue: "fish")! } /// Returns an instance representing the current shell, if recognized. public static func autodetected() -> CompletionShell? { #if os(Windows) return nil #else // FIXME: This retrieves the user's preferred shell, not necessarily the one currently in use. guard let shellVar = getenv("SHELL") else { return nil } let shellParts = String(cString: shellVar).split(separator: "/") return CompletionShell(rawValue: String(shellParts.last ?? "")) #endif } /// An array of all supported shells for completion scripts. public static var allCases: [CompletionShell] { [.zsh, .bash, .fish] } } struct CompletionsGenerator { var shell: CompletionShell var command: ParsableCommand.Type init(command: ParsableCommand.Type, shell: CompletionShell?) throws { guard let _shell = shell ?? .autodetected() else { throw ParserError.unsupportedShell() } self.shell = _shell self.command = command } init(command: ParsableCommand.Type, shellName: String?) throws { if let shellName = shellName { guard let shell = CompletionShell(rawValue: shellName) else { throw ParserError.unsupportedShell(shellName) } try self.init(command: command, shell: shell) } else { try self.init(command: command, shell: nil) } } /// Generates a Bash completion script for this generators shell and command.. func generateCompletionScript() -> String { switch shell { case .zsh: return ZshCompletionsGenerator.generateCompletionScript(command) case .bash: return BashCompletionsGenerator.generateCompletionScript(command) case .fish: return FishCompletionsGenerator.generateCompletionScript(command) default: fatalError("Invalid CompletionShell: \(shell)") } } } extension ArgumentDefinition { /// Returns a string with the arguments for the callback to generate custom completions for /// this argument. func customCompletionCall(_ commands: [ParsableCommand.Type]) -> String { let subcommandNames = commands.dropFirst().map { $0._commandName }.joined(separator: " ") let argumentName = names.preferredName?.synopsisString ?? self.help.keys.first?.rawValue ?? "---" return "---completion \(subcommandNames) -- \(argumentName)" } } extension ParsableCommand { fileprivate static var compositeCommandName: [String] { if let superCommandName = configuration._superCommandName { return [superCommandName] + _commandName.split(separator: " ").map(String.init) } else { return _commandName.split(separator: " ").map(String.init) } } } extension Sequence where Element == ParsableCommand.Type { func completionFunctionName() -> String { "_" + self.flatMap { $0.compositeCommandName } .uniquingAdjacentElements() .joined(separator: "_") } }
32.369231
98
0.680371
3a1b7b3c7b72655bbadb3b544d7c10ac4712314f
614
// // EvolutionChainTranslator.swift // Domain // // Created by Tomosuke Okada on 2021/01/31. // import DataStore import Foundation enum EvolutionChainTranslatorProvider { static func provide() -> EvolutionChainTranslator { return EvolutionChainTranslatorImpl() } } protocol EvolutionChainTranslator { func convert(from response: EvolutionChainResponse) -> EvolutionChainModel } private struct EvolutionChainTranslatorImpl: EvolutionChainTranslator { func convert(from response: EvolutionChainResponse) -> EvolutionChainModel { return EvolutionChainModel(response) } }
21.928571
80
0.760586
285bcfea4e8bea4c885a564243ac2a010ae147a0
3,323
// RUN: %target-swift-emit-sil -I %S/Inputs -enable-cxx-interop %s | %FileCheck %s import StaticVar func initStaticVars() -> CInt { return staticVar + staticVarInit + staticVarInlineInit + staticConst + staticConstInit + staticConstInlineInit + staticConstexpr + staticNonTrivial.val + staticConstNonTrivial.val + staticConstexprNonTrivial.val } // CHECK: // clang name: staticVar // CHECK: sil_global @staticVar : $Int32 // CHECK: // clang name: staticVarInit // CHECK: sil_global @staticVarInit : $Int32 // CHECK: // clang name: staticVarInlineInit // CHECK: sil_global @staticVarInlineInit : $Int32 // CHECK: // clang name: staticConst // CHECK: sil_global [let] @staticConst : $Int32 // CHECK: // clang name: staticConstInit // CHECK: sil_global [let] @staticConstInit : $Int32 // CHECK: // clang name: staticConstInlineInit // CHECK: sil_global [let] @staticConstInlineInit : $Int32 // CHECK: // clang name: staticConstexpr // CHECK: sil_global [let] @staticConstexpr : $Int32 // CHECK: // clang name: staticNonTrivial // CHECK: sil_global @staticNonTrivial : $NonTrivial // CHECK: // clang name: staticConstNonTrivial // CHECK: sil_global [let] @staticConstNonTrivial : $NonTrivial // CHECK: // clang name: staticConstexprNonTrivial // CHECK: sil_global [let] @staticConstexprNonTrivial : $NonTrivial func readStaticVar() -> CInt { return staticVar } // CHECK: sil hidden @$s4main13readStaticVars5Int32VyF : $@convention(thin) () -> Int32 // CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int32 // CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: return [[VALUE]] : $Int32 func writeStaticVar(_ v: CInt) { staticVar = v } // CHECK: sil hidden @$s4main14writeStaticVaryys5Int32VF : $@convention(thin) (Int32) -> () // CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32 // CHECK: store %0 to [[ACCESS]] : $*Int32 func readStaticNonTrivial() -> NonTrivial { return staticNonTrivial } // CHECK: sil hidden @$s4main20readStaticNonTrivialSo0dE0VyF : $@convention(thin) () -> NonTrivial // CHECK: [[ADDR:%.*]] = global_addr @staticNonTrivial : $*NonTrivial // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*NonTrivial // CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*NonTrivial // CHECK: return [[VALUE]] : $NonTrivial func writeStaticNonTrivial(_ i: NonTrivial) { staticNonTrivial = i } // CHECK: sil hidden @$s4main21writeStaticNonTrivialyySo0dE0VF : $@convention(thin) (NonTrivial) -> () // CHECK: [[ADDR:%.*]] = global_addr @staticNonTrivial : $*NonTrivial // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*NonTrivial // CHECK: store %0 to [[ACCESS]] : $*NonTrivial func modifyInout(_ c: inout CInt) { c = 42 } func passingVarAsInout() { modifyInout(&staticVar) } // CHECK: sil hidden @$s4main17passingVarAsInoutyyF : $@convention(thin) () -> () // CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32 // CHECK: [[FUNC:%.*]] = function_ref @$s4main11modifyInoutyys5Int32VzF : $@convention(thin) (@inout Int32) -> () // CHECK: apply [[FUNC]]([[ACCESS]]) : $@convention(thin) (@inout Int32) -> ()
40.036145
113
0.681312
eb5db8cd91c9393cb04b10fab47dd63b13280639
569
import UIKit class LinkTextView: UITextView { override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard let pos = closestPosition(to: point), let range = tokenizer.rangeEnclosingPosition(pos, with: .character, inDirection: .layout(.left)) else { return false } let startIndex = offset(from: beginningOfDocument, to: range.start) let link = attributedText.attribute(.link, at: startIndex, effectiveRange: nil) return link != nil } }
25.863636
155
0.609842
0aa10d5d9ce0ed1e77d4ca59fdafe686ffa5d308
229
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a = { if true { [ j : { class B { func f { class case ,
19.083333
87
0.707424
4a3b0624527767ef52745910cfb0fda96d7d4a86
5,418
// // ASToast.swift // superapp // // Created by Amit on 5/7/20. // Copyright © 2020 Amit. All rights reserved. // import Foundation public enum ASMToastAlignment: String { case center case top case bottom } @available(iOS 9.0, *) public class ASMToast: NSObject { static var sharedManager: ASMToast? public static var toastAlignment: ASMToastAlignment = ASMToastAlignment.bottom @discardableResult static func shared() -> ASMToast? { if sharedManager == nil { sharedManager = ASMToast() } return sharedManager } private override init() { } var toastView: ASMToastView? var rootPadding: CGFloat = 16 var withDuration: TimeInterval = 3 var delay: TimeInterval = 1 private func show(_ message: String?, _ props: ASMTProps? = nil) { if let viewController = ASMToast.topMostVC { toastView = ASMToastView(message, props) viewController.view.addSubview(toastView.unsafelyUnwrapped) if #available(iOS 11.0, *) { toastView?.translatesAutoresizingMaskIntoConstraints = false if props?.isToHororozontalEdge ?? false { toastView?.leftAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.leftAnchor, constant: rootPadding).isActive = true toastView?.rightAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.rightAnchor, constant: -rootPadding).isActive = true } switch props?.toastAlignment ?? ASMToast.toastAlignment { case .center: toastView?.topAnchor.constraint(greaterThanOrEqualTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: rootPadding).isActive = true toastView?.bottomAnchor.constraint(lessThanOrEqualTo: viewController.view.safeAreaLayoutGuide.bottomAnchor, constant: -rootPadding).isActive = true toastView?.centerYAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.centerYAnchor).isActive = true case .top: toastView?.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: rootPadding).isActive = true toastView?.bottomAnchor.constraint(lessThanOrEqualTo: viewController.view.safeAreaLayoutGuide.bottomAnchor, constant: -rootPadding).isActive = true case .bottom: toastView?.topAnchor.constraint(greaterThanOrEqualTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: rootPadding).isActive = true toastView?.bottomAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.bottomAnchor, constant: -rootPadding).isActive = true } toastView?.leftAnchor.constraint(greaterThanOrEqualTo: viewController.view.safeAreaLayoutGuide.leftAnchor, constant: rootPadding).isActive = true toastView?.rightAnchor.constraint(lessThanOrEqualTo: viewController.view.safeAreaLayoutGuide.rightAnchor, constant: -rootPadding).isActive = true toastView?.centerXAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.centerXAnchor).isActive = true let gesture = ASMToastGestureRecognizer(target: self, action: #selector(onTap)) gesture.numberOfTapsRequired = 1 toastView?.addGestureRecognizer(gesture) toastView?.isUserInteractionEnabled = true } else { // Fallback on earlier versions } dismissWithAnimation(toastView) } } @objc func onTap(sender : AnyObject){ dismiss(toastView) } private func dismiss(_ toastView: ASMToastView?) { var toastView = toastView toastView?.container?.layer.removeAllAnimations() toastView?.removeFromSuperview() toastView = nil } @objc private func dismissWithAnimation(_ toastView: ASMToastView?) { UIView.animate(withDuration: withDuration, delay: delay, options: [.allowUserInteraction, .curveEaseIn], animations: { () -> Void in toastView?.container?.alpha = 0 }, completion: { (finished) in self.dismiss(toastView) }) } } @available(iOS 9.0, *) extension ASMToast { public static func show(_ message: String?, _ props: ASMTProps? = nil) { if let toast = ASMToast.shared() { ASMToast.dismiss() toast.show(message, props) } } public static func dismiss() { if let toast = ASMToast.shared() { toast.dismiss(toast.toastView) } } private static var topMostVC: UIViewController? { var presentedVC = UIApplication.shared.keyWindow?.rootViewController while let pVC = presentedVC?.presentedViewController { presentedVC = pVC } if presentedVC == nil { print("Error: You don't have any views set.") } return presentedVC } } public class ASMToastGestureRecognizer: UITapGestureRecognizer { var firstObject: Any? func setFirstObject(_ sender: Any?) { self.firstObject = sender } func getFirstObject() -> Any? { return self.firstObject } }
40.133333
167
0.648025
d5ad6ecd39e971177cca00169713a270eb6bddbe
7,000
#if os(iOS) import UIKit #else import AppKit #endif extension ConstraidProxy { /** Constrains the object's leading edge to the leading edge of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading edge of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading edge of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withLeadingEdgeOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withLeadingEdgeOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's trailing edge to the trailing edge of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to trailing edge of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the trailing edge of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withTrailingEdgeOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withTrailingEdgeOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's top edge to the top edge of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to top edge of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the top edge of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withTopEdgeOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withTopEdgeOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's bottom edge to the bottom edge of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to bottom edge of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the bottom edge of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withBottomEdgeOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withBottomEdgeOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's leading & trailing edges to the leading & trailing edges of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading & trailing edges of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading & trailing edges of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withVerticalEdgesOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withVerticalEdgesOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's top & bottom edges to the top & bottom edges of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to top & bottom edges of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the top & bottom edges of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withHorizontalEdgesOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withHorizontalEdgesOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } /** Constrains the object's leading, trailing, top & bottom edge to the leading, trailing, top & bottom edge of `item` - parameter item: The `item` you want to constrain itemA against - parameter multiplier: The ratio altering the constraint relative to leading, trailing, top & bottom edges of the item prior to the `inset` being applied. - parameter inset: The amount to inset the object from the leading, trailing, top & bottom edges of the item - parameter priority: The priority this constraint uses when being evaluated against other constraints - returns: Constraid proxy containing the generated constraint */ public func flush(withEdgesOf item: Any?, times multiplier: CGFloat = 1.0, insetBy inset: CGFloat = 0.0, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self { self.constraintCollection.append(contentsOf: Constraid.flush(self.base, withEdgesOf: item, times: multiplier, insetBy: inset, priority: priority)) return self } }
50.724638
199
0.722286
db854fef8b7cc3da99652c1b990385553b552338
762
import UIKit import XCTest import IPaTokenView class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.4
111
0.606299
3a26452179d45c08a7074ff73b9bcacde9b8ab9f
28,162
// // Settings.swift // VideoGraph // // Created by Admin on 16/08/2018. // Copyright © 2018 Admin. All rights reserved. // import UIKit public enum RepeatMode: Int { case Bounce = 0 case Repeat = 1 } public enum ToneCurveMode: Int { case RGB = 0 case R = 1 case G = 2 case B = 3 } struct Project { let editSettings: EditSettings let bChangedToneCurve: Bool let bChangedTemperature: Bool let bChangedTint: Bool let cropSettings: CropSettings let priorCropSettings: CropSettings let fontObjects: [FontObject] let selectedObjectIdx: Int let leftTrimOffset: CGFloat let rightTrimOffset: CGFloat let stillImage: UIImage? let stillImageSize: CGSize let originalMaskImage: UIImage? let currentMaskImage: UIImage? var finalVideoName: String = "" init(_ originalMaskImage: UIImage?, _ currentMaskImage: UIImage?, _ finalVideoName: String = "") { self.editSettings = TheVideoEditor.editSettings self.bChangedToneCurve = TheVideoEditor.bChangedToneCurve self.bChangedTemperature = TheVideoEditor.bChangedTemperature self.bChangedTint = TheVideoEditor.bChangedTint self.cropSettings = TheVideoEditor.cropSettings self.priorCropSettings = TheVideoEditor.priorCropSettings self.fontObjects = TheVideoEditor.fontObjects.map { $0.copy() } as! [FontObject] self.selectedObjectIdx = TheVideoEditor.selectedFontObjectIdx self.leftTrimOffset = TheVideoEditor.fTrimLeftOffset self.rightTrimOffset = TheVideoEditor.fTrimRightOffset self.stillImage = TheVideoEditor.stillImage self.stillImageSize = TheVideoEditor.initialStillImageSize self.originalMaskImage = originalMaskImage self.currentMaskImage = currentMaskImage self.finalVideoName = finalVideoName } init(_ nProjectIdx: Int) { let name = "project_\(nProjectIdx)_settings" self.editSettings = EditSettings.init(nProjectIdx) self.bChangedToneCurve = UserDefaults.standard.bool(forKey: "\(name)_bChangedToneCurve") self.bChangedTemperature = UserDefaults.standard.bool(forKey: "\(name)_bChangedTemperature") self.bChangedTint = UserDefaults.standard.bool(forKey: "\(name)_bChangedTint") self.cropSettings = CropSettings.init(nProjectIdx, true) self.priorCropSettings = CropSettings.init(nProjectIdx, false) if let data = UserDefaults.standard.data(forKey: "\(name)_fontobjects"), let objects = NSKeyedUnarchiver.unarchiveObject(with: data) as? [FontObject] { self.fontObjects = objects } else { self.fontObjects = [] } self.selectedObjectIdx = UserDefaults.standard.integer(forKey: "\(name)_selectedObjectIdx") self.leftTrimOffset = CGFloat(UserDefaults.standard.double(forKey: "\(name)_leftTrimOffset")) self.rightTrimOffset = CGFloat(UserDefaults.standard.double(forKey: "\(name)_rightTrimOffset")) let stillImagePath = UserDefaults.standard.value(forKey: "\(name)_stillImage") as! String if (stillImagePath.length == 0) { self.stillImage = UIImage() } else { self.stillImage = TheGlobalPoolManager.loadImage(stillImagePath) } self.stillImageSize = NSCoder.cgSize(for: UserDefaults.standard.value(forKey: "\(name)_stillImageSize") as! String) let originalMaskImagePath = UserDefaults.standard.value(forKey: "\(name)_originalMaskImage") as! String if (originalMaskImagePath.length == 0) { self.originalMaskImage = UIImage() } else { self.originalMaskImage = TheGlobalPoolManager.loadImage(originalMaskImagePath) } let currentMaskImagePath = UserDefaults.standard.value(forKey: "\(name)_currentMaskImage") as! String if (currentMaskImagePath.length == 0) { self.currentMaskImage = UIImage() } else { self.currentMaskImage = TheGlobalPoolManager.loadImage(currentMaskImagePath) } if let finalVideoName = UserDefaults.standard.value(forKey: "final_video") as? String { self.finalVideoName = finalVideoName } else { self.finalVideoName = "" } } func deleteData(_ nProjectIdx: Int) { let name = "project_\(nProjectIdx)_settings" let stillImagePath = UserDefaults.standard.value(forKey: "\(name)_stillImage") as! String if (stillImagePath.length > 0) { TheGlobalPoolManager.deleteImage(stillImagePath) } let originalMaskImagePath = UserDefaults.standard.value(forKey: "\(name)_originalMaskImage") as! String if (originalMaskImagePath.length > 0) { TheGlobalPoolManager.deleteImage(originalMaskImagePath) } let currentMaskImagePath = UserDefaults.standard.value(forKey: "\(name)_currentMaskImage") as! String if (currentMaskImagePath.length > 0) { TheGlobalPoolManager.deleteImage(currentMaskImagePath) } if (self.finalVideoName != "") { TheGlobalPoolManager.eraseFile(self.finalVideoName) } } mutating func saveProject(_ nProjectIdx: Int, _ finalVideoName: String) { let name = "project_\(nProjectIdx)_settings" self.editSettings.save(nProjectIdx) UserDefaults.standard.set(self.bChangedToneCurve, forKey: "\(name)_bChangedToneCurve") UserDefaults.standard.set(self.bChangedTemperature, forKey: "\(name)_bChangedTemperature") UserDefaults.standard.set(self.bChangedTint, forKey: "\(name)_bChangedTint") self.cropSettings.save(nProjectIdx, true) self.priorCropSettings.save(nProjectIdx, false) let encodedData = NSKeyedArchiver.archivedData(withRootObject: self.fontObjects) UserDefaults.standard.set(encodedData, forKey: "\(name)_fontobjects") UserDefaults.standard.set(self.selectedObjectIdx, forKey: "\(name)_selectedObjectIdx") UserDefaults.standard.set(Double(self.leftTrimOffset), forKey: "\(name)_leftTrimOffset") UserDefaults.standard.set(Double(self.rightTrimOffset), forKey: "\(name)_rightTrimOffset") if (self.stillImage == nil) { UserDefaults.standard.set("", forKey: "\(name)_stillImage") } else { if TheGlobalPoolManager.saveImage(self.stillImage!, "\(name)_stillImage") { UserDefaults.standard.set("\(name)_stillImage", forKey: "\(name)_stillImage") } else { UserDefaults.standard.set("", forKey: "\(name)_stillImage") } } //let updatedStillImageSize = self.stillImage!.size //UserDefaults.standard.set(NSStringFromCGSize(updatedStillImageSize), forKey: "\(name)_stillImageSize") UserDefaults.standard.set(NSCoder.string(for: self.stillImageSize), forKey: "\(name)_stillImageSize") if (self.originalMaskImage == nil) { UserDefaults.standard.set("", forKey: "\(name)_originalMaskImage") } else { if TheGlobalPoolManager.saveImage(self.originalMaskImage!, "\(name)_originalMaskImage") { UserDefaults.standard.set("\(name)_originalMaskImage", forKey: "\(name)_originalMaskImage") } else { UserDefaults.standard.set("", forKey: "\(name)_originalMaskImage") } } if (self.currentMaskImage == nil) { UserDefaults.standard.set("", forKey: "\(name)_currentMaskImage") } else { if TheGlobalPoolManager.saveImage(self.currentMaskImage!, "\(name)_currentMaskImage") { UserDefaults.standard.set("\(name)_currentMaskImage", forKey: "\(name)_currentMaskImage") } else { UserDefaults.standard.set("", forKey: "\(name)_currentMaskImage") } } if (self.finalVideoName != "") { TheGlobalPoolManager.eraseFile(self.finalVideoName) } UserDefaults.standard.set(finalVideoName, forKey: "final_video") self.finalVideoName = finalVideoName UserDefaults.standard.synchronize() } } struct CropSettings { var entireTransform: CGAffineTransform = .identity var cropSize: CGSize = .zero var imageViewSize: CGSize = .zero var fliped: Bool = false var angle: CGFloat = 0.0 var rotateCnt: Int = 0 var contentViewFrame: CGRect = .zero var scrollViewFrame: CGRect = .zero var scrollViewContentOffset: CGPoint = .zero var bUpdated: Bool = false init() { self.entireTransform = .identity self.cropSize = .zero self.imageViewSize = .zero self.fliped = false self.angle = 0.0 self.rotateCnt = 0 self.contentViewFrame = .zero self.scrollViewFrame = .zero self.scrollViewContentOffset = .zero self.bUpdated = false } init(_ entireTransform: CGAffineTransform, _ cropSize: CGSize, _ imageViewSize: CGSize, _ fliped: Bool, _ angle: CGFloat, _ rotateCnt: Int, _ contentViewFrame: CGRect, _ scrollViewFrame: CGRect, _ scrollViewContentOffset: CGPoint) { self.entireTransform = entireTransform self.cropSize = cropSize self.imageViewSize = imageViewSize self.fliped = fliped self.angle = angle self.rotateCnt = rotateCnt self.contentViewFrame = contentViewFrame self.scrollViewFrame = scrollViewFrame self.scrollViewContentOffset = scrollViewContentOffset self.bUpdated = true } mutating func update(_ entireTransform: CGAffineTransform, _ cropSize: CGSize, _ imageViewSize: CGSize, _ fliped: Bool, _ angle: CGFloat, _ rotateCnt: Int, _ contentViewFrame: CGRect, _ scrollViewFrame: CGRect, _ scrollViewContentOffset: CGPoint) { self.entireTransform = entireTransform self.cropSize = cropSize self.imageViewSize = imageViewSize self.fliped = fliped self.angle = angle self.rotateCnt = rotateCnt self.contentViewFrame = contentViewFrame self.scrollViewFrame = scrollViewFrame self.scrollViewContentOffset = scrollViewContentOffset self.bUpdated = true } func save(_ nProjectIdx: Int, _ isCurrent: Bool) { let subName = (isCurrent ? "current" : "prior") let name = "project_\(nProjectIdx)_cropsettings_\(subName)" UserDefaults.standard.set(NSCoder.string(for: self.entireTransform), forKey: "\(name)_entireTransform") UserDefaults.standard.set(NSCoder.string(for: self.cropSize), forKey: "\(name)_cropSize") UserDefaults.standard.set(NSCoder.string(for: self.imageViewSize), forKey: "\(name)_imageViewSize") UserDefaults.standard.set(self.fliped, forKey: "\(name)_fliped") UserDefaults.standard.set(self.angle, forKey: "\(name)_angle") UserDefaults.standard.set(self.rotateCnt, forKey: "\(name)_rotateCnt") UserDefaults.standard.set(NSCoder.string(for: self.contentViewFrame), forKey: "\(name)_contentViewFrame") UserDefaults.standard.set(NSCoder.string(for: self.scrollViewFrame), forKey: "\(name)_scrollViewFrame") UserDefaults.standard.set(NSCoder.string(for: self.scrollViewContentOffset), forKey: "\(name)_scrollViewContentOffset") UserDefaults.standard.set(self.bUpdated, forKey: "\(name)_bUpdated") UserDefaults.standard.synchronize() } init(_ nProjectIdx: Int, _ isCurrent: Bool) { let subName = (isCurrent ? "current" : "prior") let name = "project_\(nProjectIdx)_cropsettings_\(subName)" self.entireTransform = NSCoder.cgAffineTransform(for: UserDefaults.standard.value(forKey: "\(name)_entireTransform") as! String) self.cropSize = NSCoder.cgSize(for: UserDefaults.standard.value(forKey: "\(name)_cropSize") as! String) self.imageViewSize = NSCoder.cgSize(for: UserDefaults.standard.value(forKey: "\(name)_imageViewSize") as! String) self.fliped = UserDefaults.standard.bool(forKey: "\(name)_fliped") self.angle = UserDefaults.standard.value(forKey: "\(name)_angle") as! CGFloat self.rotateCnt = UserDefaults.standard.integer(forKey: "\(name)_rotateCnt") self.contentViewFrame = NSCoder.cgRect(for: UserDefaults.standard.value(forKey: "\(name)_contentViewFrame") as! String) self.scrollViewFrame = NSCoder.cgRect(for: UserDefaults.standard.value(forKey: "\(name)_scrollViewFrame") as! String) self.scrollViewContentOffset = NSCoder.cgPoint(for: UserDefaults.standard.value(forKey: "\(name)_scrollViewContentOffset") as! String) self.bUpdated = UserDefaults.standard.bool(forKey: "\(name)_bUpdated") } } struct CameraSettings { var RatioIdx: Int = -1 var FPSIdx: Int = -1 var TimerIdx: Int = -1 var AWBIdx: Int = -1 init() { self.RatioIdx = 0 self.FPSIdx = 0 self.TimerIdx = 0 self.AWBIdx = 2 } } class TextSettings: NSObject, NSCoding, NSCopying { var text: String = Constants.DefaultText var colorIdx: Int = 0 var opacity: CGFloat = 1.0 var bg_colorIdx: Int = -1 var bg_opacity: CGFloat = 0.5 var fontIdx: Int = 0 var text_size: CGFloat = 20.0 var character_spacing: CGFloat = 0.0 var line_spacing: CGFloat = 1.15 var text_prospective: CGFloat = 0.0 var text_rotation: CGFloat = 0.0 var text_in_zoom: CGFloat = 4.0 var text_aligment: TextAlignment = .Center override init() { self.text = Constants.DefaultText self.colorIdx = 0 self.opacity = 1.0 self.bg_colorIdx = -1 self.bg_opacity = 0.5 self.fontIdx = 0 self.text_size = 20.0 self.character_spacing = 0.0 self.line_spacing = 1.15 self.text_prospective = 0.0 self.text_rotation = 0.0 self.text_in_zoom = 4.0 self.text_aligment = .Center } required init(_ object: TextSettings) { self.text = object.text self.fontIdx = object.fontIdx self.colorIdx = object.colorIdx self.opacity = object.opacity self.bg_colorIdx = object.bg_colorIdx self.bg_opacity = object.bg_opacity self.text_aligment = object.text_aligment self.text_size = object.text_size self.character_spacing = object.character_spacing self.line_spacing = object.line_spacing self.text_prospective = object.text_prospective self.text_rotation = object.text_rotation self.text_in_zoom = object.text_in_zoom } func copy(with zone: NSZone? = nil) -> Any { return type(of:self).init(self) } required init?(coder decoder: NSCoder) { self.text = decoder.decodeObject(forKey: "text") as! String self.fontIdx = decoder.decodeInteger(forKey: "fontIdx") self.colorIdx = decoder.decodeInteger(forKey: "colorIdx") self.opacity = CGFloat(decoder.decodeDouble(forKey: "opacity")) self.bg_colorIdx = decoder.decodeInteger(forKey: "bg_colorIdx") self.bg_opacity = CGFloat(decoder.decodeDouble(forKey: "bg_opacity")) self.text_aligment = TextAlignment(rawValue: decoder.decodeInteger(forKey: "text_aligment"))! self.text_size = CGFloat(decoder.decodeDouble(forKey: "text_size")) self.character_spacing = CGFloat(decoder.decodeDouble(forKey: "character_spacing")) self.line_spacing = CGFloat(decoder.decodeDouble(forKey: "line_spacing")) self.text_prospective = CGFloat(decoder.decodeDouble(forKey: "text_prospective")) self.text_rotation = CGFloat(decoder.decodeDouble(forKey: "text_rotation")) self.text_in_zoom = CGFloat(decoder.decodeDouble(forKey: "text_in_zoom")) } func encode(with coder: NSCoder) { coder.encode(self.text, forKey: "text") coder.encode(self.fontIdx, forKey: "fontIdx") coder.encode(self.colorIdx, forKey: "colorIdx") coder.encode(Double(self.opacity), forKey: "opacity") coder.encode(self.bg_colorIdx, forKey: "bg_colorIdx") coder.encode(Double(self.bg_opacity), forKey: "bg_opacity") coder.encode(self.text_aligment.rawValue, forKey: "text_aligment") coder.encode(Double(self.text_size), forKey: "text_size") coder.encode(Double(self.character_spacing), forKey: "character_spacing") coder.encode(Double(self.line_spacing), forKey: "line_spacing") coder.encode(Double(self.text_prospective), forKey: "text_prospective") coder.encode(Double(self.text_rotation), forKey: "text_rotation") coder.encode(Double(self.text_in_zoom), forKey: "text_in_zoom") } func reset() { //self.text = Constants.DefaultText self.colorIdx = 0 self.opacity = 1.0 self.bg_colorIdx = -1 self.bg_opacity = 0.5 self.fontIdx = 0 self.text_size = 20.0 self.character_spacing = 0.0 self.line_spacing = 1.15 self.text_prospective = 0.0 self.text_rotation = 0.0 self.text_in_zoom = 4.0 self.text_aligment = .Center } } struct EditSettings { var originalVideoURL: URL { get { return TheGlobalPoolManager.getVideoURL(self.originalVideoName) } } var originalVideoName: String = "" //video var repeatMode: RepeatMode = .Repeat var crossFade: CGFloat = 0.1 var speed: CGFloat = 1.0 var delay: CGFloat = 0.0 //brush var brushSize: CGFloat = 34.0 var brushHardness: CGFloat = 0.0 var brushOpacity: CGFloat = 100 var maskColorIdx: Int = 0 var maskOpacity: CGFloat = 80.0 var bShowMaskAlways: Bool = false // true - shows always, false - shows when masking var bMaskAll: Bool = false // true - mask all, false - unmask all (default action) //filter var filterIdx: Int = 0 //tune var temperature: CGFloat = 0.0 var tint: CGFloat = 0.0 var saturation: CGFloat = 1.0 var exposure: CGFloat = 0.0 var brightness: CGFloat = 0.0 var contrast: CGFloat = 1.0 var toneCurveMode: ToneCurveMode = .RGB var blacks: CGFloat = 0.0 var shadows: CGFloat = 0.0 var highlights: CGFloat = 0.0 var whites: CGFloat = 0.0 var blacks_r: CGFloat = 0.0 var shadows_r: CGFloat = 0.0 var highlights_r: CGFloat = 0.0 var whites_r: CGFloat = 0.0 var blacks_g: CGFloat = 0.0 var shadows_g: CGFloat = 0.0 var highlights_g: CGFloat = 0.0 var whites_g: CGFloat = 0.0 var blacks_b: CGFloat = 0.0 var shadows_b: CGFloat = 0.0 var highlights_b: CGFloat = 0.0 var whites_b: CGFloat = 0.0 var intensity: CGFloat = 0.0 var radius: CGFloat = 1.0 init() { self.originalVideoName = "" //video editing settings self.repeatMode = .Repeat self.crossFade = 0.1 self.speed = 1.0 self.delay = 0.0 //brush self.brushSize = 34.0 self.brushHardness = 6.0 self.brushOpacity = 100 self.maskColorIdx = 0 self.maskOpacity = 80 self.bShowMaskAlways = false self.bMaskAll = true //filter self.filterIdx = 0 //tone curve self.temperature = 0.0 self.tint = 0.0 self.saturation = 1.0 self.exposure = 0.0 self.brightness = 0.0 self.contrast = 1.0 self.toneCurveMode = .RGB self.blacks = 0.0 self.shadows = 0.0 self.highlights = 0.0 self.whites = 0.0 self.blacks_r = 0.0 self.shadows_r = 0.0 self.highlights_r = 0.0 self.whites_r = 0.0 self.blacks_g = 0.0 self.shadows_g = 0.0 self.highlights_g = 0.0 self.whites_g = 0.0 self.blacks_b = 0.0 self.shadows_b = 0.0 self.highlights_b = 0.0 self.whites_b = 0.0 self.intensity = 0.0 self.radius = 1.0 } mutating func resetAdjustment() { self.filterIdx = 0 self.temperature = 0.0 self.tint = 0.0 self.saturation = 1.0 self.exposure = 0.0 self.brightness = 0.0 self.contrast = 1.0 self.toneCurveMode = .RGB self.blacks = 0.0 self.shadows = 0.0 self.highlights = 0.0 self.whites = 0.0 self.blacks_r = 0.0 self.shadows_r = 0.0 self.highlights_r = 0.0 self.whites_r = 0.0 self.blacks_g = 0.0 self.shadows_g = 0.0 self.highlights_g = 0.0 self.whites_g = 0.0 self.blacks_b = 0.0 self.shadows_b = 0.0 self.highlights_b = 0.0 self.whites_b = 0.0 self.intensity = 0.0 self.radius = 1.0 } func save(_ nProjectIdx: Int) { let name = "project_\(nProjectIdx)_editsettings" UserDefaults.standard.set(self.originalVideoName, forKey: "\(name)_originalVideoName") UserDefaults.standard.set(self.repeatMode.rawValue, forKey: "\(name)_repeatMode") UserDefaults.standard.set(self.crossFade, forKey: "\(name)_crossFade") UserDefaults.standard.set(self.speed, forKey: "\(name)_speed") UserDefaults.standard.set(self.delay, forKey: "\(name)_delay") UserDefaults.standard.set(self.brushSize, forKey: "\(name)_brushSize") UserDefaults.standard.set(self.brushHardness, forKey: "\(name)_brushHardness") UserDefaults.standard.set(self.brushOpacity, forKey: "\(name)_brushOpacity") UserDefaults.standard.set(self.maskColorIdx, forKey: "\(name)_maskColorIdx") UserDefaults.standard.set(self.maskOpacity, forKey: "\(name)_maskOpacity") UserDefaults.standard.set(self.bShowMaskAlways, forKey: "\(name)_bShowMaskAlways") UserDefaults.standard.set(self.bMaskAll, forKey: "\(name)_bMaskAll") UserDefaults.standard.set(self.filterIdx, forKey: "\(name)_filterIdx") UserDefaults.standard.set(self.temperature, forKey: "\(name)_temperature") UserDefaults.standard.set(self.tint, forKey: "\(name)_tint") UserDefaults.standard.set(self.saturation, forKey: "\(name)_saturation") UserDefaults.standard.set(self.exposure, forKey: "\(name)_exposure") UserDefaults.standard.set(self.brightness, forKey: "\(name)_brightness") UserDefaults.standard.set(self.contrast, forKey: "\(name)_contrast") UserDefaults.standard.set(self.toneCurveMode.rawValue, forKey: "\(name)_toneCurveMode") UserDefaults.standard.set(self.blacks, forKey: "\(name)_blacks") UserDefaults.standard.set(self.shadows, forKey: "\(name)_shadows") UserDefaults.standard.set(self.highlights, forKey: "\(name)_highlights") UserDefaults.standard.set(self.whites, forKey: "\(name)_whites") UserDefaults.standard.set(self.blacks_r, forKey: "\(name)_blacks_r") UserDefaults.standard.set(self.shadows_r, forKey: "\(name)_shadows_r") UserDefaults.standard.set(self.highlights_r, forKey: "\(name)_highlights_r") UserDefaults.standard.set(self.whites_r, forKey: "\(name)_whites_r") UserDefaults.standard.set(self.blacks_g, forKey: "\(name)_blacks_g") UserDefaults.standard.set(self.shadows_g, forKey: "\(name)_shadows_g") UserDefaults.standard.set(self.highlights_g, forKey: "\(name)_highlights_g") UserDefaults.standard.set(self.whites_g, forKey: "\(name)_whites_g") UserDefaults.standard.set(self.blacks_b, forKey: "\(name)_blacks_b") UserDefaults.standard.set(self.shadows_b, forKey: "\(name)_shadows_b") UserDefaults.standard.set(self.highlights_b, forKey: "\(name)_highlights_b") UserDefaults.standard.set(self.whites_b, forKey: "\(name)_whites_b") UserDefaults.standard.set(self.intensity, forKey: "\(name)_intensity") UserDefaults.standard.set(self.radius, forKey: "\(name)_radius") UserDefaults.standard.synchronize() } init(_ nProjectIdx: Int) { let name = "project_\(nProjectIdx)_editsettings" self.originalVideoName = UserDefaults.standard.object(forKey: "\(name)_originalVideoName") as! String self.repeatMode = RepeatMode(rawValue: UserDefaults.standard.integer(forKey: "\(name)_repeatMode"))! self.crossFade = UserDefaults.standard.value(forKey: "\(name)_crossFade") as! CGFloat self.speed = UserDefaults.standard.value(forKey: "\(name)_speed") as! CGFloat self.delay = UserDefaults.standard.value(forKey: "\(name)_delay") as! CGFloat self.brushSize = UserDefaults.standard.value(forKey: "\(name)_brushSize") as! CGFloat self.brushHardness = UserDefaults.standard.value(forKey: "\(name)_brushHardness") as! CGFloat self.brushOpacity = UserDefaults.standard.value(forKey: "\(name)_brushOpacity") as! CGFloat self.maskColorIdx = UserDefaults.standard.integer(forKey: "\(name)_maskColorIdx") self.maskOpacity = UserDefaults.standard.value(forKey: "\(name)_maskOpacity") as! CGFloat self.bShowMaskAlways = UserDefaults.standard.bool(forKey: "\(name)_bShowMaskAlways") self.bMaskAll = UserDefaults.standard.bool(forKey: "\(name)_bMaskAll") self.filterIdx = UserDefaults.standard.integer(forKey: "\(name)_filterIdx") self.temperature = UserDefaults.standard.value(forKey: "\(name)_temperature") as! CGFloat self.tint = UserDefaults.standard.value(forKey: "\(name)_tint") as! CGFloat self.saturation = UserDefaults.standard.value(forKey: "\(name)_saturation") as! CGFloat self.exposure = UserDefaults.standard.value(forKey: "\(name)_exposure") as! CGFloat self.brightness = UserDefaults.standard.value(forKey: "\(name)_brightness") as! CGFloat self.contrast = UserDefaults.standard.value(forKey: "\(name)_contrast") as! CGFloat self.toneCurveMode = ToneCurveMode(rawValue: UserDefaults.standard.integer(forKey: "\(name)_toneCurveMode"))! self.blacks = UserDefaults.standard.value(forKey: "\(name)_blacks") as! CGFloat self.shadows = UserDefaults.standard.value(forKey: "\(name)_shadows") as! CGFloat self.highlights = UserDefaults.standard.value(forKey: "\(name)_highlights") as! CGFloat self.whites = UserDefaults.standard.value(forKey: "\(name)_whites") as! CGFloat self.blacks_r = UserDefaults.standard.value(forKey: "\(name)_blacks_r") as! CGFloat self.shadows_r = UserDefaults.standard.value(forKey: "\(name)_shadows_r") as! CGFloat self.highlights_r = UserDefaults.standard.value(forKey: "\(name)_highlights_r") as! CGFloat self.whites_r = UserDefaults.standard.value(forKey: "\(name)_whites_r") as! CGFloat self.blacks_g = UserDefaults.standard.value(forKey: "\(name)_blacks_g") as! CGFloat self.shadows_g = UserDefaults.standard.value(forKey: "\(name)_shadows_g") as! CGFloat self.highlights_g = UserDefaults.standard.value(forKey: "\(name)_highlights_g") as! CGFloat self.whites_g = UserDefaults.standard.value(forKey: "\(name)_whites_g") as! CGFloat self.blacks_b = UserDefaults.standard.value(forKey: "\(name)_blacks_b") as! CGFloat self.shadows_b = UserDefaults.standard.value(forKey: "\(name)_shadows_b") as! CGFloat self.highlights_b = UserDefaults.standard.value(forKey: "\(name)_highlights_b") as! CGFloat self.whites_b = UserDefaults.standard.value(forKey: "\(name)_whites_b") as! CGFloat self.intensity = UserDefaults.standard.value(forKey: "\(name)_intensity") as! CGFloat self.radius = UserDefaults.standard.value(forKey: "\(name)_radius") as! CGFloat } }
40.755427
252
0.656452
7a0893770e2df6fe0b058dec034fa3107efbe21e
1,728
// // ViewController.swift // obsTesting // // Created by pavel.grechikhin on 22.02.2019. // Copyright © 2019 pavel.grechikhin. All rights reserved. // import UIKit import RxSwift import RxCocoa import SnapKit import FlowDirection class ViewController: RxFlowViewController { let label = UILabel() let button = UIButton() let bag = DisposeBag() init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError() } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue setup() } func setup() { view.addSubview(label) label.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(16) make.right.equalToSuperview().offset(-16) make.centerY.equalToSuperview() } label.text = "ТЕСТ" view.addSubview(button) button.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(16) make.right.equalToSuperview().offset(-16) make.centerY.equalToSuperview().offset(50) } button.setTitle("Переход", for: .normal) button.setTitleColor(UIColor.purple, for: .normal) button.rx.tap.map { (_) -> (DirectionRoute, [RxCoordinatorMiddleware]?) in let mid = DeniedMiddleware() // return (DirectionRoute.present(flow: ViewControllerType.second, animated: true), .none) return (DirectionRoute.present(flow: ViewControllerType.second, animated: true), [mid]) } .bind(to: rxcoordinator!.rx.route) .disposed(by: bag) } }
27.870968
101
0.608218
14d20ce7332f8a448fc551d04438e04b7c2a9ad4
1,325
// // DailyFeedItemCell.swift // DailyFeed // // Created by Sumit Paul on 28/12/16. // import UIKit class DailyFeedItemCell: UICollectionViewCell { @IBOutlet weak var newsItemImageView: TSImageView! @IBOutlet weak var newsItemTitleLabel: UILabel! @IBOutlet weak var newsItemSourceLabel: UILabel! @IBOutlet weak var newsItemPublishedAtLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() setupCell() } func setupCell() { self.contentView.layer.cornerRadius = 10.0 self.contentView.layer.masksToBounds = true } func configure(with newsitems: DailyFeedModel, ltr: Bool) { self.newsItemTitleLabel.text = newsitems.title self.newsItemSourceLabel.text = newsitems.author self.newsItemPublishedAtLabel.text = newsitems.publishedAt?.dateFromTimestamp?.relativelyFormatted(short: true) if let imageURL = newsitems.urlToImage { self.newsItemImageView.downloadedFromLink(imageURL) } if ltr { self.newsItemTitleLabel.textAlignment = .right self.newsItemSourceLabel.textAlignment = .right } else { self.newsItemTitleLabel.textAlignment = .left self.newsItemSourceLabel.textAlignment = .left } } }
30.113636
119
0.670943
0ae235d2cac6799a8f3471a04feb9d2c608d2069
1,067
// // BrandModelDataMapper.swift // TasCar // // Created by Enrique Canedo on 09/07/2019. // Copyright © 2019 Enrique Canedo. All rights reserved. // import UIKit final class BrandModelDataMapper: BaseModelDataMapper<BrandModel, Brand>, BaseModelGenericDataMapper { func transform(domain: Brand?) -> BrandModel { guard let domain = domain else { return BrandModel() } let model = BrandModel() model.idBrand = domain.idBrand model.name = domain.name if let image = UIImage(named: domain.image) { model.image = image } model.file = domain.file model.color = domain.color return model } func inverseTransform(model: BrandModel?) -> Brand { guard let model = model else { return Brand() } let domain = Brand() domain.idBrand = model.idBrand domain.file = model.file domain.name = model.name domain.color = model.color return domain } }
24.813953
102
0.585754
485a0d3c1edef9883ba1af85a885b973800c7ae5
835
// // Bundle+Ext.swift // AnimalForestChat // // Created by Craig Lane on 4/10/19. // import Foundation // tag::KEYS-1[] // Bundle+Ext.swift extension Bundle { func pubSubKeys(for key: String) -> (pubKey: String, subKey: String) { // Ensure that the keys exist guard let dict = self.object(forInfoDictionaryKey: key) as? [String: String], let pubKey = dict["PubKey"], !pubKey.isEmpty, let subKey = dict["SubKey"], !subKey.isEmpty else { NSLog("Please verify that your pub/sub keys are set inside the AnimalForestChat.<CONFIG>.xcconfig files.") // This will only crash on debug configurations assertionFailure("Please ensure that your Pub/Sub keys are set inside the AnimalForestChat.xcconfig files") return ("", "") } return (pubKey, subKey) } } // end::KEYS-1[]
27.833333
113
0.661078
dd376fe4e859a7150647b703f7ef4b4b5a6de865
7,056
// Copyright SIX DAY LLC. All rights reserved. import Foundation import BigInt import PromiseKit struct RawTransaction: Decodable { let hash: String let blockNumber: String let transactionIndex: String let timeStamp: String let nonce: String let from: String let to: String let value: String let gas: String let gasPrice: String let input: String let gasUsed: String let error: String? let isError: String? /// ///It is possible for the etherscan.io API to return an empty `to` even if the transaction actually has a `to`. It doesn't seem to be linked to `"isError" = "1"`, because other transactions that fail (with isError="1") has a non-empty `to`. /// ///Eg. transaction with an empty `to` in API despite `to` is shown as non-empty in the etherscan.io web page:https: //ropsten.etherscan.io/tx/0x0c87d2acb0ecaf1221e599ad4f65edf77c97956d6534feb0afa68ee5c41c4e28 /// ///So it must be a optional var toAddress: AlphaWallet.Address? { //TODO We use the unchecked version because it was easier to provide an Address instance this way. Good to remove it return AlphaWallet.Address(uncheckedAgainstNullAddress: to) } enum CodingKeys: String, CodingKey { case hash = "hash" case blockNumber case transactionIndex case timeStamp case nonce case from case to case value case gas case gasPrice case input case gasUsed case operationsLocalized = "operations" case error = "error" case isError = "isError" } let operationsLocalized: [LocalizedOperation]? } extension TransactionInstance { static func from(transaction: RawTransaction, tokensStorage: TokensDataStore) -> Promise<TransactionInstance?> { guard let from = AlphaWallet.Address(string: transaction.from) else { return Promise.value(nil) } let state: TransactionState = { if transaction.error?.isEmpty == false || transaction.isError == "1" { return .error } return .completed }() let to = AlphaWallet.Address(string: transaction.to)?.eip55String ?? transaction.to return firstly { createOperationForTokenTransfer(forTransaction: transaction, tokensStorage: tokensStorage) }.then { operations -> Promise<TransactionInstance?> in let result = TransactionInstance( id: transaction.hash, server: tokensStorage.server, blockNumber: Int(transaction.blockNumber)!, transactionIndex: Int(transaction.transactionIndex)!, from: from.description, to: to, value: transaction.value, gas: transaction.gas, gasPrice: transaction.gasPrice, gasUsed: transaction.gasUsed, nonce: transaction.nonce, date: NSDate(timeIntervalSince1970: TimeInterval(transaction.timeStamp) ?? 0) as Date, localizedOperations: operations, state: state, isErc20Interaction: false ) return .value(result) } } static private func createOperationForTokenTransfer(forTransaction transaction: RawTransaction, tokensStorage: TokensDataStore) -> Promise<[LocalizedOperationObjectInstance]> { guard let contract = transaction.toAddress else { return Promise.value([]) } func generateLocalizedOperation(value: BigUInt, contract: AlphaWallet.Address, to recipient: AlphaWallet.Address, functionCall: DecodedFunctionCall) -> Promise<[LocalizedOperationObjectInstance]> { if let token = tokensStorage.tokenThreadSafe(forContract: contract) { let operationType = mapTokenTypeToTransferOperationType(token.type, functionCall: functionCall) let result = LocalizedOperationObjectInstance(from: transaction.from, to: recipient.eip55String, contract: contract, type: operationType.rawValue, value: String(value), tokenId: "", symbol: token.symbol, name: token.name, decimals: token.decimals) return .value([result]) } else { let getContractName = tokensStorage.getContractName(for: contract) let getContractSymbol = tokensStorage.getContractSymbol(for: contract) let getDecimals = tokensStorage.getDecimals(for: contract) let getTokenType = tokensStorage.getTokenType(for: contract) return firstly { when(fulfilled: getContractName, getContractSymbol, getDecimals, getTokenType) }.then { name, symbol, decimals, tokenType -> Promise<[LocalizedOperationObjectInstance]> in let operationType = mapTokenTypeToTransferOperationType(tokenType, functionCall: functionCall) let result = LocalizedOperationObjectInstance(from: transaction.from, to: recipient.eip55String, contract: contract, type: operationType.rawValue, value: String(value), tokenId: "", symbol: symbol, name: name, decimals: Int(decimals)) return .value([result]) }.recover { _ -> Promise<[LocalizedOperationObjectInstance]> in //NOTE: Return an empty array when failure to fetch contracts data, instead of failing whole TransactionInstance creating return Promise.value([]) } } } let data = Data(hex: transaction.input) if let functionCall = DecodedFunctionCall(data: data) { switch functionCall.type { case .erc20Transfer(let recipient, let value): return generateLocalizedOperation(value: value, contract: contract, to: recipient, functionCall: functionCall) case .erc20Approve(let spender, let value): return generateLocalizedOperation(value: value, contract: contract, to: spender, functionCall: functionCall) case .nativeCryptoTransfer, .others: break } } return Promise.value([]) } static private func mapTokenTypeToTransferOperationType(_ tokenType: TokenType, functionCall: DecodedFunctionCall) -> OperationType { switch (tokenType, functionCall.type) { case (.nativeCryptocurrency, _): return .nativeCurrencyTokenTransfer case (.erc20, .erc20Approve): return .erc20TokenApprove case (.erc20, .erc20Transfer): return .erc20TokenTransfer case (.erc721, _): return .erc721TokenTransfer case (.erc721ForTickets, _): return .erc721TokenTransfer case (.erc875, _): return .erc875TokenTransfer case (.erc20, .nativeCryptoTransfer), (.erc20, .others): return .unknown } } }
44.658228
263
0.637046
2fc6baa49d764d8224aae9f81c9e1335564e35f6
1,603
// // BusinessCell.swift // Yelp // // Created by Jiayi Wang on 2/19/18. // Copyright © 2018 Timothy Lee. All rights reserved. // import UIKit class BusinessCell: UITableViewCell{ @IBOutlet weak var thumbImageView: UIImageView! @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var reviewsCountLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! var business: Business!{ didSet{ nameLabel.text = business.name thumbImageView.setImageWith(business.imageURL!) categoriesLabel.text = business.categories addressLabel.text = business.address reviewsCountLabel.text = "\(business.reviewCount!) Reviews" ratingImageView.setImageWith(business.ratingImageURL!) distanceLabel.text = business.distance } } override func awakeFromNib() { super.awakeFromNib() thumbImageView.layer.cornerRadius = 3 thumbImageView.clipsToBounds = true nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width // Initialization code } override func layoutSubviews() { super.layoutSubviews() nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
30.826923
71
0.670618
89e98ee7a8f094a71e2be229a5057004fb8afac4
1,989
import Foundation import SwiftUI struct ShadowModifier: ViewModifier { let isVertical: Bool let show: Bool func body(content: Content) -> some View { content .shadow(color: self.show ? .black : .clear, radius: 1, x: self.isVertical ? 1 : 0, y: self.isVertical ? 0 : 1) } } extension View { func dropShadow(isVertical: Bool, show: Bool) -> some View { self.modifier(ShadowModifier(isVertical: isVertical, show: show)) } } struct BlurView: UIViewRepresentable { let style: UIBlurEffect.Style func makeUIView(context: UIViewRepresentableContext<BlurView>) -> UIView { let view = UIView(frame: .zero) view.backgroundColor = .clear let blurEffect = UIBlurEffect(style: style) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false view.insertSubview(blurView, at: 0) NSLayoutConstraint.activate([ blurView.heightAnchor.constraint(equalTo: view.heightAnchor), blurView.widthAnchor.constraint(equalTo: view.widthAnchor) ]) return view } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<BlurView>) {} } struct DummyBackground: View { let index: Int let width: CGFloat let height: CGFloat @EnvironmentObject var layoutManager: TableLayoutManager @Environment(\.backgroundColor) var backgroundColor init(index: Int, width: CGFloat, height: CGFloat) { self.index = index self.width = width self.height = height } var body: some View { Group { let zIndex = self.index == 0 ? 700 : 550 - self.index Rectangle() .fill(self.backgroundColor) .frame(width: width, height: height * self.layoutManager.scaleY, alignment: .topLeading) .zIndex(Double(zIndex)) } } }
31.078125
122
0.633484
08fc83d97c2f5b27372a2a86861e48b8d8784428
1,312
// // PreviewAction.swift // CineasteTests // // Created by Felizia Bernutz on 14.04.19. // Copyright © 2019 spacepandas.de. All rights reserved. // import UIKit enum PreviewAction { case delete case moveToWatchlist case moveToSeen func previewAction(for movie: Movie) -> UIPreviewAction { let action = UIPreviewAction( title: title, style: style) { _, _ -> Void in switch self { case .delete: store.dispatch(deleteMovie(movie)) case .moveToWatchlist: store.dispatch(markMovie(movie, watched: false)) case .moveToSeen: store.dispatch(markMovie(movie, watched: true)) } } return action } } extension PreviewAction { private var style: UIPreviewAction.Style { switch self { case .delete: return .destructive case .moveToWatchlist, .moveToSeen: return .default } } private var title: String { switch self { case .delete: return .deleteActionLong case .moveToWatchlist: return .watchlistAction case .moveToSeen: return .seenAction } } }
23.428571
68
0.543445
1a8ad624644092cfd4d79b267f4b5a2647807834
2,217
// // AVSampleBufferRenderSynchronizer+Rx.swift // // // Created by Pawel Rup on 17/06/2019. // import AVFoundation import RxSwift import RxCocoa @available(iOS 11.0, tvOS 11.0, macOS 10.13, *) extension Reactive where Base: AVSampleBufferRenderSynchronizer { /// Removes a renderer from the synchronizer. /// - Parameter renderer: Renderer /// - Parameter time: The time on the timebase's timeline at which the renderer should be removed. If the time is in the past, the renderer is immediately removed. public func removeRenderer(_ renderer: AVQueuedSampleBufferRendering, at time: CMTime) -> Single<Bool> { Single.create { event in base.removeRenderer(renderer, at: time) { (didRemoveRenderer) in event(.success(didRemoveRenderer)) } return Disposables.create() } } /// Requests invocation of a block during rendering at specified time intervals. /// - Parameter interval: The specified time interval requesting block invocation during rendering. /// - Parameter queue: The serial queue the block should be unqueued on. If you pass NULL, the main queue is used. Passing a concurrent queue results in undefined behavior. public func periodicTimeObserver(interval: CMTime, queue: DispatchQueue? = nil) -> Observable<CMTime> { Observable.create { observer in let timeObserver = base.addPeriodicTimeObserver(forInterval: interval, queue: queue) { time in observer.onNext(time) } return Disposables.create { base.removeTimeObserver(timeObserver) } } } /// Requests invocation of a block when specified times are traversed during normal rendering. /// - Parameter times: An array containing the times for which the observer requests notification. /// - Parameter queue: The serial queue the block should be unqueued on. If you pass NULL, the main queue is used. Passing a concurrent queue results in undefined behavior. public func addBoundaryTimeObserver(forTimes times: [NSValue], queue: DispatchQueue? = nil) -> Observable<Void> { Observable.create { observer in let timeObserver = base.addBoundaryTimeObserver(forTimes: times, queue: queue) { observer.onNext(()) } return Disposables.create { base.removeTimeObserver(timeObserver) } } } }
41.830189
173
0.752819
2203c68a7bec34de9c7df65193edbd07adeb291a
3,587
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation import Amplify import AWSMobileClient public class AWSAuthService: AWSAuthServiceBehavior { var mobileClient: AWSMobileClientBehavior! public convenience init() { self.init(mobileClient: nil) } init(mobileClient: AWSMobileClientBehavior? = nil) { let mobileClient = mobileClient ?? AWSMobileClientAdapter(AWSMobileClient.default()) self.mobileClient = mobileClient } public func getCognitoCredentialsProvider() -> AWSCognitoCredentialsProvider { return mobileClient.getCognitoCredentialsProvider() } public func getIdentityId() -> Result<String, AuthError> { let task = mobileClient.getIdentityId() task.waitUntilFinished() guard task.error == nil else { if let error = task.error! as? AWSMobileClientError { return .failure(map(error)) } return .failure(AuthError.unknown("Some error occuring retrieving the IdentityId.")) } guard let identityId = task.result else { let error = AuthError.unknown("Got successful response but missing IdentityId in the result.") return .failure(error) } return .success(identityId as String) } public func getToken() -> Result<String, AuthError> { var jwtToken: String? var authError: AuthError? let semaphore = DispatchSemaphore(value: 0) mobileClient.getTokens { tokens, error in if let error = error { authError = AuthError.unknown("failed to get token with error \(error.localizedDescription)") } else if let token = tokens { jwtToken = token.idToken?.tokenString } semaphore.signal() } semaphore.wait() guard authError == nil else { if let error = authError { return .failure(error) } return .failure(AuthError.unknown("not sure what happened trying to get failure for retrieving token")) } guard let token = jwtToken else { return .failure(AuthError.unknown("not sure what happened getting the jwtToken")) } return .success(token) } /// Used for testing only. Invoking this method outside of a testing scope has undefined behavior. public func reset() { mobileClient = nil } private func map(_ error: AWSMobileClientError) -> AuthError { switch error { case .identityIdUnavailable(let message): return AuthError.identity("Identity Id is Unavailable", message, """ Check for network connectivity and try again. """, error) case .guestAccessNotAllowed(let message): return AuthError.identity("Guest access is not allowed", message, """ Cognito was configured to disallow unauthenticated (guest) access. Turn on guest access and try again. """, error) default: return AuthError.unknown(error.localizedDescription) } } }
33.839623
115
0.565096
2613b856ce2218c72512b7187fb0ac6e1ac17989
2,360
// // EqualSize.swift // SwiftUITest // // Created by Thomas Visser on 06/02/2020. // Copyright © 2020 Thomas Visser. All rights reserved. // import Foundation import SwiftUI struct SizeConstraint: Equatable, CustomStringConvertible { var width: CGFloat? var height: CGFloat? var description: String { "\(width ?? -1), \(height ?? -1)" } } struct SizeKey: PreferenceKey { static let defaultValue: [CGSize] = [] static func reduce(value: inout [CGSize], nextValue: () -> [CGSize]) { value.append(contentsOf: nextValue()) } } struct SizeEnvironmentKey: EnvironmentKey { static let defaultValue: SizeConstraint? = nil } extension EnvironmentValues { var size: SizeConstraint? { get { self[SizeEnvironmentKey.self] } set { self[SizeEnvironmentKey.self] = newValue } } } fileprivate struct EqualSize: ViewModifier { @SwiftUI.Environment(\.size) private var size let alignment: SwiftUI.Alignment func body(content: Content) -> some View { content .transformEnvironment(\.size) { $0 = nil } .overlay(GeometryReader { proxy in Color.clear.preference(key: SizeKey.self, value: [proxy.size]) }) .frame(width: size?.width, height: size?.height, alignment: alignment) } } fileprivate struct EqualSizes: ViewModifier { let horizontal: Bool let vertical: Bool @State var constraint: SizeConstraint? func body(content: Content) -> some View { content .onPreferenceChange(SizeKey.self) { sizes in self.constraint = SizeConstraint( width: self.horizontal ? sizes.map { $0.width }.max() : nil, height: self.vertical ? sizes.map { $0.height }.max() : nil ) } .environment(\.size, constraint) .transformPreference(SizeKey.self) { $0.removeAll() } } } extension View { func equalSize(alignment: SwiftUI.Alignment = .center) -> some View { self.modifier(EqualSize(alignment: alignment)) } func equalSizes() -> some View { equalSizes(horizontal: true, vertical: true) } func equalSizes(horizontal: Bool, vertical: Bool) -> some View { self.modifier(EqualSizes(horizontal: horizontal, vertical: vertical)) } }
27.764706
82
0.624153
ff69057aff107917edc4957731530a84771f5702
629
// // UITabBar+Ext.swift // Ext // // Created by naijoug on 2021/1/28. // import UIKit public extension ExtWrapper where Base: UITabBar { // Reference: https://stackoverflow.com/questions/39850794/remove-top-line-from-tabbar /// 移除顶部分割线 func removeTopLine() { if #available(iOS 13.0, *) { let appearance = base.standardAppearance appearance.shadowImage = nil appearance.shadowColor = nil base.standardAppearance = appearance } else { base.shadowImage = UIImage() base.backgroundImage = UIImage() } } }
23.296296
90
0.596184
7974213af31b4bb14e7ca99bda6f7181d469e5a7
912
// // AutolayoutTests.swift // AutolayoutTests // // Created by Ashish Tyagi on 25/05/15. // Copyright (c) 2015 Ashish Tyagi. All rights reserved. // import UIKit import XCTest class AutolayoutTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.648649
111
0.618421
c133eb3dd1c603e3e830696c1ec929df8613e60d
939
import Foundation import Firebase protocol EmailProfileInteractorProtocol { /// Method to install or update authorization data func setAuthData(with data: AuthDataResult) /// Method for getting user configuration func getUserConfig(_ completion: @escaping ((User?) -> Void)) } class EmailProfileInteractor: EmailProfileInteractorProtocol { private weak var presenter: EmailProfilePresenterProtocol! fileprivate var entity: EmailProfileEntityProtocol? func setAuthData(with data: AuthDataResult) { entity?.saveAuthData(with: data) } func getUserConfig(_ completion: @escaping ((User?) -> Void)) { let user = entity?.getUser() completion(user) } // MARK: - Initialization required init(p presenter: EmailProfilePresenterProtocol) { self.presenter = presenter self.entity = EmailProfileEntity(interactor: self) } }
29.34375
67
0.693291
1400dc2010ac2e761040695ebef1771c112ea629
2,679
// // User.swift // MindMeApiPackageDescription // // Created by lieon on 2018/3/9. // import Foundation import FluentProvider import HTTP import Node import Crypto final class User: Model, NodeInitializable{ var storage: Storage = Storage() var email: String var password: String var name: String // var id: Node? struct Keys { static let email: String = "email" static let id: String = "id" static let password: String = "password" static let name: String = "name" } init(email: String, password: String, name: String) { self.email = email self.password = password self.name = name } func makeRow() throws -> Row { var row = Row() try row.set(User.Keys.email, email) try row.set(User.Keys.password, password) try row.set(User.Keys.name, name) return row } required init(row: Row) throws { email = try row.get(User.Keys.email) password = try row.get(User.Keys.password) name = try row.get(User.Keys.name) } init(node: Node, in context: Context) throws { email = try node.get(User.Keys.email) password = try node.get(User.Keys.password) name = try node.get(User.Keys.name) } } extension User: JSONConvertible { convenience init(json: JSON) throws { self.init(email: try json.get(User.Keys.email), password: try json.get(User.Keys.password), name: try json.get(User.Keys.name)) } func makeJSON() throws -> JSON { var json = JSON() try json.set(User.Keys.id, id) try json.set(User.Keys.email, email) try json.set(User.Keys.password, password) try json.set(User.Keys.name, name) return json } } extension User: ResponseRepresentable {} extension User: NodeRepresentable { func makeNode(in context: Context?) throws -> Node { return try Node(node: [ // User.Keys.id: id, User.Keys.email: email, User.Keys.name: name, User.Keys.password: password ]) } } extension User: Preparation { static func prepare(_ database: Database) throws { try database.create(self) {builder in builder.id() builder.string(User.Keys.email) builder.string(User.Keys.password) builder.string(User.Keys.name) } } static func revert(_ database: Database) throws { try database.delete(self) } } extension User { var events: Children<User, Event> { return children() } }
25.037383
61
0.588652
710a918d9e18e20a858b4ec4596c6a6d3bc57f84
3,980
// // LocationNode.swift // ARKit+CoreLocation // // Created by Andrew Hart on 02/07/2017. // Copyright © 2017 Project Dent. All rights reserved. // import Foundation import SceneKit import CoreLocation open class LocationAnnotationNode: LocationNode { /// Subnodes and adjustments should be applied to this subnode /// Required to allow scaling at the same time as having a 2D 'billboard' appearance public let annotationNode: AnnotationNode public init(location: CLLocation?, image: UIImage) { let plane = SCNPlane(width: image.size.width / 100, height: image.size.height / 100) plane.firstMaterial!.diffuse.contents = image plane.firstMaterial!.lightingModel = .constant annotationNode = AnnotationNode(view: nil, image: image) annotationNode.geometry = plane annotationNode.removeFlicker() super.init(location: location) let billboardConstraint = SCNBillboardConstraint() billboardConstraint.freeAxes = SCNBillboardAxis.Y constraints = [billboardConstraint] addChildNode(annotationNode) } @available(iOS 10.0, *) /// Use this constructor to add a UIView as an annotation. Keep in mind that it is not live, instead /// it's a "snapshot" of that UIView. UIView is more configurable then a UIImage, allowing you to add /// background image, labels, etc. /// /// - Parameters: /// - location: The location of the node in the world. /// - view: The view to display at the specified location. public convenience init(location: CLLocation?, view: UIView) { self.init(location: location, image: view.image) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updatePositionAndScale(setup: Bool = false, scenePosition: SCNVector3?, locationNodeLocation nodeLocation: CLLocation, locationManager: SceneLocationManager, onCompletion: (() -> Void)) { guard let position = scenePosition, let location = locationManager.currentLocation else { return } SCNTransaction.begin() SCNTransaction.animationDuration = setup ? 0.0 : 0.1 let distance = self.location(locationManager.bestLocationEstimate).distance(from: location) let adjustedDistance = self.adjustedDistance(setup: setup, position: position, locationNodeLocation: nodeLocation, locationManager: locationManager) // The scale of a node with a billboard constraint applied is ignored // The annotation subnode itself, as a subnode, has the scale applied to it let appliedScale = self.scale self.scale = SCNVector3(x: 1, y: 1, z: 1) var scale: Float if scaleRelativeToDistance { scale = appliedScale.y annotationNode.scale = appliedScale annotationNode.childNodes.forEach { child in child.scale = appliedScale } } else { let scaleFunc = scalingScheme.getScheme() scale = scaleFunc(distance, adjustedDistance) annotationNode.scale = SCNVector3(x: scale, y: scale, z: scale) annotationNode.childNodes.forEach { node in node.scale = SCNVector3(x: scale, y: scale, z: scale) } } self.pivot = SCNMatrix4MakeTranslation(0, -1.1 * scale, 0) SCNTransaction.commit() onCompletion() } } // MARK: - Image from View public extension UIView { @available(iOS 10.0, *) /// Gets you an image from the view. var image: UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } }
36.181818
122
0.638442
5b4369c7051e679d9a4303bd32a1833685e9fe9d
2,192
// // UIView+ShadowTests.swift // KeyboardKitTests // // Created by Daniel Saidi on 2019-05-28. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Quick import Nimble import KeyboardKit import UIKit class UIView_ShadowTests: QuickSpec { override func spec() { describe("applying shadow") { it("applies shadow properties") { let view = UIView() let shadow = Shadow.test() let layer = view.layer view.applyShadow(shadow) expect(layer.shadowColor).to(equal(shadow.color.cgColor)) expect(layer.shadowOpacity).to(equal(shadow.alpha)) expect(layer.shadowOffset.width).to(equal(0)) expect(layer.shadowOffset.height).to(equal(0)) expect(layer.shadowRadius).to(equal(shadow.blur/2)) } it("applies behavior properties") { let view = UIView() let shadow = Shadow.test() let layer = view.layer view.applyShadow(shadow) expect(layer.shouldRasterize).to(beTrue()) expect(layer.rasterizationScale).to(equal(UIScreen.main.scale)) } it("does not apply shadow path if spread is zero") { let view = UIView() let shadow = Shadow.test(spread: 0) let layer = view.layer view.applyShadow(shadow) expect(layer.shadowPath).toNot(beNil()) } it("applies shadow path if spread is not zero") { let view = UIView() let shadow = Shadow.test(spread: 0.5) let layer = view.layer view.applyShadow(shadow) expect(layer.shadowPath).toNot(beNil()) } } } } private extension Shadow { static func test(spread: CGFloat = 0.8) -> Shadow { return Shadow( alpha: 0.75, blur: 0.123, color: .red, spread: spread, x: 100.1, y: 200.2) } }
30.444444
79
0.510036
6243204ee0f48aa7e80989cd7bbcd10568ab6041
8,708
extension Component { public final class TextInput: AutoRenderable, Focusable { public let configurator: (View) -> Void public let styleSheet: StyleSheet public let focusEligibility: FocusEligibility /// Creates Component.TextInput /// - parameter title: Label of a the text input which describes it (i.e: "E-mail"). /// - parameter placeholder: Placeholder which is displayed instead of text when text is empty. /// - parameter text: Pre-filled value of the TextInput. It can be modifed by user. (i.e: "[email protected]"). Limited to only one line. /// - parameter keyboardType: UIKit keyboard type. /// - parameter isEnabled: Indicates if user can change a text value. /// - parameter accessory: Additional icon displayed on the right side. /// - parameter textWillChange: Closure which may rejected text changes. /// - parameter textDidChange: Closure which notifies about text changes. /// - parameter didTapAccessory: Closure which is invoked when user taps on the accessory. /// - parameter styleSheet: StyleSheet with styling. public init( title: String? = nil, placeholder: String? = nil, text: TextValue? = nil, keyboardType: UIKeyboardType = .default, isEnabled: Bool = true, accessory: Accessory = .none, textWillChange: Optional<(TextChange) -> Bool> = nil, textDidChange: Optional<(String?) -> Void> = nil, didTapAccessory: Optional<() -> Void> = nil, styleSheet: StyleSheet ) { self.configurator = { view in view.titleLabel.text = title view.titleLabel.isHidden = title?.isEmpty ?? true view.textField.placeholder = placeholder view.textField.keyboardType = keyboardType view.textField.isEnabled = isEnabled text?.apply(to: view.textField) view.accessoryView.accessory = accessory.toAccessoryViewAccessory view.accessoryView.didTap = didTapAccessory view.textWillChange = textWillChange view.textDidChange = textDidChange } let isNotEmpty = text?.isEmpty ?? false self.focusEligibility = isNotEmpty ? .eligible(.populated) : .eligible(.empty) self.styleSheet = styleSheet } } } extension Component.TextInput { public struct TextChange { public let current: String? public let change: String public let range: NSRange public var result: String { guard let current = self.current, let range = Range(range, in: current) else { return "" } return current.replacingCharacters(in: range, with: change) } } } extension Component.TextInput { public final class View: BaseView, UITextFieldDelegate { public enum TitleStyle { case fit case fillProportionally(CGFloat) } fileprivate let contentView = UIView() private var titleLabelWidthConstraint: NSLayoutConstraint? { willSet { titleLabelWidthConstraint?.isActive = false } didSet { titleLabelWidthConstraint?.isActive = true } } fileprivate let titleLabel = UILabel() fileprivate let textField = UITextField() fileprivate let accessoryView = AccessoryView() fileprivate var titleStyle: TitleStyle = .fit { didSet { switch titleStyle { case .fit: titleLabelWidthConstraint = nil case let .fillProportionally(proportion): titleLabelWidthConstraint = titleLabel.widthAnchor.constraint( equalTo: contentView.widthAnchor, multiplier: proportion ) .withPriority(.required) } } } var textWillChange: Optional<(TextChange) -> Bool> = nil var textDidChange: Optional<(String?) -> Void> = nil override init(frame: CGRect) { super.init(frame: frame) setupLayout() } private func setupLayout() { preservesSuperviewLayoutMargins = true contentView .add(to: self) .pinEdges(to: layoutMarginsGuide) titleLabel.setContentHuggingPriority(.required, for: .horizontal) titleLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) textField.setContentHuggingPriority(.defaultLow, for: .horizontal) textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) stack(.horizontal, spacing: 16.0, distribution: .fill, alignment: .center)( titleLabel, textField, accessoryView ) .add(to: contentView) .pinEdges(to: contentView.layoutMarginsGuide) textField.addTarget(self, action: #selector(textDidChangeOn(_:)), for: UIControl.Event.editingChanged) textField.delegate = self } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func textDidChangeOn(_ textField: UITextField) { self.textDidChange?(textField.text) } @objc public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return textWillChange?( .init(current: textField.text, change: string, range: range) ) ?? true } @objc public func textFieldShouldReturn(_ textField: UITextField) -> Bool { withFocusCoordinator { coordinator in if !coordinator.move(.backward) { textField.resignFirstResponder() } } return false } @objc public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { updateReturnKey() textField.inputAccessoryView = FocusToolbar(view: self) return true } public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) { textField.inputAccessoryView = nil } private func updateReturnKey() { withFocusCoordinator { coordinator in let usesNextKey = coordinator.canMove(.backward) textField.returnKeyType = usesNextKey ? .next : .done } } } } extension Component.TextInput.View: FocusableView { public func focus() { textField.becomeFirstResponder() } public func neighboringFocusEligibilityDidChange() { updateReturnKey() (textField.inputAccessoryView as? FocusToolbar)?.updateFocusEligibility(with: self) textField.reloadInputViews() } } extension Component.TextInput { public final class StyleSheet: BaseViewStyleSheet<View> { public var titleStyle: View.TitleStyle public let title: LabelStyleSheet public let text: TextFieldStylesheet public let content: ViewStyleSheet<UIView> public init( titleStyle: View.TitleStyle = .fillProportionally(0.25), title: LabelStyleSheet = LabelStyleSheet( font: UIFont.preferredFont(forTextStyle: .body), textAlignment: .leading ), text: TextFieldStylesheet = TextFieldStylesheet(), content: ViewStyleSheet<UIView> = ViewStyleSheet(layoutMargins: .zero) ) { self.titleStyle = titleStyle self.title = title self.text = text self.content = content } public override func apply(to element: Component.TextInput.View) { super.apply(to: element) element.titleStyle = titleStyle title.apply(to: element.titleLabel) text.apply(to: element.textField) content.apply(to: element.contentView) } } } extension Component.TextInput { public enum Accessory { case icon(UIImage) case none fileprivate var toAccessoryViewAccessory: AccessoryView.Accessory { switch self { case let .icon(image): return .icon(image) case .none: return .none } } } }
36.742616
146
0.601056
1a198e1dbae0b890ce76d8b3fbf256cf995edff4
957
// // HotImgView.swift // musicSheet // // Created by Jz D on 2019/10/17. // Copyright © 2019 Jz D. All rights reserved. // import Foundation import UIKit class HotImg: UIImageView{ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let width = bounds.size.width let height = bounds.size.height let offset: CGFloat = 15 let frame = CGRect(x: offset * (-1), y: offset * (-1), width: width + offset * 2, height: height + offset * 2) return frame.contains(point) } } class HotBtn: UIButton{ override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let width = bounds.size.width let height = bounds.size.height let offset: CGFloat = 15 let frame = CGRect(x: offset * (-1), y: offset * (-1), width: width + offset * 2, height: height + offset * 2) return frame.contains(point) } }
22.255814
118
0.595611
87635eb59b38c5463e57bc62964274df6d79c85b
751
import XCTest import SPUserCenterUI class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.896552
111
0.603196
7608965fbf4cafbe4fc549f9b8e1c7289025e54f
14,891
// // AutomaticEvents.swift // Mixpanel // // Created by Yarden Eitan on 3/8/17. // Copyright © 2017 Mixpanel. All rights reserved. // protocol AEDelegate { func track(event: String?, properties: Properties?) func setOnce(properties: Properties) func increment(property: String, by: Double) #if DECIDE func trackPushNotification(_ userInfo: [AnyHashable: Any], event: String, properties: Properties) #endif } #if DECIDE || TV_AUTO_EVENTS import Foundation import UIKit import StoreKit import UserNotifications class AutomaticEvents: NSObject, SKPaymentTransactionObserver, SKProductsRequestDelegate { var _minimumSessionDuration: UInt64 = 10000 var minimumSessionDuration: UInt64 { set { _minimumSessionDuration = newValue } get { return _minimumSessionDuration } } var _maximumSessionDuration: UInt64 = UINT64_MAX var maximumSessionDuration: UInt64 { set { _maximumSessionDuration = newValue } get { return _maximumSessionDuration } } var awaitingTransactions = [String: SKPaymentTransaction]() let defaults = UserDefaults(suiteName: "Mixpanel") var delegate: AEDelegate? var sessionLength: TimeInterval = 0 var sessionStartTime: TimeInterval = Date().timeIntervalSince1970 var hasAddedObserver = false var automaticPushTracking = true var firstAppOpen = false let awaitingTransactionsWriteLock = DispatchQueue(label: "com.mixpanel.awaiting_transactions_writeLock", qos: .utility) func initializeEvents() { let firstOpenKey = "MPFirstOpen" if let defaults = defaults, !defaults.bool(forKey: firstOpenKey) { if !isExistingUser() { firstAppOpen = true } defaults.set(true, forKey: firstOpenKey) defaults.synchronize() } if let defaults = defaults, let infoDict = Bundle.main.infoDictionary { let appVersionKey = "MPAppVersion" let appVersionValue = infoDict["CFBundleShortVersionString"] let savedVersionValue = defaults.string(forKey: appVersionKey) if let appVersionValue = appVersionValue as? String, let savedVersionValue = savedVersionValue, appVersionValue.compare(savedVersionValue, options: .numeric, range: nil, locale: nil) == .orderedDescending { delegate?.track(event: "$ae_updated", properties: ["$ae_updated_version": appVersionValue]) defaults.set(appVersionValue, forKey: appVersionKey) defaults.synchronize() } else if savedVersionValue == nil { defaults.set(appVersionValue, forKey: appVersionKey) defaults.synchronize() } } NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) #if DECIDE SKPaymentQueue.default().add(self) DispatchQueue.main.async { [weak self] in guard let self = self else { return } if self.automaticPushTracking { self.setupAutomaticPushTracking() } } #endif } @objc func appWillResignActive(_ notification: Notification) { sessionLength = roundOneDigit(num: Date().timeIntervalSince1970 - sessionStartTime) if sessionLength >= Double(minimumSessionDuration / 1000) && sessionLength <= Double(maximumSessionDuration / 1000) { delegate?.track(event: "$ae_session", properties: ["$ae_session_length": sessionLength]) delegate?.increment(property: "$ae_total_app_sessions", by: 1) delegate?.increment(property: "$ae_total_app_session_length", by: sessionLength) } } @objc func appDidBecomeActive(_ notification: Notification) { sessionStartTime = Date().timeIntervalSince1970 if firstAppOpen { if let allInstances = MixpanelManager.sharedInstance.getAllInstances() { for instance in allInstances { instance.track(event: "$ae_first_open", properties: ["$ae_first_app_open_date": Date()]) instance.setOnce(properties: ["$ae_first_app_open_date": Date()]) } } firstAppOpen = false } } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { var productsRequest = SKProductsRequest() var productIdentifiers: Set<String> = [] awaitingTransactionsWriteLock.sync { for transaction:AnyObject in transactions { if let trans = transaction as? SKPaymentTransaction { switch trans.transactionState { case .purchased: productIdentifiers.insert(trans.payment.productIdentifier) awaitingTransactions[trans.payment.productIdentifier] = trans break case .failed: break case .restored: break default: break } } } } if productIdentifiers.count > 0 { productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers) productsRequest.delegate = self productsRequest.start() } } func roundOneDigit(num: TimeInterval) -> TimeInterval { return round(num * 10.0) / 10.0 } func isExistingUser() -> Bool { do { if let searchPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).last { let pathContents = try FileManager.default.contentsOfDirectory(atPath: searchPath) for path in pathContents { if path.hasPrefix("mixpanel-") { return true } } } } catch { return false } return false } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { awaitingTransactionsWriteLock.sync { for product in response.products { if let trans = awaitingTransactions[product.productIdentifier] { delegate?.track(event: "$ae_iap", properties: ["$ae_iap_price": "\(product.price)", "$ae_iap_quantity": trans.payment.quantity, "$ae_iap_name": product.productIdentifier]) awaitingTransactions.removeValue(forKey: product.productIdentifier) } } } } #if DECIDE func setupAutomaticPushTracking() { guard let appDelegate = MixpanelInstance.sharedUIApplication()?.delegate else { return } var selector: Selector? = nil var newSelector: Selector? = nil let aClass: AnyClass = type(of: appDelegate) var newClass: AnyClass? if #available(iOS 10.0, *), let UNDelegate = UNUserNotificationCenter.current().delegate { newClass = type(of: UNDelegate) } else if #available(iOS 10.0, *) { UNUserNotificationCenter.current().addDelegateObserver(ae: self) hasAddedObserver = true } if let newClass = newClass, #available(iOS 10.0, *), class_getInstanceMethod(newClass, NSSelectorFromString("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")) != nil { selector = NSSelectorFromString("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:") newSelector = #selector(NSObject.mp_userNotificationCenter(_:newDidReceive:withCompletionHandler:)) } else if class_getInstanceMethod(aClass, NSSelectorFromString("application:didReceiveRemoteNotification:fetchCompletionHandler:")) != nil { selector = NSSelectorFromString("application:didReceiveRemoteNotification:fetchCompletionHandler:") newSelector = #selector(UIResponder.mp_application(_:newDidReceiveRemoteNotification:fetchCompletionHandler:)) } else if class_getInstanceMethod(aClass, NSSelectorFromString("application:didReceiveRemoteNotification:")) != nil { selector = NSSelectorFromString("application:didReceiveRemoteNotification:") newSelector = #selector(UIResponder.mp_application(_:newDidReceiveRemoteNotification:)) } if let selector = selector, let newSelector = newSelector { let block = { (view: AnyObject?, command: Selector, param1: AnyObject?, param2: AnyObject?) in if let param2 = param2 as? [AnyHashable: Any] { self.delegate?.trackPushNotification(param2, event: "$campaign_received", properties: [:]) } } Swizzler.swizzleSelector(selector, withSelector: newSelector, for: newClass ?? aClass, name: "notification opened", block: block) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if #available(iOS 10.0, *), keyPath == "delegate", let UNDelegate = UNUserNotificationCenter.current().delegate { let delegateClass: AnyClass = type(of: UNDelegate) if class_getInstanceMethod(delegateClass, NSSelectorFromString("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")) != nil { let selector = NSSelectorFromString("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:") let newSelector = #selector(NSObject.mp_userNotificationCenter(_:newDidReceive:withCompletionHandler:)) let block = { (view: AnyObject?, command: Selector, param1: AnyObject?, param2: AnyObject?) in if let param2 = param2 as? [AnyHashable: Any] { self.delegate?.trackPushNotification(param2, event: "$campaign_received", properties: [:]) } } Swizzler.swizzleSelector(selector, withSelector: newSelector, for: delegateClass, name: "notification opened", block: block) } } } deinit { if #available(iOS 10.0, *), hasAddedObserver { UNUserNotificationCenter.current().removeDelegateObserver(ae: self) } } #endif // DECIDE } #if DECIDE @available(iOS 10.0, *) extension UNUserNotificationCenter { func addDelegateObserver(ae: AutomaticEvents) { addObserver(ae, forKeyPath: #keyPath(delegate), options: [.old, .new], context: nil) } func removeDelegateObserver(ae: AutomaticEvents) { removeObserver(ae, forKeyPath: #keyPath(delegate)) } } extension UIResponder { @objc func mp_application(_ application: UIApplication, newDidReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Swift.Void) { let originalSelector = NSSelectorFromString("application:didReceiveRemoteNotification:fetchCompletionHandler:") if let originalMethod = class_getInstanceMethod(type(of: self), originalSelector), let swizzle = Swizzler.swizzles[originalMethod] { typealias MyCFunction = @convention(c) (AnyObject, Selector, UIApplication, NSDictionary, @escaping (UIBackgroundFetchResult) -> Void) -> Void let curriedImplementation = unsafeBitCast(swizzle.originalMethod, to: MyCFunction.self) curriedImplementation(self, originalSelector, application, userInfo as NSDictionary, completionHandler) for (_, block) in swizzle.blocks { block(self, swizzle.selector, application as AnyObject?, userInfo as AnyObject?) } } } @objc func mp_application(_ application: UIApplication, newDidReceiveRemoteNotification userInfo: [AnyHashable : Any]) { let originalSelector = NSSelectorFromString("application:didReceiveRemoteNotification:") if let originalMethod = class_getInstanceMethod(type(of: self), originalSelector), let swizzle = Swizzler.swizzles[originalMethod] { typealias MyCFunction = @convention(c) (AnyObject, Selector, UIApplication, NSDictionary) -> Void let curriedImplementation = unsafeBitCast(swizzle.originalMethod, to: MyCFunction.self) curriedImplementation(self, originalSelector, application, userInfo as NSDictionary) for (_, block) in swizzle.blocks { block(self, swizzle.selector, application as AnyObject?, userInfo as AnyObject?) } } } } @available(iOS 10.0, *) extension NSObject { @objc func mp_userNotificationCenter(_ center: UNUserNotificationCenter, newDidReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let originalSelector = NSSelectorFromString("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:") if let originalMethod = class_getInstanceMethod(type(of: self), originalSelector), let swizzle = Swizzler.swizzles[originalMethod] { typealias MyCFunction = @convention(c) (AnyObject, Selector, UNUserNotificationCenter, UNNotificationResponse, @escaping () -> Void) -> Void let curriedImplementation = unsafeBitCast(swizzle.originalMethod, to: MyCFunction.self) curriedImplementation(self, originalSelector, center, response, completionHandler) for (_, block) in swizzle.blocks { block(self, swizzle.selector, center as AnyObject?, response.notification.request.content.userInfo as AnyObject?) } } } } #endif // DECIDE #endif
46.102167
217
0.62568
1c8e800bce3b344ba20899b3357c05e61c81d1c5
696
// // Notification.swift // tl2swift // // Created by Code Generator // import Foundation /// Contains information about a notification public struct Notification: Codable { /// Notification date public let date: Int /// Unique persistent identifier of this notification public let id: Int /// True, if the notification was initially silent public let isSilent: Bool /// Notification type public let type: NotificationType public init( date: Int, id: Int, isSilent: Bool, type: NotificationType ) { self.date = date self.id = id self.isSilent = isSilent self.type = type } }
17.4
57
0.62069
2639039f682a59f3d4a1151e8ae5f1ddc5ebef33
13,883
// // OKTradeFeeViewController.swift // OneKey // // Created by xuxiwen on 2021/3/21. // Copyright © 2021 Onekey. All rights reserved. // import UIKit import Reusable import PanModal enum OKTradeFeeSelect { case slow case medium case fast case custum } class OKTradeFeeViewController: PanModalViewController { @IBOutlet weak var navView: OKModalNavView! @IBOutlet weak var slowFeeView: UIView! @IBOutlet weak var slowFeeSpeed: UILabel! @IBOutlet weak var slowFeeSelected: UIImageView! @IBOutlet weak var slowFeeCoinValue: UILabel! @IBOutlet weak var slowFeeRmbValue: UILabel! @IBOutlet weak var slowFeeTimeValue: UILabel! @IBOutlet weak var mediumFeeView: UIView! @IBOutlet weak var mediumFeeSpeed: UILabel! @IBOutlet weak var mediumFeeSelected: UIImageView! @IBOutlet weak var mediumFeeCoinValue: UILabel! @IBOutlet weak var mediumFeeRmbValue: UILabel! @IBOutlet weak var mediumFeeTimeValue: UILabel! @IBOutlet weak var fastFeeView: UIView! @IBOutlet weak var fastFeeSpeed: UILabel! @IBOutlet weak var fastFeeSelected: UIImageView! @IBOutlet weak var fastFeeCoinValue: UILabel! @IBOutlet weak var fastFeeRmbValue: UILabel! @IBOutlet weak var fastFeeTimeValue: UILabel! @IBOutlet weak var custumFeeView: UIView! @IBOutlet weak var custumFeeTitle: UILabel! @IBOutlet weak var custumFeeTime: UILabel! @IBOutlet weak var custumFeeValue: UILabel! @IBOutlet weak var custumFeeSelected: UIImageView! @IBOutlet weak var custunFeeGasTitle: UILabel! @IBOutlet weak var custunFeeGasTextFiled: UITextField! @IBOutlet weak var custunFeeGasPriceTitle: UILabel! @IBOutlet weak var custunFeeGasPriceTextFiled: UITextField! @IBOutlet weak var custumFeeFoldView: UIView! @IBOutlet weak var custumFeeFoldTitle: UILabel! @IBOutlet weak var custumFeeTipLabel: UILabel! var model: OKDefaultFeeInfoModel? var selectGasType: OKTradeFeeSelect = .medium var feeModel: OKSendFeeModel? var alertTipsContent: String = "" var callBackFee: ((OKTradeFeeSelect, OKSendFeeModel?) -> Void)? private var defaultFeeModel: OKDefaultFeeInfoModel? private var perTime: NSDecimalNumber? private var perRmb: NSDecimalNumber? private var perFee: NSDecimalNumber? private var allValue: NSDecimalNumber? private var keyboardDistance: CGFloat = 10 override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) IQKeyboardManager.shared().keyboardDistanceFromTextField = keyboardDistance } override func viewDidLoad() { super.viewDidLoad() keyboardDistance = IQKeyboardManager.shared().keyboardDistanceFromTextField IQKeyboardManager.shared().keyboardDistanceFromTextField = 30 navView.setNavTitle(string: "Miners fee".localized) slowFeeSpeed.text = "slow".localized mediumFeeSpeed.text = "recommended".localized fastFeeSpeed.text = "fast".localized custumFeeTitle.text = "The custom".localized custumFeeFoldTitle.text = "The custom".localized custunFeeGasTitle.text = "Gas Price (GWEI)" custunFeeGasPriceTitle.text = "Gas" setDefaultValue() custunFeeGasTextFiled.keyboardType = .numberPad custunFeeGasPriceTextFiled.keyboardType = .numberPad custunFeeGasTextFiled.addTarget(self, action: #selector(didChangeText), for: .editingChanged) custunFeeGasPriceTextFiled.addTarget(self, action: #selector(didChangeText), for: .editingChanged) navView.setNavPop { [weak self] in guard let self = self else { return } self.popAction() } slowFeeView.addTapGestureRecognizer { [weak self] in guard let self = self else { return } self.updateSelectedUI(type: .slow) } mediumFeeView.addTapGestureRecognizer { [weak self] in guard let self = self else { return } self.updateSelectedUI(type: .medium) } fastFeeView.addTapGestureRecognizer { [weak self] in guard let self = self else { return } self.updateSelectedUI(type: .fast) } custumFeeFoldView.addTapGestureRecognizer { [weak self] in guard let self = self else { return } self.selectGasType = .custum self.updateSelectedUI(type: .custum) } custunFeeGasTextFiled.delegate = self custunFeeGasPriceTextFiled.delegate = self if let model = model { updateDefaultFeeInfo(model: model) } updateSelectedUI(type: selectGasType) } private func setDefaultValue() { slowFeeCoinValue.text = "--" slowFeeRmbValue.text = "--" slowFeeTimeValue.text = "--" mediumFeeCoinValue.text = "--" mediumFeeRmbValue.text = "--" mediumFeeTimeValue.text = "--" fastFeeCoinValue.text = "--" fastFeeRmbValue.text = "--" fastFeeTimeValue.text = "--" custumFeeValue.text = "--" custumFeeTime.text = "--" custunFeeGasTextFiled.text = "0" custunFeeGasPriceTextFiled.text = "0" } func updateDefaultFeeInfo(model: OKDefaultFeeInfoModel) { defaultFeeModel = model let token = tokenName() slowFeeCoinValue.text = model.slow.fee + " " + token slowFeeRmbValue.text = model.slow.fiat slowFeeTimeValue.text = "About 0 minutes".localized.replacingOccurrences(of: "0", with: " \(model.slow.time) ") mediumFeeCoinValue.text = model.normal.fee + " " + token mediumFeeRmbValue.text = model.normal.fiat mediumFeeTimeValue.text = "About 0 minutes".localized.replacingOccurrences(of: "0", with: " \(model.normal.time) ") fastFeeCoinValue.text = model.fast.fee + " " + token fastFeeRmbValue.text = model.fast.fiat fastFeeTimeValue.text = "About 0 minutes".localized.replacingOccurrences(of: "0", with: " \(model.fast.time) ") if self.selectGasType == .custum, let m = feeModel { custunFeeGasTextFiled.text = m.gas_limit custunFeeGasPriceTextFiled.text = m.gas_price } else { custunFeeGasTextFiled.text = model.normal.gas_limit custunFeeGasPriceTextFiled.text = model.normal.gas_price } let gasLimit = NSDecimalNumber(string: model.normal.gas_limit) let gasPrice = NSDecimalNumber(string: model.normal.gas_price) allValue = gasLimit.multiplying(by: gasPrice) perTime = NSDecimalNumber(string: model.normal.time) perRmb = NSDecimalNumber(string: model.normal.fiat.split(" ").first ?? "0") perFee = NSDecimalNumber(string: model.normal.fee) } private func updateSelectedUI(type: OKTradeFeeSelect) { selectGasType = type custumFeeTipLabel.text = "" let feeViews = [slowFeeView, mediumFeeView, fastFeeView] let selectedViews = [slowFeeSelected, mediumFeeSelected, fastFeeSelected] var highlightView: UIView! var selectedView: UIView! switch selectGasType { case .slow: highlightView = slowFeeView selectedView = slowFeeSelected feeModel = defaultFeeModel?.slow case .medium: highlightView = mediumFeeView selectedView = mediumFeeSelected feeModel = defaultFeeModel?.normal case .fast: highlightView = fastFeeView selectedView = fastFeeSelected feeModel = defaultFeeModel?.fast break case .custum: highlightView = custumFeeFoldView selectedView = custumFeeSelected didChangeText() break } feeViews.forEach { $0?.borderColor = highlightView == $0 ? UIColor.tintBrand() : UIColor.fg_B03() } selectedViews.forEach { $0?.isHidden = selectedView != $0 } let isSelectedCustum = highlightView == custumFeeFoldView custumFeeView.isHidden = !isSelectedCustum custumFeeFoldView.isHidden = isSelectedCustum } private func popAction() { func callBack() { if (model != nil) { callBackFee?(self.selectGasType, self.feeModel) } navigationController?.popViewController(animated: true) } if (alertTipsContent.isEmpty || selectGasType != .custum) { callBack() } else { let alert = UIAlertController(title: "prompt".localized, message: self.alertTipsContent, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "cancel".localized, style: .cancel, handler: { _ in })) alert.addAction(UIAlertAction(title: "Continue".localized, style: .default, handler: { _ in callBack() })) present(alert, animated: true, completion: nil) } } // MARK: - Pan Modal Presentable override var shortFormHeight: PanModalHeight { .contentHeight(500) } override var longFormHeight: PanModalHeight { .maxHeight } override func shouldRespond(to panModalGestureRecognizer: UIPanGestureRecognizer) -> Bool { true } @objc private func didChangeText() { updateCustumValue() } private func updateCustumValue() { func rest() { custumFeeValue.text = "--" custumFeeTime.text = "--" custumFeeTipLabel.text = "" alertTipsContent = "" selectGasType = .medium custunFeeGasTextFiled.textColor = .fg_B01() custunFeeGasPriceTextFiled.textColor = .fg_B01() } rest() guard let model = model else { return } if let gasPrice = custunFeeGasPriceTextFiled.text, !gasPrice.isEmpty, let gas = custunFeeGasTextFiled.text, !gas.isEmpty, let allValue = allValue, let perTime = perTime, let perRmb = perRmb, let perFee = perFee { let gasLimitDecimalNumber = NSDecimalNumber(string:gas) let gasPriceDecimalNumber = NSDecimalNumber(string: gasPrice) if gasLimitDecimalNumber.floatValue < (Float(model.normal.gas_limit) ?? 0) { custunFeeGasTextFiled.textColor = .tintRed() alertTipsContent = "Too little Gas Limit will cause the transaction to fail. Do you want to continue?".localized custumFeeTipLabel.text = String(format: "The minimum gas limit %@".localized, String(model.normal.gas_limit)) } if gasLimitDecimalNumber.floatValue > (Float(model.normal.gas_limit) ?? 0) * 10 { custunFeeGasTextFiled.textColor = .tintRed() alertTipsContent = "Gas Limit is too much, do you want to continue?".localized custumFeeTipLabel.text = String(format: "The maximum gas limit %@".localized, String((Int(model.normal.gas_limit) ?? 0) * 10)) } if gasPriceDecimalNumber.floatValue < 1 { custunFeeGasPriceTextFiled.textColor = .tintRed() alertTipsContent = "Too little Gas Price will cause the transaction to fail. Do you want to continue?".localized custumFeeTipLabel.text = String(format: "The minimum limit of Gas Price %@ gwei".localized, "1") } if gasPriceDecimalNumber.floatValue > (Float(model.fast.gas_price) ?? 0) * 10 { custunFeeGasPriceTextFiled.textColor = .tintRed() alertTipsContent = "Gas Price is too much, do you want to continue?".localized custumFeeTipLabel.text = String(format: "Gas Price maximum limit %@ gwei".localized, String((Int(model.fast.gas_price) ?? 0) * 10)) } if gasPrice == "0" || gas == "0" { return } func behavior(scale: Int16) -> NSDecimalNumberHandler { return NSDecimalNumberHandler( roundingMode: .down, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true ) } let ratio = gasLimitDecimalNumber.multiplying(by: gasPriceDecimalNumber).dividing(by: allValue) let time = NSDecimalNumber(string:"1").dividing(by: ratio).multiplying(by: perTime, withBehavior: behavior(scale: 0)).intValue let rmb = ratio.multiplying(by: perRmb, withBehavior: behavior(scale: 2)).stringValue let fee = ratio.multiplying(by: perFee, withBehavior: behavior(scale: 9)).stringValue custumFeeTime.text = "About 0 minutes".localized.replacingOccurrences(of: "0", with: " \(time) ") custumFeeValue.text = fee + " \(tokenName())" + " ≈ ¥" + rmb let model = OKSendFeeModel() model.fee = fee model.fiat = rmb model.gas_price = gasPrice model.gas_limit = gas model.time = String(time) selectGasType = .custum self.feeModel = model } } private func tokenName() -> String { return OKWalletManager.sharedInstance().currentWalletInfo?.coinType.chainNameToTokenName() ?? "" } } extension OKTradeFeeViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { (self.navigationController as? PanModalNavViewController)?.panModalTransition(to: .longForm) return true } } extension OKTradeFeeViewController: StoryboardSceneBased { static let sceneStoryboard = UIStoryboard(name: "Tab_Discover", bundle: nil) static var sceneIdentifier = "OKTradeFeeViewController" }
39.552707
147
0.644169
1d3c1fd3ce6be4c8328db18282faf7e96a8028a5
246
protocol OverloadedFunctionExample { func answers(for id: String) func answers(in ids: [String]) func answers(for id: String, archived: Bool) func answers(for id: String, archived: Bool) -> Int var answers: [String] { get } }
30.75
55
0.678862
612b0d1a4d7c165227a0022ea7b3d077a813fde1
1,956
// // ServiceEndpoint.swift // FilmInspector // // Created by Paul Jackson on 31/12/2020. // import Foundation /// Handles constructing URLs for remote server calls. enum ServiceEndpoint { case search(text: String) case detail(id: String) /// Returns a URL instance based on the endpoint request type. var url: URL { switch self { case .search(let text): return buildURL(key: "s", value: text) case .detail(let id): return buildURL(key: "i", value: id) } } /// Builds a URL for the remote request type. /// /// - Parameters: /// - key: Query string key name. /// - value: Query string key value. /// - Returns: URL instance. private func buildURL(key: String, value: String) -> URL { // The API calls to the OMDB API are all GET requests where // the search and item calls are only differentiated by a // single query string parameter: "s" for searching and "i" // for detailed information calls. // // All calls require an API Key obtained from OMDB directly. // The FREE account allows up to 1000 requests per day. var components = URLComponents(string: baseURL.absoluteString)! components.queryItems = [ .init(name: key, value: value), .init(name: "apikey", value: apiKey) ] return components.url! } private var baseURL: URL { URL(string: "https://www.omdbapi.com/")! } // My personal API Key has been hidden from source control by adding // a template Constants file, which was initially tracked, and then // I've removed tracking with the command: // // `git update-index --skip-worktree <file>` // // Where I removed the Constants file from the index and can now update // freely locally without the changes being tracked. private var apiKey: String { Constants.apiKey } }
31.548387
75
0.621677
119d67335c8e82d1f513f8d7b00d9d0a1ecfebf3
4,018
/* Copyright (c) 2019, Apple Inc. 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(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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 OWNER 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 internal class OCKScatterLayer: OCKCartesianCoordinatesLayer, OCKGradientPlotable { internal let gradientLayer = CAGradientLayer() internal let pointsLayer = CAShapeLayer() internal var markerSize: CGFloat = 3.0 { didSet { pointsLayer.path = makePath(points: points) } } internal var startColor: UIColor = .blue { didSet { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] } } internal var endColor: UIColor = .red { didSet { gradientLayer.colors = [startColor.cgColor, endColor.cgColor] } } internal var offset: CGSize = .zero { didSet { setNeedsLayout() } } internal override init() { super.init() setupSublayers() } override init(layer: Any) { super.init(layer: layer) setupSublayers() } required internal init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSublayers() } private func setupSublayers() { pointsLayer.fillColor = UIColor.black.cgColor pointsLayer.strokeColor = nil addSublayer(pointsLayer) gradientLayer.colors = [startColor.cgColor, endColor.cgColor] gradientLayer.startPoint = CGPoint(x: 0.5, y: 1) gradientLayer.endPoint = CGPoint(x: 0.5, y: 0) gradientLayer.mask = pointsLayer addSublayer(gradientLayer) } internal override func layoutSublayers() { super.layoutSublayers() drawPoints(points) } override func animateInGraphCoordinates(from oldPoints: [CGPoint], to newPoints: [CGPoint]) { let grow = CABasicAnimation(keyPath: #keyPath(CAShapeLayer.path)) grow.fromValue = pointsLayer.presentation()?.path ?? makePath(points: oldPoints) grow.toValue = makePath(points: newPoints) grow.duration = 1.0 pointsLayer.add(grow, forKey: "grow") } internal func makePath(points: [CGPoint]) -> CGPath { let path = UIBezierPath() points.forEach { point in let adjustedPoint = CGPoint(x: point.x + offset.width, y: point.y + offset.height) path.move(to: adjustedPoint) path.addArc(withCenter: adjustedPoint, radius: markerSize, startAngle: 0, endAngle: 2 * .pi, clockwise: true) } return path.cgPath } }
38.634615
121
0.698855
9b66f3321b36ac0795f7749b016b8ca818e599d3
2,618
import CXShim import CXTestUtility import Foundation import Nimble import Quick class ReceiveOnSpec: QuickSpec { override func spec() { // MARK: - Relay describe("Relay") { // MARK: 1.1 should receive events on the specified queue it("should receive events on the specified queue") { let subject = PassthroughSubject<Int, Never>() let scheduler = DispatchQueue(label: UUID().uuidString).cx let pub = subject.receive(on: scheduler) var received = ( subscription: false, value: false, completion: false ) let sub = TracingSubscriber<Int, Never>(receiveSubscription: { s in s.request(.max(100)) received.subscription = true // Versioning: see VersioningReceiveOnSpec // expect(scheduler.isCurrent) == false }, receiveValue: { _ in received.value = true expect(scheduler.base.isCurrent) == true return .none }, receiveCompletion: { _ in received.completion = true expect(scheduler.base.isCurrent) == true }) pub.subscribe(sub) // Versioning: see VersioningReceiveOnSpec expect(sub.subscription).toEventuallyNot(beNil()) subject.send(contentsOf: 0..<1000) subject.send(completion: .finished) expect([ received.subscription, received.value, received.completion ]).toEventually(equal([true, true, true])) } // MARK: 1.2 should send values as many as demand it("should send values as many as demand") { let subject = PassthroughSubject<Int, Never>() let scheduler = DispatchQueue(label: UUID().uuidString).cx let pub = subject.receive(on: scheduler) let sub = pub.subscribeTracingSubscriber(initialDemand: .max(10)) expect(sub.subscription).toEventuallyNot(beNil()) subject.send(contentsOf: 0..<100) expect(sub.eventsWithoutSubscription.count).toEventually(equal(10)) } } } }
36.873239
83
0.488923
0a204e36485dea7bf82375481147273f447286cb
2,276
// // ViewController.swift // SwifterUI // // Created by Brandon Maldonado Alonso on 17/12/17. // Copyright © 2017 Brandon Maldonado Alonso. All rights reserved. // import UIKit import DeepDiff extension String: SFDataType { } class Model { let names = SFDataManager<String>() init() { names.update(data: [["Brandon", "Maldonado", "Alonso"], ["Jula"], ["Celina"]]) DispatchQueue.delay(by: 3, dispatchLevel: .main) { self.names.update(data: [["Celina"], ["Jula"], ["Brandon", "Maldonado", "Alonso"]]) } } } class View: SFView { lazy var tableView: SFTableView = { let view = SFTableView(automaticallyAdjustsColorStyle: self.automaticallyAdjustsColorStyle, style: .grouped) view.translatesAutoresizingMaskIntoConstraints = false return view }() override func prepareSubviews() { addSubview(tableView) super.prepareSubviews() } override func setConstraints() { tableView.clipSides() super.setConstraints() } } class ViewController: SFViewController, SFVideoPlayerDelegate { let model = Model() let adapter = SFTableAdapter<String, SFTableViewCell, SFTableViewHeaderView, SFTableViewFooterView>() lazy var backgroundView: View = { let view = View() view.translatesAutoresizingMaskIntoConstraints = false return view }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(backgroundView) backgroundView.clipSides() adapter.configure(tableView: backgroundView.tableView, dataManager: model.names) adapter.delegate = self } } extension ViewController: SFTableAdapterDelegate { var useCustomHeader: Bool { return true } func prepareHeader<DataType>(_ view: SFTableViewHeaderView, with data: SFDataSection<DataType>, index: Int) where DataType: Hashable { view.textLabel?.text = "Prueba - \(index)" } func prepareCell<DataType>(_ cell: SFTableViewCell, at indexPath: IndexPath, with data: DataType) where DataType: Hashable { guard let name = data as? String else { return } cell.textLabel?.text = name } }
26.776471
138
0.64587
e486b2a9779f1530ef5b083ac96b4013d6200e9e
816
// // AppDelegate.swift // Demo // // Created by Suguru Kishimoto on 2/18/17. // Copyright © 2017 Suguru Kishimoto. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
22.666667
143
0.732843
462074f06574eb9c269766e5a0120c58fcbbd329
17,971
//////////////////////////////////////////////////////////////////////////// // // Copyright 2021 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift class SwiftUISyncTestHostUITests: SwiftSyncTestCase { override func tearDown() { logoutAllUsers() application.terminate() super.tearDown() } override func setUp() { super.setUp() application.launchEnvironment["app_id"] = appId } // Application private let application = XCUIApplication() private func openRealm(configuration: Realm.Configuration, for user: User) throws -> Realm { var configuration = configuration if configuration.objectTypes == nil { configuration.objectTypes = [SwiftPerson.self] } let realm = try Realm(configuration: configuration) waitForDownloads(for: realm) return realm } @discardableResult private func populateForEmail(_ email: String, n: Int) throws -> User { let user = logInUser(for: basicCredentials(name: email, register: true)) let config = user.configuration(partitionValue: user.id) let realm = try openRealm(configuration: config, for: user) try realm.write { for _ in (1...n) { realm.add(SwiftPerson(firstName: randomString(7), lastName: randomString(7))) } } waitForUploads(for: realm) return user } // Login for given user private enum UserType: Int { case first = 1 case second = 2 } private func loginUser(_ type: UserType) { let loginButton = application.buttons["login_button_\(type.rawValue)"] XCTAssertTrue(loginButton.waitForExistence(timeout: 2)) loginButton.tap() let loggingView = application.staticTexts["logged_view"] XCTAssertTrue(loggingView.waitForExistence(timeout: 6)) } private func asyncOpen() { loginUser(.first) // Query for button to start syncing let syncButtonView = application.buttons["sync_button"] XCTAssertTrue(syncButtonView.waitForExistence(timeout: 2)) syncButtonView.tap() } private func logoutAllUsers() { let loginButton = application.buttons["logout_users_button"] XCTAssertTrue(loginButton.waitForExistence(timeout: 2)) loginButton.tap() } } // MARK: - AsyncOpen extension SwiftUISyncTestHostUITests { func testDownloadRealmAsyncOpenApp() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" let user = try populateForEmail(email, n: 1) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "async_open" application.launchEnvironment["partition_value"] = user.id application.launch() asyncOpen() // Test progress is greater than 0 let progressView = application.staticTexts["progress_text_view"] XCTAssertTrue(progressView.waitForExistence(timeout: 2)) let progressValue = progressView.value as! String XCTAssertTrue(Int64(progressValue)! > 0) // Query for button to navigate to next view let nextViewView = application.buttons["show_list_button_view"] nextViewView.tap() // Test show ListView after syncing realm environment let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 1) } func testDownloadRealmAsyncOpenAppWithEnvironmentPartitionValue() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 2) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "async_open_environment_partition" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) } func testDownloadRealmAsyncOpenAppWithEnvironmentConfiguration() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 3) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "async_open_environment_configuration" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 3) } func testObservedResults() throws { // This test ensures that `@ObservedResults` correctly observes both local // and sync changes to a collection. let partitionValue = "test" let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" let email2 = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" let user1 = logInUser(for: basicCredentials(name: email, register: true)) let user2 = logInUser(for: basicCredentials(name: email2, register: true)) let config1 = user1.configuration(partitionValue: partitionValue) let config2 = user2.configuration(partitionValue: partitionValue) let realm = try Realm(configuration: config1) try realm.write { realm.add(SwiftPerson(firstName: "Joe", lastName: "Blogs")) realm.add(SwiftPerson(firstName: "Jane", lastName: "Doe")) } user1.waitForUpload(toFinish: partitionValue) application.launchEnvironment["email1"] = email application.launchEnvironment["email2"] = email2 application.launchEnvironment["async_view_type"] = "async_open_environment_partition" application.launchEnvironment["partition_value"] = partitionValue application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) loginUser(.second) // Query for button to start syncing let syncButtonView = application.buttons["sync_button"] XCTAssertTrue(syncButtonView.waitForExistence(timeout: 2)) syncButtonView.tap() // Test show ListView after logging new user XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) let realm2 = try Realm(configuration: config2) waitForDownloads(for: realm2) try! realm2.write { realm2.add(SwiftPerson(firstName: "Joe2", lastName: "Blogs")) realm2.add(SwiftPerson(firstName: "Jane2", lastName: "Doe")) } user2.waitForUpload(toFinish: partitionValue) XCTAssertEqual(table.cells.count, 4) loginUser(.first) waitForDownloads(for: realm) // Make sure the first user also has 4 SwiftPerson's XCTAssertTrue(syncButtonView.waitForExistence(timeout: 2)) syncButtonView.tap() XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 4) } func testAsyncOpenMultiUser() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 2) let email2 = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email2, n: 1) application.launchEnvironment["email1"] = email application.launchEnvironment["email2"] = email2 application.launchEnvironment["async_view_type"] = "async_open_environment_partition" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) loginUser(.second) // Query for button to start syncing let syncButtonView = application.buttons["sync_button"] XCTAssertTrue(syncButtonView.waitForExistence(timeout: 2)) syncButtonView.tap() // Test show ListView after logging new user XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 1) } func testAsyncOpenAndLogout() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 2) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "async_open_environment_partition" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) let logoutButtonView = application.buttons["logout_button"] XCTAssertTrue(logoutButtonView.waitForExistence(timeout: 2)) logoutButtonView.tap() let waitingUserView = application.staticTexts["waiting_user_view"] XCTAssertTrue(waitingUserView.waitForExistence(timeout: 2)) } } // MARK: - AutoOpen extension SwiftUISyncTestHostUITests { func testDownloadRealmAutoOpenApp() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" let user = try populateForEmail(email, n: 1) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "auto_open" application.launchEnvironment["partition_value"] = user.id application.launch() // Test that the user is already logged in asyncOpen() // Test progress is greater than 0 let progressView = application.staticTexts["progress_text_view"] XCTAssertTrue(progressView.waitForExistence(timeout: 2)) let progressValue = progressView.value as! String XCTAssertTrue(Int64(progressValue)! > 0) // Query for button to navigate to next view let nextViewView = application.buttons["show_list_button_view"] nextViewView.tap() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 1) } func testDownloadRealmAutoOpenAppWithEnvironmentPartitionValue() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 2) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "auto_open_environment_partition" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) } func testDownloadRealmAutoOpenAppWithEnvironmentConfiguration() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 3) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "auto_open_environment_configuration" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 3) } func testAutoOpenMultiUser() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 2) let email2 = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email2, n: 1) application.launchEnvironment["email1"] = email application.launchEnvironment["email2"] = email2 application.launchEnvironment["async_view_type"] = "auto_open_environment_partition" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) loginUser(.second) // Query for button to start syncing let syncButtonView = application.buttons["sync_button"] XCTAssertTrue(syncButtonView.waitForExistence(timeout: 2)) syncButtonView.tap() // Test show ListView after logging new user XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 1) } func testAutoOpenAndLogout() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateForEmail(email, n: 2) application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "auto_open_environment_partition" application.launch() asyncOpen() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 2) let logoutButtonView = application.buttons["logout_button"] XCTAssertTrue(logoutButtonView.waitForExistence(timeout: 2)) logoutButtonView.tap() let waitingUserView = application.staticTexts["waiting_user_view"] XCTAssertTrue(waitingUserView.waitForExistence(timeout: 2)) } } // MARK: - Flexible Sync extension SwiftUISyncTestHostUITests { private func populateFlexibleSyncForEmail(_ email: String, n: Int, _ block: @escaping (Realm) -> Void) throws { let user = logInUser(for: basicCredentials(name: email, register: true, app: flexibleSyncApp), app: flexibleSyncApp) let config = user.flexibleSyncConfiguration() let realm = try Realm(configuration: config) let subs = realm.subscriptions let ex = expectation(description: "state change complete") subs.write({ subs.append(QuerySubscription<SwiftPerson>(name: "person_age", where: "TRUEPREDICATE")) }, onComplete: { error in if error == nil { ex.fulfill() } else { XCTFail("Subscription Set could not complete with \(error!)") } }) waitForExpectations(timeout: 20.0, handler: nil) try realm.write { block(realm) } waitForUploads(for: realm) } func testFlexibleSyncAsyncOpenRoundTrip() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateFlexibleSyncForEmail(email, n: 10) { realm in for index in (1...10) { realm.add(SwiftPerson(firstName: "\(#function)", lastName: "Smith", age: index)) } } application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "async_open_flexible_sync" // Override appId for flexible app Id application.launchEnvironment["app_id"] = flexibleSyncAppId application.launchEnvironment["firstName"] = "\(#function)" application.launch() asyncOpen() // Query for button to navigate to next view let nextViewView = application.buttons["show_list_button_view"] XCTAssertTrue(nextViewView.waitForExistence(timeout: 10)) nextViewView.tap() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 5) } func testFlexibleSyncAutoOpenRoundTrip() throws { let email = "realm_tests_do_autoverify\(randomString(7))@\(randomString(7)).com" try populateFlexibleSyncForEmail(email, n: 10) { realm in for index in (1...20) { realm.add(SwiftPerson(firstName: "\(#function)", lastName: "Smith", age: index)) } } application.launchEnvironment["email1"] = email application.launchEnvironment["async_view_type"] = "auto_open_flexible_sync" // Override appId for flexible app Id application.launchEnvironment["app_id"] = flexibleSyncAppId application.launchEnvironment["firstName"] = "\(#function)" application.launch() asyncOpen() // Query for button to navigate to next view let nextViewView = application.buttons["show_list_button_view"] XCTAssertTrue(nextViewView.waitForExistence(timeout: 10)) nextViewView.tap() // Test show ListView after syncing realm let table = application.tables.firstMatch XCTAssertTrue(table.waitForExistence(timeout: 6)) XCTAssertEqual(table.cells.count, 18) } }
38.481799
124
0.670024
462566708d7cf1a0b4ab0806bffa60c3bf01da08
2,219
// // AppDelegate.swift // InstantDoc // // Created by Kartik's MacG on 11/05/18. // Copyright © 2018 kaTRIX. All rights reserved. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.285714
285
0.753943
3ae0af3a8c4d8fa95b24c6eb7d211c28ce820604
10,597
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 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 Swift project authors */ import Basics import PackageModel import TSCBasic import TSCUtility /// Wrapper struct containing result of a pkgConfig query. public struct PkgConfigResult { /// The name of the pkgConfig file. public let pkgConfigName: String /// The cFlags from pkgConfig. public let cFlags: [String] /// The library flags from pkgConfig. public let libs: [String] /// Available provider, if any. public let provider: SystemPackageProviderDescription? /// Any error encountered during operation. public let error: Swift.Error? /// If the pc file was not found. public var couldNotFindConfigFile: Bool { switch error { case PkgConfigError.couldNotFindConfigFile?: return true default: return false } } /// Create a result. fileprivate init( pkgConfigName: String, cFlags: [String] = [], libs: [String] = [], error: Swift.Error? = nil, provider: SystemPackageProviderDescription? = nil ) { self.cFlags = cFlags self.libs = libs self.error = error self.provider = provider self.pkgConfigName = pkgConfigName } } /// Get pkgConfig result for a system library target. public func pkgConfigArgs(for target: SystemLibraryTarget, brewPrefix: AbsolutePath? = .none, fileSystem: FileSystem, observabilityScope: ObservabilityScope) -> [PkgConfigResult] { // If there is no pkg config name defined, we're done. guard let pkgConfigNames = target.pkgConfig else { return [] } // Compute additional search paths for the provider, if any. let provider = target.providers?.first { $0.isAvailable } let additionalSearchPaths = provider?.pkgConfigSearchPath(brewPrefixOverride: brewPrefix) ?? [] var ret: [PkgConfigResult] = [] // Get the pkg config flags. for pkgConfigName in pkgConfigNames.components(separatedBy: " ") { let result: PkgConfigResult do { let pkgConfig = try PkgConfig( name: pkgConfigName, additionalSearchPaths: additionalSearchPaths, diagnostics: observabilityScope.makeDiagnosticsEngine(), fileSystem: fileSystem, brewPrefix: brewPrefix ) // Run the allow list checker. let filtered = try allowlist(pcFile: pkgConfigName, flags: (pkgConfig.cFlags, pkgConfig.libs)) // Remove any default flags which compiler adds automatically. let (cFlags, libs) = try removeDefaultFlags(cFlags: filtered.cFlags, libs: filtered.libs) // Set the error if there are any unallowed flags. var error: Swift.Error? if !filtered.unallowed.isEmpty { error = PkgConfigError.prohibitedFlags(filtered.unallowed.joined(separator: ", ")) } result = PkgConfigResult( pkgConfigName: pkgConfigName, cFlags: cFlags, libs: libs, error: error, provider: provider ) } catch { result = PkgConfigResult(pkgConfigName: pkgConfigName, error: error, provider: provider) } // If there is no pc file on system and we have an available provider, emit a warning. if let provider = result.provider, result.couldNotFindConfigFile { observabilityScope.emit(warning: "you may be able to install \(result.pkgConfigName) using your system-packager:\n\(provider.installText)") } else if let error = result.error { observabilityScope.emit( warning: "\(error)", metadata: .pkgConfig(pcFile: result.pkgConfigName, targetName: target.name) ) } ret.append(result) } return ret } extension SystemPackageProviderDescription { public var installText: String { switch self { case .brew(let packages): return " brew install \(packages.joined(separator: " "))\n" case .apt(let packages): return " apt-get install \(packages.joined(separator: " "))\n" case .yum(let packages): return " yum install \(packages.joined(separator: " "))\n" } } /// Check if the provider is available for the current platform. var isAvailable: Bool { guard let platform = Platform.currentPlatform else { return false } switch self { case .brew: if case .darwin = platform { return true } case .apt: if case .linux(.debian) = platform { return true } if case .android = platform { return true } case .yum: if case .linux(.fedora) = platform { return true } } return false } func pkgConfigSearchPath(brewPrefixOverride: AbsolutePath?) -> [AbsolutePath] { switch self { case .brew(let packages): let brewPrefix: String if let brewPrefixOverride = brewPrefixOverride { brewPrefix = brewPrefixOverride.pathString } else { // Homebrew can have multiple versions of the same package. The // user can choose another version than the latest by running // ``brew switch NAME VERSION``, so we shouldn't assume to link // to the latest version. Instead use the version as symlinked // in /usr/local/opt/(NAME)/lib/pkgconfig. struct Static { static let value = { try? Process.checkNonZeroExit(args: "brew", "--prefix").spm_chomp() }() } if let value = Static.value { brewPrefix = value } else { return [] } } return packages.map({ AbsolutePath(brewPrefix).appending(components: "opt", $0, "lib", "pkgconfig") }) case .apt: return [] case .yum: return [] } } // FIXME: Get rid of this method once we move on to new Build code. static func providerForCurrentPlatform(providers: [SystemPackageProviderDescription]) -> SystemPackageProviderDescription? { return providers.first(where: { $0.isAvailable }) } } /// Filters the flags with allowed arguments so unexpected arguments are not passed to /// compiler/linker. List of allowed flags: /// cFlags: -I, -F /// libs: -L, -l, -F, -framework, -w public func allowlist( pcFile: String, flags: (cFlags: [String], libs: [String]) ) throws -> (cFlags: [String], libs: [String], unallowed: [String]) { // Returns a tuple with the array of allowed flag and the array of unallowed flags. func filter(flags: [String], filters: [String]) throws -> (allowed: [String], unallowed: [String]) { var allowed = [String]() var unallowed = [String]() var it = flags.makeIterator() while let flag = it.next() { guard let filter = filters.filter({ flag.hasPrefix($0) }).first else { unallowed += [flag] continue } // Warning suppression flag has no arguments and is not suffixed. guard !flag.hasPrefix("-w") || flag == "-w" else { unallowed += [flag] continue } // If the flag and its value are separated, skip next flag. if flag == filter && flag != "-w" { guard let associated = it.next() else { throw InternalError("Expected associated value") } if flag == "-framework" { allowed += [flag, associated] continue } } allowed += [flag] } return (allowed, unallowed) } let filteredCFlags = try filter(flags: flags.cFlags, filters: ["-I", "-F"]) let filteredLibs = try filter(flags: flags.libs, filters: ["-L", "-l", "-F", "-framework", "-w"]) return (filteredCFlags.allowed, filteredLibs.allowed, filteredCFlags.unallowed + filteredLibs.unallowed) } /// Remove the default flags which are already added by the compiler. /// /// This behavior is similar to pkg-config cli tool and helps avoid conflicts between /// sdk and default search paths in macOS. public func removeDefaultFlags(cFlags: [String], libs: [String]) throws -> ([String], [String]) { /// removes a flag from given array of flags. func remove(flag: (String, String), from flags: [String]) throws -> [String] { var result = [String]() var it = flags.makeIterator() while let curr = it.next() { switch curr { case flag.0: // Check for <flag><space><value> style. guard let val = it.next() else { throw InternalError("Expected associated value") } // If we found a match, don't add these flags and just skip. if val == flag.1 { continue } // Otherwise add both the flags. result.append(curr) result.append(val) case flag.0 + flag.1: // Check for <flag><value> style. continue default: // Otherwise just append this flag. result.append(curr) } } return result } return ( try remove(flag: ("-I", "/usr/include"), from: cFlags), try remove(flag: ("-L", "/usr/lib"), from: libs) ) } extension ObservabilityMetadata { public static func pkgConfig(pcFile: String, targetName: String) -> Self { var metadata = ObservabilityMetadata() metadata.pcFile = "\(pcFile).pc" metadata.targetName = targetName return metadata } } extension ObservabilityMetadata { public var pcFile: String? { get { self[pcFileKey.self] } set { self[pcFileKey.self] = newValue } } enum pcFileKey: Key { typealias Value = String } }
35.800676
180
0.579975
5bf27f9c1f7d0645d348c976a46a5bc53def2dee
1,631
// // LoginViewController.swift // RocketReserver // // Created by Ellen Shapiro on 11/25/19. // Copyright © 2019 Apollo GraphQL. All rights reserved. // import UIKit class LoginViewController: UIViewController { static let loginKeychainKey = "login" @IBOutlet private var emailTextField: UITextField! @IBOutlet private var errorLabel: UILabel! @IBOutlet private var submitButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.errorLabel.text = nil self.enableSubmitButton(true) } @IBAction private func cancelTapped() { self.dismiss(animated: true) } @IBAction private func submitTapped() { self.errorLabel.text = nil self.enableSubmitButton(false) guard let email = self.emailTextField.text else { self.errorLabel.text = "Please enter an email address." self.enableSubmitButton(true) return } guard self.validate(email: email) else { self.errorLabel.text = "Please enter a valid email." self.enableSubmitButton(true) return } // TODO: Actually log the user in } private func validate(email: String) -> Bool { return email.contains("@") } private func enableSubmitButton(_ isEnabled: Bool) { self.submitButton.isEnabled = isEnabled if isEnabled { self.submitButton.setTitle("Submit", for: .normal) } else { self.submitButton.setTitle("Submitting...", for: .normal) } } }
26.737705
69
0.609442
3a3f26565fdaa706a3da9e14aa04fc2777ab4e61
12,379
// // DiscussionNewPostViewController.swift // edX // // Created by Tang, Jeff on 6/1/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit struct DiscussionNewThread { let courseID: String let topicID: String let type: DiscussionThreadType let title: String let rawBody: String } public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate { public typealias Environment = protocol<DataManagerProvider, NetworkManagerProvider, OEXRouterProvider> private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text private let environment: Environment private let growingTextController = GrowingTextViewController() private let insetsController = ContentInsetsController() @IBOutlet private var scrollView: UIScrollView! @IBOutlet private var backgroundView: UIView! @IBOutlet private var contentTextView: OEXPlaceholderTextView! @IBOutlet private var titleTextField: UITextField! @IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl! @IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint! @IBOutlet private var topicButton: UIButton! @IBOutlet private var postButton: SpinnerButton! private let loadController = LoadStateViewController() private let courseID: String private let topics = BackedStream<[DiscussionTopic]>() private var selectedTopic: DiscussionTopic? private var optionsViewController: MenuOptionsViewController? private var selectedThreadType: DiscussionThreadType = .Discussion { didSet { switch selectedThreadType { case .Discussion: self.contentTextView.placeholder = Strings.courseDashboardDiscussion postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion) case .Question: self.contentTextView.placeholder = Strings.question postButton.applyButtonStyle(OEXStyles.sharedStyles().filledPrimaryButtonStyle, withTitle: Strings.postQuestion) } } } public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) { self.environment = environment self.courseID = courseID super.init(nibName: "DiscussionNewPostViewController", bundle: nil) let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID).topics topics.backWithStream(stream.map { return DiscussionTopic.linearizeTopics($0) } ) self.selectedTopic = selectedTopic ?? self.firstSelectableTopic } private var firstSelectableTopic : DiscussionTopic? { let selectablePredicate = { (topic : DiscussionTopic) -> Bool in topic.isSelectable } guard let topics = self.topics.value, selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else { return nil } return topics[selectableTopicIndex] } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func postTapped(sender: AnyObject) { postButton.enabled = false postButton.showProgress = true // create new thread (post) if let topic = selectedTopic, topicID = topic.id { let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType ?? .Discussion, title: titleTextField.text ?? "", rawBody: contentTextView.text) let apiRequest = DiscussionAPI.createNewThread(newThread) environment.networkManager.taskForRequest(apiRequest) {[weak self] result in self?.dismissViewControllerAnimated(true, completion: nil) self?.postButton.enabled = true self?.postButton.showProgress = false } } } override public func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = Strings.post let cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: nil) cancelItem.oex_setAction { [weak self]() -> Void in self?.dismissViewControllerAnimated(true, completion: nil) } self.navigationItem.leftBarButtonItem = cancelItem contentTextView.textContainer.lineFragmentPadding = 0 contentTextView.textContainerInset = OEXStyles.sharedStyles().standardTextViewInsets contentTextView.typingAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes contentTextView.placeholderTextColor = OEXStyles.sharedStyles().neutralLight() contentTextView.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) contentTextView.delegate = self self.view.backgroundColor = OEXStyles.sharedStyles().neutralXLight() let segmentOptions : [(title : String, value : DiscussionThreadType)] = [ (title : Strings.discussion, value : .Discussion), (title : Strings.question, value : .Question), ] let options = segmentOptions.withItemIndexes() for option in options { discussionQuestionSegmentedControl.setTitle(option.value.title, forSegmentAtIndex: option.index) } discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in if let segmentedControl = control as? UISegmentedControl { let index = segmentedControl.selectedSegmentIndex let threadType = segmentOptions[index].value self?.selectedThreadType = threadType } else { assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum") } }, forEvents: UIControlEvents.ValueChanged) titleTextField.placeholder = Strings.title titleTextField.defaultTextAttributes = OEXStyles.sharedStyles().textAreaBodyStyle.attributes if let topic = selectedTopic, name = topic.name { let title = Strings.topic(topic: name) topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(title), forState: .Normal) } let insets = OEXStyles.sharedStyles().standardTextViewInsets topicButton.titleEdgeInsets = UIEdgeInsetsMake(0, insets.left, 0, insets.right) topicButton.applyBorderStyle(OEXStyles.sharedStyles().entryFieldBorderStyle) topicButton.localizedHorizontalContentAlignment = .Leading let dropdownLabel = UILabel() let style = OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(style) topicButton.addSubview(dropdownLabel) dropdownLabel.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(topicButton).offset(-insets.right) make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0) } topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in self?.showTopicPicker() }, forEvents: UIControlEvents.TouchUpInside) postButton.enabled = false titleTextField.oex_addAction({[weak self] _ in self?.validatePostButton() }, forEvents: .EditingChanged) let tapGesture = UITapGestureRecognizer() tapGesture.addAction {[weak self] _ in self?.contentTextView.resignFirstResponder() self?.titleTextField.resignFirstResponder() } self.backgroundView.addGestureRecognizer(tapGesture) self.growingTextController.setupWithScrollView(scrollView, textView: contentTextView, bottomView: postButton) self.insetsController.setupInController(self, scrollView: scrollView) // Force setting it to call didSet which is only called out of initialization context self.selectedThreadType = .Discussion loadController.setupInController(self, contentView: self.scrollView) updateLoadState() } private func updateLoadState() { if let _ = self.topics.value { loadController.state = LoadState.Loaded } else { loadController.state = LoadState.failed(message: Strings.failedToLoadTopics) return } } func showTopicPicker() { if self.optionsViewController != nil { return } self.optionsViewController = MenuOptionsViewController() self.optionsViewController?.menuHeight = min((CGFloat)(self.view.frame.height - self.topicButton.frame.minY - self.topicButton.frame.height), MenuOptionsViewController.menuItemHeight * (CGFloat)(topics.value?.count ?? 0)) self.optionsViewController?.menuWidth = self.topicButton.frame.size.width self.optionsViewController?.delegate = self guard let courseTopics = topics.value else { //Don't need to configure an empty state here because it's handled in viewDidLoad() return } self.optionsViewController?.options = courseTopics.map { return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "") } self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex() self.view.addSubview(self.optionsViewController!.view) self.optionsViewController!.view.snp_makeConstraints { (make) -> Void in make.trailing.equalTo(self.topicButton) make.leading.equalTo(self.topicButton) make.top.equalTo(self.topicButton.snp_bottom).offset(-3) make.bottom.equalTo(self.view.snp_bottom) } self.optionsViewController?.view.alpha = 0.0 UIView.animateWithDuration(0.3) { self.optionsViewController?.view.alpha = 1.0 } } private func selectedTopicIndex() -> Int? { guard let selected = selectedTopic else { return 0 } return self.topics.value?.firstIndexMatching { return $0.id == selected.id } } public func viewTapped(sender: UITapGestureRecognizer) { contentTextView.resignFirstResponder() titleTextField.resignFirstResponder() } public func textViewDidChange(textView: UITextView) { validatePostButton() growingTextController.handleTextChange() } public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool { return self.topics.value?[index].isSelectable ?? false } private func validatePostButton() { self.postButton.enabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil } func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) { selectedTopic = self.topics.value?[index] if let topic = selectedTopic, name = topic.name where topic.id != nil { topicButton.setAttributedTitle(OEXTextStyle(weight : .Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()).attributedStringWithText(Strings.topic(topic: name)), forState: .Normal) UIView.animateWithDuration(0.3, animations: { self.optionsViewController?.view.alpha = 0.0 }, completion: {(finished: Bool) in self.optionsViewController?.view.removeFromSuperview() self.optionsViewController = nil }) } } public override func viewDidLayoutSubviews() { self.insetsController.updateInsets() growingTextController.scrollToVisible() } }
41.540268
229
0.665159
fbcee74b3c205a6fac4f1a8e5a950fc4da311496
6,043
// // Copyright © 2016年 xiAo_Ju. All rights reserved. // class MTSheet: UIView, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate { var selectedIndex: ((Int) -> Void)? var cancelAction: (() -> Void)? private let tableView = UITableView() private var listData: [(icon: String, title: String)]! private var title: String! private let cusomerView = UIView() private let SCREEN_SIZE = UIScreen.mainScreen().bounds.size init(list: [(icon: String, title: String)], title: String, selectedIndex: ((Int) -> Void)? = nil, cancelHandle: (() -> Void)? = nil) { super.init(frame: CGRect(origin: CGPoint.zero, size: SCREEN_SIZE)) tableView.frame = CGRect(x: 5, y: 0, width: SCREEN_SIZE.width - 10, height: 44 * CGFloat(list.count) + 45) tableView.dataSource = self tableView.delegate = self tableView.scrollEnabled = false tableView.layer.cornerRadius = 5 cusomerView.addSubview(tableView) let cancelLabel = UILabel(frame: CGRect(x: 5, y: tableView.frame.height + 10, width: tableView.frame.width, height: 44)) cancelLabel.layer.cornerRadius = 5 cancelLabel.layer.backgroundColor = UIColor.whiteColor().CGColor cancelLabel.text = "取消" cancelLabel.textAlignment = .Center cancelLabel.textColor = .blueColor() let tap = UITapGestureRecognizer(target: self, action: #selector(hide)) cancelLabel.userInteractionEnabled = true cancelLabel.addGestureRecognizer(tap) cusomerView.addSubview(cancelLabel) cusomerView.frame = CGRect(x: 0, y: SCREEN_SIZE.height, width: SCREEN_SIZE.width, height: tableView.frame.height + 60) cusomerView.backgroundColor = .clearColor() addSubview(cusomerView) listData = list self.title = title self.selectedIndex = selectedIndex cancelAction = cancelHandle } //MARK: - UIGestureRecognizerDelegate func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { return touch.view is MTSheet } func animeData() { let tap = UITapGestureRecognizer(target: self, action: #selector(hide)) tap.delegate = self self.addGestureRecognizer(tap) UIView.animateWithDuration(0.25) { [unowned self] in self.backgroundColor = UIColor(red: 160 / 255, green: 160 / 255, blue: 160 / 255, alpha: 0.6) self.cusomerView.frame.origin.y = self.SCREEN_SIZE.height - self.cusomerView.frame.height } } func show() { UIApplication.sharedApplication().keyWindow?.rootViewController?.view.addSubview(self) animeData() } func tapped() { UIView.animateWithDuration(0.25, animations: { [unowned self] in self.alpha = 0 self.cusomerView.frame.origin.y = self.SCREEN_SIZE.height }) { [unowned self] (finished) in if finished { for subview in self.cusomerView.subviews { subview.removeFromSuperview() } } } } func hide() { if let cancelAction = self.cancelAction { cancelAction() } tapped() } //MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listData.count + 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == 0 { let cellId = "TitleCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: cellId) } cell?.textLabel?.text = title cell?.textLabel?.textAlignment = .Center cell?.userInteractionEnabled = false return cell ?? UITableViewCell() } else { let cellId = "DownSheetCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? SheetCell if cell == nil { cell = SheetCell(style: .Default, reuseIdentifier: cellId) } cell?.setData(listData[indexPath.row - 1]) return cell ?? SheetCell() } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return indexPath.row == 0 ? 45 : 44 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tapped() if let selectedIndex = self.selectedIndex { selectedIndex(indexPath.row) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SheetCell: UITableViewCell { private let leftView = UIImageView() private let titleLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) titleLabel.backgroundColor = .clearColor() contentView.addSubview(titleLabel) contentView.addSubview(leftView) selectionStyle = .None } override func layoutSubviews() { super.layoutSubviews() leftView.frame = CGRect(x: 20, y: (frame.height - 30) / 2, width: 30, height: 30) titleLabel.frame = CGRect(x: leftView.frame.maxX + 15, y: (frame.height - 20) / 2, width: 150, height: 20) titleLabel.textColor = .blueColor() } func setData(item: (icon: String, title: String)) { leftView.image = UIImage(named: item.icon) titleLabel.text = item.title } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
37.534161
138
0.619394
6a5e9a652589a92761c221659f0fb7eb9f98aadb
2,056
// // EquipmentTabViewController.swift // PrincessGuide // // Created by zzk on 2018/5/6. // Copyright © 2018 zzk. All rights reserved. // import UIKit import Tabman import Pageboy class EquipmentTabViewController: TabmanViewController, PageboyViewControllerDataSource, TMBarDataSource { private var viewControllers = [UIViewController]() private var items = [TMBarItem]() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Equipments", comment: "") viewControllers = [EquipmentViewController(equipmentType: .dropped), EquipmentViewController(equipmentType: .crafted), UniqueEquipmentViewController()] dataSource = self self.items = EquipmentType.allCases.map { TMBarItem(title: $0.description) } let bar = TMBarView<TMHorizontalBarLayout, TMLabelBarButton, TMBarIndicator.None>() bar.layout.contentInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) bar.layout.transitionStyle = .progressive addBar(bar, dataSource: self, at: .bottom) view.backgroundColor = Theme.dynamic.color.background bar.indicator.tintColor = Theme.dynamic.color.tint bar.buttons.customize({ (button) in button.selectedTintColor = Theme.dynamic.color.tint button.tintColor = Theme.dynamic.color.lightText }) bar.backgroundView.style = .blur(style: .systemMaterial) } func numberOfViewControllers(in pageboyViewController: PageboyViewController) -> Int { return viewControllers.count } func viewController(for pageboyViewController: PageboyViewController, at index: PageboyViewController.PageIndex) -> UIViewController? { return viewControllers[index] } func defaultPage(for pageboyViewController: PageboyViewController) -> PageboyViewController.Page? { return nil } func barItem(for bar: TMBar, at index: Int) -> TMBarItemable { return items[index] } }
36.070175
159
0.693093
392ac067b277d97d579d1b31c55f448696169228
18,702
// JFBrightnessView.swift // JFPlayerDemo // // Created by jumpingfrog0 on 14/12/2016. // // // Copyright (c) 2016 Jumpingfrog0 LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import NVActivityIndicatorView open class JFProgressSlider: UISlider { open override func trackRect(forBounds bounds: CGRect) -> CGRect { let trackHeight = CGFloat(2.0) let positon = CGPoint(x: 0, y: 14) let customBounds = CGRect(origin: positon, size: CGSize(width: bounds.size.width, height: trackHeight)) super.trackRect(forBounds: customBounds) return customBounds } open override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect { let rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value) let newX = rect.origin.x - 10 let newRect = CGRect(x: newX, y: 0, width: 30, height: 30) return newRect } } class JFPlayerControlView: UIView { weak var delegate: JFPlayerControlViewDelegate? /// Mask view var mainMaskView = UIView() var topBar = UIView() var bottomBar = UIView() /// Top var backButton = UIButton(type: UIButtonType.custom) var titleLabel = UILabel() var definitionSelectionView = UIView() var definitionPreview = JFPlayerButton() var modeButton = JFPlayerButton() // only display in VR player /// Bottom var currentTimeLabel = UILabel() var totalTimeLabel = UILabel() var progressSlider = JFProgressSlider() var progressView = UIProgressView() var playButton = UIButton(type: UIButtonType.custom) var fullScreenButton = UIButton(type: UIButtonType.custom) /// Center var loadingIndicator = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) var replayButton = UIButton(type: UIButtonType.custom) var seekView = UIView() var seekImageView = UIImageView() var seekLabel = UILabel() var seekProgressView = UIProgressView() var lockButton = UIButton() var configuration = JFPlayerConfiguration() var isFullScreen = false var definitionSelectionIsShrinked = true var isVrPlayer = false { didSet { modeButton.isHidden = !isVrPlayer definitionPreview.isHidden = isVrPlayer definitionSelectionView.isHidden = isVrPlayer } } var definitionCount = 0 var currentDefinitionIndex = 0 // MARK: - Initialize override init(frame: CGRect) { super.init(frame: frame) initUI() layout() setupGestures() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initUI() layout() setupGestures() } func initUI() { // Mask view addSubview(mainMaskView) mainMaskView.addSubview(topBar) mainMaskView.addSubview(bottomBar) mainMaskView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4) // Top topBar.addSubview(backButton) topBar.addSubview(titleLabel) topBar.addSubview(modeButton) topBar.addSubview(definitionPreview) mainMaskView.addSubview(definitionSelectionView) backButton.setImage(JFImageResourcePath("JFPlayer_back"), for: .normal) titleLabel.text = "" titleLabel.textColor = UIColor.white titleLabel.font = UIFont.systemFont(ofSize: 16) definitionSelectionView.clipsToBounds = true modeButton.isHidden = true modeButton.setTitle("VR", for: .normal) modeButton.setTitle("普通", for: .selected) // Bottom bottomBar.addSubview(playButton) bottomBar.addSubview(currentTimeLabel) bottomBar.addSubview(totalTimeLabel) bottomBar.addSubview(progressView) bottomBar.addSubview(progressSlider) bottomBar.addSubview(fullScreenButton) playButton.setImage(JFImageResourcePath("JFPlayer_play"), for: .normal) playButton.setImage(JFImageResourcePath("JFPlayer_pause"), for: .selected) currentTimeLabel.textColor = UIColor.white currentTimeLabel.font = UIFont.systemFont(ofSize: 12) currentTimeLabel.text = "00:00" currentTimeLabel.textAlignment = .center totalTimeLabel.textColor = UIColor.white totalTimeLabel.font = UIFont.systemFont(ofSize: 12) totalTimeLabel.text = "00:00" totalTimeLabel.textAlignment = .center progressSlider.maximumValue = 1.0 progressSlider.minimumValue = 0.0 progressSlider.value = 0.0 progressSlider.setThumbImage(JFImageResourcePath("JFPlayer_slider_thumb"), for: .normal) progressSlider.maximumTrackTintColor = UIColor.clear progressSlider.minimumTrackTintColor = configuration.tintColor progressView.tintColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6) progressView.trackTintColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3) fullScreenButton.setImage(JFImageResourcePath("JFPlayer_fullscreen"), for: .normal) // Center mainMaskView.addSubview(loadingIndicator) loadingIndicator.type = configuration.loaderType loadingIndicator.color = configuration.tintColor mainMaskView.addSubview(replayButton) replayButton.isHidden = true replayButton.setImage(JFImageResourcePath("JFPlayer_replay"), for: .normal) replayButton.addTarget(self, action: #selector(pressedReplayButton(_:)), for: .touchUpInside) mainMaskView.addSubview(seekView) seekView.addSubview(seekImageView) seekView.addSubview(seekLabel) seekView.addSubview(seekProgressView) seekLabel.font = UIFont.systemFont(ofSize: 13) seekLabel.textColor = UIColor.white seekLabel.textAlignment = .center seekProgressView.progressTintColor = UIColor.white seekProgressView.trackTintColor = UIColor.lightGray.withAlphaComponent(0.4) seekView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.8) seekView.layer.cornerRadius = 4 seekView.layer.masksToBounds = true seekView.isHidden = true seekImageView.image = JFImageResourcePath("JFPlayer_fast_forward") mainMaskView.addSubview(lockButton) lockButton.setImage(JFImageResourcePath("JFPlayer_unlock_nor"), for: .normal) lockButton.setImage(JFImageResourcePath("JFPlayer_lock_nor"), for: .selected) } func layout() { // Main mask view mainMaskView.snp.makeConstraints { (make) in make.edges.equalTo(self) } topBar.snp.makeConstraints { (make) in make.top.left.right.equalTo(mainMaskView) make.height.equalTo(65) } bottomBar.snp.makeConstraints { (make) in make.bottom.left.right.equalTo(mainMaskView) make.height.equalTo(50) } // Top backButton.snp.makeConstraints { (make) in make.width.height.equalTo(50) make.left.bottom.equalTo(topBar) } titleLabel.snp.makeConstraints { (make) in make.left.equalTo(backButton.snp.right) make.centerY.equalTo(backButton) } definitionPreview.snp.makeConstraints { (make) in make.right.equalTo(topBar.snp.right).offset(-25) make.top.equalTo(titleLabel.snp.top).offset(-4) make.width.equalTo(50) make.height.equalTo(25) } definitionSelectionView.snp.makeConstraints { (make) in make.right.equalTo(topBar.snp.right).offset(-20) make.top.equalTo(titleLabel.snp.top).offset(-4) make.width.equalTo(60) make.height.equalTo(30) } modeButton.snp.makeConstraints { (make) in make.right.equalTo(topBar.snp.right).offset(-25) make.top.equalTo(titleLabel.snp.top).offset(-4) make.width.equalTo(50) make.height.equalTo(25) } // Bottom playButton.snp.makeConstraints { (make) in make.width.height.equalTo(50) make.left.bottom.equalTo(bottomBar) } currentTimeLabel.snp.makeConstraints { (make) in make.left.equalTo(playButton.snp.right) make.centerY.equalTo(playButton) make.width.equalTo(40) } progressSlider.snp.makeConstraints { (make) in make.centerY.equalTo(currentTimeLabel) make.left.equalTo(currentTimeLabel.snp.right).offset(10).priority(750) make.height.equalTo(30) } progressView.snp.makeConstraints { (make) in make.centerY.left.right.equalTo(progressSlider) make.height.equalTo(2) } totalTimeLabel.snp.makeConstraints { (make) in make.centerY.equalTo(currentTimeLabel) make.left.equalTo(progressSlider.snp.right).offset(5) make.width.equalTo(40) } fullScreenButton.snp.makeConstraints { (make) in make.width.height.equalTo(50) make.centerY.equalTo(currentTimeLabel) make.left.equalTo(totalTimeLabel.snp.right) make.right.equalTo(bottomBar.snp.right) } // Center loadingIndicator.snp.makeConstraints { (make) in make.centerX.equalTo(mainMaskView.snp.centerX) make.centerY.equalTo(mainMaskView.snp.centerY) } replayButton.snp.makeConstraints { (make) in make.centerX.equalTo(mainMaskView.snp.centerX) make.centerY.equalTo(mainMaskView.snp.centerY) make.width.height.equalTo(50) } seekView.snp.makeConstraints { (make) in make.center.equalTo(self) make.width.equalTo(125) make.height.equalTo(80) } seekImageView.snp.makeConstraints { (make) in make.height.equalTo(32) make.width.equalTo(32) make.top.equalTo(5) make.centerX.equalTo(seekView.snp.centerX) } seekLabel.snp.makeConstraints { (make) in make.leading.trailing.equalTo(0) make.top.equalTo(seekImageView.snp.bottom).offset(2) } seekProgressView.snp.makeConstraints { (make) in make.leading.equalTo(12) make.trailing.equalTo(-12) make.top.equalTo(seekLabel.snp.bottom).offset(10) } lockButton.snp.makeConstraints { (make) in make.left.equalTo(mainMaskView).offset(15) make.centerY.equalTo(mainMaskView.snp.centerY) make.width.height.equalTo(32) } } func setupGestures() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAtSlider(_:))) progressSlider.addGestureRecognizer(tapGesture) } // MARK: - Actions func pressedReplayButton(_ button: UIButton) { button.isHidden = true } func handleTapAtSlider(_ recognizer: UITapGestureRecognizer) { let slider = recognizer.view as? JFProgressSlider let location = recognizer.location(in: slider) let length = slider!.bounds.width let tapValue = location.x / length progressSlider.value = Float(tapValue) delegate?.controlView(self, didTapProgressSliderAt: Float(tapValue)) } func definitionButtonDidSelect(_ button: UIButton) { let height = definitionSelectionIsShrinked ? definitionCount * 40 : 35 definitionSelectionView.snp.updateConstraints { (make) in make.height.equalTo(height) } UIView.animate(withDuration: 0.3, animations: { self.layoutIfNeeded() }) definitionSelectionIsShrinked = !definitionSelectionIsShrinked definitionPreview.isHidden = !definitionSelectionIsShrinked definitionSelectionView.isHidden = definitionSelectionIsShrinked // if selection view is expanding, set the current definition button being selected if !definitionSelectionIsShrinked { for button in definitionSelectionView.subviews as! [JFPlayerButton] { if button.tag == currentDefinitionIndex { button.isSelected = true } else { button.isSelected = false } } } else { // will shrink selection view and change definetion let curIndex = button.tag if currentDefinitionIndex != curIndex { let preIndex = currentDefinitionIndex currentDefinitionIndex = curIndex let preButton = definitionSelectionView.subviews[preIndex] as? JFPlayerButton let curButton = definitionSelectionView.subviews[curIndex] as? JFPlayerButton preButton?.isSelected = false curButton?.isSelected = true delegate?.controlView(self, didSelectDefinitionAt: button.tag) definitionPreview.setTitle(curButton?.titleLabel?.text, for: .normal) } } } // MARK: - Public Methods func prepareDefinitionView(withItems items: [JFPlayerDefinitionProtocol]) { definitionCount = items.count definitionSelectionIsShrinked = true definitionSelectionView.isHidden = true for (idx, item) in items.enumerated() { let button = JFPlayerButton() button.tag = idx button.setTitle(item.definitionName, for: .normal) button.addTarget(self, action: #selector(definitionButtonDidSelect(_:)), for: .touchUpInside) definitionSelectionView.addSubview(button) button.snp.makeConstraints({ (make) in make.top.equalTo(definitionSelectionView.snp.top).offset(35 * idx) make.width.equalTo(50) make.height.equalTo(25) make.centerX.equalTo(definitionSelectionView) }) if idx == 0 { definitionPreview.setTitle(item.definitionName, for: .normal) definitionPreview.addTarget(self, action: #selector(definitionButtonDidSelect(_:)), for: .touchUpInside) if items.count == 1 { definitionPreview.isEnabled = false } } } } func showUIComponents() { topBar.alpha = 1.0 bottomBar.alpha = 1.0 mainMaskView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4) isHidden = false if definitionCount == 0 { definitionPreview.isHidden = true } else { definitionPreview.isHidden = !isFullScreen } } func hideUIComponents() { replayButton.isHidden = true definitionSelectionView.isHidden = true definitionPreview.isHidden = true definitionSelectionIsShrinked = true topBar.alpha = 0.0 bottomBar.alpha = 0.0 mainMaskView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) } func showPlayToEndView() { replayButton.isHidden = false } func hidePlayToEndView() { replayButton.isHidden = true } func updateUI(isForFullScreen: Bool) { isFullScreen = isForFullScreen lockButton.isHidden = !isFullScreen if definitionCount == 0 { definitionPreview.isHidden = true } else { definitionPreview.isHidden = !isFullScreen } if isForFullScreen { fullScreenButton.setImage(JFImageResourcePath("JFPlayer_portialscreen"), for: .normal) } else { fullScreenButton.setImage(JFImageResourcePath("JFPlayer_fullscreen"), for: .normal) } } func showLoader() { loadingIndicator.isHidden = false loadingIndicator.startAnimating() } func hideLoader() { loadingIndicator.stopAnimating() loadingIndicator.isHidden = true } func seek(to draggedTime: TimeInterval, totalDuration: TimeInterval, isForword: Bool) { if draggedTime.isNaN || totalDuration.isNaN { // avoid value being NaN return } let rotate = isForword ? 0 : CGFloat(M_PI) seekImageView.transform = CGAffineTransform(rotationAngle: rotate) seekLabel.text = JFPlayer.formatSecondsToString(Int(draggedTime)) + " / " + JFPlayer.formatSecondsToString(Int(totalDuration)) seekProgressView.setProgress( Float(draggedTime / totalDuration), animated: true) progressSlider.value = Float(draggedTime / totalDuration) currentTimeLabel.text = JFPlayer.formatSecondsToString(Int(draggedTime)) } func seekViewDraggedBegin() { seekView.isHidden = false } func seekViewDraggedEnd() { seekView.isHidden = true } }
36.104247
134
0.622607
cc532485c59181de14d27a889e938e7ea957ea18
11,579
// Copyright (c) 2017 Philip M. Hubbard // // 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. // // http://opensource.org/licenses/MIT import XCTest @testable import SUtility // Tests of Animation.swift. class TestAnimation: XCTestCase { func equal<T: FloatingPoint>(_ x: T, _ y: T, eps: T) -> Bool { return (abs(x - y) < eps) } static var evalResult: Float? = nil let eval = { val in evalResult = val } func testValuesNotRepeating() { let val0A: Float = -5.0 let val1A: Float = 5.0 let val0B: Float = val1A let val1B: Float = 25.0 let durationA: TimeInterval = 12.3 let durationB: TimeInterval = 45.6 let segments = [ Animation.Segment(val0: val0A, val1: val1A, duration: durationA, onEvaluate: eval), Animation.Segment(val0: val0B, val1: val1B, duration: durationB, onEvaluate: eval) ] let t0: TimeInterval = 7.8 let animation = Animation(segments: segments, repeating: false, t0: t0) XCTAssertFalse(animation.finished(t: t0 - 1.0)) TestAnimation.evalResult = nil animation.evaluate(t: t0 - 1.0) XCTAssertNil(TestAnimation.evalResult) XCTAssertFalse(animation.finished(t: t0 + durationA * 0.25)) TestAnimation.evalResult = nil animation.evaluate(t: t0 + durationA * 0.25) XCTAssertNotNil(TestAnimation.evalResult) XCTAssertGreaterThan(TestAnimation.evalResult!, val0A) XCTAssertLessThan(TestAnimation.evalResult!, val1A) XCTAssertFalse(animation.finished(t: t0 + durationA + durationB * 0.75)) TestAnimation.evalResult = nil animation.evaluate(t: t0 + durationA + durationB * 0.75) XCTAssertNotNil(TestAnimation.evalResult) XCTAssertGreaterThan(TestAnimation.evalResult!, val0B) XCTAssertLessThan(TestAnimation.evalResult!, val1B) XCTAssertTrue(animation.finished(t: t0 + durationA + durationB + 1.0)) TestAnimation.evalResult = nil animation.evaluate(t: t0 + durationA + durationB + 1.0) XCTAssertNotNil(TestAnimation.evalResult) XCTAssertEqual(TestAnimation.evalResult!, val1B) } func testValuesRepeating() { let val0A: Float = 100 let val1A: Float = 200 let val0B: Float = val1A let val1B: Float = val0A let durationA: TimeInterval = 10.9 let durationB: TimeInterval = 8.7 let segments = [ Animation.Segment(val0: val0A, val1: val1A, duration: durationA, onEvaluate: eval), Animation.Segment(val0: val0B, val1: val1B, duration: durationB, onEvaluate: eval) ] let t0: TimeInterval = 6.5 let animation = Animation(segments: segments, repeating: true, t0: t0) XCTAssertFalse(animation.finished(t: t0 - 1.0)) TestAnimation.evalResult = nil animation.evaluate(t: t0 - 1.0) XCTAssertNil(TestAnimation.evalResult) XCTAssertFalse(animation.finished(t: t0 + durationA * 0.6)) TestAnimation.evalResult = nil animation.evaluate(t: t0 + durationA * 0.6) XCTAssertNotNil(TestAnimation.evalResult) XCTAssertGreaterThan(TestAnimation.evalResult!, val0A) XCTAssertLessThan(TestAnimation.evalResult!, val1A) XCTAssertFalse(animation.finished(t: t0 + durationA + durationB * 0.3)) TestAnimation.evalResult = nil animation.evaluate(t: t0 + durationA + durationB * 0.3) XCTAssertNotNil(TestAnimation.evalResult) XCTAssertLessThan(TestAnimation.evalResult!, val0B) XCTAssertGreaterThan(TestAnimation.evalResult!, val1B) XCTAssertFalse(animation.finished(t: t0 + durationA + durationB + 1.0)) TestAnimation.evalResult = nil animation.evaluate(t: t0 + durationA + durationB + 1.0) XCTAssertNotNil(TestAnimation.evalResult) XCTAssertGreaterThan(TestAnimation.evalResult!, val0A) XCTAssertLessThan(TestAnimation.evalResult!, val1A) } func testEaseInOut() { var vals: Array<Float> = [] let evalArray = { val in vals.append(val) } let duration: TimeInterval = 10.0 let t0: TimeInterval = 0.0 let segments = [Animation.Segment(val0: 0.0, val1: 9.0, duration: duration, onEvaluate: evalArray)] let animation = Animation(segments: segments, t0: t0) let n = 20 let deltaT = duration / TimeInterval(n) var ts: Array<TimeInterval> = [] for i in 0..<n { ts.append(t0 + TimeInterval(i) * deltaT) } for t in ts { animation.evaluate(t: t) } var intervals: Array<Float> = [] var valPrev: Float? = nil for val in vals { if let valPrev = valPrev { intervals.append(val - valPrev) } valPrev = val } let mid = intervals.count / 2 let firstHalf = intervals.prefix(upTo: mid) let secondHalf = intervals.suffix(from: mid) var intervalPrev: Float? = nil for interval in firstHalf { if let intervalPrev = intervalPrev { XCTAssertGreaterThan(interval, intervalPrev) } intervalPrev = interval } intervalPrev = nil for interval in secondHalf { if let intervalPrev = intervalPrev { XCTAssertLessThan(interval, intervalPrev) } intervalPrev = interval } } func assertDetourTransition(animation: Animation, detour: Animation, t: TimeInterval) { let tDelta = 1e-4 TestAnimation.evalResult = nil animation.evaluate(t: t - tDelta) XCTAssertNotNil(TestAnimation.evalResult) let valA = TestAnimation.evalResult! TestAnimation.evalResult = nil animation.evaluate(t: t) XCTAssertNotNil(TestAnimation.evalResult) let valB = TestAnimation.evalResult! let change = valB - valA TestAnimation.evalResult = nil detour.evaluate(t: t) XCTAssertNotNil(TestAnimation.evalResult) let detourValA = TestAnimation.evalResult! TestAnimation.evalResult = nil detour.evaluate(t: t + tDelta) XCTAssertNotNil(TestAnimation.evalResult) let detourValB = TestAnimation.evalResult! let detourChange = detourValB - detourValA XCTAssertTrue(equal(change, detourChange, eps: 1e-4)) } func assertDetourValues(animation: Animation, detour: Animation, detourEndMagnitude: Float, t: TimeInterval) { TestAnimation.evalResult = nil animation.evaluate(t: t) XCTAssertNotNil(TestAnimation.evalResult) let val = TestAnimation.evalResult! TestAnimation.evalResult = nil detour.evaluate(t: t) XCTAssertNotNil(TestAnimation.evalResult) let valDetour = TestAnimation.evalResult! XCTAssertTrue(equal(val, valDetour, eps: 1e-4)) TestAnimation.evalResult = nil detour.evaluate(t: detour.t0 + detour.duration) XCTAssertNotNil(TestAnimation.evalResult) let val1Detour = TestAnimation.evalResult! XCTAssertTrue(equal(val1Detour, detourEndMagnitude, eps: 1e-4)) } func testDetourIdentical() { let val0: Float = 9 let val1: Float = 8 let duration: TimeInterval = 7 let segments = [Animation.Segment(val0: val0, val1: val1, duration: duration, onEvaluate: eval)] let t0: TimeInterval = 6 let animation = Animation(segments: segments, repeating: false, t0: t0) let tDetour = t0 + duration / 3 let detourEndMagnitude: Float = val1 let detourDuration: TimeInterval = duration let detour = animation.detour(t: tDetour, endMagnitude: detourEndMagnitude, duration: detourDuration) XCTAssertNotNil(detour) assertDetourValues(animation: animation, detour: detour!, detourEndMagnitude: detourEndMagnitude, t: tDetour) assertDetourTransition(animation: animation, detour: detour!, t: tDetour) } func testDetour() { let val0: Float = 5 let val1: Float = 6 let duration: TimeInterval = 7 let segments = [Animation.Segment(val0: val0, val1: val1, duration: duration, onEvaluate: eval)] let t0: TimeInterval = 8 let animation = Animation(segments: segments, repeating: false, t0: t0) let tDetour = t0 + duration / 3 let detourEndMagnitude: Float = 9 let detourDuration: TimeInterval = duration / 2 let detour = animation.detour(t: tDetour, endMagnitude: detourEndMagnitude, duration: detourDuration) XCTAssertNotNil(detour) assertDetourValues(animation: animation, detour: detour!, detourEndMagnitude: detourEndMagnitude, t: tDetour) assertDetourTransition(animation: animation, detour: detour!, t: tDetour) } func testDetourTooEarly() { let val0: Float = 123 let val1: Float = 456 let duration: TimeInterval = 789 let segments = [Animation.Segment(val0: val0, val1: val1, duration: duration, onEvaluate: eval)] let t0: TimeInterval = 10 let animation = Animation(segments: segments, t0: t0) let tDetour = t0 - 1 let detourEndMagnitude: Float = 2 let detourDuration: TimeInterval = 3 let detour = animation.detour(t: tDetour, endMagnitude: detourEndMagnitude, duration: detourDuration) XCTAssertNil(detour) } func testDetourTooSlow() { let val0: Float = 123 let val1: Float = 456 let duration: TimeInterval = 789 let segments = [Animation.Segment(val0: val0, val1: val1, duration: duration, onEvaluate: eval)] let t0: TimeInterval = 10 let animation = Animation(segments: segments, t0: t0) let tDetour = t0 + duration / 2 let detourEndMagnitude: Float = val0 + (val1 - val0) / 2 let detourDuration = duration let detour = animation.detour(t: tDetour, endMagnitude: detourEndMagnitude, duration: detourDuration) XCTAssertNotNil(detour) assertDetourValues(animation: animation, detour: detour!, detourEndMagnitude: detourEndMagnitude, t: tDetour) } }
40.204861
117
0.641506
268df630674a67dbf25da73452d85fc995e14eee
994
// // SVGDesignableTests.swift // SVGDesignableTests // // Created by Daniel Asher on 14/03/2018. // Copyright © 2018 LEXI LABS. All rights reserved. // import XCTest @testable import SVGDesignable class SVGDesignableTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.864865
111
0.640845
5b33dde3fbb64d85c43e6f6338d5150bbd7f103e
5,791
import UIKit class LoginViewController: UIViewController { @IBOutlet weak var mainStackView: UIStackView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var loginError: UILabel! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var emailErrorLabel: UILabel! @IBOutlet weak var passwordTextfield: UITextField! @IBOutlet weak var passwordErrorLabel: UILabel! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Login button initially disabled self.loginButton.isEnabled = false // All errors initially hidden self.loginError.isHidden = true self.emailErrorLabel.isHidden = true self.passwordErrorLabel.isHidden = true // Send errors to back so it doesn't look ugly when animating in/out self.loginError.sendToBack() self.emailErrorLabel.sendToBack() self.passwordErrorLabel.sendToBack() // Wire textfield events to the "updateUI" function to keep ui updated self.emailTextField.addTarget(self, action: #selector(self.emailTextFieldChanged), for: .allEditingEvents) self.passwordTextfield.addTarget(self, action: #selector(self.passwordTextFieldChanged), for: .allEditingEvents) } /// Shows/hides errors related to email textfields @objc private func emailTextFieldChanged() { // We check if the password is valid let validEmail = self.emailTextField.text?.isValidEmail() ?? false // We update the UI with the new calculated value and the previous one that was stored on isHidden self.updateUI(validEmail: validEmail, validPassword: self.passwordErrorLabel.isHidden) } /// Shows/hides errors related to password textfields @objc private func passwordTextFieldChanged() { // We check if the password is valid let validPassword = self.passwordTextfield.text?.isValidPassword() ?? false // We update the UI with the new calculated value and the previous one that was stored on isHidden self.updateUI(validEmail: self.emailErrorLabel.isHidden, validPassword: validPassword) } /// Updates the UI based on whether the email and password are valid /// /// - parameter validEmail: Whether the email is valid /// - parameter validPassword: Whether the password is valid private func updateUI(validEmail: Bool, validPassword: Bool) { UIView.animate(withDuration: 0.3) { // If the email is not valid the error label below the email textfielf is shown if self.emailErrorLabel.isHidden != validEmail { // To prevent bug with StackViews self.emailErrorLabel.isHidden = validEmail } // If the password is not valid the error label below the password textfielf is shown if self.passwordErrorLabel.isHidden != validPassword { // To prevent bug with StackViews self.passwordErrorLabel.isHidden = validPassword } // Only when both email and password are valid the login button is made enabled self.loginButton.isEnabled = validEmail && validPassword } } /// Action fired when the login button is activated @IBAction func onLoginButtonTouchUpInside() { // If we don't have both an email and a password we show an error and short the function guard let email = self.emailTextField.text, let password = self.passwordTextfield.text else { // The the UI to show the wrong credentials error return self.setLoginError(.wrongCredentials) } // Set the UI to the loading state self.setLoading(true) // Hide any login error that might be currently showing self.setLoginError(nil) // Request the user for the given email+password to the service, if any Services.login(email: email, password: password) { [weak self] result in self?.setLoading(false) switch result { case .success: break; case .failure(let error): self?.setLoginError(error) } } } /// Set the UI to the loading state /// ///- parameter isLoading: Whether the UI should be shown as loading or not private func setLoading(_ isLoading: Bool) { self.view.isUserInteractionEnabled = !isLoading self.mainStackView.alpha = isLoading ? 0.3 : 1.0 if isLoading { self.activityIndicator.startAnimating() } else { self.activityIndicator.stopAnimating() } } /// Updates the UI to show/hide login errors /// /// - parameter error: The error to show or nil if no error should be shown at all. private func setLoginError(_ error: LoginError?) { UIView.animate(withDuration: 0.5) { switch error { case .none: self.loginError.isHidden = true case .some(.wrongCredentials): self.loginError.text = "Email or password does not match" self.loginError.isHidden = false case .some(.contactSupport): self.loginError.text = "Please contact support" self.loginError.isHidden = false } } } } extension LoginViewController { /// Convenience factory to instantiate and instace from the Main storyboard static func createFromStoryboard() -> UIViewController { UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Login") } }
41.963768
120
0.645657
1efb90c86c7142cb70838f064bac1666399d514b
8,362
// // OAuthWebViewController.swift // OAuthSwift // // Created by Dongri Jin on 2/11/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit public typealias OAuthViewController = UIViewController #elseif os(watchOS) import WatchKit public typealias OAuthViewController = WKInterfaceController #elseif os(OSX) import AppKit public typealias OAuthViewController = NSViewController #endif /// Delegate for OAuthWebViewController public protocol OAuthWebViewControllerDelegate: AnyObject { #if os(iOS) || os(tvOS) /// Did web view presented (work only without navigation controller) func oauthWebViewControllerDidPresent() /// Did web view dismiss (work only without navigation controller) func oauthWebViewControllerDidDismiss() #endif func oauthWebViewControllerWillAppear() func oauthWebViewControllerDidAppear() func oauthWebViewControllerWillDisappear() func oauthWebViewControllerDidDisappear() } /// A web view controller, which handler OAuthSwift authentification. Must be override to display a web view. open class OAuthWebViewController: OAuthViewController, OAuthSwiftURLHandlerType { #if os(iOS) || os(tvOS) || os(OSX) /// Delegate for this view public weak var delegate: OAuthWebViewControllerDelegate? #endif #if os(iOS) || os(tvOS) /// If controller have an navigation controller, application top view controller could be used if true public var useTopViewControlerInsteadOfNavigation = false /// Set false to disable present animation. public var presentViewControllerAnimated = true /// Set false to disable dismiss animation. public var dismissViewControllerAnimated = true public var topViewController: UIViewController? { #if !OAUTH_APP_EXTENSIONS return UIApplication.topViewController #else return nil #endif } #elseif os(OSX) /// How to present this view controller if parent view controller set public enum Present { case asModalWindow case asSheet case asPopover(relativeToRect: NSRect, ofView: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) case transitionFrom(fromViewController: NSViewController, options: NSViewController.TransitionOptions) case animator(animator: NSViewControllerPresentationAnimator) case segue(segueIdentifier: String) } public var present: Present = .asModalWindow #endif open func handle(_ url: URL) { // do UI in main thread OAuthSwift.main { [unowned self] in self.doHandle(url) } } #if os(watchOS) public static var userActivityType: String = "org.github.dongri.oauthswift.connect" #endif open func doHandle(_ url: URL) { OAuthSwift.log?.trace("OAuthWebViewController: present Safari view controller, url: \(url)") #if os(iOS) || os(tvOS) let completion: () -> Void = { [unowned self] in self.delegate?.oauthWebViewControllerDidPresent() } if let navigationController = self.navigationController, (!useTopViewControlerInsteadOfNavigation || self.topViewController == nil) { navigationController.pushViewController(self, animated: presentViewControllerAnimated) } else if let p = self.parent { p.present(self, animated: presentViewControllerAnimated, completion: completion) } else if let topViewController = topViewController { topViewController.present(self, animated: presentViewControllerAnimated, completion: completion) } else { // assert no presentation assertionFailure("Failed to present. Maybe add a parent") } #elseif os(watchOS) if url.scheme == "http" || url.scheme == "https" { self.updateUserActivity(OAuthWebViewController.userActivityType, userInfo: nil, webpageURL: url) } #elseif os(OSX) if let p = self.parent { // default behaviour if this controller affected as child controller switch self.present { case .asSheet: p.presentAsSheet(self) case .asModalWindow: p.presentAsModalWindow(self) // FIXME: if we present as window, window close must detected and oauthswift.cancel() must be called... case .asPopover(let positioningRect, let positioningView, let preferredEdge, let behavior): p.present(self, asPopoverRelativeTo: positioningRect, of: positioningView, preferredEdge: preferredEdge, behavior: behavior) case .transitionFrom(let fromViewController, let options): let completion: () -> Void = { /*[unowned self] in*/ // self.delegate?.oauthWebViewControllerDidPresent() } p.transition(from: fromViewController, to: self, options: options, completionHandler: completion) case .animator(let animator): p.present(self, animator: animator) case .segue(let segueIdentifier): p.performSegue(withIdentifier: segueIdentifier, sender: self) // The segue must display self.view } } else if let window = self.view.window { window.makeKeyAndOrderFront(nil) } else { assertionFailure("Failed to present. Add controller into a window or add a parent") } // or create an NSWindow or NSWindowController (/!\ keep a strong reference on it) #endif } open func dismissWebViewController() { OAuthSwift.log?.trace("OAuthWebViewController: dismiss view controller") #if os(iOS) || os(tvOS) let completion: () -> Void = { [weak self] in self?.delegate?.oauthWebViewControllerDidDismiss() } if let navigationController = self.navigationController, (!useTopViewControlerInsteadOfNavigation || self.topViewController == nil) { navigationController.popViewController(animated: dismissViewControllerAnimated) } else if let parentViewController = self.parent { // The presenting view controller is responsible for dismissing the view controller it presented parentViewController.dismiss(animated: dismissViewControllerAnimated, completion: completion) } else if let topViewController = topViewController { topViewController.dismiss(animated: dismissViewControllerAnimated, completion: completion) } else { // keep old code... self.dismiss(animated: dismissViewControllerAnimated, completion: completion) } #elseif os(watchOS) self.dismiss() #elseif os(OSX) if self.presentingViewController != nil { self.dismiss(nil) if self.parent != nil { self.removeFromParent() } } else if let window = self.view.window { window.performClose(nil) } #endif } // MARK: overrides #if os(iOS) || os(tvOS) open override func viewWillAppear(_ animated: Bool) { self.delegate?.oauthWebViewControllerWillAppear() } open override func viewDidAppear(_ animated: Bool) { self.delegate?.oauthWebViewControllerDidAppear() } open override func viewWillDisappear(_ animated: Bool) { self.delegate?.oauthWebViewControllerWillDisappear() } open override func viewDidDisappear(_ animated: Bool) { self.delegate?.oauthWebViewControllerDidDisappear() } #elseif os(OSX) open override func viewWillAppear() { self.delegate?.oauthWebViewControllerWillAppear() } open override func viewDidAppear() { self.delegate?.oauthWebViewControllerDidAppear() } open override func viewWillDisappear() { self.delegate?.oauthWebViewControllerWillDisappear() } open override func viewDidDisappear() { self.delegate?.oauthWebViewControllerDidDisappear() } #endif }
42.446701
145
0.653671
1a75a9f065210c5f10e0b70cb18afe6bf5f3fdf2
1,503
// // PrimaryButton.swift // CaelinCore // // Created by Caelin Jackson-King on 2019-01-02. // import UIKit public class PrimaryButton: UIButton { static let height: CGFloat = 40 static let outsideMargin: CGFloat = 40 let colour: UIColor override public var isEnabled: Bool { didSet { self.backgroundColor = isEnabled ? colour : InterfaceColours.steel } } public init(text: String, colour: UIColor = .red) { self.colour = colour super.init(frame: .zero) self.setTitle(text, for: .normal) self.setTitle("Unavailable (\(text))", for: .disabled) self.layer.cornerRadius = PrimaryButton.height / 6 self.backgroundColor = colour self.translatesAutoresizingMaskIntoConstraints = false self.showsTouchWhenHighlighted = true } // MARK: Annoying Boilerplate required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PrimaryButton: OpinionatedView { public func buildConstraints() -> [NSLayoutConstraint] { guard let superview = superview else { return [] } return [ heightAnchor.constraint(equalToConstant: PrimaryButton.height), leftAnchor.constraint(equalTo: superview.leftAnchor, constant: PrimaryButton.outsideMargin), centerXAnchor.constraint(equalTo: superview.centerXAnchor) ] } }
28.903846
104
0.636727
75963deb13a6812dea242661f589a1ed7bf73058
2,493
// // AppDelegate.swift // Exmoney // // Created by Galina Gaynetdinova on 03/02/2017. // Copyright © 2017 Galina Gaynetdinova. All rights reserved. // import UIKit import RealmSwift var realm: Realm { get { do { let realm = try Realm() return realm } catch { print("Could not access database: ", error) } return realm } } let userDefaults = Foundation.UserDefaults.standard @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
39.571429
285
0.726434
1e8121f5e50c2a08b748eb33f4d3137ba0aefcf4
11,964
import Basic import Foundation import TuistCore import XcodeProj protocol ConfigGenerating: AnyObject { func generateProjectConfig(project: Project, pbxproj: PBXProj, fileElements: ProjectFileElements, options: GenerationOptions) throws -> XCConfigurationList func generateTargetConfig(_ target: Target, pbxTarget: PBXTarget, pbxproj: PBXProj, projectSettings: Settings, fileElements: ProjectFileElements, graph: Graphing, options: GenerationOptions, sourceRootPath: AbsolutePath) throws } final class ConfigGenerator: ConfigGenerating { // MARK: - Attributes let fileGenerator: FileGenerating // MARK: - Init init(fileGenerator: FileGenerating = FileGenerator()) { self.fileGenerator = fileGenerator } // MARK: - ConfigGenerating func generateProjectConfig(project: Project, pbxproj: PBXProj, fileElements: ProjectFileElements, options _: GenerationOptions) throws -> XCConfigurationList { /// Configuration list let configurationList = XCConfigurationList(buildConfigurations: []) pbxproj.add(object: configurationList) try project.settings.configurations.sortedByBuildConfigurationName().forEach { try generateProjectSettingsFor(buildConfiguration: $0.key, configuration: $0.value, project: project, fileElements: fileElements, pbxproj: pbxproj, configurationList: configurationList) } return configurationList } func generateTargetConfig(_ target: Target, pbxTarget: PBXTarget, pbxproj: PBXProj, projectSettings: Settings, fileElements: ProjectFileElements, graph: Graphing, options _: GenerationOptions, sourceRootPath: AbsolutePath) throws { let configurationList = XCConfigurationList(buildConfigurations: []) pbxproj.add(object: configurationList) pbxTarget.buildConfigurationList = configurationList let projectBuildConfigurations = projectSettings.configurations.keys let targetConfigurations = target.settings?.configurations ?? [:] let targetBuildConfigurations = targetConfigurations.keys let buildConfigurations = Set(projectBuildConfigurations).union(targetBuildConfigurations) let configurationsTuples: [(BuildConfiguration, Configuration?)] = buildConfigurations .map { buildConfiguration in if let configuration = target.settings?.configurations[buildConfiguration] { return (buildConfiguration, configuration) } return (buildConfiguration, nil) } let configurations = Dictionary(uniqueKeysWithValues: configurationsTuples) let nonEmptyConfigurations = !configurations.isEmpty ? configurations : Settings.default.configurations let orderedConfigurations = nonEmptyConfigurations.sortedByBuildConfigurationName() try orderedConfigurations.forEach { try generateTargetSettingsFor(target: target, buildConfiguration: $0.key, configuration: $0.value, fileElements: fileElements, graph: graph, pbxproj: pbxproj, configurationList: configurationList, sourceRootPath: sourceRootPath) } } // MARK: - Fileprivate private func generateProjectSettingsFor(buildConfiguration: BuildConfiguration, configuration: Configuration?, project: Project, fileElements: ProjectFileElements, pbxproj: PBXProj, configurationList: XCConfigurationList) throws { let variant: BuildSettingsProvider.Variant = (buildConfiguration == .debug) ? .debug : .release let defaultConfigSettings = BuildSettingsProvider.projectDefault(variant: variant) let defaultSettingsAll = BuildSettingsProvider.projectDefault(variant: .all) var settings: [String: Any] = [:] extend(buildSettings: &settings, with: defaultSettingsAll) extend(buildSettings: &settings, with: project.settings.base) extend(buildSettings: &settings, with: defaultConfigSettings) let variantBuildConfiguration = XCBuildConfiguration(name: buildConfiguration.xcodeValue, baseConfiguration: nil, buildSettings: [:]) if let variantConfig = configuration { extend(buildSettings: &settings, with: variantConfig.settings) if let xcconfig = variantConfig.xcconfig { let fileReference = fileElements.file(path: xcconfig) variantBuildConfiguration.baseConfiguration = fileReference } } variantBuildConfiguration.buildSettings = settings pbxproj.add(object: variantBuildConfiguration) configurationList.buildConfigurations.append(variantBuildConfiguration) } private func generateTargetSettingsFor(target: Target, buildConfiguration: BuildConfiguration, configuration: Configuration?, fileElements: ProjectFileElements, graph: Graphing, pbxproj: PBXProj, configurationList: XCConfigurationList, sourceRootPath: AbsolutePath) throws { let product = settingsProviderProduct(target) let platform = settingsProviderPlatform(target) let variant: BuildSettingsProvider.Variant = (buildConfiguration == .debug) ? .debug : .release var settings: [String: Any] = [:] extend(buildSettings: &settings, with: BuildSettingsProvider.targetDefault(variant: .all, platform: platform, product: product, swift: true)) extend(buildSettings: &settings, with: BuildSettingsProvider.targetDefault(variant: variant, platform: platform, product: product, swift: true)) extend(buildSettings: &settings, with: target.settings?.base ?? [:]) extend(buildSettings: &settings, with: configuration?.settings ?? [:]) let variantBuildConfiguration = XCBuildConfiguration(name: buildConfiguration.xcodeValue, baseConfiguration: nil, buildSettings: [:]) if let variantConfig = configuration, let xcconfig = variantConfig.xcconfig { let fileReference = fileElements.file(path: xcconfig) variantBuildConfiguration.baseConfiguration = fileReference } updateTargetDerived(buildSettings: &settings, target: target, graph: graph, sourceRootPath: sourceRootPath) variantBuildConfiguration.buildSettings = settings pbxproj.add(object: variantBuildConfiguration) configurationList.buildConfigurations.append(variantBuildConfiguration) } private func settingsProviderPlatform(_ target: Target) -> BuildSettingsProvider.Platform? { var platform: BuildSettingsProvider.Platform? switch target.platform { case .iOS: platform = .iOS case .macOS: platform = .macOS case .tvOS: platform = .tvOS // case .watchOS: platform = .watchOS } return platform } private func settingsProviderProduct(_ target: Target) -> BuildSettingsProvider.Product? { switch target.product { case .app: return .application case .dynamicLibrary: return .dynamicLibrary case .staticLibrary: return .staticLibrary case .framework, .staticFramework: return .framework default: return nil } } private func extend(buildSettings: inout [String: Any], with other: [String: Any]) { other.forEach { key, value in if buildSettings[key] == nil || (value as? String)?.contains("$(inherited)") == false { buildSettings[key] = value } else { let previousValue: Any = buildSettings[key]! if let previousValueString = previousValue as? String, let newValueString = value as? String { buildSettings[key] = "\(previousValueString) \(newValueString)" } else { buildSettings[key] = value } } } } private func updateTargetDerived(buildSettings settings: inout [String: Any], target: Target, graph: Graphing, sourceRootPath: AbsolutePath) { settings["PRODUCT_BUNDLE_IDENTIFIER"] = target.bundleId if let infoPlist = target.infoPlist { settings["INFOPLIST_FILE"] = "$(SRCROOT)/\(infoPlist.relative(to: sourceRootPath).pathString)" } if let entitlements = target.entitlements { settings["CODE_SIGN_ENTITLEMENTS"] = "$(SRCROOT)/\(entitlements.relative(to: sourceRootPath).pathString)" } settings["SDKROOT"] = target.platform.xcodeSdkRoot settings["SUPPORTED_PLATFORMS"] = target.platform.xcodeSupportedPlatforms // TODO: We should show a warning here if settings["SWIFT_VERSION"] == nil { settings["SWIFT_VERSION"] = Constants.swiftVersion } if target.product == .staticFramework { settings["MACH_O_TYPE"] = "staticlib" } if target.product.testsBundle { let appDependency = graph.targetDependencies(path: sourceRootPath, name: target.name).first { targetNode in targetNode.target.product == .app } if let app = appDependency { settings["TEST_TARGET_NAME"] = "\(app.target.name)" if target.product == .unitTests { settings["TEST_HOST"] = "$(BUILT_PRODUCTS_DIR)/\(app.target.productNameWithExtension)/\(app.target.name)" settings["BUNDLE_LOADER"] = "$(TEST_HOST)" } } } } }
48.634146
125
0.54338
6a624f40e32e6dbddd565344549e56724e9d863a
1,031
//tuples class dataStructs{ var tupleName = (1, 2.0, "a", "ab"); var error501 = (501, "not implemented") print("error /(error501)") //or var error501 = (errorCode: 501, description: "not implemented") print(error501.errorCode) print(error501.description) print("testing xocde \(10+10) with string interpolation ") // hold command and / to comment whole line out struct Town { //structs in swift let you create your own data structures let name:String var citizens:[String] var resources:[String: Int] init(name: String, people: [String], stats:[String:Int]){ self.name = name self.citizens = people self.resources = stats } func fortify(){ print("Wall created") } } var myTown = Town(name: "town name", people: ["person", "person 2"], stats: ["gold" : 100]) print(myTown.name) print(myTown.citizens[0]) print(myTown.resources["gold"]!) }
28.638889
95
0.580989
d70acd9e69953d2c8d200d689eca0b9387b7c3b2
3,661
// // TechStatusRouter.swift // RCNetworking // // Created by Rupesh Chhetri on 6/29/20. // Copyright © 2020 com.home.rupesh. All rights reserved. // import Foundation enum NewTechStatusRouter { case techStatus case updateTechStatus(techstatus: String, workOrderNumber: String?, acctNum: String, isPhtV4:Bool, eventID:String, isUpdateOnGeoFenceError: Bool, jobLocation: [String:String], techLocation: [String:String]) } /* extension NewTechStatusRouter: RouterConfig { fileprivate var microServicesPath: MicroserviceContent? { return ConfigurationManagerMiddleware.shared.properties?.microservices.techStatus } var host: String { return microServicesPath?.baseUrl ?? "" } var bodyParameters: [String : Any]? { return nil } var method: HTTPMethod { switch self { case .techStatus: return .get case .updateTechStatus(_,_,_,_,_,_,_,_): return .put } } var path: String { switch self { case .techStatus: return microServicesPath?.search(forKey: .GET_TECH_STATUS)?.value ?? "" case .updateTechStatus(_,_,_,_,_,_,_,_): return microServicesPath?.search(forKey: .UPDATE_TECH_STATUS)!.value ?? "" } } var headers: HTTPHeaders { var _headers = CCAppHeaders.tech360Headers() var headerInfo: String? switch self { case .techStatus: headerInfo = microServicesPath?.search(forKey: .GET_TECH_STATUS)?.xVersion case .updateTechStatus(_,_,_,_,_,_,_,_): headerInfo = microServicesPath?.search(forKey: .UPDATE_TECH_STATUS)?.xVersion } if let xVersion = headerInfo { _headers[HTTPHeaderKey.CustomKey.version.rawValue] = xVersion } return _headers } var timeoutInterval: TimeInterval? { let defaultTimeoutString = "\(String(NetworkCommon.shared.defaultTimeout))" switch self { case .techStatus: return Double(microServicesPath?.search(forKey: .GET_TECH_STATUS)?.timeout ?? defaultTimeoutString)! case .updateTechStatus(_,_,_,_,_,_,_,_): return Double(microServicesPath?.search(forKey: .UPDATE_TECH_STATUS)?.timeout ?? defaultTimeoutString)! } } // FIXME:- need to use QueryParams type var queryItems: [String: Any]? { switch self { case .techStatus: return nil case .updateTechStatus(let techstatus, let workOrderNumber, let acctNum, let phtV4,let eventID, let isUpdateOnGeoFenceError, let jobLocation, let techLocation): if let woNum = workOrderNumber { return [ Constants.UpdateTechStatusParams.techStatus.rawValue: techstatus as Any, Constants.UpdateTechStatusParams.workOrderNumber.rawValue:woNum as Any, Constants.UpdateTechStatusParams.accountNumber.rawValue: acctNum as Any, Constants.UpdateTechStatusParams.phtV4.rawValue: phtV4 as Any, Constants.UpdateTechStatusParams.isUpdateOnGeoFenceError.rawValue: isUpdateOnGeoFenceError as Any, Constants.UpdateTechStatusParams.jobLocation.rawValue: jobLocation as Any, Constants.UpdateTechStatusParams.techLocation.rawValue: techLocation as Any ] } return [Constants.UpdateTechStatusParams.techStatus.rawValue: techstatus,Constants.UpdateTechStatusParams.eventID.rawValue:eventID] } } } */
33.281818
210
0.636984
acd3885dad75e4e11f1c41944d3d325d5b26184d
554
// // Color+Extension.swift // Shine // // Created by Jovins on 2021/8/1. // import SwiftUI extension Color { // eg: Color(hex: 0x5a5a5a) init(hex: Int, alpha: Double = 1) { let components = ( R: Double((hex >> 16) & 0xff) / 255, G: Double((hex >> 08) & 0xff) / 255, B: Double((hex >> 00) & 0xff) / 255 ) self.init( .sRGB, red: components.R, green: components.G, blue: components.B, opacity: alpha ) } }
19.785714
48
0.456679
01cdd72c59d7ff5a550ba11a6346ffa181e77188
852
import CoreGraphics public struct HorizontalAlignment: Hashable { let key: AlignmentKey public init(_ id: AlignmentID.Type) { let bits = unsafeBitCast(id as Any.Type, to: UInt.self) self.key = AlignmentKey(bits: bits) } } extension HorizontalAlignment { enum Leading: AlignmentID { static func defaultValue(in context: ViewDimensions) -> CGFloat { 0 } } public static let leading = HorizontalAlignment(Leading.self) enum Center: AlignmentID { static func defaultValue(in context: ViewDimensions) -> CGFloat { context.width / 2 } } public static let center = HorizontalAlignment(Center.self) enum Trailing: AlignmentID { static func defaultValue(in context: ViewDimensions) -> CGFloat { context.width } } public static let trailing = HorizontalAlignment(Trailing.self) }
23.027027
69
0.707746
e23a6a6dbcf38e848cace98ab546b956414f3e0e
1,542
/* * Copyright (c) 2018 Nordic Semiconductor ASA. * * SPDX-License-Identifier: Apache-2.0 */ import UIKit class RootViewController: UINavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() if #available(iOS 13.0, *) { let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() navBarAppearance.backgroundColor = UIColor.dynamicColor(light: .nordic, dark: .black) navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] navigationBar.standardAppearance = navBarAppearance navigationBar.scrollEdgeAppearance = navBarAppearance } else { // Fallback on earlier versions } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let introShown = UserDefaults.standard.bool(forKey: "introShown") if !introShown { UserDefaults.standard.set(true, forKey: "introShown") showIntro(animated: false) } } func showIntro(animated: Bool) { if let intro = storyboard?.instantiateViewController(withIdentifier: "intro") { intro.modalPresentationStyle = .fullScreen present(intro, animated: animated) } } }
32.808511
97
0.652399
16bf4dc568a4531eca06b42534dca63759d337af
1,027
// // YGHorizontalScrollerDemoTests.swift // YGHorizontalScrollerDemoTests // // Created by Yi Gu on 5/9/16. // Copyright © 2016 yigu. All rights reserved. // import XCTest @testable import YGHorizontalScrollerDemo class YGHorizontalScrollerDemoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
27.756757
111
0.653359
acc492a383d251d3b2f93bd51a53e0828c771c1c
2,177
// // AppDelegate.swift // ManejoLocalizacion // // Created by Carlos on 16/08/2017. // Copyright © 2017 Woowrale. 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.319149
285
0.756086
61db476aada10dd5c29b51c1100d9514072c35c6
5,025
// // NotificationHandler.swift // UserNotificationDemo // // Created by WANG WEI on 2016/08/03. // Copyright © 2016年 OneV's Den. All rights reserved. // import UIKit import UserNotifications enum UserNotificationType: String { case timeInterval case timeIntervalForeground case pendingRemoval case pendingUpdate case deliveredRemoval case deliveredUpdate case actionable case mutableContent case media case customUI } extension UserNotificationType { var descriptionText: String { switch self { case .timeInterval: return "You need to switch to background to see the notification." case .timeIntervalForeground: return "The notification will show in-app. See NotificationHandler for more." default: return rawValue } } var title: String { switch self { case .timeInterval: return "Time" case .timeIntervalForeground: return "Foreground" default: return rawValue } } } enum UserNotificationCategoryType: String { case saySomething case customUI } enum SaySomethingCategoryAction: String { case input case goodbye case none } enum CustomizeUICategoryAction: String { case `switch` case open case dismiss } class NotificationHandler: NSObject, UNUserNotificationCenterDelegate { fileprivate let speecher = Speaker() // The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { guard let notificationType = UserNotificationType(rawValue: notification.request.identifier) else { completionHandler([]) return } let options: UNNotificationPresentationOptions switch notificationType { case .timeIntervalForeground: options = [.alert, .sound] case .pendingRemoval: options = [.alert, .sound] case .pendingUpdate: options = [.alert, .sound] case .deliveredRemoval: options = [.alert, .sound] case .deliveredUpdate: options = [.alert, .sound] case .actionable: options = [.alert, .sound] case .media: options = [.alert, .sound] default: options = [] } completionHandler(options) } // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { if let speech = response.notification.request.content.userInfo["speech"] as? String { speecher.speak(content: speech) } else { speecher.speak(content: "收到一个没有speech字段的通知") } if let category = UserNotificationCategoryType(rawValue: response.notification.request.content.categoryIdentifier) { switch category { case .saySomething: handleSaySomthing(response: response) case .customUI: handleCustomUI(response: response) } } completionHandler() } @available(iOS 10.0, *) private func handleSaySomthing(response: UNNotificationResponse) { let text: String if let actionType = SaySomethingCategoryAction(rawValue: response.actionIdentifier) { switch actionType { case .input: text = (response as! UNTextInputNotificationResponse).userText case .goodbye: text = "Goodbye" case .none: text = "" } } else { // Only tap or clear. (You will not receive this callback when user clear your notification unless you set .customDismissAction as the option of category) text = "" } if !text.isEmpty { UIAlertController.showConfirmAlertFromTopViewController(message: "You just said \(text)") } } @available(iOS 10.0, *) private func handleCustomUI(response: UNNotificationResponse) { print(response.actionIdentifier) } }
34.895833
451
0.662886
56f86dbbf8661d3495f663a59ca8ec001acd235a
1,250
// // WalletBackupCautionRouter.swift // RaccoonWallet // // Created by Taizo Kusuda on 2018/08/23. // Copyright © 2018年 T TECH, LIMITED LIABILITY CO. All rights reserved. // import Foundation import UIKit class WalletBackupCautionRouter: WalletBackupCautionWireframe { weak var viewController: UIViewController? static func assembleModule(_ wallet: Wallet, from origin: WalletBackupOrigin) -> UIViewController { let view = R.storyboard.walletBackupCautionStoryboard.walletBackupCautionView()! let presenter = WalletBackupCautionPresenter() let interactor = WalletBackupCautionInteractor() let router = WalletBackupCautionRouter() view.presenter = presenter presenter.view = view presenter.interactor = interactor presenter.router = router presenter.wallet = wallet presenter.origin = origin interactor.output = presenter router.viewController = view return view } func presentWalletBackup(_ wallet: Wallet, from origin: WalletBackupOrigin) { viewController?.navigationController?.pushViewController(WalletBackupRouter.assembleModule(wallet, from: origin), animated: true) } }
31.25
137
0.7056
2315b1d53ac230a841d2991994111ff68f982e05
6,687
// // MessagesViewController.swift // MessagesExtension // // Created by Hossam Ghareeb on 7/20/16. // Copyright © 2016 Hossam Ghareeb. All rights reserved. // import UIKit import Messages import GoogleAPIClient import GTMOAuth2 class MessagesViewController: MSMessagesAppViewController { private let kKeychainItemName = "Drive API" private let kClientID = "718517467805-eee201q0idi08q8l9tkbmkh2nr63m9pn.apps.googleusercontent.com" // If modifying these scopes, delete your previously saved credentials by // resetting the iOS simulator or uninstall the app. private let scopes = [kGTLAuthScopeDriveMetadataReadonly] private let service = GTLServiceDrive() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychain(forName: kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth } } override func viewDidAppear(_ animated: Bool) { if let authorizer = service.authorizer, let canAuth = authorizer.canAuthorize, canAuth { fetchFiles() } else { present(createAuthController(), animated: true, completion: nil) } } // Construct a query to get names and IDs of 10 files using the Google Drive API func fetchFiles() { if let query = GTLQueryDrive.queryForFilesList(){ query.pageSize = 20 query.fields = "nextPageToken, files(id, name, webViewLink, webContentLink)" service.executeQuery(query, delegate: self, didFinish: #selector(MessagesViewController.displayResultWithTicket(ticket:finishedWithObject:error:))) } } // Parse results and display func displayResultWithTicket(ticket : GTLServiceTicket, finishedWithObject response : GTLDriveFileList, error : NSError?) { if let error = error { showAlert(title: "Error", message: error.localizedDescription) return } var filesString = "" let files = response.files as! [GTLDriveFile] if !files.isEmpty{ filesString += "Files:\n" for file in files { filesString += "\(file.name) (\(file.webContentLink) (\(file.webViewLink))\n" } } else { filesString = "No files found." } print(filesString) } // Creates the auth controller for authorizing access to Drive API private func createAuthController() -> GTMOAuth2ViewControllerTouch { let scopeString = scopes.joined(separator:" ") return GTMOAuth2ViewControllerTouch( scope: scopeString, clientID: kClientID, clientSecret: nil, keychainItemName: kKeychainItemName, delegate: self, finishedSelector: #selector(MessagesViewController.viewController(vc:finishedWithAuth:error:)) ) } // Handle completion of the authorization process, and update the Drive API // with the new credentials. func viewController(vc : UIViewController, finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) { if let error = error { service.authorizer = nil showAlert(title: "Authentication Error", message: error.localizedDescription) return } service.authorizer = authResult dismiss(animated: true, completion: nil) fetchFiles() } // Helper for showing an alert func showAlert(title : String, message: String) { let alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) let ok = UIAlertAction( title: "OK", style: UIAlertActionStyle.default, handler: nil ) alert.addAction(ok) present(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Conversation Handling override func willBecomeActive(with conversation: MSConversation) { // Called when the extension is about to move from the inactive to active state. // This will happen when the extension is about to present UI. // Use this method to configure the extension and restore previously stored state. } override func didResignActive(with conversation: MSConversation) { // Called when the extension is about to move from the active to inactive state. // This will happen when the user dissmises the extension, changes to a different // conversation or quits Messages. // Use this method to release shared resources, save user data, invalidate timers, // and store enough state information to restore your extension to its current state // in case it is terminated later. } override func didReceive(_ message: MSMessage, conversation: MSConversation) { // Called when a message arrives that was generated by another instance of this // extension on a remote device. // Use this method to trigger UI updates in response to the message. } override func didStartSending(_ message: MSMessage, conversation: MSConversation) { // Called when the user taps the send button. } override func didCancelSending(_ message: MSMessage, conversation: MSConversation) { // Called when the user deletes the message without sending it. // Use this to clean up state related to the deleted message. } override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) { // Called before the extension transitions to a new presentation style. // Use this method to prepare for the change in presentation style. } override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) { // Called after the extension transitions to a new presentation style. // Use this method to finalize any behaviors associated with the change in presentation style. } }
35.194737
159
0.630776
efba5f33c717bb68be5d6c50e99039da916a6e01
232
// // PresentingByLocation.swift // Remindly // // Created by Joachim Kret on 26.01.2018. // Copyright © 2018 JK. All rights reserved. // import Foundation protocol PresentingByLocation { func show(_ location: Location) }
16.571429
45
0.706897
d715ec367cb78267b82ea7b7f0aa1406a6c7a513
2,225
// // WKWebView+Extensions.swift // Pods // // Created by Andron338 on 13/5/20. // // import WebKit var toolBarHandle: UInt8 = 0 extension WKWebView { func addInputAccessoryView(toolbar: UIView?) { guard let toolbar = toolbar else {return} objc_setAssociatedObject(self, &toolBarHandle, toolbar, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) var candidateView: UIView? = nil for view in self.scrollView.subviews { let description : String = String(describing: type(of: view)) if description.hasPrefix("WKContent") { candidateView = view break } } guard let targetView = candidateView else {return} let newClass: AnyClass? = classWithCustomAccessoryView(targetView: targetView) guard let targetNewClass = newClass else {return} object_setClass(targetView, targetNewClass) } func classWithCustomAccessoryView(targetView: UIView) -> AnyClass? { guard let _ = targetView.superclass else {return nil} let customInputAccesoryViewClassName = "_CustomInputAccessoryView" var newClass: AnyClass? = NSClassFromString(customInputAccesoryViewClassName) if newClass == nil { newClass = objc_allocateClassPair(object_getClass(targetView), customInputAccesoryViewClassName, 0) } else { return newClass } let newMethod = class_getInstanceMethod(WKWebView.self, #selector(WKWebView.getCustomInputAccessoryView)) class_addMethod(newClass.self, #selector(getter: WKWebView.inputAccessoryView), method_getImplementation(newMethod!), method_getTypeEncoding(newMethod!)) objc_registerClassPair(newClass!) return newClass } @objc func getCustomInputAccessoryView() -> UIView? { var superWebView: UIView? = self while (superWebView != nil) && !(superWebView is WKWebView) { superWebView = superWebView?.superview } guard let webView = superWebView else {return nil} let customInputAccessory = objc_getAssociatedObject(webView, &toolBarHandle) return customInputAccessory as? UIView } }
34.230769
161
0.681348
67fc0403675f9531361651624c199a2e6ff94a02
3,051
// // SettingsPasswordViewController.swift // BillionWallet // // Created by Evolution Group Ltd on 10/08/2017. // Copyright © 2017 Evolution Group Ltd. All rights reserved. // import UIKit class SettingsPasswordViewController: BaseViewController<SettingsPasswordVM> { typealias LocalizedStrings = Strings.Settings.Password weak var router: MainRouter? fileprivate var dataManager: StackViewDataManager! fileprivate var titledView: TitledView! fileprivate var menuStackView: MenuStackView! override func viewDidLoad() { super.viewDidLoad() setupMenuStackView() viewModel.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) removeSwipeDownGesture() navigationController?.addSwipeDownPop() } fileprivate func setupMenuStackView() { titledView = TitledView() titledView.title = viewModel.title titledView.subtitle = viewModel.subtitle view.addSubview(titledView) menuStackView = MenuStackView() view.addSubview(menuStackView) dataManager = StackViewDataManager(stackView: menuStackView.stackView) } fileprivate func show(isTouchIdEnabled: Bool) { let title = viewModel.securityButtonTitle dataManager.clear() dataManager.append(container: ViewContainer<SectionView>(item: [ ViewContainer<SwitchSheetView>(item: (title: title, isOn: isTouchIdEnabled), actions: [touchIdAction()]), ViewContainer<ButtonSheetView>(item: .filetree(title: LocalizedStrings.passwordChange), actions: [changePasswordAction()]) ])) dataManager.append(container: ViewContainer<SectionView>(item: [ ViewContainer<ButtonSheetView>(item: .default(title: LocalizedStrings.back), actions: [dismissAction()]) ])) menuStackView.resize(in: view) } fileprivate func touchIdAction() -> ViewContainerAction<SwitchSheetView> { return ViewContainerAction<SwitchSheetView>(.switch) { [weak self] data in guard let isOn = data.userInfo?["isOn"] as? Bool else { return } self?.viewModel.isTouchIdEnabled = isOn } } fileprivate func changePasswordAction() -> ViewContainerAction<ButtonSheetView> { return ViewContainerAction<ButtonSheetView>(.click) { [weak self] data in self?.router?.showPasscodeView(passcodeCase: .updateOld, output: self?.viewModel) } } } // MARK: - SettingsPasswordVMDelegate extension SettingsPasswordViewController: SettingsPasswordVMDelegate { func didEnableTouchId(_ isOn: Bool) { show(isTouchIdEnabled: isOn) } func didPasswordChanged() { let popup = PopupView(type: .ok, labelString: LocalizedStrings.passwordChanged) UIApplication.shared.keyWindow?.addSubview(popup) } }
32.806452
138
0.663061
5d0224bff7e07cb67fe5e0ea5273f80d2d7aa376
893
// // MovieFlickrPhotosRepositoryMock.swift // Decade of MoviesTests // // Created by marko nazmy on 7/20/20. // Copyright © 2020 MarkoNazmy. All rights reserved. // import Foundation @testable import Decade_of_Movies struct SuccessMovieFlickrPhotosRepositoryMock: MovieFlickrPhotosRepositoryProtocol { func fetchMoviesList(movieTitle: String, page: Int, photosPerPage: Int, result: @escaping MovieFlickrPhotosResult) { if page == 1 { result(.success(response: photosResponse1)) } else { result(.success(response: photosResponse2)) } } } struct FailureMovieFlickrPhotosRepositoryMock: MovieFlickrPhotosRepositoryProtocol { func fetchMoviesList(movieTitle: String, page: Int, photosPerPage: Int, result: @escaping MovieFlickrPhotosResult) { result(.failure(error: AppError(fromError: nil))) } }
28.806452
120
0.712206
ccf09ad339dcfe985ab343158b75862658a1ecb3
324
// // MovieCollectionViewCell.swift // Flicks // // Created by Quoc Huy Ngo on 10/15/16. // Copyright © 2016 Quoc Huy Ngo. All rights reserved. // import UIKit class MovieCollectionViewCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var posterImageView: UIImageView! }
20.25
55
0.719136
0a39c7b9fcf147c783ef6fe6d65b4ff8199d1973
1,113
import Intents import CoreLocation class IntentHandler: INExtension, SelectRegionIntentHandling { func provideRegionOptionsCollection(for intent: SelectRegionIntent, with completion: @escaping (INObjectCollection<RegionConfigOption>?, Error?) -> Void) { let options = CLLocationManager().isAuthorizedForWidgetUpdates ? RegionOption.allOptions : RegionOption.aRegions let regions: [RegionConfigOption] = options.map { region in let option = RegionConfigOption( identifier: "\(region.id)", display: region.name) option.regionId = NSNumber(value: region.id) return option } let collection = INObjectCollection(items: regions) completion(collection, nil); } override func handler(for intent: INIntent) -> Any { // This is the default implementation. If you want different objects to handle different intents, // you can override this and return the handler you want for that particular intent. return self } }
38.37931
167
0.65319
f5daa26e0b483a19e174a3500c01c9646dad9e28
2,193
// // AppDelegate.swift // currency-converter // // Created by WF | Dimitar Zabaznoski on 1/27/19. // Copyright © 2019 WebFactory. 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.659574
285
0.755586
1abaf0474f1a46d053a33b80de2e0ef10399b019
2,545
// // ViewController.swift // CustomPinProject // // Created by Jeff Schmitz on 1/7/17. // Copyright © 2017 Codefume. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.mapView.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Center the map on Boston let BostonCoordinates: CLLocationCoordinate2D = CLLocationCoordinate2DMake(42.3601, -71.0589) let viewRegion: MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(BostonCoordinates, 500, 500) let adjustedRegion: MKCoordinateRegion = self.mapView!.regionThatFits(viewRegion) self.mapView?.setRegion(adjustedRegion, animated:true) let point1: CustomPointAnnotation = CustomPointAnnotation() point1.coordinate = CLLocationCoordinate2DMake(42.3601, -71.0589) point1.price = 3 self.mapView?.addAnnotation(point1) let point2: CustomPointAnnotation = CustomPointAnnotation() point2.coordinate = CLLocationCoordinate2DMake(42.3606, -71.0583) point2.price = 5 self.mapView?.addAnnotation(point2) } // MARK: - MKMapViewDelegate func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { // Don't do anything if it's the users location if annotation is MKUserLocation { return nil } var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "Pin") if annotationView == nil { if annotation is CustomPointAnnotation { // annotationView = CustomPinAnnotationView(annotation: annotation) annotationView = CustomPinAnnotationView(annotation: annotation, reuseIdentifier: "Pin") annotationView?.canShowCallout = false } else { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "Pin") } } else { annotationView?.annotation = annotation } return annotationView } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { if view.isKind(of: CustomPinAnnotationView.self) { for subView in view.subviews { subView.removeFromSuperview() } } } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { print("Selected annotation: \(view.description)") } }
31.419753
104
0.715521
8f6c07254f4e3c3fcb548efc25f994bd33de79b1
548
// // AppDelegate.swift // Mach-SwiftDemo-macOS // // Created by Daisuke T on 2019/04/10. // Copyright © 2019 Mach-SwiftDemo-macOS. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
20.296296
71
0.684307
8951c6febd8c4cccb7767c3495a7ae7473907072
378
// // Language.swift // MuslimData // // Created by Kosrat D. Ahmad on 10/11/18. // import Foundation /// List of languages that supported by MuslimData database for translations /// /// - en: English /// - ar: Arabic /// - ckb: Central Kurdish /// - fa: Farsi /// - ru: Russian public enum Language: String { case en case ar case ckb case fa case ru }
15.75
76
0.624339
b9a5812b4c2cb886dcdd8d3c1c2564d7b8b1fcd8
5,037
/// Continuation.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Moho public struct ParameterSemantics { var parameter: Parameter var mustDestroy: Bool } public final class Continuation: NominalValue, GraphNode { public enum CallingConvention { /// The default calling convention for Silt functions. case `default` /// The indirect calling convention for Silt functions. /// /// When calling the function, an extra indirect return parameter is /// added before the return continuation parameter. The caller is required /// to allocate a buffer of the appropriate size and pass it in that /// position. The callee is then required to initialize that buffer by /// storing into it before the return continuation is called with the /// caller-provided buffer. Finally, the return continuation must be /// caller-controlled and call the appropriate resource destruction primop /// on the buffer it allocated. case indirectResult } public private(set) var parameters = [Parameter]() public private(set) var indirectReturnParameter: Parameter? public private(set) var cleanups = [PrimOp]() public let bblikeSuffix: String? weak var module: GIRModule? var predecessorList: Successor public weak var terminalOp: TerminalOp? public var hasPredecessors: Bool { return self.predecessorList.next != nil } public var singlePredecessor: Continuation? { let it = self.predecessors.makeIterator() guard it.next() != nil else { return nil } return it.next() } public var predecessors: AnySequence<Continuation> { return AnySequence { () in return PredecessorIterator(self.predecessorList) } } public var successors: [Continuation] { guard let terminal = self.terminalOp else { return [] } return terminal.successors.map { succ in return succ.successor! } } public var callingConvention: CallingConvention { if self.indirectReturnParameter != nil { return .indirectResult } return .default } public init(name: QualifiedName, suffix: String? = nil) { self.predecessorList = Successor(nil) self.bblikeSuffix = suffix super.init(name: name, type: BottomType.shared /*to be overwritten*/, category: .address) } @discardableResult public func appendParameter(type: GIRType) -> Parameter { let param = Parameter(parent: self, index: parameters.count, type: type) parameters.append(param) return param } public func appendCleanupOp(_ cleanup: PrimOp) { self.cleanups.append(cleanup) } @discardableResult public func appendIndirectReturnParameter(type: GIRType) -> Parameter { precondition(type.category == .address, "Can only add indirect return parameter with address type") let param = Parameter(parent: self, index: parameters.count, type: type) indirectReturnParameter = param parameters.append(param) return param } @discardableResult public func setReturnParameter(type: Value) -> Parameter { guard let module = module else { fatalError() } let returnTy = module.functionType(arguments: [type], returnType: module.bottomType) let param = Parameter(parent: self, index: parameters.count, type: returnTy) parameters.append(param) return param } public var returnValueType: Value { guard let module = module else { fatalError() } guard let lastTy = parameters.last?.type else { return module.bottomType } guard let funcTy = lastTy as? FunctionType else { return module.bottomType } return funcTy.arguments[0] } public var formalParameters: [Parameter] { // FIXME: This is a bloody awful heuristic for this. guard self.bblikeSuffix == nil else { return self.parameters } return Array(self.parameters.dropLast()) } public override var type: Value { guard let module = module else { fatalError("cannot get type of Continuation without module") } let returnTy = parameters.last?.type ?? module.bottomType let paramTys = parameters.dropLast().map { $0.type } return module.functionType(arguments: paramTys, returnType: returnTy) } public override func mangle<M: Mangler>(into mangler: inout M) { self.module?.mangle(into: &mangler) Identifier(self.baseName + (self.bblikeSuffix ?? "")).mangle(into: &mangler) guard let contTy = self.type as? FunctionType else { fatalError() } self.returnValueType.mangle(into: &mangler) contTy.arguments.mangle(into: &mangler) mangler.append("f") mangler.append("F") } } extension Continuation: DeclarationContext { public var contextKind: DeclarationContextKind { return .continuation } public var parent: DeclarationContext? { return self.module } }
30.161677
80
0.691086
219a25738c3dccb23b5e6d644ebc4dff9e75ad37
1,413
// // Created for xikolo-ios under MIT license. // Copyright © HPI. All rights reserved. // import Foundation import SyncEngine final class QuizOption: NSObject, NSCoding, IncludedPullable { var id: String var text: String? var position: Int32 var correct: Bool var explanation: String? required init(object: ResourceData) throws { self.id = try object.value(for: "id") self.text = try object.value(for: "text") self.position = try object.value(for: "position") self.correct = try object.value(for: "correct") self.explanation = try object.value(for: "explanation") } required init?(coder decoder: NSCoder) { guard let id = decoder.decodeObject(forKey: "id") as? String else { return nil } self.id = id self.text = decoder.decodeObject(forKey: "text") as? String self.position = decoder.decodeInt32(forKey: "position") self.correct = decoder.decodeBool(forKey: "correct") self.explanation = decoder.decodeObject(forKey: "explanation") as? String } func encode(with coder: NSCoder) { coder.encode(self.id, forKey: "id") coder.encode(self.text, forKey: "text") coder.encode(self.position, forKey: "position") coder.encode(self.correct, forKey: "correct") coder.encode(self.explanation, forKey: "explanation") } }
30.717391
81
0.641897
09486f4eba64919a9e13af6529ce48ac1371b9d3
191
// // Description.swift // TodayNews // // Created by shi_mhua on 2019/7/10. // Copyright © 2019 chisalsoft. All rights reserved. // import Foundation /** 这里的类作用: 小Demo,用于熟悉第三方框架 */
12.733333
53
0.664921
91518e7c12d3a3557802c42ce511834d97791ba5
2,119
// // Copyright © 2016 Square, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import CoreAardvark import Foundation @objc public class Aardvark : NSObject { /// Creates and returns a gesture recognizer that when triggered will call `bugReporter.composeBugReport()`. @nonobjc public static func add<GestureRecognizer: UIGestureRecognizer>( bugReporter: ARKBugReporter, triggeringGestureRecognizerClass: GestureRecognizer.Type ) -> GestureRecognizer? { return UIApplication.shared.add( bugReporter: bugReporter, triggeringGestureRecognizerClass: triggeringGestureRecognizerClass ) } /// Creates and returns a gesture recognizer that when triggered will call `bugReporter.composeBugReport()`. @objc(addBugReporter:gestureRecognizerClass:) public static func objc_add( bugReporter: ARKBugReporter, triggeringGestureRecognizerClass gestureRecognizerClass: AnyClass ) -> AnyObject? { guard let triggeringGestureRecognizerClass = gestureRecognizerClass as? UIGestureRecognizer.Type else { noteImproperAPIUse("\(gestureRecognizerClass) is not a gesture recognizer class!") return nil } return UIApplication.shared.add( bugReporter: bugReporter, triggeringGestureRecognizerClass: triggeringGestureRecognizerClass ) } } func noteImproperAPIUse(_ message: String) { do { throw NSError(domain: "ARKImproperAPIUsageDomain", code: 0, userInfo: nil) } catch _ { NSLog(message) } }
35.316667
112
0.710241
69d8863da00795893c2f16cb135a22370c848db4
6,072
// // HLSWriterTests.swift // mamba // // Created by David Coufal on 7/13/16. // Copyright © 2016 Comcast Cable Communications Management, LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import mamba class HLSWriterTests: XCTestCase { let roundTripTestFixture = "hls_writer_parser_roundtrip_tester.txt" let positionOfSEQUENCETag = 66 // the position of a #EXT-X-MEDIA-SEQUENCE tag in the playlist // MARK: Test Success Paths func testWriterParserRoundTrip_String() { guard let hlsString = FixtureLoader.loadAsString(fixtureName: roundTripTestFixture as NSString) else { XCTAssert(false, "Fixture is missing?") return } do { let writer = HLSWriter(suppressMambaIdentityString: true) let playlist = parseMasterPlaylist(inString: hlsString) let stream = OutputStream.toMemory() stream.open() try writer.write(playlist: playlist, toStream: stream) guard let data = stream.property(forKey: .dataWrittenToMemoryStreamKey) as? Data else { XCTFail("No data written in write from HLSWriter") return } let hlsOut = String(data: data, encoding: .utf8)! stream.close() XCTAssert(hlsOut == hlsString, "Incoming HLS not identical to Output HLS") } catch { XCTAssert(false, "Exception was thrown while parsing: \(error)") } } // MARK: Test Failure Paths func testWriterParserRoundTrip_StringFailure() { guard let hlsString = FixtureLoader.loadAsString(fixtureName: roundTripTestFixture as NSString) else { XCTAssert(false, "Fixture is missing?") return } let stream = OutputStream.toMemory() stream.open() do { let writer = HLSWriter() var playlist = parseMasterPlaylist(inString: hlsString) // remove a required value to force a failure of the writer XCTAssert(playlist.tags[positionOfSEQUENCETag].tagDescriptor == PantosTag.EXT_X_MEDIA_SEQUENCE, "If this fails, the \"\(roundTripTestFixture)\" fixture has been edited so that a EXT_X_MEDIA_SEQUENCE tag is no longer in the \(positionOfSEQUENCETag)st spot. Adjust the number so that we grab the correct tag.") var tag = playlist.tags[positionOfSEQUENCETag] tag.removeValue(forValueIdentifier: PantosValue.sequence) // we have to have a single value for a single-value tag, so replace the removed sequence number with this dummy value tag.set(value: "dummy_value", forKey: "dummy_key") playlist.delete(atIndex: positionOfSEQUENCETag) playlist.insert(tag: tag, atIndex: positionOfSEQUENCETag) try writer.write(playlist: playlist, toStream: stream) XCTAssert(false, "Expecting an exception") } catch OutputStreamError.invalidData(_) { // expected } catch { XCTAssert(false, "Exception was thrown while parsing: \(error)") } stream.close() } func testCustomIdentityString() { guard let hlsString = FixtureLoader.loadAsString(fixtureName: "hls_singleMediaFile.txt" as NSString) else { XCTAssert(false, "Fixture is missing?") return } do { let sampleIdentityString = " Sample Ident String" let writer = HLSWriter(identityString: sampleIdentityString) let playlist = parseVariantPlaylist(inString: hlsString) let stream = OutputStream.toMemory() stream.open() try writer.write(playlist: playlist, toStream: stream) guard let data = stream.property(forKey: .dataWrittenToMemoryStreamKey) as? Data else { XCTFail("No data written in write from HLSWriter") return } let hlsOut = String(data: data, encoding: .utf8)! stream.close() XCTAssert(hlsOut.hasPrefix("#EXTM3U\n#\(sampleIdentityString)\n\(standardMambaString)")) } catch { XCTAssert(false, "Exception was thrown while parsing: \(error)") } } func testMambaStandardString() { guard let hlsString = FixtureLoader.loadAsString(fixtureName: "hls_singleMediaFile.txt" as NSString) else { XCTAssert(false, "Fixture is missing?") return } do { let writer = HLSWriter() let playlist = parseVariantPlaylist(inString: hlsString) let stream = OutputStream.toMemory() stream.open() try writer.write(playlist: playlist, toStream: stream) guard let data = stream.property(forKey: .dataWrittenToMemoryStreamKey) as? Data else { XCTFail("No data written in write from HLSWriter") return } let hlsOut = String(data: data, encoding: .utf8)! stream.close() XCTAssert(hlsOut.hasPrefix("#EXTM3U\n\(standardMambaString)")) } catch { XCTAssert(false, "Exception was thrown while parsing: \(error)") } } let standardMambaString = "# Generated by Mamba(\(Mamba.version)) Copyright (c) 2017 Comcast Corporation\n" }
39.174194
320
0.61693
d5ddc6bc7717dc6e49458415c74a95aef9b2588b
7,211
// // InlineKeyboardButtonType.swift // tl2swift // // Created by Code Generator // import Foundation /// Describes the type of an inline keyboard button public enum InlineKeyboardButtonType: Codable { /// A button that opens a specified URL case inlineKeyboardButtonTypeUrl(InlineKeyboardButtonTypeUrl) /// A button that opens a specified URL and automatically authorize the current user if allowed to do so case inlineKeyboardButtonTypeLoginUrl(InlineKeyboardButtonTypeLoginUrl) /// A button that sends a callback query to a bot case inlineKeyboardButtonTypeCallback(InlineKeyboardButtonTypeCallback) /// A button that asks for password of the current user and then sends a callback query to a bot case inlineKeyboardButtonTypeCallbackWithPassword(InlineKeyboardButtonTypeCallbackWithPassword) /// A button with a game that sends a callback query to a bot. This button must be in the first column and row of the keyboard and can be attached only to a message with content of the type messageGame case inlineKeyboardButtonTypeCallbackGame /// A button that forces an inline query to the bot to be inserted in the input field case inlineKeyboardButtonTypeSwitchInline(InlineKeyboardButtonTypeSwitchInline) /// A button to buy something. This button must be in the first column and row of the keyboard and can be attached only to a message with content of the type messageInvoice case inlineKeyboardButtonTypeBuy /// A button to open a chat with a user case inlineKeyboardButtonTypeUser(InlineKeyboardButtonTypeUser) private enum Kind: String, Codable { case inlineKeyboardButtonTypeUrl case inlineKeyboardButtonTypeLoginUrl case inlineKeyboardButtonTypeCallback case inlineKeyboardButtonTypeCallbackWithPassword case inlineKeyboardButtonTypeCallbackGame case inlineKeyboardButtonTypeSwitchInline case inlineKeyboardButtonTypeBuy case inlineKeyboardButtonTypeUser } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: DtoCodingKeys.self) let type = try container.decode(Kind.self, forKey: .type) switch type { case .inlineKeyboardButtonTypeUrl: let value = try InlineKeyboardButtonTypeUrl(from: decoder) self = .inlineKeyboardButtonTypeUrl(value) case .inlineKeyboardButtonTypeLoginUrl: let value = try InlineKeyboardButtonTypeLoginUrl(from: decoder) self = .inlineKeyboardButtonTypeLoginUrl(value) case .inlineKeyboardButtonTypeCallback: let value = try InlineKeyboardButtonTypeCallback(from: decoder) self = .inlineKeyboardButtonTypeCallback(value) case .inlineKeyboardButtonTypeCallbackWithPassword: let value = try InlineKeyboardButtonTypeCallbackWithPassword(from: decoder) self = .inlineKeyboardButtonTypeCallbackWithPassword(value) case .inlineKeyboardButtonTypeCallbackGame: self = .inlineKeyboardButtonTypeCallbackGame case .inlineKeyboardButtonTypeSwitchInline: let value = try InlineKeyboardButtonTypeSwitchInline(from: decoder) self = .inlineKeyboardButtonTypeSwitchInline(value) case .inlineKeyboardButtonTypeBuy: self = .inlineKeyboardButtonTypeBuy case .inlineKeyboardButtonTypeUser: let value = try InlineKeyboardButtonTypeUser(from: decoder) self = .inlineKeyboardButtonTypeUser(value) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: DtoCodingKeys.self) switch self { case .inlineKeyboardButtonTypeUrl(let value): try container.encode(Kind.inlineKeyboardButtonTypeUrl, forKey: .type) try value.encode(to: encoder) case .inlineKeyboardButtonTypeLoginUrl(let value): try container.encode(Kind.inlineKeyboardButtonTypeLoginUrl, forKey: .type) try value.encode(to: encoder) case .inlineKeyboardButtonTypeCallback(let value): try container.encode(Kind.inlineKeyboardButtonTypeCallback, forKey: .type) try value.encode(to: encoder) case .inlineKeyboardButtonTypeCallbackWithPassword(let value): try container.encode(Kind.inlineKeyboardButtonTypeCallbackWithPassword, forKey: .type) try value.encode(to: encoder) case .inlineKeyboardButtonTypeCallbackGame: try container.encode(Kind.inlineKeyboardButtonTypeCallbackGame, forKey: .type) case .inlineKeyboardButtonTypeSwitchInline(let value): try container.encode(Kind.inlineKeyboardButtonTypeSwitchInline, forKey: .type) try value.encode(to: encoder) case .inlineKeyboardButtonTypeBuy: try container.encode(Kind.inlineKeyboardButtonTypeBuy, forKey: .type) case .inlineKeyboardButtonTypeUser(let value): try container.encode(Kind.inlineKeyboardButtonTypeUser, forKey: .type) try value.encode(to: encoder) } } } /// A button that opens a specified URL public struct InlineKeyboardButtonTypeUrl: Codable { /// HTTP or tg:// URL to open public let url: String public init(url: String) { self.url = url } } /// A button that opens a specified URL and automatically authorize the current user if allowed to do so public struct InlineKeyboardButtonTypeLoginUrl: Codable { /// If non-empty, new text of the button in forwarded messages public let forwardText: String /// Unique button identifier public let id: Int64 /// An HTTP URL to open public let url: String public init( forwardText: String, id: Int64, url: String ) { self.forwardText = forwardText self.id = id self.url = url } } /// A button that sends a callback query to a bot public struct InlineKeyboardButtonTypeCallback: Codable { /// Data to be sent to the bot via a callback query public let data: Data public init(data: Data) { self.data = data } } /// A button that asks for password of the current user and then sends a callback query to a bot public struct InlineKeyboardButtonTypeCallbackWithPassword: Codable { /// Data to be sent to the bot via a callback query public let data: Data public init(data: Data) { self.data = data } } /// A button that forces an inline query to the bot to be inserted in the input field public struct InlineKeyboardButtonTypeSwitchInline: Codable { /// True, if the inline query must be sent from the current chat public let inCurrentChat: Bool /// Inline query to be sent to the bot public let query: String public init( inCurrentChat: Bool, query: String ) { self.inCurrentChat = inCurrentChat self.query = query } } /// A button to open a chat with a user public struct InlineKeyboardButtonTypeUser: Codable { /// User identifier public let userId: Int64 public init(userId: Int64) { self.userId = userId } }
36.236181
205
0.711552
14e811f323a9044a5bdec5638d67cb16b62d2c53
2,215
// // VisitorController.swift // WeiBoSwift // // Created by itogame on 2017/8/23. // Copyright © 2017年 itogame. All rights reserved. // import UIKit class VisitorController: UIViewController { @objc lazy var gradientLayer: CAGradientLayer = { let layT : CAGradientLayer = CAGradientLayer() layT.frame = self.gradientView.bounds layT.colors = [UIColor(white: 1, alpha: 1).cgColor, UIColor(white: 1, alpha: 0).cgColor] layT.startPoint = CGPoint(x: 0, y: 0.6) layT.endPoint = CGPoint(x: 0, y: 0) return layT }() // 旋转图 @IBOutlet weak var rotaIcon: UIImageView! // 渐变图 @IBOutlet weak var gradientView: UIView! override func viewDidLoad() { super.viewDidLoad() gradientView.backgroundColor = UIColor.clear // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let ani = CABasicAnimation(keyPath: "transform.rotation") ani.toValue = Double.pi * 2 ani.duration = 8.0 ani.repeatCount = Float(CGFloat.greatestFiniteMagnitude) ani.autoreverses = false ani.isRemovedOnCompletion = false ani.fillMode = kCAFillModeForwards rotaIcon.layer.add(ani, forKey: "rotation") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // ASLog(t: gradientView.frame) gradientView.layer.addSublayer(gradientLayer) //gradientView.layer.mask = gradientLayer } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) rotaIcon.layer.removeAllAnimations() } // 找感兴趣的人 @IBAction func findInterests(_ sender: UIButton) { ASLog("") } /* // 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. } */ }
29.932432
106
0.646953
1481be12d3d8cf9294de39c66e8b0b8ed56db9ab
552
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // extension UITextView { override open func dmTraitCollectionDidChange(_ previousTraitCollection: DMTraitCollection?) { super.dmTraitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { return } dm_updateDynamicColors() keyboardAppearance = { if DMTraitCollection.override.userInterfaceStyle == .dark { return .dark } else { return .default } }() } }
21.230769
96
0.666667
fbe1b2472327bbbcc0c835e50e686dca45988e01
2,442
//****************************************************************************** // Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import Dispatch public class CpuDevice : ComputeDevice { // initializers public init(log: Log?, service: CpuComputeService, deviceId: Int) { self.currentLog = log self.id = deviceId self.service = service self.path = "\(service.name).\(deviceId)" // this is a singleton trackingId = objectTracker.register(type: self) objectTracker.markStatic(trackingId: trackingId) } deinit { objectTracker.remove(trackingId: trackingId) } //---------------------------------------------------------------------------- // properties public private(set) var trackingId = 0 public var attributes = [String : String]() public var availableMemory: Int = 0 public var maxThreadsPerBlock: Int { return 1 /*this should be number of cores*/ } public let name: String = "CPU" public weak var service: ComputeService! public let id: Int public let path: String public let usesUnifiedAddressing = true private var streamId = AtomicCounter() // logging public var logLevel = LogLevel.error public var nestingLevel = 0 public weak var currentLog: Log? //---------------------------------------------------------------------------- public func select() throws { } public func supports(dataType: DataType) -> Bool { return true } //------------------------------------- // createArray // This creates memory on the device public func createArray(count: Int) throws -> DeviceArray { return CpuDeviceArray(log: currentLog, device: self, count: count) } //------------------------------------- // createStream public func createStream(label: String) throws -> DeviceStream { return try CpuStream(log: currentLog, device: self, id: streamId.increment(), label: label) } } // CpuDevice
33.452055
83
0.628174
91b89aa605023792a5c6fc7fa6a2a75587895429
448
// // String+Extension.swift // Wei // // Created by yuzushioh on 2018/05/16. // Copyright © 2018 popshoot All rights reserved. // import Foundation extension String { func stripEthereumPrefix() -> String { let address: String let prefix = "ethereum:" if hasPrefix(prefix) { address = String(dropFirst(prefix.count)) } else { address = self } return address } }
19.478261
53
0.580357
4a3b2510d26fe046c3c7666ea2296fc8d5c87f86
457
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -emit-ir {return(t:f{}var f={extension{struct BidirectionalCollection
45.7
79
0.761488
3a1898f5885e40f404330758cab7d17f23ff0607
11,530
import Foundation import AVFoundation import MapboxDirections import MapboxCoreNavigation extension NSAttributedString { @available(iOS 10.0, *) public func pronounced(_ pronunciation: String) -> NSAttributedString { let phoneticWords = pronunciation.components(separatedBy: " ") let phoneticString = NSMutableAttributedString() for (word, phoneticWord) in zip(string.components(separatedBy: " "), phoneticWords) { // AVSpeechSynthesizer doesn’t recognize some common IPA symbols. let phoneticWord = phoneticWord.byReplacing([("ɡ", "g"), ("ɹ", "r")]) if phoneticString.length > 0 { phoneticString.append(NSAttributedString(string: " ")) } phoneticString.append(NSAttributedString(string: word, attributes: [ NSAttributedStringKey(rawValue: AVSpeechSynthesisIPANotationAttribute): phoneticWord, ])) } return phoneticString } } extension SpokenInstruction { @available(iOS 10.0, *) func attributedText(for legProgress: RouteLegProgress) -> NSAttributedString { let attributedText = NSMutableAttributedString(string: text) if let step = legProgress.upComingStep, let name = step.names?.first, let phoneticName = step.phoneticNames?.first { let nameRange = attributedText.mutableString.range(of: name) if (nameRange.location != NSNotFound) { attributedText.replaceCharacters(in: nameRange, with: NSAttributedString(string: name).pronounced(phoneticName)) } } if let step = legProgress.followOnStep, let name = step.names?.first, let phoneticName = step.phoneticNames?.first { let nameRange = attributedText.mutableString.range(of: name) if (nameRange.location != NSNotFound) { attributedText.replaceCharacters(in: nameRange, with: NSAttributedString(string: name).pronounced(phoneticName)) } } return attributedText } } /** The `RouteVoiceController` class provides voice guidance. */ @objc(MBRouteVoiceController) open class RouteVoiceController: NSObject, AVSpeechSynthesizerDelegate, AVAudioPlayerDelegate { lazy var speechSynth = AVSpeechSynthesizer() var audioPlayer: AVAudioPlayer? /** A boolean value indicating whether instructions should be announced by voice or not. */ @objc public var isEnabled: Bool = true /** Volume of announcements. */ @objc public var volume: Float = 1.0 /** SSML option which controls at which speed Polly instructions are read. */ @objc public var instructionVoiceSpeedRate = 1.08 /** SSML option that specifies the voice loudness. */ @objc public var instructionVoiceVolume = "default" /** If true, a noise indicating the user is going to be rerouted will play prior to rerouting. */ @objc public var playRerouteSound = true /** Sound to play prior to reroute. Inherits volume level from `volume`. */ @objc public var rerouteSoundPlayer: AVAudioPlayer = try! AVAudioPlayer(data: NSDataAsset(name: "reroute-sound", bundle: .mapboxNavigation)!.data, fileTypeHint: AVFileType.mp3.rawValue) /** Buffer time between announcements. After an announcement is given any announcement given within this `TimeInterval` will be suppressed. */ @objc public var bufferBetweenAnnouncements: TimeInterval = 3 /** Delegate used for getting metadata information about a particular spoken instruction. */ public weak var voiceControllerDelegate: VoiceControllerDelegate? var lastSpokenInstruction: SpokenInstruction? var legProgress: RouteLegProgress? var volumeToken: NSKeyValueObservation? = nil var muteToken: NSKeyValueObservation? = nil /** Default initializer for `RouteVoiceController`. */ override public init() { super.init() if !Bundle.main.backgroundModes.contains("audio") { assert(false, "This application’s Info.plist file must include “audio” in UIBackgroundModes. This background mode is used for spoken instructions while the application is in the background.") } speechSynth.delegate = self rerouteSoundPlayer.delegate = self resumeNotifications() } deinit { suspendNotifications() speechSynth.stopSpeaking(at: .immediate) } func resumeNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(didPassSpokenInstructionPoint(notification:)), name: .routeControllerDidPassSpokenInstructionPoint, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(pauseSpeechAndPlayReroutingDing(notification:)), name: .routeControllerWillReroute, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(didReroute(notification:)), name: .routeControllerDidReroute, object: nil) volumeToken = NavigationSettings.shared.observe(\.voiceVolume) { [weak self] (settings, change) in self?.audioPlayer?.volume = settings.voiceVolume } muteToken = NavigationSettings.shared.observe(\.voiceMuted) { [weak self] (settings, change) in if settings.voiceMuted { self?.audioPlayer?.stop() self?.speechSynth.stopSpeaking(at: .immediate) } } } func suspendNotifications() { NotificationCenter.default.removeObserver(self, name: .routeControllerDidPassSpokenInstructionPoint, object: nil) NotificationCenter.default.removeObserver(self, name: .routeControllerWillReroute, object: nil) NotificationCenter.default.removeObserver(self, name: .routeControllerDidReroute, object: nil) } @objc func didReroute(notification: NSNotification) { // Play reroute sound when a faster route is found if notification.userInfo?[RouteControllerDidFindFasterRouteKey] as! Bool { pauseSpeechAndPlayReroutingDing(notification: notification) } } @objc func pauseSpeechAndPlayReroutingDing(notification: NSNotification) { speechSynth.stopSpeaking(at: .word) guard playRerouteSound && !NavigationSettings.shared.voiceMuted else { return } rerouteSoundPlayer.volume = volume rerouteSoundPlayer.play() } @objc public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { do { try unDuckAudio() } catch { voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) } } @objc public func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { do { try unDuckAudio() } catch { voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) } } func validateDuckingOptions() throws { let category = AVAudioSessionCategoryPlayback let categoryOptions: AVAudioSessionCategoryOptions = [.duckOthers, .interruptSpokenAudioAndMixWithOthers] try AVAudioSession.sharedInstance().setMode(AVAudioSessionModeSpokenAudio) try AVAudioSession.sharedInstance().setCategory(category, with: categoryOptions) } func duckAudio() throws { try validateDuckingOptions() try AVAudioSession.sharedInstance().setActive(true) } func unDuckAudio() throws { try AVAudioSession.sharedInstance().setActive(false, with: [.notifyOthersOnDeactivation]) } @objc open func didPassSpokenInstructionPoint(notification: NSNotification) { guard !NavigationSettings.shared.voiceMuted else { return } let routeProgress = notification.userInfo![RouteControllerDidPassSpokenInstructionPointRouteProgressKey] as! RouteProgress legProgress = routeProgress.currentLegProgress guard let instruction = routeProgress.currentLegProgress.currentStepProgress.currentSpokenInstruction else { return } lastSpokenInstruction = instruction speak(instruction) } /** Reads aloud the given instruction. - parameter instruction: The instruction to read aloud. */ open func speak(_ instruction: SpokenInstruction) { if speechSynth.isSpeaking, let lastSpokenInstruction = lastSpokenInstruction { voiceControllerDelegate?.voiceController?(self, didInterrupt: lastSpokenInstruction, with: instruction) } do { try duckAudio() } catch { voiceControllerDelegate?.voiceController?(self, spokenInstructionsDidFailWith: error) } var utterance: AVSpeechUtterance? if Locale.preferredLocalLanguageCountryCode == "en-US" { // Alex can’t handle attributed text. utterance = AVSpeechUtterance(string: instruction.text) utterance!.voice = AVSpeechSynthesisVoice(identifier: AVSpeechSynthesisVoiceIdentifierAlex) } if #available(iOS 10.0, *), utterance?.voice == nil, let legProgress = legProgress { utterance = AVSpeechUtterance(attributedString: instruction.attributedText(for: legProgress)) } else { utterance = AVSpeechUtterance(string: instruction.text) } // Only localized languages will have a proper fallback voice if utterance?.voice == nil { utterance?.voice = AVSpeechSynthesisVoice(language: Locale.preferredLocalLanguageCountryCode) } utterance?.volume = volume if let utterance = utterance { speechSynth.speak(utterance) } } } /** The `VoiceControllerDelegate` protocol defines methods that allow an object to respond to significant events related to spoken instructions. */ @objc(MBVoiceControllerDelegate) public protocol VoiceControllerDelegate { /** Called when the voice controller failed to speak an instruction. - parameter voiceController: The voice controller that experienced the failure. - parameter error: An error explaining the failure and its cause. The `MBSpokenInstructionErrorCodeKey` key of the error’s user info dictionary is a `SpokenInstructionErrorCode` indicating the cause of the failure. */ @objc(voiceController:spokenInstrucionsDidFailWithError:) optional func voiceController(_ voiceController: RouteVoiceController, spokenInstructionsDidFailWith error: Error) /** Called when one spoken instruction interrupts another instruction currently being spoken. - parameter voiceController: The voice controller that experienced the interruption. - parameter interruptedInstruction: The spoken instruction currently in progress that has been interrupted. - parameter interruptingInstruction: The spoken instruction that is interrupting the current instruction. */ @objc(voiceController:didInterruptSpokenInstruction:withInstruction:) optional func voiceController(_ voiceController: RouteVoiceController, didInterrupt interruptedInstruction: SpokenInstruction, with interruptingInstruction: SpokenInstruction) }
41.326165
219
0.689419
5dd1a14b9ea22ed33a0cf9e959b1133a2c24d49e
9,374
// // AuthorizationCodeGrantFlowInputViewController.swift // MHIdentityKitTestsHost // // Created by Milen Halachev on 9/24/17. // Copyright © 2017 Milen Halachev. All rights reserved. // import UIKit import MHIdentityKit class AuthorizationCodeGrantFlowInputViewController: UITableViewController, UITextFieldDelegate { @IBOutlet weak var clientTextField: UITextField! @IBOutlet weak var secretTextField: UITextField! @IBOutlet weak var scopeTextField: UITextField! @IBOutlet weak var authorizationURLTextField: UITextField! @IBOutlet weak var tokenURLTextField: UITextField! @IBOutlet weak var redirectURLTextField: UITextField! private var accessTokenRequest: URLRequest? private var accessTokenResponse: AccessTokenResponse? private var accessTokenError: Error? override func viewDidLoad() { super.viewDidLoad() } private func setErrorIndicator(to textField: UITextField) { textField.layer.borderColor = UIColor.red.cgColor textField.layer.borderWidth = 1 textField.layer.masksToBounds = true textField.layer.cornerRadius = 4 } private func clearErrorIndicator(from textField: UITextField) { textField.layer.borderColor = nil textField.layer.borderWidth = 0 textField.layer.masksToBounds = false textField.layer.cornerRadius = 0 } private func clearErrorIndicatorFromAllTextFields() { self.clearErrorIndicator(from: self.clientTextField) self.clearErrorIndicator(from: self.secretTextField) self.clearErrorIndicator(from: self.scopeTextField) self.clearErrorIndicator(from: self.authorizationURLTextField) self.clearErrorIndicator(from: self.tokenURLTextField) self.clearErrorIndicator(from: self.redirectURLTextField) } private func clearResult() { self.accessTokenRequest = nil self.accessTokenResponse = nil self.accessTokenError = nil } private func showResult() { let accessTokenRequestAvailable = self.accessTokenRequest != nil let accessTokenResponseAvailable = self.accessTokenResponse != nil let accessTokenErrorAvailable = self.accessTokenError != nil let title = "Result summary" let message = """ Access token request: \(accessTokenRequestAvailable ? "available" : "none") Access token response: \(accessTokenResponseAvailable ? "available" : "none") Access token error: \(accessTokenErrorAvailable ? "available" : "none") """ let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) if accessTokenRequestAvailable, let request = self.accessTokenRequest { alertController.addAction(UIAlertAction(title: "View access token request", style: .default, handler: { (_) in let value = """ URL: \(request.url?.absoluteString ?? "nil") Method: \(request.httpMethod ?? "nil") Headers: \(request.allHTTPHeaderFields?.map({ "\($0): \($1)" }).joined(separator: "\n") ?? "nil") Body: \(request.httpBody == nil ? "nil" : String(data: request.httpBody!, encoding: .utf8) ?? "nil") """ self.showAlert(title: "Access token request", value: value) })) } if accessTokenResponseAvailable, let response = self.accessTokenResponse { alertController.addAction(UIAlertAction(title: "View access token response", style: .default, handler: { (_) in let value = response.parameters.map({ (key, value) -> String in return "\(key): \n\(value as? String ?? "nil")" }).joined(separator: "\n\n") self.showAlert(title: "Access token response", value: value) })) } if accessTokenErrorAvailable, let error = self.accessTokenError { alertController.addAction(UIAlertAction(title: "View access token error", style: .default, handler: { (_) in self.showAlert(title: "Access token error", value: error.localizedDescription) })) } alertController.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } private func showAlert(title: String?, value: String?) { let alertController = UIAlertController(title: title, message: value, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Copy", style: .default, handler: { (_) in UIPasteboard.general.string = value })) alertController.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } //MARK: - Actions @IBAction func loginAction() { self.clearErrorIndicatorFromAllTextFields() self.clearResult() guard let client = self.clientTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), client.isEmpty == false else { self.setErrorIndicator(to: self.clientTextField) self.clientTextField.becomeFirstResponder() return } var secret: String? = self.secretTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) if secret?.isEmpty == true { secret = nil } var scope: Scope? = nil if let scopeString = self.scopeTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), scopeString.isEmpty == false { scope = Scope(value: scopeString) } guard let authorizationURLString = self.authorizationURLTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), authorizationURLString.isEmpty == false, let authorizationURL = URL(string: authorizationURLString) else { self.setErrorIndicator(to: self.authorizationURLTextField) self.authorizationURLTextField.becomeFirstResponder() return } guard let tokenURLString = self.tokenURLTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), tokenURLString.isEmpty == false, let tokenURL = URL(string: tokenURLString) else { self.setErrorIndicator(to: self.tokenURLTextField) self.tokenURLTextField.becomeFirstResponder() return } guard let redirectURLString = self.redirectURLTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines), redirectURLString.isEmpty == false, let redirectURL = URL(string: redirectURLString) else { self.setErrorIndicator(to: self.redirectURLTextField) self.redirectURLTextField.becomeFirstResponder() return } let userAgent = PresentableUserAgent(WebViewUserAgentViewController(), presentationHandler: { [weak self] (webViewController) in self?.navigationController?.pushViewController(webViewController, animated: true) }) { [weak self] (webViewController) in self?.navigationController?.popViewController(animated: true) } let networkClient = AnyNetworkClient { [weak self] (request, completion) in self?.accessTokenRequest = request _defaultNetworkClient.perform(request, completion: completion) } var flow: AuthorizationGrantFlow? = AuthorizationCodeGrantFlow(authorizationEndpoint: authorizationURL, tokenEndpoint: tokenURL, clientID: client, secret: secret, redirectURI: redirectURL, scope: scope, userAgent: userAgent, networkClient: networkClient) flow?.authenticate { [weak self] (accessTokenResponse, error) in self?.accessTokenResponse = accessTokenResponse self?.accessTokenError = error self?.showResult() flow = nil } } //MARK: - UITableViewDataSource & UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath) if let textField = (cell?.contentView.subviews.first as? UITextField) { textField.becomeFirstResponder() } if let label = cell?.contentView.subviews.first as? UILabel, label.text == "View Result" { self.showResult() } } //MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
38.735537
262
0.620333
87a84288b04cd6ee5a03e023eb40448fab47468a
344
// // ContentView.swift // WorkingWithList // // Created by Tien Le P. VN.Danang on 8/4/21. // import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .padding() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
15.636364
46
0.604651
f472ecbf30400bc0dfbe7f18efbaee0f747f476a
1,313
// // ProfileFlow.swift // DCM_iOS // // Created by 강민석 on 2020/09/08. // Copyright © 2020 MinseokKang. All rights reserved. // import RxFlow import RxSwift import RxCocoa import UIKit class ProfileFlow: Flow { // MARK: - Properties var root: Presentable { return self.rootViewController } private let rootViewController = UINavigationController() private let services: DCMService // MARK: - Init init(withServices services: DCMService) { self.services = services } deinit { print("\(type(of: self)): \(#function)") } // MARK: - Navigation Swtich func navigate(to step: Step) -> FlowContributors { guard let step = step as? DCMStep else { return .none } switch step { case .profileIsRequired: return navigateToProfile() default: return .none } } } extension ProfileFlow { func navigateToProfile() -> FlowContributors { let viewModel = ProfileViewModel() let viewController = ProfileViewController.instantiate(withViewModel: viewModel, andServices: self.services) self.rootViewController.pushViewController(viewController, animated: true) viewController.title = "프로필" return .none } }
23.872727
116
0.631379
e8269e98f2f7bdf24246aa71014760d024c99b32
847
// // IngredientCheckTableViewCell.swift // smoothies // // Created by zhen xin tan ruan on 3/18/19. // Copyright © 2019 zhen xin tan ruan. All rights reserved. // import UIKit class IngredientCheckTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var checkButton: UIButton! var callBack: ((_ index: Int) -> Void)? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func checkbox(_ sender: UIButton) { sender.isSelected = !sender.isSelected callBack?(sender.tag) } func loadData(data: IngredientModel, index: Int) { checkButton.isSelected = data.isSelect checkButton.tag = index titleLabel.text = data.name } }
23.527778
63
0.697757
752ec10196a72c88e73077c771cc5cde8927d03a
367
import UIKit public class ScoreElement: UIView { override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clearColor() tintColor = UIColor.blackColor() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.clearColor() tintColor = UIColor.blackColor() } }
21.588235
50
0.702997
180254374c12f54bf5e8c16c0e285c9afd26cb2d
560
// // MainCoordinator.swift // Conferences // // Created by Zagahr on 26/03/2019. // Copyright © 2019 Timon Blask. All rights reserved. // import UIKit final class MainCoordinator { let tabBarController: UITabBarController init() { self.tabBarController = UITabBarController() } func start() { self.tabBarController.tabBar.tintColor = .primaryText self.tabBarController.tabBar.barTintColor = .elementBackground self.tabBarController.setViewControllers([SplitViewController()], animated: false) } }
21.538462
90
0.698214
339a0f8b25fc1a3006ab86c84e88dccbb2fc0474
3,115
// // SuperheroViewController.swift // Flix // // Created by Hye Lim Joun on 2/6/18. // Copyright © 2018 hyelim. All rights reserved. // import UIKit class SuperheroViewController: UIViewController, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! var movies: [Movie] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. collectionView.dataSource = self let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.minimumInteritemSpacing = 5 layout.minimumLineSpacing = layout.minimumInteritemSpacing let cellsPerLine: CGFloat = 2 let interItemSpacingTotal = layout.minimumLineSpacing * (cellsPerLine - 1) let width = collectionView.frame.size.width / cellsPerLine - interItemSpacingTotal / cellsPerLine layout.itemSize = CGSize(width: width, height: width * 3 / 2) fetchMovies() } func fetchMovies() { let url = URL(string: "https://api.themoviedb.org/3/movie/284053/similar?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed&language=en-US&page=1")! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) { (data, response, error) in // This will run when the network request returns if let error = error { print(error.localizedDescription) } else if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let movieDictionaries = dataDictionary["results"] as! [[String: Any]] self.movies = Movie.movies(dictionaries: movieDictionaries) // Wait for network request self.collectionView.reloadData() } } task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return movies.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PosterCell", for: indexPath) as! PosterCell let movie = movies[indexPath.item] if movie.posterUrl != nil { cell.posterImageView.af_setImage(withURL: movie.posterUrl!) } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let cell = sender as! UICollectionViewCell // Get the index path from the cell that was tapped if let indexPath = collectionView.indexPath(for: cell) { let movie = movies[indexPath.row] let detailViewController = segue.destination as! DetailViewController // Pass on the data to the Detail ViewController detailViewController.movie = movie } } }
37.083333
142
0.712039
723284b3276d98ac97ebb96eaf72e9e934cd9a4a
1,451
// // TestCoadbleViewController.swift // SwiftDemo // // Created by 崔林豪 on 2021/12/27. // import UIKit struct GoodItem: Codable { let payType: String? let linkUrl: String? //Return from initializer without initializing all stored properties init(linkUrl: String, payType: String) { self.linkUrl = linkUrl self.payType = payType } } struct GoodItem2: Codable { let payType: String? let linkUrl: String? //Return from initializer without initializing all stored properties init(linkUrl: String, payType: String) { self.linkUrl = linkUrl self.payType = payType } } class TestCoadbleViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .lightGray //self.handleOpenURL(item.linkUrl.flatMap({ URL.init(string: $0) })) //Argument type 'String' does not conform to expected type 'Decoder' let item = GoodItem(linkUrl: "https:ww.baidu.com", payType: "haha") let url = item.linkUrl.flatMap({ //print("_____url:\(String(describing: URL.init(string:$0)))") //print("___\(item.linkUrl?.count)") URL.init(string:$0) }) print(">>>>>+++\(String(describing: url))") print("___\(url)") } } extension TestCoadbleViewController { func test() { //报错 //Call can throw, but it is not marked with 'try' and the error is not handled //let item = GoodItem2(from: <#Decoder#>) //item.linkUrl = "123456" } }
18.602564
80
0.674018
8a21c14fb5a1263373a549d461b89718f0d83894
2,534
// // Transformable+Deprecated.swift // FilestackSDK // // Created by Ruben Nine on 10/09/2019. // Copyright © 2019 Filestack. All rights reserved. // import Foundation // MARK: - Deprecated extension Transformable { /// Stores a copy of the transformation results to your preferred filestore. /// /// - Parameter fileName: Change or set the filename for the converted file. /// - Parameter location: An `StorageLocation` value. /// - Parameter path: Where to store the file in your designated container. For S3, this is /// the key where the file will be stored at. /// - Parameter container: The name of the bucket or container to write files to. /// - Parameter region: S3 specific parameter. The name of the S3 region your bucket is located /// in. All regions except for `eu-central-1` (Frankfurt), `ap-south-1` (Mumbai), /// and `ap-northeast-2` (Seoul) will work. /// - Parameter access: An `StorageAccess` value. /// - Parameter base64Decode: Specify that you want the data to be first decoded from base64 /// before being written to the file. For example, if you have base64 encoded image data, /// you can use this flag to first decode the data before writing the image file. /// - Parameter queue: The queue on which the completion handler is dispatched. /// - Parameter completionHandler: Adds a handler to be called once the request has finished. @objc @available(*, deprecated, message: "Marked for removal in version 3.0. Use the new store(using:base64Decode:queue:completionHandler) instead") @discardableResult public func store(fileName: String? = nil, location: StorageLocation, path: String? = nil, container: String? = nil, region: String? = nil, access: StorageAccess, base64Decode: Bool, queue: DispatchQueue? = .main, completionHandler: @escaping (FileLink?, JSONResponse) -> Void) -> Self { let options = StorageOptions(location: location, region: region, container: container, path: path, filename: fileName, access: access) return store(using: options, base64Decode: base64Decode, queue: queue, completionHandler: completionHandler) } }
47.811321
146
0.610103
1120b46bf88345b818f58405dabfac64dd1a5d15
2,248
/** * Copyright (c) 2017 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 MapKit import Contacts extension Walk: MKAnnotation { var title: String? { return walkTitle } var subtitle: String? { return location } var coordinate: CLLocationCoordinate2D { return mapCoordinates } // map button opens this mapItem in Maps app func mapItem() -> MKMapItem { let addressDictionary = [CNPostalAddressStreetKey: subtitle!] let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary) let mapItem = MKMapItem(placemark: placemark) mapItem.name = title return mapItem } }
38.101695
93
0.752224
6a3f7430eeebfdc5e1b0a85a8bc35fbf9f893e3e
1,858
// // NSObject+Rx+RawRepresentable.swift // RxCocoa // // Created by Krunoslav Zaher on 11/9/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !os(Linux) import Foundation #if !RX_NO_MODULE import RxSwift #endif extension Reactive where Base: NSObject { /** Specialization of generic `observe` method. This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. It is useful for observing bridged ObjC enum values. For more information take a look at `observe` method. */ // @warn_unused_result(message:"http://git.io/rxs.uo") public func observe<E: RawRepresentable>(_ type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable<E?> where E.RawValue: KVORepresentable { return observe(E.RawValue.KVOType.self, keyPath, options: options, retainSelf: retainSelf) .map(E.init) } } #if !DISABLE_SWIZZLING // observeWeakly + RawRepresentable extension Reactive where Base: NSObject { /** Specialization of generic `observeWeakly` method. This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. It is useful for observing bridged ObjC enum values. For more information take a look at `observeWeakly` method. */ // @warn_unused_result(message:"http://git.io/rxs.uo") public func observeWeakly<E: RawRepresentable>(_ type: E.Type, _ keyPath: String, options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable<E?> where E.RawValue: KVORepresentable { return observeWeakly(E.RawValue.KVOType.self, keyPath, options: options) .map(E.init) } } #endif #endif
33.178571
215
0.682992
1eeba756b2e63d6dbba63e9766ccdf6ca2861bbd
1,052
/* A subsequence is created by deleting zero or more elements from a list while maintaining the order. An inversion is a strictly decreasing subsequence of length 3 in this problem. given i>j>k */ // Approach 1 func maxInversions(arr: [Int]) -> Int { var length = 0 for i in 0..<arr.count-1{ var first = 0 var second = 0 for j in i+1..<arr.count{ if (arr[i]>arr[j]){ first += 1 } } var j = i - 1 while j >= 0 { if arr[i] < arr[j] { second += 1 } j -= 1 } length += first*second } return length } // Approach 2 func maxInversions(arr: [Int]) -> Int { var length = 0 for i in 0..<arr.count-2{ for j in i+1...arr.count-1 { if (arr[i]>arr[j]){ for k in j+1..<arr.count { if (arr[j]>arr[k]){ length += 1 } } } } } return length } print(maxInversions(arr: [15, 10, 1, 7, 8])) // 3 print(maxInversions(arr: [4,1,3,2,5])) // 1 print(maxInversions(arr: [5,4,3,2,1])) // 10
19.481481
100
0.518061
e4dd8ae140d02cb5413a816bb9e2d0557d5660d1
279
import MixboxMocksRuntime extension RecordedCallArgument: Equatable { public static func ==(lhs: RecordedCallArgument, rhs: RecordedCallArgument) -> Bool { return lhs.name == rhs.name && lhs.type == rhs.type && lhs.value == rhs.value } }
27.9
89
0.637993
bbec7d80e8c95b790edbab84543c7cada1b25e91
297
import Foundation extension Double { func toFormatedString() -> String { // 60分を超えるものについては追加で記述が必要 let formatter: DateFormatter = DateFormatter() formatter.dateFormat = "mm:ss" return formatter.string(from: Date(timeIntervalSinceReferenceDate: self)) } }
24.75
81
0.683502