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
|
---|---|---|---|---|---|
c16f8b57a430c0f5763aa439fe5b60dfe3f14a70 | 2,290 | //
// SceneDelegate.swift
// Prototype
//
// Created by Will Saults on 3/12/22.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.207547 | 147 | 0.712664 |
1ae1ab6fa51c3ce43f92ad6c46b4ae7e2a595c78 | 132 | import Foundation
extension CoredataProfile {
public override func awakeFromInsert() {
super.awakeFromInsert()
}
}
| 16.5 | 44 | 0.704545 |
643ec0bb434e1c841d620fe5f773ee6d21485488 | 2,696 | import Basic
import Foundation
import SPMUtility
import TuistSupport
protocol VersionsControlling: AnyObject {
typealias Installation = (AbsolutePath) throws -> Void
func install(version: String, installation: Installation) throws
func uninstall(version: String) throws
func path(version: String) -> AbsolutePath
func versions() -> [InstalledVersion]
func semverVersions() -> [Version]
}
enum InstalledVersion: CustomStringConvertible, Equatable {
case semver(Version)
case reference(String)
var description: String {
switch self {
case let .reference(value): return value
case let .semver(value): return value.description
}
}
static func == (lhs: InstalledVersion, rhs: InstalledVersion) -> Bool {
switch (lhs, rhs) {
case let (.semver(lhsVersion), .semver(rhsVersion)):
return lhsVersion == rhsVersion
case let (.reference(lhsRef), .reference(rhsRef)):
return lhsRef == rhsRef
default:
return false
}
}
}
class VersionsController: VersionsControlling {
// MARK: - VersionsControlling
func install(version: String, installation: Installation) throws {
let tmpDir = try TemporaryDirectory(removeTreeOnDeinit: true)
try installation(tmpDir.path)
// Copy only if there's file in the folder
if !tmpDir.path.glob("*").isEmpty {
let dstPath = path(version: version)
if FileHandler.shared.exists(dstPath) {
try FileHandler.shared.delete(dstPath)
}
try FileHandler.shared.copy(from: tmpDir.path, to: dstPath)
}
}
func uninstall(version: String) throws {
let path = self.path(version: version)
if FileHandler.shared.exists(path) {
try FileHandler.shared.delete(path)
}
}
func path(version: String) -> AbsolutePath {
return Environment.shared.versionsDirectory.appending(component: version)
}
func versions() -> [InstalledVersion] {
return Environment.shared.versionsDirectory.glob("*").map { path in
let versionStringValue = path.components.last!
if let version = Version(string: versionStringValue) {
return InstalledVersion.semver(version)
} else {
return InstalledVersion.reference(versionStringValue)
}
}
}
func semverVersions() -> [Version] {
return versions().compactMap { version in
if case let InstalledVersion.semver(semver) = version {
return semver
}
return nil
}
}
}
| 30.636364 | 81 | 0.625371 |
387a30b96a70ff7d5f6c46c01188aedf548aad21 | 1,955 | // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Created by Sam Deane on 28/02/21.
// All code (c) 2021 - present day, Elegant Chaos Limited.
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
import Foundation
extension String {
static let examinedFlag = "examined"
}
class ExamineCommand: NonExclusiveTargetedCommand {
init() {
super.init(keywords: ["examine", "look at", "look in", "look out of", "look through", "look", "search", "l", "ex", "read"])
}
override func perform(in context: CommandContext) {
if !matchedAll || includedInExamineAll(context) {
let object = context.target
let description = object.getDescriptionAndContents()
let prefix = context.hasMultipleTargets ? "\(object.getDefinite().sentenceCased): " : ""
object.setFlag(.examinedFlag)
object.setFlag(.awareFlag)
context.engine.output("\(prefix)\(description)")
context.engine.post(event: Event(.examined, target: context.target))
}
}
func includedInExamineAll(_ context: CommandContext) -> Bool {
let object = context.target
if object == context.player { return false }
if object.location == context.player { return false }
guard let playerLocation = context.player.location else { return false }
return object.isVisibleFrom(playerLocation)
}
}
class ExamineFallbackCommand: ExamineCommand {
override func matches(_ context: CommandContext) -> Bool {
keywordMatches(in: context) && arguments.count == 0
}
override func kind(in context: CommandContext) -> Command.Match.Kind {
return .fallback
}
override func perform(in context: CommandContext) {
if let description = PlayerBehaviour(context.player)?.describeLocation() {
context.engine.output(description)
}
}
}
| 36.886792 | 131 | 0.595396 |
0eccb33ecbb470058d8064b154dd1938c9795327 | 2,610 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class MapLoadedViewController: UIViewController {
@IBOutlet var mapView:AGSMapView!
@IBOutlet var bannerLabel:UILabel!
private var map:AGSMap!
override func viewDidLoad() {
super.viewDidLoad()
//setup source code bar button item
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["MapLoadedViewController"]
//initialize map with basemap
self.map = AGSMap(basemap: AGSBasemap.imageryWithLabels())
//assign map to map view
self.mapView.map = self.map
//register as an observer for loadStatus property on map
self.map.addObserver(self, forKeyPath: "loadStatus", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//update the banner label on main thread
DispatchQueue.main.async { [weak self] in
if let weakSelf = self {
//get the string for load status
let loadStatusString = weakSelf.loadStatusString(weakSelf.map.loadStatus)
//set it on the banner label
weakSelf.bannerLabel.text = "Load status : \(loadStatusString)"
}
}
}
private func loadStatusString(_ status: AGSLoadStatus) -> String {
switch status {
case .failedToLoad:
return "Failed_To_Load"
case .loaded:
return "Loaded"
case .loading:
return "Loading"
case .notLoaded:
return "Not_Loaded"
default:
return "Unknown"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
self.map.removeObserver(self, forKeyPath: "loadStatus")
}
}
| 32.625 | 151 | 0.635632 |
5679f53a7b04420ce4f8156cd63205644fb7883c | 3,029 | //
// Autogenerated by gaxb at 07:44:08 AM on 11/12/21
//
// swiftlint:disable superfluous_disable_command
// swiftlint:disable cyclomatic_complexity
// swiftlint:disable identifier_name
// swiftlint:disable force_cast
// swiftlint:disable type_body_length
// swiftlint:disable function_body_length
// swiftlint:disable line_length
// swiftlint:disable file_length
import UIKit
open class ControllerBase: Object {
open var notifications: [Notification] = []
open func customCopyTo(_ other: Controller) {
// can be overriden by subclasses to provide custom copying
}
open override func copy() -> GaxbElement {
let copied = super.copy() as! Controller
for child in notifications {
let childCopy = child.copy() as! Notification
copied.notifications.append(childCopy)
childCopy.parent = copied
}
customCopyTo(copied)
return copied
}
open override func visit(_ visitor: (GaxbElement) -> Void) {
super.visit(visitor)
for child in notifications { child.visit(visitor) }
}
override open func setElement(_ element: GaxbElement, key: String) {
if let e = element as? Notification {
notifications.append(e)
e.setParent(self)
return
}
super.setElement(element, key: key)
}
override open func isKindOfClass(_ className: String) -> Bool {
if className == "Controller" {
return true
}
return super.isKindOfClass(className)
}
override open func setAttribute(_ value: String, key: String) {
super.setAttribute(value, key: key)
switch key {
default:
break
}
}
override open func imprintAttributes(_ receiver: GaxbElement?) -> GaxbElement? {
return super.imprintAttributes(receiver)
}
override open func attributesXML(_ useOriginalValues: Bool) -> String {
var xml = ""
if useOriginalValues {
for (key, value) in originalValues {
xml += " \(key)='\(value)'"
}
} else {
}
xml += super.attributesXML(useOriginalValues)
return xml
}
override open func sequencesXML(_ useOriginalValues: Bool) -> String {
var xml = ""
for notification in notifications {
xml += notification.toXML()
}
xml += super.sequencesXML(useOriginalValues)
return xml
}
override open func toXML(_ useOriginalValues: Bool) -> String {
var xml = "<Controller"
if parent == nil || parent?.xmlns != xmlns {
xml += " xmlns='\(xmlns)'"
}
xml += attributesXML(useOriginalValues)
let sXML = sequencesXML(useOriginalValues)
xml += sXML == "" ? "/>": ">\(sXML)</Controller>"
return xml
}
override open func toXML() -> String {
return toXML(false)
}
override open func description() -> String {
return toXML()
}
}
| 26.33913 | 84 | 0.606471 |
f4fb82a23d2033627a894356c669bd807725bb7e | 456 | //
// NodeAnimation.swift
// DuckHuntAR
//
// Created by Wojciech Trzasko Nomtek on 27.02.2018.
// Copyright © 2018 Nomtek. All rights reserved.
//
import SceneKit
struct NodeAnimation {
let keyframes: [NodeAnimationKeyframe]
init(keyframes: [NodeAnimationKeyframe]) {
self.keyframes = keyframes
}
func generateAction() -> SCNAction {
return SCNAction.sequence(keyframes.map { $0.generateAction() })
}
}
| 20.727273 | 72 | 0.664474 |
4817d1891746e3f0721adb574da24fa83932db6f | 920 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// MARK: Catalog by convention
import MaterialMotionCoreAnimationTransitions
extension FadeInViewController {
class func catalogBreadcrumbs() -> [String] {
return ["1. Fade in"]
}
}
extension SlideInViewController {
class func catalogBreadcrumbs() -> [String] {
return ["2. Slide in"]
}
}
| 28.75 | 73 | 0.756522 |
e8d397ba8a77f53694e908adf7d67cdec2e491bf | 4,812 | import XCTest
@testable import Xit
class PatchTest: XCTestCase
{
let testBundle = Bundle(identifier: "com.uncommonplace.XitTests")!
var loremURL, lorem2URL: URL!
var loremData, lorem2Data: Data!
var loremText, lorem2Text: String!
var patch: Patch!
override func setUpWithError() throws
{
try super.setUpWithError()
loremURL = testBundle.url(forResource: "lorem",
withExtension: "txt")!
lorem2URL = testBundle.url(forResource: "lorem2",
withExtension: "txt")!
loremData = try Data(contentsOf: loremURL)
loremText = try XCTUnwrap(String(data: loremData, encoding: .utf8))
lorem2Data = try Data(contentsOf: lorem2URL)
lorem2Text = try XCTUnwrap(String(data: lorem2Data, encoding: .utf8))
patch = GitPatch(oldData: loremData, newData: lorem2Data)
}
func testApplyFirst()
{
guard let hunk1 = patch.hunk(at: 0)
else {
XCTFail("no hunk")
return
}
let applied = hunk1.applied(to: loremText, reversed: false)!
XCTAssert(applied.hasPrefix(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec maximus mauris. Quisque varius nisi ac augue rutrum ullamcorper. Sed tincidunt leo in erat commodo, tempor ultricies quam sagittis.\n" +
"Duis risus quam, malesuada vel ante at, tincidunt sagittis erat. Phasellus a ante erat. Donec tristique lorem leo, sit amet congue est convallis vitae. Vestibulum a faucibus nisl. Pellentesque vitae sem vitae enim pharetra lacinia.\n" +
"Pellentesque mattis ante eget dignissim cursus. Nullam lacinia sit amet sapien ac feugiat. Aenean sagittis eros dignissim volutpat faucibus. Proin laoreet tempus nunc in suscipit.\n\n"))
}
func testDiscardFirst()
{
guard let hunk1 = patch.hunk(at: 0)
else {
XCTFail("no hunk")
return
}
let applied = hunk1.applied(to: lorem2Text, reversed: true)!
XCTAssert(applied.hasPrefix(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec nec maximus mauris. Quisque varius nisi ac augue rutrum ullamcorper. Sed tincidunt leo in erat commodo, tempor ultricies quam sagittis.\n" +
"Duis risus quam, malesuada vel ante at, tincidunt sagittis erat. Phasellus a ante erat. Donec tristique lorem leo, sit amet congue est convallis vitae. Vestibulum a faucibus nisl. Pellentesque vitae sem vitae enim pharetra lacinia.\n" +
"Pellentesque mattis ante eget dignissim cursus. Nullam lacinia sit amet sapien ac feugiat. Aenean sagittis eros dignissim volutpat faucibus. Proin laoreet tempus nunc in suscipit.\n" +
"Cras vestibulum id neque eu imperdiet. Pellentesque a lacus ipsum. Nulla ultrices consectetur congue.\n"))
}
func testApplyLast()
{
guard let hunk = patch.hunk(at: patch.hunkCount-1)
else {
XCTFail("no hunk")
return
}
let applied = hunk.applied(to: loremText, reversed: false)!
XCTAssert(applied.hasSuffix(
"Cras et rutrum dolor awk.\n" +
"Thistledown.\n" +
"Proin sit amet justo egestas, pulvinar mauris sit amet, ultrices tellus.\n" +
"Ut molestie elit justo, at pellentesque metus lacinia eu. Duis vitae hendrerit justo. Nam porta in augue viverra blandit.\n" +
"Phasellus id aliquam quam, gravida volutpat nunc. Aliquam at ligula sem. Mauris in luctus ante, sit amet lacinia nunc.\n" +
"Maecenas dictum, ipsum vitae iaculis dignissim, nulla ligula rhoncus tortor, eget rutrum velit lacus fringilla dui. Nulla facilisis urna eu facilisis ornare.\n" +
"Mauris iaculis metus nibh, et dapibus ante ultricies quis.\n"))
}
func testDiscardLast()
{
guard let hunk = patch.hunk(at: patch.hunkCount-1)
else {
XCTFail("no hunk")
return
}
let applied = hunk.applied(to: lorem2Text, reversed: true)!
XCTAssert(applied.hasSuffix(
"Cras et rutrum dolor.\n" +
"Proin sit amet justo egestas, pulvinar mauris sit amet, ultrices tellus.\n" +
"Ut molestie elit justo, at pellentesque metus lacinia eu. Duis vitae hendrerit justo. Nam porta in augue viverra blandit.\n" +
"Phasellus id aliquam quam, gravida volutpat nunc. Aliquam at ligula sem. Mauris in luctus ante, sit amet lacinia nunc.\n" +
"Maecenas dictum, ipsum vitae iaculis dignissim, nulla ligula rhoncus tortor, eget rutrum velit lacus fringilla dui. Nulla facilisis urna eu facilisis ornare.\n" +
"Mauris iaculis metus nibh, et dapibus ante ultricies quis.\n"))
}
func testNotApplied()
{
let lorem2Text = String(data: lorem2Data, encoding: .utf8)!
guard let hunk1 = patch.hunk(at: 0)
else {
XCTFail("no hunk")
return
}
XCTAssertNil(hunk1.applied(to: lorem2Text, reversed: false))
}
}
| 44.971963 | 245 | 0.694098 |
1da46d51aef36e08701cc1c91208cee649112c4e | 7,544 | //
// ViewController.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
import DropDown
class ViewController: UIViewController {
//MARK: - Properties
@IBOutlet weak var chooseArticleButton: UIButton!
@IBOutlet weak var amountButton: UIButton!
@IBOutlet weak var chooseButton: UIButton!
@IBOutlet weak var centeredDropDownButton: UIButton!
@IBOutlet weak var rightBarButton: UIBarButtonItem!
let textField = UITextField()
//MARK: - DropDown's
let chooseArticleDropDown = DropDown()
let amountDropDown = DropDown()
let chooseDropDown = DropDown()
let centeredDropDown = DropDown()
let rightBarDropDown = DropDown()
lazy var dropDowns: [DropDown] = {
return [
self.chooseArticleDropDown,
self.amountDropDown,
self.chooseDropDown,
self.centeredDropDown,
self.rightBarDropDown
]
}()
//MARK: - Actions
@IBAction func chooseArticle(_ sender: AnyObject) {
chooseArticleDropDown.show()
}
@IBAction func changeAmount(_ sender: AnyObject) {
amountDropDown.show()
}
@IBAction func choose(_ sender: AnyObject) {
chooseDropDown.show()
}
@IBAction func showCenteredDropDown(_ sender: AnyObject) {
centeredDropDown.show()
}
@IBAction func showBarButtonDropDown(_ sender: AnyObject) {
rightBarDropDown.show()
}
@IBAction func changeDIsmissMode(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: dropDowns.forEach { $0.dismissMode = .automatic }
case 1: dropDowns.forEach { $0.dismissMode = .onTap }
default: break;
}
}
@IBAction func changeDirection(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: dropDowns.forEach { $0.direction = .any }
case 1: dropDowns.forEach { $0.direction = .bottom }
case 2: dropDowns.forEach { $0.direction = .top }
default: break;
}
}
@IBAction func changeUI(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: setupDefaultDropDown()
case 1: customizeDropDown(self)
default: break;
}
}
@IBAction func showKeyboard(_ sender: AnyObject) {
textField.becomeFirstResponder()
}
@IBAction func hideKeyboard(_ sender: AnyObject) {
view.endEditing(false)
}
func setupDefaultDropDown() {
DropDown.setupDefaultAppearance()
dropDowns.forEach {
$0.cellNib = UINib(nibName: "DropDownCell", bundle: Bundle(for: DropDownCell.self))
$0.customCellConfiguration = nil
}
}
func customizeDropDown(_ sender: AnyObject) {
let appearance = DropDown.appearance()
appearance.cellHeight = 60
appearance.backgroundColor = UIColor(white: 1, alpha: 1)
appearance.selectionBackgroundColor = UIColor(red: 0.6494, green: 0.8155, blue: 1.0, alpha: 0.2)
// appearance.separatorColor = UIColor(white: 0.7, alpha: 0.8)
appearance.cornerRadius = 10
appearance.shadowColor = UIColor(white: 0.6, alpha: 1)
appearance.shadowOpacity = 0.9
appearance.shadowRadius = 25
appearance.animationduration = 0.25
appearance.textColor = .darkGray
// appearance.textFont = UIFont(name: "Georgia", size: 14)
dropDowns.forEach {
/*** FOR CUSTOM CELLS ***/
$0.cellNib = UINib(nibName: "MyCell", bundle: nil)
$0.customCellConfiguration = { (index: Index, item: String, cell: DropDownCell) -> Void in
guard let cell = cell as? MyCell else { return }
// Setup your custom UI components
cell.suffixLabel.text = "Suffix \(index)"
}
/*** ---------------- ***/
}
}
//MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
setupDropDowns()
dropDowns.forEach { $0.dismissMode = .onTap }
dropDowns.forEach { $0.direction = .any }
view.addSubview(textField)
}
//MARK: - Setup
func setupDropDowns() {
setupChooseArticleDropDown()
setupAmountDropDown()
setupChooseDropDown()
setupCenteredDropDown()
setupRightBarDropDown()
}
func setupChooseArticleDropDown() {
chooseArticleDropDown.anchorView = chooseArticleButton
// Will set a custom with instead of anchor view width
// dropDown.width = 100
// By default, the dropdown will have its origin on the top left corner of its anchor view
// So it will come over the anchor view and hide it completely
// If you want to have the dropdown underneath your anchor view, you can do this:
chooseArticleDropDown.bottomOffset = CGPoint(x: 0, y: chooseArticleButton.bounds.height)
// You can also use localizationKeysDataSource instead. Check the docs.
chooseArticleDropDown.dataSource = [
["iPhone SE | Black | 64G",
"Samsung S7"],[
"Huawei P8 Lite Smartphone 4G",
"Asus Zenfone Max 4G",
"Apple Watwh | Sport Edition"]
]
chooseArticleDropDown.titles = ["sd", "sdf"]
// Action triggered on selection
chooseArticleDropDown.selectionAction = { [unowned self] (index, item) in
self.chooseArticleButton.setTitle(item, for: .normal)
}
// Action triggered on dropdown cancelation (hide)
// dropDown.cancelAction = { [unowned self] in
// // You could for example deselect the selected item
// self.dropDown.deselectRowAtIndexPath(self.dropDown.indexForSelectedRow)
// self.actionButton.setTitle("Canceled", forState: .Normal)
// }
// You can manually select a row if needed
// dropDown.selectRowAtIndex(3)
}
func setupAmountDropDown() {
amountDropDown.anchorView = amountButton
// By default, the dropdown will have its origin on the top left corner of its anchor view
// So it will come over the anchor view and hide it completely
// If you want to have the dropdown underneath your anchor view, you can do this:
amountDropDown.bottomOffset = CGPoint(x: 0, y: amountButton.bounds.height)
// You can also use localizationKeysDataSource instead. Check the docs.
amountDropDown.dataSource = [
"10 €",
"20 €",
"30 €",
"40 €",
"50 €",
"60 €",
"70 €",
"80 €",
"90 €",
"100 €",
"110 €",
"120 €"
]
// Action triggered on selection
amountDropDown.selectionAction = { [unowned self] (index, item) in
self.amountButton.setTitle(item, for: .normal)
}
}
func setupChooseDropDown() {
chooseDropDown.anchorView = chooseButton
// By default, the dropdown will have its origin on the top left corner of its anchor view
// So it will come over the anchor view and hide it completely
// If you want to have the dropdown underneath your anchor view, you can do this:
chooseDropDown.bottomOffset = CGPoint(x: 0, y: chooseButton.bounds.height)
// You can also use localizationKeysDataSource instead. Check the docs.
chooseDropDown.dataSource = [
"Lorem ipsum dolor",
"sit amet consectetur",
"cadipisci en..."
]
// Action triggered on selection
chooseDropDown.selectionAction = { [unowned self] (index, item) in
self.chooseButton.setTitle(item, for: .normal)
}
}
func setupCenteredDropDown() {
// Not setting the anchor view makes the drop down centered on screen
// centeredDropDown.anchorView = centeredDropDownButton
// You can also use localizationKeysDataSource instead. Check the docs.
centeredDropDown.dataSource = [
"The drop down",
"Is centered on",
"the view because",
"it has no anchor view defined.",
"Click anywhere to dismiss."
]
}
func setupRightBarDropDown() {
rightBarDropDown.anchorView = rightBarButton
// You can also use localizationKeysDataSource instead. Check the docs.
rightBarDropDown.dataSource = [
"Menu 1",
"Menu 2",
"Menu 3",
"Menu 4"
]
}
}
| 28.04461 | 98 | 0.704799 |
0ec161e1b1a50491c665029c0f8ff0554ff15ee9 | 1,696 | //
// Copyright © 2017 Yoti Limited. All rights reserved.
//
import Foundation
final class CallbackBackendService: NSObject, URLSessionDelegate {
private lazy var urlSession = URLSession(configuration: .default,
delegate: self,
delegateQueue: nil)
func callbackBackend(scenario: Scenario,
token: String,
completion: @escaping (Data?, Error?) -> Void) {
guard let callbackBackendURL = scenario.callbackBackendURL else {
completion(nil, CallbackBackendError.invalidCallbackBackendURL("Value received \(String(describing: scenario.callbackBackendURL?.absoluteString))"))
return
}
var urlComponments = URLComponents(url: callbackBackendURL, resolvingAgainstBaseURL: true)
urlComponments?.queryItems = [URLQueryItem(name: "token", value: token)]
guard let url = urlComponments?.url else {
completion(nil, CallbackBackendError.invalidCallbackBackendURL("Value received \(String(describing: scenario.callbackBackendURL?.absoluteString))"))
return
}
urlSession.dataTask(with: url) { (data, response, error) in
guard let httpResponse = response as? HTTPURLResponse, error == nil else {
completion(nil, error)
return
}
let statusCode = httpResponse.statusCode
guard 200...299 ~= statusCode else {
completion(nil, CallbackBackendError.httpRequestError(statusCode))
return
}
completion(data, nil)
}.resume()
}
}
| 35.333333 | 160 | 0.60967 |
febde52762037af77cdcdbcecad2d535465226a4 | 2,271 | //
// MonsterConfigurableWidget.swift
// UhooiPicBookWidgets
//
// Created by Takehito Koshimizu on 2020/11/14.
//
import WidgetKit
import SwiftUI
private struct MonsterProvider {
typealias Entry = MonsterEntry
typealias Intent = SelectMonsterIntent
private let imageManager: ImageCacheManagerProtocol
init(imageManager: ImageCacheManagerProtocol) {
self.imageManager = imageManager
}
}
struct MonsterConfigurableWidget: Widget {
var body: some WidgetConfiguration {
IntentConfiguration(
kind: "MonsterConfigurable",
intent: SelectMonsterIntent.self,
provider: MonsterProvider(imageManager: ImageCacheManager())
) { entry in
MonsterEntryView(entry: entry)
}
.configurationDisplayName("configurationDisplayName")
.description("configurableDescription")
.supportedFamilies([.systemSmall, .systemMedium])
}
}
extension MonsterProvider: IntentTimelineProvider {
func placeholder(in context: Context) -> Entry {
.createDefault()
}
func getSnapshot(for intent: Intent, in context: Context, completion: @escaping (Entry) -> Void) {
completion(.createDefault())
}
func getTimeline(for intent: Intent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
convertDTOToEntry(dto: intent.monster?.convertToDTO()) { entry in
let entries = [entry ?? .createDefault()]
completion(Timeline(entries: entries, policy: .never))
}
}
private func convertDTOToEntry(dto: MonsterDTO?, completion: @escaping (Entry?) -> Void) {
if let dto = dto, let iconUrl = URL(string: dto.iconUrlString) {
self.imageManager.cacheImage(imageUrl: iconUrl) { result in
switch result {
case let .success(icon):
let name = dto.name
let description = dto.description.replacingOccurrences(of: "\\n", with: "\n")
completion(Entry(date: Date(), name: name, description: description, icon: icon))
case .failure:
completion(nil)
}
}
} else {
completion(nil)
}
}
}
| 32.442857 | 112 | 0.626156 |
56aff894f67b912a243c8a107ffb4d3b82b4d107 | 731 | //
// PlaceCommentsWorkerSpy.swift
// Travelling
//
// Created by Dimitri Strauneanu on 12/10/2020.
// Copyright (c) 2020 Travelling. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
@testable import Travelling
class PlaceCommentsWorkerSpy: PlaceCommentsWorker {
var fetchItemsCalled: Bool = false
var fetchImageCalled: Bool = false
override func fetchItems(placeId: String?, page: Int, limit: Int) {
self.fetchItemsCalled = true
}
override func fetchImage(item: PlaceCommentsModels.DisplayedItem) {
self.fetchImageCalled = true
}
}
| 27.074074 | 71 | 0.708618 |
1dce8e05fe4ae0081af88a1299cbfa6e53a02c9d | 1,834 | //
// SFViewController.swift
// shtickerz
//
// Created by bill donner on 7/14/16.
// Copyright © 2016 Bill Donner/ midnightrambler All rights reserved.
//
import UIKit
import SafariServices
//import stikz
public func openwebsite(_ presentor:UIViewController) {
let url = URL(string:websitePath)!
let vc = SFViewController(url: url)
let nav = UINavigationController(rootViewController: vc)
vc.delegate = vc
presentor.present(nav, animated: true, completion: nil)
}
public func openInAnotherApp(url:URL)->Bool {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url,options:[:]){ b in }
return true
}
return false
}
/// SFViewController wraps sfafari
class SFViewController: SFSafariViewController {
func done(_:AnyObject){
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.done))
}
}
extension SFViewController : SFSafariViewControllerDelegate {
func allDone(_:AnyObject) {
print ("AllDone ")
}
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
print("+++++ safariViewControllerDidFinish \(controller)")
}
private func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: NSURL, title: String?) -> [UIActivity] {
print("+++++ safariViewController activityItemsFor \(controller)")
return []
}
func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
print("+++++ safariViewController didCompleteInitialLoad \(controller)")
}
}
| 31.084746 | 138 | 0.695747 |
75e916d865277ba6846607de3d0cfdd8ca07c652 | 159 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(asciieditTests.allTests),
]
}
#endif
| 15.9 | 45 | 0.672956 |
e6c9e5aeed51deb847ea82d379bc4a54cdf2e67e | 11,078 | //
// UserProfileView.swift
// edX
//
// Created by Akiva Leffert on 4/4/16.
// Copyright © 2016 edX. All rights reserved.
//
class UserProfileView : UIView, UIScrollViewDelegate {
private let margin = 4
private class SystemLabel: UILabel {
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines).insetBy(dx: 10, dy: 0)
}
override func drawText(in rect: CGRect) {
let newRect = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
super.drawText(in: rect.inset(by: newRect))
}
}
typealias Environment = OEXSessionProvider & OEXStylesProvider
private var environment : Environment
private let scrollView = UIScrollView()
private let usernameLabel = UILabel()
private let messageLabel = UILabel()
private let countryLabel = UILabel()
private let languageLabel = UILabel()
private let bioText = UITextView()
private let tabs = TabContainerView()
private let bioSystemMessage = SystemLabel()
private let avatarImage = ProfileImageView()
private let header = ProfileBanner()
private let bottomBackground = UIView()
init(environment: Environment, frame: CGRect) {
self.environment = environment
super.init(frame: frame)
self.addSubview(scrollView)
setupViews()
setupConstraints()
setAccessibilityIdentifiers()
}
private func setupViews() {
scrollView.backgroundColor = environment.styles.primaryBaseColor()
scrollView.delegate = self
avatarImage.borderWidth = 3.0
scrollView.addSubview(avatarImage)
usernameLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(usernameLabel)
messageLabel.numberOfLines = 0
messageLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(messageLabel)
languageLabel.accessibilityHint = Strings.Profile.languageAccessibilityHint
languageLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(languageLabel)
countryLabel.accessibilityHint = Strings.Profile.countryAccessibilityHint
countryLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical)
scrollView.addSubview(countryLabel)
bioText.backgroundColor = UIColor.clear
bioText.textAlignment = .natural
bioText.isScrollEnabled = false
bioText.isEditable = false
bioText.textContainer.lineFragmentPadding = 0;
bioText.textContainerInset = UIEdgeInsets.zero
tabs.layoutMargins = UIEdgeInsets(top: StandardHorizontalMargin, left: StandardHorizontalMargin, bottom: StandardHorizontalMargin, right: StandardHorizontalMargin)
tabs.items = [bioTab]
scrollView.addSubview(tabs)
bottomBackground.backgroundColor = bioText.backgroundColor
scrollView.insertSubview(bottomBackground, belowSubview: tabs)
bioSystemMessage.isHidden = true
bioSystemMessage.numberOfLines = 0
bioSystemMessage.backgroundColor = environment.styles.neutralXLight()
scrollView.insertSubview(bioSystemMessage, aboveSubview: tabs)
header.style = .LightContent
header.backgroundColor = scrollView.backgroundColor
header.isHidden = true
self.addSubview(header)
bottomBackground.backgroundColor = environment.styles.standardBackgroundColor()
}
private func setAccessibilityIdentifiers() {
accessibilityIdentifier = "UserProfileView:"
scrollView.accessibilityIdentifier = "UserProfileView:scroll-view"
usernameLabel.accessibilityIdentifier = "UserProfileView:username-label"
messageLabel.accessibilityIdentifier = "UserProfileView:message-label"
countryLabel.accessibilityIdentifier = "UserProfileView:country-label"
languageLabel.accessibilityIdentifier = "UserProfileView:language-label"
bioText.accessibilityIdentifier = "UserProfileView:bio-text-view"
bioSystemMessage.accessibilityIdentifier = "UserProfileView:bio-system-message-label"
header.accessibilityIdentifier = "UserProfileView:profile-header-view"
bottomBackground.accessibilityIdentifier = "UserProfileView:bottom-background-view"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupConstraints() {
scrollView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
avatarImage.snp.makeConstraints { make in
make.width.equalTo(avatarImage.snp.height)
make.width.equalTo(166)
make.centerX.equalTo(scrollView)
make.top.equalTo(scrollView.snp.topMargin).offset(20)
}
usernameLabel.snp.makeConstraints { make in
make.top.equalTo(avatarImage.snp.bottom).offset(margin)
make.centerX.equalTo(scrollView)
}
messageLabel.snp.makeConstraints { make in
make.top.equalTo(usernameLabel.snp.bottom).offset(margin).priority(.high)
make.centerX.equalTo(scrollView)
}
languageLabel.snp.makeConstraints { make in
make.top.equalTo(messageLabel.snp.bottom)
make.centerX.equalTo(scrollView)
}
countryLabel.snp.makeConstraints { make in
make.top.equalTo(languageLabel.snp.bottom)
make.centerX.equalTo(scrollView)
}
tabs.snp.makeConstraints { make in
make.top.equalTo(countryLabel.snp.bottom).offset(35).priority(.high)
make.bottom.equalTo(scrollView)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.width.equalTo(scrollView)
}
bioSystemMessage.snp.makeConstraints { make in
make.top.equalTo(tabs)
make.bottom.greaterThanOrEqualTo(self)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.width.equalTo(scrollView)
}
bottomBackground.snp.makeConstraints { make in
make.edges.equalTo(bioSystemMessage)
}
header.snp.makeConstraints { make in
make.top.equalTo(scrollView)
make.leading.equalTo(scrollView)
make.trailing.equalTo(scrollView)
make.height.equalTo(56)
}
}
private func setMessage(message: String?) {
guard let message = message else {
messageLabel.text = nil
return
}
let messageStyle = OEXTextStyle(weight: .light, size: .xSmall, color: environment.styles.neutralWhiteT())
messageLabel.attributedText = messageStyle.attributedString(withText: message)
}
private func messageForProfile(profile : UserProfile, editable : Bool) -> String? {
if profile.sharingLimitedProfile {
return editable ? Strings.Profile.showingLimited : Strings.Profile.learnerHasLimitedProfile(platformName: OEXConfig.shared().platformName())
}
else {
return nil
}
}
private var bioTab : TabItem {
return TabItem(name: "About", view: bioText, identifier: "bio")
}
private func setDefaultValues() {
bioText.text = nil
countryLabel.text = nil
languageLabel.text = nil
}
func populateFields(profile: UserProfile, editable : Bool, networkManager : NetworkManager) {
let usernameStyle = OEXTextStyle(weight : .normal, size: .xxLarge, color: environment.styles.neutralWhiteT())
let infoStyle = OEXTextStyle(weight: .light, size: .xSmall, color: environment.styles.neutralWhiteT())
let bioStyle = environment.styles.textAreaBodyStyle
let messageStyle = OEXMutableTextStyle(weight: .bold, size: .large, color: environment.styles.neutralXDark())
messageStyle.alignment = .center
usernameLabel.attributedText = usernameStyle.attributedString(withText: profile.username)
bioSystemMessage.isHidden = true
avatarImage.remoteImage = profile.image(networkManager: networkManager)
setDefaultValues()
setMessage(message: messageForProfile(profile: profile, editable: editable))
if profile.sharingLimitedProfile {
if (profile.parentalConsent ?? false) && editable {
let message = NSMutableAttributedString(attributedString: messageStyle.attributedString(withText: Strings.Profile.ageLimit))
bioSystemMessage.attributedText = message
bioSystemMessage.isHidden = false
}
} else {
if let language = profile.language {
let icon = Icon.Comment.attributedTextWithStyle(style: infoStyle)
let langText = infoStyle.attributedString(withText: language)
languageLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon, langText])
}
if let country = profile.country {
let icon = Icon.Country.attributedTextWithStyle(style: infoStyle)
let countryText = infoStyle.attributedString(withText: country)
countryLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [icon, countryText])
}
if let bio = profile.bio {
bioText.attributedText = bioStyle.attributedString(withText: bio)
bioText.isAccessibilityElement = true
bioText.accessibilityLabel = Strings.Accessibility.Account.bioLabel
} else {
let message = messageStyle.attributedString(withText: Strings.Profile.noBio)
bioSystemMessage.attributedText = message
bioSystemMessage.isHidden = false
let accessibilityLabelText = "\(Strings.Accessibility.Account.bioLabel), \(Strings.Profile.noBio)"
bioSystemMessage.accessibilityLabel = accessibilityLabelText
bioSystemMessage.isAccessibilityElement = true
bioText.isAccessibilityElement = false
}
}
header.showProfile(profile: profile, networkManager: networkManager)
}
var extraTabs : [ProfileTabItem] = [] {
didSet {
let instantiatedTabs = extraTabs.map {tab in tab(scrollView) }
tabs.items = [bioTab] + instantiatedTabs
}
}
@objc func scrollViewDidScroll(_ scrollView: UIScrollView) {
UIView.animate(withDuration: 0.25) {
self.header.isHidden = scrollView.contentOffset.y < self.avatarImage.frame.maxY
}
}
func chooseTab(identifier: String) {
tabs.showTab(withIdentifier: identifier)
}
}
| 40.878229 | 171 | 0.673407 |
03857a8a139f6c28b87d87e57cdc6a506d2ff2d2 | 550 | //
// AppDelegate.swift
// ScrolleableView
//
// Created by EZen on 2022/2/24.
//
import Cocoa
@main
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}
| 17.741935 | 81 | 0.692727 |
f5c8228ef650143690eff3ebd3ba9f3e679b5390 | 2,510 | //
// ValidationViewModel.swift
// RxSwiftForms
//
// Created by Michael Long on 3/8/18.
// Copyright © 2018 Hoy Long. All rights reserved.
//
import UIKit
class ValidationViewModel {
var fields = FxFields<String>()
func setupFields() {
fields.add("required")
.placeholder("Sample")
.required()
.message("Required.")
fields.add("creditcard")
.validate(FxRules.creditcard())
.placeholder("0000 0000 0000 0000")
.keyboardType(.numbersAndPunctuation)
fields.add("currency")
.placeholder("0.00")
.validate(FxRules.currency())
.keyboardType(.decimalPad)
fields.add("custom")
.placeholder("Test")
.validate("Anything other than 'Test' is invalid", { $0.asText.lowercased() == "test" })
fields.add("cvc")
.title("CVC")
.placeholder("000")
.validate(FxRules.cvc())
.keyboardType(.decimalPad)
fields.add("email")
.title("Email Address")
.placeholder("[email protected]")
.validate(FxRules.email())
.keyboardType(.emailAddress)
fields.add("decimal")
.placeholder("0.0")
.validate(FxRules.decimal())
.keyboardType(.decimalPad)
fields.add("expires2")
.placeholder("mm/yy")
.validate(FxRules.expiresYear2())
.keyboardType(.numbersAndPunctuation)
fields.add("expires4")
.placeholder("mm/yyyy")
.validate(FxRules.expiresYear4())
.keyboardType(.numbersAndPunctuation)
fields.add("integer")
.placeholder("0")
.validate(FxRules.integer())
.keyboardType(.decimalPad)
fields.add("ssn")
.title("SSN")
.placeholder("000-00-0000")
.validate(FxRules.ssn())
.keyboardType(.numbersAndPunctuation)
fields.add("phone")
.placeholder("000-000-0000")
.validate(FxRules.phone())
.keyboardType(.numbersAndPunctuation)
fields.add("zip")
.placeholder("00000")
.validate(FxRules.zipcode())
.keyboardType(.decimalPad)
fields.add("zip4")
.title("Zip Plus 4")
.placeholder("00000-0000")
.validate(FxRules.zipPlusFour())
.keyboardType(.numbersAndPunctuation)
}
}
| 27.282609 | 100 | 0.541833 |
2371d4f8cffb663ec09db49c83f4486dd33319ab | 2,125 | /*:
# The Hurdle Race
[HackerRank Problem - The Hurdle Race](https:www.hackerrank.com/challenges/the-hurdle-race/problem "HackerRank Problem - The Hurdle Race")
---
### Problem Statement
Dan is playing a video game in which his character competes in a hurdle race. Hurdles are of varying heights, and Dan has a maximum height he can jump. There is a magic potion he can take that will increase his maximum height by unit for each dose. How many doses of the potion must he take to be able to jump all of the hurdles.
Given an array of hurdle heights `height`, and an initial maximum height Dan can jump, `k`, determine the minimum number of doses Dan must take to be able to clear all the hurdles in the race.
For example, if `height = [1, 2, 3, 3, 2]` and Dan can jump `1` unit high naturally, he must take `3 - 1 = 2` doses of potion to be able to jump all of the hurdles.
### Function Description
Complete the hurdleRace function in the editor below. It should return the minimum units of potion Dan needs to drink to jump all of the hurdles.
hurdleRace has the following parameter(s):
+ k: an integer denoting the height Dan can jump naturally
+ height: an array of integers denoting the heights of each hurdle
### Input Format
The first line contains two space-separated integers `n` and `k`, the number of hurdles and the maximum height Dan can jump naturally.
The second line contains `n` space-separated integers `height[i]` where `0 ≤ i < n`.
### Constraints
+ 1 ≤ n, k ≤ 100
+ 1 ≤ height[i] ≤ 100
### Output Format
Print an integer denoting the minimum doses of magic potion Dan must drink to complete the hurdle race.
### Sample Input
```
5 4
1 6 3 5 2
```
### Sample Output
```
2
```
*/
import Foundation
// Complete the hurdleRace function below.
func hurdleRace(k: Int, height: [Int]) -> Int {
if let maxHurdleHeight = height.max(), k < maxHurdleHeight {
return maxHurdleHeight - k
}
return 0
}
hurdleRace(k: 4, height: [1, 6, 3, 5, 2]) // 2
hurdleRace(k: 7, height: [2, 5, 4, 5, 2]) // 0
hurdleRace(k: 1, height: [1, 2, 3, 3, 2]) // 2
| 30.797101 | 331 | 0.699294 |
f57d27f8a0a6a609418237a6d854dfbc80eccfb1 | 1,249 | //
// HTTPMethod.swift
// WeatherAPI
//
// Copyright (c) 2021 Rocket Insights, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Foundation
public enum HTTPMethod: String {
case GET
}
| 39.03125 | 79 | 0.745396 |
b92f69cacc09058aed277a82b638ee98fdf38bea | 2,358 | //
// SceneDelegate.swift
// RGB Bluetooth Reader
//
// Created by João Costa on 14/01/2020.
// Copyright © 2020 João Costa. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.666667 | 147 | 0.71374 |
9c15df0d4f2fa6777e638e063f6a0f86de80562d | 1,859 | //
// StoryboardViewController.swift
// MaterialDesignWidgetsDemo
//
// Created by Michael Ho on 5/28/20.
// Copyright © 2020 Michael Ho. All rights reserved.
//
import UIKit
class StoryboardViewController: UIViewController {
@IBOutlet weak var topSegmentedControl: UISegmentedControl!
@IBOutlet weak var contentView: UIView!
private var widgetsView: UIView!
private var buttonsView: UIView!
// loadView
override func loadView() {
super.loadView()
widgetsView = WidgetsViewController().view
buttonsView = ButtonsViewController().view
self.contentView.addSubViews([widgetsView, buttonsView])
widgetsView.setAnchors(top: self.contentView, bottom: self.contentView,
left: self.contentView, right: self.contentView)
buttonsView.setAnchors(top: self.contentView, bottom: self.contentView,
left: self.contentView, right: self.contentView)
}
// viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
topSegmentedControl.selectedSegmentIndex = 0
topSegmentDidChange(topSegmentedControl)
self.hideKeyboardWhenTappedAround()
}
/**
traitCollectionDidChange is called when user switch between dark and light mode. Whenever this is
called, reset the UI.
*/
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
loadView()
viewDidLoad()
}
@IBAction func topSegmentDidChange(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
contentView.bringSubviewToFront(widgetsView)
case 1:
contentView.bringSubviewToFront(buttonsView)
default:
break
}
}
}
| 30.983333 | 102 | 0.655191 |
90357d65318d994e3e248fc20868f454cf636eb1 | 12,015 | // This file was automatically generated and should not be edited.
import Apollo
public final class RepositoryQuery: GraphQLQuery {
public let operationDefinition =
"query Repository {\n repository(owner: \"apollographql\", name: \"apollo-ios\") {\n __typename\n issueOrPullRequest(number: 13) {\n __typename\n ... on Issue {\n body\n ... on UniformResourceLocatable {\n url\n }\n author {\n __typename\n avatarUrl\n }\n }\n ... on Reactable {\n viewerCanReact\n ... on Comment {\n author {\n __typename\n login\n }\n }\n }\n }\n }\n}"
public let operationName = "Repository"
public init() {
}
public struct Data: GraphQLSelectionSet {
public static let possibleTypes = ["Query"]
public static let selections: [GraphQLSelection] = [
GraphQLField("repository", arguments: ["owner": "apollographql", "name": "apollo-ios"], type: .object(Repository.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(repository: Repository? = nil) {
self.init(unsafeResultMap: ["__typename": "Query", "repository": repository.flatMap { (value: Repository) -> ResultMap in value.resultMap }])
}
/// Lookup a given repository by the owner and repository name.
public var repository: Repository? {
get {
return (resultMap["repository"] as? ResultMap).flatMap { Repository(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "repository")
}
}
public struct Repository: GraphQLSelectionSet {
public static let possibleTypes = ["Repository"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("issueOrPullRequest", arguments: ["number": 13], type: .object(IssueOrPullRequest.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(issueOrPullRequest: IssueOrPullRequest? = nil) {
self.init(unsafeResultMap: ["__typename": "Repository", "issueOrPullRequest": issueOrPullRequest.flatMap { (value: IssueOrPullRequest) -> ResultMap in value.resultMap }])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// Returns a single issue-like object from the current repository by number.
public var issueOrPullRequest: IssueOrPullRequest? {
get {
return (resultMap["issueOrPullRequest"] as? ResultMap).flatMap { IssueOrPullRequest(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "issueOrPullRequest")
}
}
public struct IssueOrPullRequest: GraphQLSelectionSet {
public static let possibleTypes = ["Issue", "PullRequest"]
public static let selections: [GraphQLSelection] = [
GraphQLTypeCase(
variants: ["Issue": AsIssue.selections],
default: [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("viewerCanReact", type: .nonNull(.scalar(Bool.self))),
GraphQLField("author", type: .object(Author.selections)),
]
)
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public static func makePullRequest(viewerCanReact: Bool, author: Author? = nil) -> IssueOrPullRequest {
return IssueOrPullRequest(unsafeResultMap: ["__typename": "PullRequest", "viewerCanReact": viewerCanReact, "author": author.flatMap { (value: Author) -> ResultMap in value.resultMap }])
}
public static func makeIssue(body: String, url: String, author: AsIssue.Author? = nil, viewerCanReact: Bool) -> IssueOrPullRequest {
return IssueOrPullRequest(unsafeResultMap: ["__typename": "Issue", "body": body, "url": url, "author": author.flatMap { (value: AsIssue.Author) -> ResultMap in value.resultMap }, "viewerCanReact": viewerCanReact])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// Can user react to this subject
public var viewerCanReact: Bool {
get {
return resultMap["viewerCanReact"]! as! Bool
}
set {
resultMap.updateValue(newValue, forKey: "viewerCanReact")
}
}
/// The actor who authored the comment.
public var author: Author? {
get {
return (resultMap["author"] as? ResultMap).flatMap { Author(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "author")
}
}
public struct Author: GraphQLSelectionSet {
public static let possibleTypes = ["Organization", "User", "Bot"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("login", type: .nonNull(.scalar(String.self))),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public static func makeOrganization(login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Organization", "login": login])
}
public static func makeUser(login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "User", "login": login])
}
public static func makeBot(login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Bot", "login": login])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// The username of the actor.
public var login: String {
get {
return resultMap["login"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "login")
}
}
}
public var asIssue: AsIssue? {
get {
if !AsIssue.possibleTypes.contains(__typename) { return nil }
return AsIssue(unsafeResultMap: resultMap)
}
set {
guard let newValue = newValue else { return }
resultMap = newValue.resultMap
}
}
public struct AsIssue: GraphQLSelectionSet {
public static let possibleTypes = ["Issue"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("body", type: .nonNull(.scalar(String.self))),
GraphQLField("url", type: .nonNull(.scalar(String.self))),
GraphQLField("author", type: .object(Author.selections)),
GraphQLField("viewerCanReact", type: .nonNull(.scalar(Bool.self))),
GraphQLField("author", type: .object(Author.selections)),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public init(body: String, url: String, author: Author? = nil, viewerCanReact: Bool) {
self.init(unsafeResultMap: ["__typename": "Issue", "body": body, "url": url, "author": author.flatMap { (value: Author) -> ResultMap in value.resultMap }, "viewerCanReact": viewerCanReact])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// Identifies the body of the issue.
public var body: String {
get {
return resultMap["body"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "body")
}
}
/// The HTTP URL for this issue
public var url: String {
get {
return resultMap["url"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "url")
}
}
/// The actor who authored the comment.
public var author: Author? {
get {
return (resultMap["author"] as? ResultMap).flatMap { Author(unsafeResultMap: $0) }
}
set {
resultMap.updateValue(newValue?.resultMap, forKey: "author")
}
}
/// Can user react to this subject
public var viewerCanReact: Bool {
get {
return resultMap["viewerCanReact"]! as! Bool
}
set {
resultMap.updateValue(newValue, forKey: "viewerCanReact")
}
}
public struct Author: GraphQLSelectionSet {
public static let possibleTypes = ["Organization", "User", "Bot"]
public static let selections: [GraphQLSelection] = [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("avatarUrl", type: .nonNull(.scalar(String.self))),
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("login", type: .nonNull(.scalar(String.self))),
]
public private(set) var resultMap: ResultMap
public init(unsafeResultMap: ResultMap) {
self.resultMap = unsafeResultMap
}
public static func makeOrganization(avatarUrl: String, login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Organization", "avatarUrl": avatarUrl, "login": login])
}
public static func makeUser(avatarUrl: String, login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "User", "avatarUrl": avatarUrl, "login": login])
}
public static func makeBot(avatarUrl: String, login: String) -> Author {
return Author(unsafeResultMap: ["__typename": "Bot", "avatarUrl": avatarUrl, "login": login])
}
public var __typename: String {
get {
return resultMap["__typename"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "__typename")
}
}
/// A URL pointing to the actor's public avatar.
public var avatarUrl: String {
get {
return resultMap["avatarUrl"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "avatarUrl")
}
}
/// The username of the actor.
public var login: String {
get {
return resultMap["login"]! as! String
}
set {
resultMap.updateValue(newValue, forKey: "login")
}
}
}
}
}
}
}
}
| 36.969231 | 533 | 0.565293 |
b955c362d799648a3089dffed0667600c6eabed9 | 3,532 | //
// Settings.swift
// Doughy
//
// Created by urickg on 3/20/20.
// Copyright © 2020 George Urick. All rights reserved.
//
import UIKit
fileprivate let hasInitializedDefaultsKey = "hasInitializedDefaultsKey"
fileprivate let preferredTempKey = "preferredTempKey"
class Settings: NSObject {
private let recipeConverter = RecipeConverter.shared
private let recipeReader = RecipeReader.shared
private let recipeWriter = RecipeWriter.shared
private let defaultRecipeFactory = DefaultRecipeFactory.shared
private let userDefaults = UserDefaults.standard
private let coreDataGateway = CoreDataGateway.shared
lazy var recipes = self.refreshRecipes()
static let shared = Settings()
private override init() {
super.init()
self.initializeDefaultRecipes()
}
func refreshRecipes() -> [RecipeCollection] {
let recipes = recipeReader.getRecipes().map {
recipeConverter.convertToExternal(recipe: $0)
}
var collectionsMap = [String : RecipeCollection]()
for recipe in recipes {
if let collection = collectionsMap[recipe.collection] {
collection.recipes.append(recipe)
}
else {
let newCollection = RecipeCollection(name: recipe.collection)
newCollection.recipes.append(recipe)
collectionsMap[recipe.collection] = newCollection
}
}
let collections = collectionsMap.values.sorted { (a, b) -> Bool in
return a.name < b.name
}
return collections
}
}
extension Settings {
func initializeDefaultRecipes() {
if !userDefaults.bool(forKey: hasInitializedDefaultsKey) {
setPreferredTemp(measurement: .fahrenheit)
defaultRecipeFactory.create().forEach {
try! recipeWriter.writeRecipe(recipe: $0)
}
userDefaults.set(true, forKey: hasInitializedDefaultsKey)
}
}
}
extension Settings {
func preferredTemp() -> Temperature.Measurement {
let prefersCelsius = userDefaults.bool(forKey: preferredTempKey)
return prefersCelsius ? .celsius : .fahrenheit
}
func setPreferredTemp(measurement: Temperature.Measurement) {
userDefaults.set(measurement == .celsius, forKey: preferredTempKey)
}
func updateRecipeTemps(original: Temperature.Measurement,
target: Temperature.Measurement) throws {
let recipes = recipeReader.getRecipes()
recipes
.flatMap { $0.ingredients!.array as! [XCIngredient] }
.forEach {
if let currentTemp = $0.temperature {
let newTemp = TemperatureConverter.shared.convert(temperature: currentTemp.doubleValue, source: original, target: target)
$0.temperature = NSNumber(floatLiteral: newTemp)
}
}
recipes
.compactMap { $0.preferment?.ingredients?.array as? [XCIngredient] }
.flatMap { $0 }
.forEach {
if let currentTemp = $0.temperature {
let newTemp = TemperatureConverter.shared.convert(temperature: currentTemp.doubleValue, source: original, target: target)
$0.temperature = NSNumber(floatLiteral: newTemp)
}
}
try self.coreDataGateway.managedObjectConext.save()
}
}
| 33.638095 | 141 | 0.618347 |
086d11a7e72db5afda191a4453ecdb1830f88ab2 | 11,781 | @testable import Danger
import XCTest
final class GitHubTests: XCTestCase {
private var dateFormatter: DateFormatter {
return DateFormatter.defaultDateFormatter
}
private var decoder: JSONDecoder!
override func setUp() {
decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
}
override func tearDown() {
decoder = nil
super.tearDown()
}
func test_GitHubUser_decode() throws {
guard let data = GitHubUserJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let correctUser = GitHub.User(id: 25_879_490, login: "yhkaplan", userType: .user)
let testUser: GitHub.User = try JSONDecoder().decode(GitHub.User.self, from: data)
XCTAssertEqual(testUser, correctUser)
}
func test_GitHubBot_decode() throws {
guard let data = GitHubBotJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let correctUser = GitHub.User(id: 27_856_297, login: "dependabot-preview[bot]", userType: .bot)
let testBot = try JSONDecoder().decode(GitHub.User.self, from: data)
XCTAssertEqual(testBot, correctUser)
}
func test_GitHubMilestone_decodeWithSomeParameters() throws {
guard let data = GitHubMilestoneJSONWithSomeParameters.data(using: .utf8),
let createdAt = dateFormatter.date(from: "2018-01-20T16:29:28Z"),
let updatedAt = dateFormatter.date(from: "2018-02-27T06:23:58Z") else {
XCTFail("Could not generate data")
return
}
let creator = GitHub.User(id: 739_696, login: "rnystrom", userType: .user)
let correctMilestone = GitHub.Milestone(id: 3_050_458,
number: 11,
state: .open,
title: "1.19.0",
description: "kdsjfls",
creator: creator,
openIssues: 0,
closedIssues: 2,
createdAt: createdAt,
updatedAt: updatedAt,
closedAt: nil,
dueOn: nil)
let testMilestone: GitHub.Milestone = try decoder.decode(GitHub.Milestone.self, from: data)
XCTAssertEqual(testMilestone, correctMilestone)
}
func test_GitHubMilestone_decodeWithAllParameters() throws {
guard let data = GitHubMilestoneJSONWithAllParameters.data(using: .utf8),
let createdAt = dateFormatter.date(from: "2018-01-20T16:29:28Z"),
let updatedAt = dateFormatter.date(from: "2018-02-27T06:23:58Z"),
let closedAt = dateFormatter.date(from: "2018-03-20T09:46:21Z"),
let dueOn = dateFormatter.date(from: "2018-03-27T07:10:01Z") else {
XCTFail("Could not generate data")
return
}
let creator = GitHub.User(id: 739_696, login: "rnystrom", userType: .user)
let correctMilestone = GitHub.Milestone(id: 3_050_458,
number: 11,
state: .open,
title: "1.19.0",
description: "kdsjfls",
creator: creator,
openIssues: 0,
closedIssues: 2,
createdAt: createdAt,
updatedAt: updatedAt,
closedAt: closedAt,
dueOn: dueOn)
let testMilestone: GitHub.Milestone = try decoder.decode(GitHub.Milestone.self, from: data)
XCTAssertEqual(testMilestone, correctMilestone)
}
func test_GitHubMilestone_decodeWithoutDescription() throws {
guard let data = GitHubMilestoneJSONWithoutDescription.data(using: .utf8),
let createdAt = dateFormatter.date(from: "2018-01-20T16:29:28Z"),
let updatedAt = dateFormatter.date(from: "2018-02-27T06:23:58Z") else {
XCTFail("Could not generate data")
return
}
let creator = GitHub.User(id: 739_696, login: "rnystrom", userType: .user)
let correctMilestone = GitHub.Milestone(id: 3_050_458,
number: 11,
state: .open,
title: "1.19.0",
description: nil,
creator: creator,
openIssues: 0,
closedIssues: 2,
createdAt: createdAt,
updatedAt: updatedAt,
closedAt: nil,
dueOn: nil)
let testMilestone: GitHub.Milestone = try decoder.decode(GitHub.Milestone.self, from: data)
XCTAssertEqual(testMilestone, correctMilestone)
}
func test_GitHubTeam_decode() throws {
guard let data = GitHubTeamJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let correctTeam = GitHub.Team(id: 1, name: "Justice League")
let testTeam = try decoder.decode(GitHub.Team.self, from: data)
XCTAssertEqual(testTeam, correctTeam)
}
func test_GitHubMergeRef_decode() throws {
guard let data = GitHubPRJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let user = GitHub.User(id: 1, login: "octocat", userType: .user)
let repo = GitHub.Repo(id: 1_296_269,
name: "Hello-World",
fullName: "octocat/Hello-World",
owner: user,
isPrivate: false,
description: "This your first repo!",
isFork: true,
htmlURL: "https://github.com/octocat/Hello-World")
let correctMergeRef = GitHub.MergeRef(label: "new-topic",
ref: "new-topic1",
sha: "6dcb09b5b57875f334f61aebed695e2e4193db5e",
user: user,
repo: repo)
let testPR = try decoder.decode(GitHub.PullRequest.self, from: data)
XCTAssertEqual(testPR.head, correctMergeRef)
}
func test_GitHubRepo_decode() throws {
guard let data = GitHubRepoJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let user = GitHub.User(id: 1, login: "octocat", userType: .user)
let correctRepo = GitHub.Repo(id: 1_296_269,
name: "Hello-World",
fullName: "octocat/Hello-World",
owner: user,
isPrivate: false,
description: "This your first repo!",
isFork: false,
htmlURL: "https://github.com/octocat/Hello-World")
let testRepo = try decoder.decode(GitHub.Repo.self, from: data)
XCTAssertEqual(testRepo, correctRepo)
}
func test_GitHubReview_decode() throws {}
func test_GitHubCommit_decode() throws {}
func test_GitHubIssueLabel_decode() throws {}
func test_GitHubIssue_decode() throws {
guard let data = GitHubIssueJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let user = GitHub.User(id: 2_538_074, login: "davdroman", userType: .user)
let correctIssue = GitHub.Issue(
id: 447_357_592,
number: 96,
title: "Some commit that modifies a Swift file",
user: user,
state: .closed,
isLocked: false,
body: "Some body for the issue",
commentCount: 1,
assignee: nil,
assignees: [],
milestone: nil,
createdAt: Date(timeIntervalSince1970: 1_558_561_570),
updatedAt: Date(timeIntervalSince1970: 1_558_566_949),
closedAt: Date(timeIntervalSince1970: 1_558_566_946),
labels: []
)
let testIssue = try decoder.decode(GitHub.Issue.self, from: data)
XCTAssertEqual(testIssue, correctIssue)
}
func test_GitHubIssue_emptyBody_decode() throws {
guard let data = GitHubEmptyBodyIssueJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let user = GitHub.User(id: 2_538_074, login: "davdroman", userType: .user)
let correctIssue = GitHub.Issue(
id: 447_357_592,
number: 96,
title: "Some commit that modifies a Swift file",
user: user,
state: .closed,
isLocked: false,
body: nil,
commentCount: 1,
assignee: nil,
assignees: [],
milestone: nil,
createdAt: Date(timeIntervalSince1970: 1_558_561_570),
updatedAt: Date(timeIntervalSince1970: 1_558_566_949),
closedAt: Date(timeIntervalSince1970: 1_558_566_946),
labels: []
)
let testIssue = try decoder.decode(GitHub.Issue.self, from: data)
XCTAssertEqual(testIssue, correctIssue)
}
func test_GitHubCommit_decodesJSONWithEmptyAuthor() throws {
guard let data = GitHubCommitWithEmptyAuthorJSON.data(using: .utf8) else {
XCTFail("Could not generate data")
return
}
let expectedAuthor = Git.Commit.Author(name: "Franco Meloni", email: "[email protected]", date: "2019-04-20T17:46:50Z")
let testCommit = try decoder.decode(GitHub.Commit.self, from: data)
XCTAssertNil(testCommit.author)
XCTAssertEqual(testCommit.sha, "cad494648f773cd4fad5a9ea948c1bfabf36032a")
XCTAssertEqual(testCommit.url, "https://api.github.com/repos/danger/swift/commits/cad494648f773cd4fad5a9ea948c1bfabf36032a")
XCTAssertEqual(testCommit.commit, Git.Commit(sha: nil,
author: expectedAuthor,
committer: expectedAuthor,
message: "Re use the same executor on the runner",
parents: nil,
url: "https://api.github.com/repos/danger/swift/git/commits/cad494648f773cd4fad5a9ea948c1bfabf36032a"))
XCTAssertEqual(testCommit.committer, GitHub.User(id: 17_830_956, login: "f-meloni", userType: .user))
}
func test_GitHubPR_decode() throws {}
func test_GitHub_decode() throws {}
}
| 42.075 | 156 | 0.511417 |
50761bcf683015090401b3b62e6d70fe42ff263e | 6,234 | #if !canImport(ObjectiveC)
import XCTest
extension CaptureTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__CaptureTests = [
("test_capture", test_capture),
("test_capture_detects_bad_syntax", test_capture_detects_bad_syntax),
]
}
extension CaseTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__CaseTests = [
("test_assign_from_case", test_assign_from_case),
("test_case", test_case),
("test_case_on_length_with_else", test_case_on_length_with_else),
("test_case_on_size", test_case_on_size),
("test_case_on_size_with_else", test_case_on_size_with_else),
("test_case_when_comma", test_case_when_comma),
("test_case_when_or", test_case_when_or),
("test_case_with_else", test_case_with_else),
]
}
extension CycleTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__CycleTests = [
("test_cycle", test_cycle),
("test_multiple_cycles", test_multiple_cycles),
("test_multiple_named_cycles", test_multiple_named_cycles),
("test_multiple_named_cycles_with_names_from_context", test_multiple_named_cycles_with_names_from_context),
]
}
extension FilterTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__FilterTests = [
("testAbs", testAbs),
("testAppendToString", testAppendToString),
("testCapitalize", testCapitalize),
("testCeil", testCeil),
("testCompact", testCompact),
("testConcat", testConcat),
("testDate", testDate),
("testDefault", testDefault),
("testDividedBy", testDividedBy),
("testDowncase", testDowncase),
("testEscape", testEscape),
("testEscapeOnce", testEscapeOnce),
("testFirst", testFirst),
("testFloor", testFloor),
("testJoin", testJoin),
("testLast", testLast),
("testLstrip", testLstrip),
("testMap", testMap),
("testMinus", testMinus),
("testModulo", testModulo),
("testNewlineToBr", testNewlineToBr),
("testPlus", testPlus),
("testPrepend", testPrepend),
("testRemove", testRemove),
("testRemoveFirst", testRemoveFirst),
("testReplace", testReplace),
("testReplaceFirst", testReplaceFirst),
("testReverse", testReverse),
("testRound", testRound),
("testRstrip", testRstrip),
("testSize", testSize),
("testSlice", testSlice),
("testSort", testSort),
("testSortNatural", testSortNatural),
("testSplit", testSplit),
("testStrip", testStrip),
("testStripHtml", testStripHtml),
("testStripNewLines", testStripNewLines),
("testTimes", testTimes),
("testTruncate", testTruncate),
("testTruncateWords", testTruncateWords),
("testUnique", testUnique),
("testUpcase", testUpcase),
("testUrlDecode", testUrlDecode),
("testUrlEncode", testUrlEncode),
]
}
extension ForTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__ForTests = [
("test_for", test_for),
("test_for_and_if", test_for_and_if),
("test_for_else", test_for_else),
("test_for_helpers", test_for_helpers),
("test_for_reversed", test_for_reversed),
("test_for_with_break", test_for_with_break),
("test_for_with_continue", test_for_with_continue),
("test_for_with_range", test_for_with_range),
("test_for_with_variable_range", test_for_with_variable_range),
("test_limiting", test_limiting),
]
}
extension IfElseTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__IfElseTests = [
("test_comparison_of_strings_containing_and_or_or", test_comparison_of_strings_containing_and_or_or),
("test_comparisons_on_null", test_comparisons_on_null),
("test_else_if", test_else_if),
("test_hash_miss_generates_false", test_hash_miss_generates_false),
("test_if", test_if),
("test_if_and", test_if_and),
("test_if_boolean", test_if_boolean),
("test_if_else", test_if_else),
("test_if_from_variable", test_if_from_variable),
("test_if_or", test_if_or),
("test_if_or_with_operators", test_if_or_with_operators),
("test_literal_comparisons", test_literal_comparisons),
("test_nested_if", test_nested_if),
("test_unended_if", test_unended_if),
]
}
extension LexerTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__LexerTests = [
("testTextToken", testTextToken),
]
}
extension LiquidTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__LiquidTests = [
("testExample", testExample),
]
}
extension ValueTests {
// DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain`
// to regenerate.
static let __allTests__ValueTests = [
("testComparable", testComparable),
]
}
public func __allTests() -> [XCTestCaseEntry] {
return [
testCase(CaptureTests.__allTests__CaptureTests),
testCase(CaseTests.__allTests__CaseTests),
testCase(CycleTests.__allTests__CycleTests),
testCase(FilterTests.__allTests__FilterTests),
testCase(ForTests.__allTests__ForTests),
testCase(IfElseTests.__allTests__IfElseTests),
testCase(LexerTests.__allTests__LexerTests),
testCase(LiquidTests.__allTests__LiquidTests),
testCase(ValueTests.__allTests__ValueTests),
]
}
#endif
| 35.420455 | 115 | 0.65608 |
4a924184072d13053b108eed52f1a021684dd500 | 3,231 | //: [`Previous`](@previous)
/*:
## Reverse All the Words in a Sentence
Given a string containing a set of words separated by whitespace, we would like to transform it to a string in which the words appear in the reverse order. For example, `Alice likes Bob` transforms to `Bob likes Alice`. We do not need to keep the original string.
Implement a function to reverse words in a string `s`.
_HINT: It's easier to solve this using more than one pass._
Input: "Alice likes Bob"
Output: "Bob likes Alice"
*/
/// Reverse words in the specified string.
///
func reverse(s: String) -> String {
// First of all, reverse all characters in the string
var rc: [Character] = s.reversed()
// Get ready to track boundaries of each word
var lhs = rc.start(), rhs = lhs
// Scan all the characters of the string
while rhs <= rc.end() {
// Apply word reverse on space or end of the string
if rhs == rc.end() || rc[rhs] == " " {
// Reverse characters of the word
rc.reverse(lhs..<rhs++)
// Reset trackers
lhs = rhs
// Move on to the next character
continue
}
// Move on to the next character
rhs++
}
// Finally, all characters and words have been reversed
return String(rc)
}
//: Assertions for examples from description
reverse(s: "Alice likes Bob") ?>> "Bob likes Alice"
reverse(s: "ram is costly") ?>> "costly is ram"
//: Assertions for more involved use cases and edge conditions
reverse(s: IN_0) ?>> OUT_0
reverse(s: IN_1) ?>> OUT_1
reverse(s: IN_2) ?>> OUT_2
reverse(s: IN_3) ?>> OUT_3
reverse(s: IN_4) ?>> OUT_4
reverse(s: IN_5) ?>> OUT_5
reverse(s: IN_6) ?>> OUT_6
reverse(s: IN_7) ?>> OUT_7
reverse(s: IN_8) ?>> OUT_8
reverse(s: IN_9) ?>> OUT_9
reverse(s: IN_10) ?>> OUT_10
/*:
- callout(Solution): The code for computing the position of each character in the final result in a single pass is intricate.
However, for the special case where each word is a single character, the desired result is simply the reverse of `s`.
For the general case, reversing `s` gets the words to their correct relative positions. However, for words that are longer than one character, their letters appear in reverse order. This situation can be corrected by reversing the individual words.
For example, `ram is costly` reversed yields `yltsoc si mar`. We obtain the final result by reversing each word to obtain `costly is ram`.
```
void ReverseWords(string* s) {
// Reverses the whole string first.
reverse(s->begin(), s->end);
size_t start = 0, end;
while ((end = s->find(" ", start)) != string::npos) {
// Reverses each word in the string
reverse(s->begin() + start, s->begin() + end);
start = end + 1;
}
// Reverses the last word.
reverse(s->begin() + start, s->end());
}
```
Since we spend `O(1)` per character, the time complexity is `O(n)`, where `n` is the length of `s`. If strings are mutable, we can perform the computation in place, i.e., the additional space complexity is `O(1)`. If the string cannot be changed, the additional space complexity is `O(n)`, since we need to create a new string of length `n`.
*/
//: [`Next`](@next)
| 38.927711 | 342 | 0.661096 |
fb091b2639722fc50c179f40164ced17ab4a278f | 2,092 | //
// AppDelegate.swift
// RKAndSwiftUISpike
//
// Created by msp on 18/01/2022.
//
import UIKit
import SwiftUI
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
}
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.
}
}
| 41.84 | 285 | 0.74283 |
e9c311e4d807bc2eb7de90a896c150bdb69aa829 | 1,965 | import Foundation
import XCTest
@testable import Nimble
final class BeIdenticalToTest: XCTestCase {
func testBeIdenticalToPositive() {
let value = NSDate()
expect(value).to(beIdenticalTo(value))
}
func testBeIdenticalToNegative() {
expect(NSNumber(value: 1)).toNot(beIdenticalTo(NSString(string: "yo")))
expect(NSArray(array: [NSNumber(value: 1)])).toNot(beIdenticalTo(NSArray(array: [NSNumber(value: 1)])))
}
func testBeIdenticalToPositiveMessage() {
let num1 = NSNumber(value: 1)
let num2 = NSNumber(value: 2)
let message = "expected to be identical to \(identityAsString(num2)), got \(identityAsString(num1))"
failsWithErrorMessage(message) {
expect(num1).to(beIdenticalTo(num2))
}
}
func testBeIdenticalToNegativeMessage() {
let value1 = NSArray(array: [])
let value2 = value1
let message = "expected to not be identical to \(identityAsString(value2)), got \(identityAsString(value1))"
failsWithErrorMessage(message) {
expect(value1).toNot(beIdenticalTo(value2))
}
}
func testOperators() {
let value = NSDate()
expect(value) === value
expect(NSNumber(value: 1)) !== NSNumber(value: 2)
}
func testBeAlias() {
let value = NSDate()
expect(value).to(be(value))
expect(NSNumber(value: 1)).toNot(be(NSString(string: "turtles")))
#if canImport(Darwin)
expect([1]).toNot(be([1]))
#else
expect(NSArray(array: [NSNumber(value: 1)])).toNot(beIdenticalTo(NSArray(array: [NSNumber(value: 1)])))
#endif
let value1 = NSArray(array: [])
let value2 = value1
let message = "expected to not be identical to \(identityAsString(value1)), got \(identityAsString(value2))"
failsWithErrorMessage(message) {
expect(value1).toNot(be(value2))
}
}
}
| 33.87931 | 116 | 0.618321 |
14750a2ea9f559c74eabcf98dc505f7c0fefd6d5 | 917 | //
// SwiftExtensionTests.swift
// SwiftExtensionTests
//
// Created by PomCat on 2021/3/19.
//
import XCTest
@testable import SwiftExtension
class SwiftExtensionTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.970588 | 111 | 0.671756 |
de91fc153c7e33329f1ee14341ccfae68861b632 | 241 | public class BlinkingLabel : UILabel {
public func startBlinking() {
print("yaya startBlinking function run version 0.1.3")
}
public func stopBlinking() {
alpha = 1
layer.removeAllAnimations()
}
}
| 21.909091 | 61 | 0.618257 |
69da1ce257b02ffe818debd1531646aa61421e30 | 2,502 | //
// UserLoginStatusView.swift
// Diurna
//
// Created by Nicolas Gaulard-Querol on 16/07/2020.
// Copyright © 2020 Nicolas Gaulard-Querol. All rights reserved.
//
import AppKit
// MARK: - UserLoginStatusViewDelegate
@objc protocol UserLoginStatusViewDelegate: class {
func userDidRequestLogin()
func userDidRequestLogout()
}
// MARK: - UserLoginStatusView
class UserLoginStatusView: NSView {
// MARK: Outlets
@IBOutlet var view: NSView!
@IBOutlet var userButton: NSPopUpButton!
@IBOutlet var userMenu: NSMenu!
@IBOutlet var userStatusIndicator: NSImageView!
// MARK: Properties
weak var delegate: UserLoginStatusViewDelegate?
var user: String? {
didSet {
updateButton()
updateStatusIndicator()
}
}
// MARK: Initializers
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit(frame frameRect: NSRect? = nil) {
Bundle.main.loadNibNamed(
.userLoginStatusView,
owner: self,
topLevelObjects: nil
)
addSubview(view)
view.frame = frameRect ?? bounds
}
private func updateButton() {
userMenu.removeAllItems()
if let user = user {
userMenu.addItem(withTitle: user, action: nil, keyEquivalent: "")
userMenu.addItem(
withTitle: "Log out",
action: #selector(delegate?.userDidRequestLogout),
keyEquivalent: ""
)
} else {
userMenu.addItem(withTitle: "Logged out", action: nil, keyEquivalent: "")
userMenu.addItem(
withTitle: "Log in",
action: #selector(delegate?.userDidRequestLogin),
keyEquivalent: ""
)
}
}
private func updateStatusIndicator() {
if let user = user {
userStatusIndicator.animator().image = NSImage(named: NSImage.statusAvailableName)
userStatusIndicator.toolTip = "Logged in as \(user)"
} else {
userStatusIndicator.animator().image = NSImage(named: NSImage.statusNoneName)
userStatusIndicator.toolTip = "Logged out"
}
}
}
// MARK: - NSNib.Name
extension NSNib.Name {
fileprivate static let userLoginStatusView = "UserLoginStatusView"
}
| 24.291262 | 94 | 0.604716 |
0abbafcc7fa45945018d0c0e1e7458f26231e952 | 510 | //
// TreeClass.swift
// WrkstrmFoundation
//
// Created by Cristian Monterroza on 8/16/18.
// Copyright © 2018 Cristian Monterroza. All rights reserved.
//
import Foundation
public class Tree<T> {
/// The value contained in this node
public let value: T
public var children = [Tree]()
public weak var parent: Tree?
public func add(_ child: Tree) {
children.append(child)
child.parent = self
}
public init(_ value: T) {
self.value = value
}
}
| 17.586207 | 62 | 0.62549 |
bf6e9bb4809a1d5cce6aa002dc0c35931260a311 | 2,783 | //
// CommenterViewController.swift
// uprm1
//
// Created by Javier Bustillo on 8/18/17.
// Copyright © 2017 Javier Bustillo. All rights reserved.
//
import UIKit
import Parse
class CommenterViewController: UIViewController,UITextViewDelegate {
@IBOutlet weak var characterCountLabel: UILabel!
@IBOutlet weak var textView: UITextView!
var textFlag: Int!
@objc var originalID: String!
override func viewDidLoad() {
super.viewDidLoad()
textView.delegate = self
textView.text = "Write your post here"
textView.textColor = UIColor.lightGray
textFlag=0
characterCountLabel.text = ""
// Do any additional setup after loading the view.
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = nil
textView.textColor = UIColor.black
textFlag=textFlag+1
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.textColor = UIColor.lightGray
}
}
func textViewDidChange(_ textView: UITextView) {
characterCountLabel.text = "\(textView.text.count)"
if(textView.text!.count>140){
characterCountLabel.textColor = UIColor.red
}else{
characterCountLabel.textColor = UIColor.black
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButton(_ sender: Any) {
self.dismiss(animated: true) {
}
}
@IBAction func postButton(_ sender: Any) {
if(textFlag==0||textView.text.isEmpty){
print("error should appear saying you need to write something")
}
else if(textView.text!.count>140){
print("Less characters dude")
}
else{
let userName = PFUser.current()?.username
let thisComment = Comment(comment: self.textView.text, steps: 0, originalID: originalID, user: userName!)
thisComment.poster()
view.endEditing(true)
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func onTap(_ sender: Any) {
view.endEditing(true)
}
/*
// 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.
}
*/
}
| 28.690722 | 117 | 0.618757 |
2071f0de814cbc621040079802d357da2a5d325a | 3,439 | //
// AbstractPeopleTableViewController.swift
// MayTheForceBeWith_LucasSantos
//
// Created by Lucas Felipe on 15/01/2020.
// Copyright © 2020 Lucas Felipe. All rights reserved.
//
import UIKit
private let reuseIdentifier = "peopleCell"
private let personDetailSegueIdentifier = "PersonDetailSegue"
class AbstractPeopleTableViewController: UITableViewController {
var activityIndicatorView: UIActivityIndicatorView!
var apiPeopleGateway: PeopleGateway!
var apiClient: ApiClient = ApiClientImpl(urlSessionConfiguration: URLSessionConfiguration.default, completionHandlerQueue: OperationQueue.main)
var nextPage: Int = 1
var people = [ApiPeople]()
var peopleCount: Int {
return people.count
}
var peopleSelectedIndex: Int = -1
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
func configure() {
self.configureApiPeopleGateway()
self.configureActivityIndicatorView()
}
func configureActivityIndicatorView() {
self.activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.medium)
self.tableView.backgroundView = activityIndicatorView
}
func configureApiPeopleGateway() {
self.apiPeopleGateway = ApiPeopleGateway(apiClient: apiClient)
}
func handlePeopleReceived(response: ApiPeopleResponse) {
self.nextPage = response.nextPage
self.people.append(contentsOf: response.people)
self.activityIndicatorView.stopAnimating()
self.tableView.reloadData()
}
func handlePeopleError(_ error: Error) {
self.activityIndicatorView.stopAnimating()
showAlert(title: "Error", message: error.localizedDescription)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.peopleCount
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! PeopleTableViewCell
configure(cell: cell, at: indexPath.row)
return cell
}
private func configure(cell: PeopleTableViewCell, at row: Int) {
let person = people[row]
cell.display(name: person.name ?? "")
cell.display(height: person.height ?? 0, mass: person.mass ?? 0)
cell.display(birthYear: person.birthYear ?? "")
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.peopleSelectedIndex = indexPath.row
self.performSegue(withIdentifier: personDetailSegueIdentifier, sender: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let destination = segue.destination as? PersonDetailViewController else { return }
let person = people[self.peopleSelectedIndex]
destination.person = person
}
}
| 33.067308 | 147 | 0.697296 |
8fe26050e3ccca95147246a14978cad157cd4201 | 9,766 | //
// EventValidatorTests.swift
// SplitTests
//
// Created by Javier L. Avrudsky on 22/01/2019.
// Copyright © 2019 Split. All rights reserved.
//
import XCTest
@testable import Split
class EventValidatorTests: XCTestCase {
var validator: EventValidator!
override func setUp() {
let split1 = newSplit(trafficType: "custom")
let split2 = newSplit(trafficType: "other")
let split3 = newSplit(trafficType: "archivedtraffictype", status: .archived)
let splitCache = InMemorySplitCache()
splitCache.addSplit(splitName: split1.name!, split: split1)
splitCache.addSplit(splitName: split2.name!, split: split2)
splitCache.addSplit(splitName: split3.name!, split: split3)
validator = DefaultEventValidator(splitCache: splitCache)
}
override func tearDown() {
}
func testValidEventAllValues() {
XCTAssertNil(validator.validate(key: "key", trafficTypeName: "custom", eventTypeId: "type1", value: 1.0, properties: nil))
}
func testValidEventNullValue() {
XCTAssertNil(validator.validate(key: "key", trafficTypeName: "custom", eventTypeId: "type1", value: nil, properties: nil))
}
func testNullKey() {
let errorInfo = validator.validate(key: nil, trafficTypeName: "custom", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed a null key, the key must be a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testEmptyKey() {
let errorInfo = validator.validate(key: "", trafficTypeName: "custom", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed an empty string, matching key must a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testLongKey() {
let key = String(repeating: "p", count: 300)
let errorInfo = validator.validate(key: key, trafficTypeName: "custom", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("matching key too long - must be \(ValidationConfig.default.maximumKeyLength) characters or less", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testNullType() {
let errorInfo = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: nil, value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed a null or undefined event_type, event_type must be a non-empty String", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testEmptyType() {
let errorInfo = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: "", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed an empty event_type, event_type must be a non-empty String", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testTypeName() {
let nameHelper = EventTypeNameHelper()
let errorInfo1 = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: nameHelper.validAllValidChars, value: nil, properties: nil)
let errorInfo2 = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: nameHelper.validStartNumber, value: nil, properties: nil)
let errorInfo3 = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: nameHelper.invalidChars, value: nil, properties: nil)
let errorInfo4 = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: nameHelper.invalidUndercoreStart, value: nil, properties: nil)
let errorInfo5 = validator.validate(key: "key1", trafficTypeName: "custom", eventTypeId: nameHelper.invalidHypenStart, value: nil, properties: nil)
XCTAssertNil(errorInfo1)
XCTAssertNil(errorInfo2)
XCTAssertNotNil(errorInfo3)
XCTAssertTrue(errorInfo3?.isError ?? false)
XCTAssertEqual(errorMessage(for: nameHelper.invalidChars), errorInfo3?.errorMessage)
XCTAssertEqual(errorInfo3?.warnings.count, 0)
XCTAssertNotNil(errorInfo4)
XCTAssertTrue(errorInfo4?.isError ?? false)
XCTAssertEqual(errorMessage(for: nameHelper.invalidUndercoreStart), errorInfo4?.errorMessage)
XCTAssertEqual(errorInfo4?.warnings.count, 0)
XCTAssertNotNil(errorInfo5)
XCTAssertTrue(errorInfo5?.isError ?? false)
XCTAssertEqual(errorMessage(for: nameHelper.invalidHypenStart), errorInfo5?.errorMessage)
XCTAssertEqual(errorInfo5?.warnings.count, 0)
}
func testNullTrafficType() {
let errorInfo = validator.validate(key: "key1", trafficTypeName: nil, eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed a null or undefined traffic_type_name, traffic_type_name must be a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testEmptyTrafficType() {
let errorInfo = validator.validate(key: "key1", trafficTypeName: "", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertTrue(errorInfo?.isError ?? false)
XCTAssertEqual("you passed an empty traffic_type_name, traffic_type_name must be a non-empty string", errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 0)
}
func testUppercaseCharsInTrafficType() {
let upperCaseMsg = "traffic_type_name should be all lowercase - converting string to lowercase"
let errorInfo1 = validator.validate(key: "key1", trafficTypeName: "Custom", eventTypeId: "type1", value: nil, properties: nil)
let errorInfo2 = validator.validate(key: "key1", trafficTypeName: "cUSTom", eventTypeId: "type1", value: nil, properties: nil)
let errorInfo3 = validator.validate(key: "key1", trafficTypeName: "custoM", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo1)
XCTAssertFalse(errorInfo1?.isError ?? true)
XCTAssertEqual(upperCaseMsg, errorInfo1?.warnings.values.map ({$0})[0])
XCTAssertEqual(errorInfo1?.warnings.count, 1)
XCTAssertTrue(errorInfo1?.hasWarning(.trafficTypeNameHasUppercaseChars) ?? false)
XCTAssertNotNil(errorInfo2)
XCTAssertFalse(errorInfo2?.isError ?? true)
XCTAssertEqual(upperCaseMsg, errorInfo2?.warnings.values.map ({$0})[0])
XCTAssertEqual(errorInfo2?.warnings.count, 1)
XCTAssertTrue(errorInfo2?.hasWarning(.trafficTypeNameHasUppercaseChars) ?? false)
XCTAssertNotNil(errorInfo3)
XCTAssertFalse(errorInfo3?.isError ?? true)
XCTAssertEqual(upperCaseMsg, errorInfo3?.warnings.values.map ({$0})[0])
XCTAssertEqual(errorInfo3?.warnings.count, 1)
XCTAssertTrue(errorInfo3?.hasWarning(.trafficTypeNameHasUppercaseChars) ?? false)
}
func testNoChachedServerTrafficType() {
let errorInfo = validator.validate(key: "key1", trafficTypeName: "nocached", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertNil(errorInfo?.error)
XCTAssertNil(errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 1)
XCTAssertEqual("traffic_type_name nocached does not have any corresponding Splits in this environment, make sure you’re tracking your events to a valid traffic type defined in the Split console", errorInfo?.warnings.values.map ({$0})[0])
XCTAssertTrue(errorInfo?.hasWarning(.trafficTypeWithoutSplitInEnvironment) ?? false)
}
func testNoChachedServerAndUppercasedTrafficType() {
let errorInfo = validator.validate(key: "key1", trafficTypeName: "noCached", eventTypeId: "type1", value: nil, properties: nil)
XCTAssertNotNil(errorInfo)
XCTAssertNil(errorInfo?.error)
XCTAssertNil(errorInfo?.errorMessage)
XCTAssertEqual(errorInfo?.warnings.count, 2)
XCTAssertTrue(errorInfo?.hasWarning(.trafficTypeWithoutSplitInEnvironment) ?? false)
XCTAssertTrue(errorInfo?.hasWarning(.trafficTypeNameHasUppercaseChars) ?? false)
XCTAssertEqual("traffic_type_name should be all lowercase - converting string to lowercase", errorInfo?.warnings[.trafficTypeNameHasUppercaseChars])
XCTAssertEqual("traffic_type_name noCached does not have any corresponding Splits in this environment, make sure you’re tracking your events to a valid traffic type defined in the Split console", errorInfo?.warnings[.trafficTypeWithoutSplitInEnvironment])
}
private func newSplit(trafficType: String, status: Status = .active) -> Split {
let split = Split()
split.name = UUID().uuidString
split.trafficTypeName = trafficType
split.status = status
return split
}
private func errorMessage(for typeName: String) -> String {
return "you passed \(typeName), event name must adhere to the regular expression \(ValidationConfig.default.trackEventNamePattern). This means an event name must be alphanumeric, cannot be more than 80 characters long, and can only include a dash, underscore, period, or colon as separators of alphanumeric characters"
}
}
| 51.4 | 326 | 0.713291 |
721449d676dee27b56f8edc78797a21a384fd896 | 3,369 | //
// Solution146.swift
// leetcode
//
// Created by youzhuo wang on 2020/3/25.
// Copyright © 2020 youzhuo wang. All rights reserved.
//
import Foundation
// LRU--访问过的放在最前面
// 字典 + 链表
class LRUCache {
var map: [Int: LRUCacheNode]
var count:Int
var capacity:Int
var head: LRUCacheNode?
var tail: LRUCacheNode?
init(_ capacity: Int) {
self.capacity = capacity
count = 0
head = nil
tail = nil
self.map = [Int: LRUCacheNode]()
}
// 获取key的value值,并且将该节点设置到head
func get(_ key: Int) -> Int {
guard let node = map[key] else{
return -1
}
if node.prev != nil {
if node == tail {
// 如果node是尾节点
tail = node.prev
}
// node的前节点 下个指向 node 的后节点
node.prev!.next = node.next
// node的后节点 前指向 node的前节点
node.next?.prev = node.prev
node.next = head
head?.prev = node
node.prev = nil
head = node
}
// 头节点
return node.val
}
//
func put(_ key: Int, _ value: Int) {
// 加到头, 先看是否有该key
if let node = map[key]{
// 已经有该node了
node.val = value
if node.prev != nil {
if node == tail {
// 如果node是尾节点
tail = node.prev
}
// node的前节点 下个指向 node 的后节点
node.prev!.next = node.next
// node的后节点 前指向 node的前节点
node.next?.prev = node.prev
node.next = head
head?.prev = node
node.prev = nil
head = node
}
}else {
// 新建node 加到head
let putNode = LRUCacheNode.init(key, value)
map[key] = putNode
if head == nil {
tail = putNode
}
count = count + 1
//加到head
putNode.next = head
head?.prev = putNode
head = putNode
if count > capacity {
// map清除
map.removeValue(forKey: tail!.key)
//清除尾部
tail?.prev?.next = nil
tail = tail?.prev
}
}
}
}
class LRUCacheNode:Equatable {
static func == (lhs: LRUCacheNode, rhs: LRUCacheNode) -> Bool {
return lhs.val == rhs.val && lhs.key == rhs.key
}
var val:Int
var key:Int
var next:LRUCacheNode?
var prev:LRUCacheNode?
init(_ key: Int, _ val:Int) {
self.key = key
self.val = val
self.next = nil
self.prev = nil
}
}
class LRUCacheTest {
func test() {
let cache = LRUCache(2)
cache.put(2, 1)
cache.put(1, 1)
cache.put(2, 3)
cache.put(4, 1)
print(cache.get(1))
print(cache.get(2))
// print(cache.get(1))
// cache.put(3, 3)
// print(cache.get(2))
// cache.put(4, 4)
// print(cache.get(1))
// print(cache.get(3))
// print(cache.get(4))
}
}
| 22.763514 | 67 | 0.423865 |
7518c597a2b87e11bc6d370b42dcf6f1b349db9b | 478 | //
// Router.swift
// GithubBrowser
//
protocol AppRouter {
associatedtype Parameter
var routeParams: [String: Parameter] { get }
func setParmeters(parameters: Parameter...)
}
class Router<T>: AppRouter {
var routeParams = Dictionary<String, T>()
func setParmeters(parameters: T...) {
for(index, parameter) in parameters.enumerated() {
let key = "arg\(index)"
routeParams[key] = parameter
}
}
}
| 19.916667 | 58 | 0.598326 |
7ad0b5f9bf87ee420483b9fb48edafa85b297129 | 9,149 | //
// JSONDecoder+Ext.swift
// SwiftEasyExtension
//
// Created by Arvind on 6/5/20.
// Copyright © 2020 Arvind. All rights reserved.
//
import Foundation
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
class JSONCodingKey: CodingKey {
let key: String
required init?(intValue: Int) {
return nil
}
required init?(stringValue: String) {
key = stringValue
}
var intValue: Int? {
return nil
}
var stringValue: String {
return key
}
}
class JSONAny: Codable {
let value: Any
static func decodingError(forCodingPath codingPath: [CodingKey]) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: "Cannot decode JSONAny")
return DecodingError.typeMismatch(JSONAny.self, context)
}
static func encodingError(forValue value: Any, codingPath: [CodingKey]) -> EncodingError {
let context = EncodingError.Context(codingPath: codingPath, debugDescription: "Cannot encode JSONAny")
return EncodingError.invalidValue(value, context)
}
static func decode(from container: SingleValueDecodingContainer) throws -> Any {
if let value = try? container.decode(Bool.self) {
return value
}
if let value = try? container.decode(Int64.self) {
return value
}
if let value = try? container.decode(Double.self) {
return value
}
if let value = try? container.decode(String.self) {
return value
}
if container.decodeNil() {
return JSONNull()
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decode(from container: inout UnkeyedDecodingContainer) throws -> Any {
if let value = try? container.decode(Bool.self) {
return value
}
if let value = try? container.decode(Int64.self) {
return value
}
if let value = try? container.decode(Double.self) {
return value
}
if let value = try? container.decode(String.self) {
return value
}
if let value = try? container.decodeNil() {
if value {
return JSONNull()
}
}
if var container = try? container.nestedUnkeyedContainer() {
return try decodeArray(from: &container)
}
if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self) {
return try decodeDictionary(from: &container)
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decode(from container: inout KeyedDecodingContainer<JSONCodingKey>, forKey key: JSONCodingKey) throws -> Any {
if let value = try? container.decode(Bool.self, forKey: key) {
return value
}
if let value = try? container.decode(Int64.self, forKey: key) {
return value
}
if let value = try? container.decode(Double.self, forKey: key) {
return value
}
if let value = try? container.decode(String.self, forKey: key) {
return value
}
if let value = try? container.decodeNil(forKey: key) {
if value {
return JSONNull()
}
}
if var container = try? container.nestedUnkeyedContainer(forKey: key) {
return try decodeArray(from: &container)
}
if var container = try? container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key) {
return try decodeDictionary(from: &container)
}
throw decodingError(forCodingPath: container.codingPath)
}
static func decodeArray(from container: inout UnkeyedDecodingContainer) throws -> [Any] {
var arr: [Any] = []
while !container.isAtEnd {
let value = try decode(from: &container)
arr.append(value)
}
return arr
}
static func decodeDictionary(from container: inout KeyedDecodingContainer<JSONCodingKey>) throws -> [String: Any] {
var dict = [String: Any]()
for key in container.allKeys {
let value = try decode(from: &container, forKey: key)
dict[key.stringValue] = value
}
return dict
}
static func encode(to container: inout UnkeyedEncodingContainer, array: [Any]) throws {
for value in array {
if let value = value as? Bool {
try container.encode(value)
} else if let value = value as? Int64 {
try container.encode(value)
} else if let value = value as? Double {
try container.encode(value)
} else if let value = value as? String {
try container.encode(value)
} else if value is JSONNull {
try container.encodeNil()
} else if let value = value as? [Any] {
var container = container.nestedUnkeyedContainer()
try encode(to: &container, array: value)
} else if let value = value as? [String: Any] {
var container = container.nestedContainer(keyedBy: JSONCodingKey.self)
try encode(to: &container, dictionary: value)
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
}
static func encode(to container: inout KeyedEncodingContainer<JSONCodingKey>, dictionary: [String: Any]) throws {
for (key, value) in dictionary {
let key = JSONCodingKey(stringValue: key)!
if let value = value as? Bool {
try container.encode(value, forKey: key)
} else if let value = value as? Int64 {
try container.encode(value, forKey: key)
} else if let value = value as? Double {
try container.encode(value, forKey: key)
} else if let value = value as? String {
try container.encode(value, forKey: key)
} else if value is JSONNull {
try container.encodeNil(forKey: key)
} else if let value = value as? [Any] {
var container = container.nestedUnkeyedContainer(forKey: key)
try encode(to: &container, array: value)
} else if let value = value as? [String: Any] {
var container = container.nestedContainer(keyedBy: JSONCodingKey.self, forKey: key)
try encode(to: &container, dictionary: value)
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
}
static func encode(to container: inout SingleValueEncodingContainer, value: Any) throws {
if let value = value as? Bool {
try container.encode(value)
} else if let value = value as? Int64 {
try container.encode(value)
} else if let value = value as? Double {
try container.encode(value)
} else if let value = value as? String {
try container.encode(value)
} else if value is JSONNull {
try container.encodeNil()
} else {
throw encodingError(forValue: value, codingPath: container.codingPath)
}
}
public required init(from decoder: Decoder) throws {
if var arrayContainer = try? decoder.unkeyedContainer() {
self.value = try JSONAny.decodeArray(from: &arrayContainer)
} else if var container = try? decoder.container(keyedBy: JSONCodingKey.self) {
self.value = try JSONAny.decodeDictionary(from: &container)
} else {
let container = try decoder.singleValueContainer()
self.value = try JSONAny.decode(from: container)
}
}
public func encode(to encoder: Encoder) throws {
if let arr = self.value as? [Any] {
var container = encoder.unkeyedContainer()
try JSONAny.encode(to: &container, array: arr)
} else if let dict = self.value as? [String: Any] {
var container = encoder.container(keyedBy: JSONCodingKey.self)
try JSONAny.encode(to: &container, dictionary: dict)
} else {
var container = encoder.singleValueContainer()
try JSONAny.encode(to: &container, value: self.value)
}
}
}
| 36.450199 | 159 | 0.595256 |
081632f757fa23af12200613db2eea015d6f8155 | 3,148 | //
// HTTPHeaderParser.swift
// Embassy
//
// Created by Fang-Pen Lin on 5/19/16.
// Copyright © 2016 Fang-Pen Lin. All rights reserved.
//
import Foundation
extension String {
/// String without leading spaces
var withoutLeadingSpaces: String {
var firstNoneSpace: Int = characters.count
for (i, char) in characters.enumerated() {
if char != " " {
firstNoneSpace = i
break
}
}
return substring(from: index(startIndex, offsetBy: firstNoneSpace))
}
}
/// Parser for HTTP headers
public struct HTTPHeaderParser {
private static let CR = UInt8(13)
private static let LF = UInt8(10)
private static let NEWLINE = (CR, LF)
public enum Element {
case head(method: String, path: String, version: String)
case header(key: String, value: String)
case end(bodyPart: Data)
}
private enum State {
case head
case headers
}
private var state: State = .head
private var buffer: Data = Data()
/// Feed data to HTTP parser
/// - Parameter data: the data to feed
/// - Returns: parsed headers elements
mutating func feed(_ data: Data) -> [Element] {
buffer.append(data)
var elements = [Element]()
while buffer.count > 0 {
// pair of (0th, 1st), (1st, 2nd), (2nd, 3rd) ... chars, so that we can find <LF><CR>
let charPairs: [(UInt8, UInt8)] = Array(zip(
buffer[0..<buffer.count - 1],
buffer[1..<buffer.count]
))
// ensure we have <CR><LF> in current buffer
guard let index = (charPairs).index(where: { $0 == HTTPHeaderParser.NEWLINE }) else {
// no <CR><LF> found, just return the current elements
return elements
}
let bytes = Array(buffer[0..<index])
let string = String(bytes: bytes, encoding: String.Encoding.utf8)!
buffer = buffer.subdata(in: (index + 2)..<buffer.count)
// TODO: the initial usage of this HTTP server is for iOS API server mocking only,
// we don't usually see malform requests, but if it's necessary, like if we want to put
// this server in real production, we should handle malform header then
switch state {
case .head:
let parts = string.components(separatedBy: " ")
elements.append(.head(method: parts[0], path: parts[1], version: parts[2..<parts.count].joined(separator: " ")))
state = .headers
case .headers:
// end of headers
guard bytes.count > 0 else {
elements.append(.end(bodyPart: buffer))
return elements
}
let parts = string.components(separatedBy: ":")
let key = parts[0]
let value = parts[1..<parts.count].joined(separator: ":").withoutLeadingSpaces
elements.append(.header(key: key, value: value))
}
}
return elements
}
}
| 35.772727 | 128 | 0.554956 |
87f925f717fca6a14045c60d6bee20752a2e3735 | 693 | //
// Created by Thomas Christensen on 24/08/16.
// Copyright (c) 2016 Nordija A/S. All rights reserved.
//
import Foundation
// Extend the String object with helpers
extension String {
// String.replace(); similar to JavaScript's String.replace() and Ruby's String.gsub()
func replace(_ pattern: String, replacement: String) throws -> String {
let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
return regex.stringByReplacingMatches(
in: self,
options: [.withTransparentBounds],
range: NSRange(location: 0, length: self.characters.count),
withTemplate: replacement
)
}
}
| 28.875 | 90 | 0.662338 |
714b53e39e54753f5cae0fd53d0b12ce7690d38a | 1,270 | //
// ProductsQuery.swift
// IAP
//
// Created by Roman Karpievich on 4/9/19.
// Copyright © 2019 Roman Karpievich. All rights reserved.
//
import Foundation
import StoreKit
class ProductsQuery: NSObject, SKProductsRequestDelegate {
private let request: SKProductsRequest
private let completion: (ProductsQueryResult) -> Void
init(identifiers: Set<String>, completion: @escaping (ProductsQueryResult) -> Void) {
request = SKProductsRequest(productIdentifiers: identifiers)
self.completion = completion
super.init()
request.delegate = self
}
public func start() {
request.start()
}
public func cancel() {
request.cancel()
}
// MARK: - SKProductsRequestDelegate
func productsRequest(_: SKProductsRequest, didReceive response: SKProductsResponse) {
let invalidIdentifiers = response.invalidProductIdentifiers
let products = response.products
let result = ProductsQueryResult.success((products, invalidIdentifiers))
completion(result)
}
func requestDidFinish(_: SKRequest) {}
func request(_: SKRequest, didFailWithError error: Error) {
let result = ProductsQueryResult.failure(error)
completion(result)
}
}
| 25.918367 | 89 | 0.687402 |
618fb07e2ae0d0fdb519e2fd4fbbe4d0c8dc2ef4 | 1,504 | //
// ActionEvent.swift
// ShipBook
//
// Created by Elisha Sterngold on 26/11/2017.
// Copyright © 2018 ShipBook Ltd. All rights reserved.
//
import Foundation
class ActionEvent: BaseEvent {
var action: String
var sender: String?
var senderTitle: String?
var target: String?
init(action: String, sender: String?, senderTitle: String?, target: String?) {
self.action = action
self.sender = sender
self.senderTitle = senderTitle
self.target = target
super.init(type: "actionEvent")
}
enum CodingKeys: String, CodingKey {
case action
case sender
case senderTitle
case target
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.action = try container.decode(String.self, forKey: .action)
self.sender = try container.decodeIfPresent(String.self, forKey: .sender)
self.senderTitle = try container.decodeIfPresent(String.self, forKey: .senderTitle)
self.target = try container.decodeIfPresent(String.self, forKey: .target)
try super.init(from: decoder)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(action, forKey: .action)
try container.encodeIfPresent(sender, forKey: .sender)
try container.encodeIfPresent(senderTitle, forKey: .senderTitle)
try container.encodeIfPresent(target, forKey: .target)
try super.encode(to: encoder)
}
}
| 30.08 | 87 | 0.714761 |
ed48d890f830b5ed47f8a5e858b52482e0595337 | 1,084 | //===--- NopDeinit.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
// <rdar://problem/17838787>
import TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "NopDeinit",
runFunction: run_NopDeinit,
tags: [.regression],
legacyFactor: 100)
class X<T : Comparable> {
let deinitIters = 10000
var elem: T
init(_ x : T) {elem = x}
deinit {
for _ in 1...deinitIters {
if (elem > elem) { }
}
}
}
public func run_NopDeinit(_ n: Int) {
for _ in 1...n {
var arr :[X<Int>] = []
let size = 5
for i in 1...size { arr.append(X(i)) }
arr.removeAll()
check(arr.count == 0)
}
}
| 25.209302 | 80 | 0.558118 |
0192cffbb35d47d439d3d6e24148d11f517155bd | 1,024 | //
// ViewController.swift
// WebHelperLibExamples
//
// Created by Hushan on 11/4/19.
// Copyright © 2019 Hushan M Khan. All rights reserved.
//
import UIKit
import WebHelperLib
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Get API
WebHelperLib.shared.Request(.GET, urlString: "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty", parameters: [],requestParam:["Auth":"121543545311","Auth2":"251546"], loading: true, complitionHandler: { (data, res) in
print(data)
}) { (error) in
}
}
func postApi() {
WebHelperLib.shared.Request(.POST, urlString: "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty", parameters: [], loading: true, complitionHandler: { (obj, res) in
}) { (error) in
}
}
}
| 24.380952 | 243 | 0.586914 |
f4a23ac5f42adfbfe793d1cf89982bda5882fc1f | 662 | //
// MessageImageViewCell.swift
// jlpt-ios-release
//
// Created by Nguyen Trong Tung on 2017/11/17.
// Copyright © 2017 Nguyen Trong Tung. All rights reserved.
//
import UIKit
class MessageImageViewCell: UICollectionViewCell, ConfigurableCell {
typealias DataType = MessageImageModel
static var identifier: String { return String(describing: self) }
override init(frame: CGRect) {
super.init(frame: frame)
setUpView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpView() {
}
func configure(data: MessageImageModel) {
}
}
| 20.6875 | 69 | 0.672205 |
18d3bfc8559d5c4ffc096587ca33b938a0c3c400 | 1,073 | //
// MenuItemCellViewModel.swift
// ViewModel
//
// Created by Григорий Сухоруков on 21/04/2020.
// Copyright © 2020 Григорий Сухоруков. All rights reserved.
//
import UIKit
class MenuItemCellViewModel: CellViewModel {
// static let height .0= 66
init(title: String, color: UIColor) {
super.init()
layout { (layout) in
layout.height = 66.0
layout.flexDirection = .column
layout.alignItems = .center
layout.justifyContent = .flexStart
}
let avatarViewModel = SimpleViewModel()
avatarViewModel.configuration.backgroundColor = color
avatarViewModel.layout { (layout) in
layout.width = 28.0
layout.height = 28.0
}
add(avatarViewModel)
let textViewModel = TextViewModel(title)
.attributes([.font: UIFont.systemFont(ofSize: 13)])
.lines(2)
.layout {
$0.marginTop = 6.0
}
add(textViewModel)
}
}
| 24.386364 | 63 | 0.555452 |
3314b39864fb748bdb0a87e97dca586db4b4b7d4 | 1,237 | //
// JQHUDString-Extension.swift
// JQProgressHUD
//
// Created by HJQ on 2017/7/1.
// Copyright © 2017年 HJQ. All rights reserved.
//
import Foundation
import UIKit
public extension String {
public func jq_heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
#if swift(>=4.0)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
#else
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
#endif
return boundingBox.height
}
}
public extension NSAttributedString {
public func jq_heightWithConstrainedWidth(width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
return ceil(boundingBox.height)
}
}
| 36.382353 | 184 | 0.7308 |
0e9c566917a1784c6125ebd52e863bc2c01d80bf | 388 | //
// *******************************************
//
// NBPointDetailModel.swift
// NightBusiness
//
// Created by Noah_Shan on 2020/7/10.
// Copyright © 2018 Inpur. All rights reserved.
//
// *******************************************
//
import UIKit
class NBPointDetailModel: NSObject {
var descriptions: String = "sdfasdfasdf"
var screenshots: [String]? = []
}
| 17.636364 | 48 | 0.494845 |
14cd5f6b73c2e9a7654dd5b22912a2c35e9ff01a | 2,646 | //
// NWListener.swift
// Network
//
// Created by Brandon Wiley on 9/4/18.
//
import Foundation
import Socket
import Dispatch
public class NWListener
{
public enum State
{
case cancelled
case failed(NWError)
case ready
case setup
case waiting(NWError)
}
public var debugDescription: String = "[NWListener]"
public var newConnectionHandler: ((NWConnection) -> Void)?
public let parameters: NWParameters
public var port: NWEndpoint.Port?
public var queue: DispatchQueue?
public var stateUpdateHandler: ((NWListener.State) -> Void)?
private var usingUDP: Bool
private var socket: Socket
// Note: It is unclear from the documentation how to use the Network framework to listen on a IPv6 address, or if this is even possible.
// Therefore, this is not currently supported in NetworkLinux.
public required init(using: NWParameters, on port: NWEndpoint.Port) throws
{
self.parameters=using
self.port=port
print("Port: \(String(describing: self.port))")
usingUDP = false
if let prot = using.defaultProtocolStack.internetProtocol
{
if let _ = prot as? NWProtocolUDP.Options {
usingUDP = true
}
}
if(usingUDP)
{
guard let socket = try? Socket.create(family: Socket.ProtocolFamily.inet, type: Socket.SocketType.datagram, proto: .udp) else {
throw NWError.posix(POSIXErrorCode.EADDRINUSE)
}
self.socket = socket
do
{
try socket.listen(on: Int(port.rawValue))
}
catch
{
throw NWError.posix(POSIXErrorCode.EADDRINUSE)
}
}
else
{
guard let socket = try? Socket.create(family: Socket.ProtocolFamily.inet, type: Socket.SocketType.stream, proto: .tcp) else {
throw NWError.posix(POSIXErrorCode.EADDRINUSE)
}
self.socket = socket
do
{
try socket.listen(on: Int(port.rawValue), node: "0.0.0.0")
}
catch
{
throw NWError.posix(POSIXErrorCode.EADDRINUSE)
}
}
}
public func start(queue: DispatchQueue)
{
if let state = stateUpdateHandler {
state(.ready)
}
}
public func cancel()
{
if let state = stateUpdateHandler {
state(.cancelled)
}
}
}
| 26.727273 | 140 | 0.55291 |
9c760aea24cd3aadcdaddbc59ad6fd1f01894e2b | 2,394 | // RUN: %target-swift-frontend %s -emit-ir | FileCheck %s
// REQUIRES: CPU=x86_64
//
// Type parameters
//
infix operator ~> { precedence 255 }
func ~> <Target, Args, Result> (
target: Target,
method: Target -> Args -> Result)
-> Args -> Result
{
return method(target)
}
protocol Runcible {
associatedtype Element
}
struct Mince {}
struct Spoon: Runcible {
typealias Element = Mince
}
func split<Seq: Runcible>(seq: Seq) -> (Seq.Element -> Bool) -> () {
return {(isSeparator: Seq.Element -> Bool) in
return ()
}
}
var seq = Spoon()
var x = seq ~> split
//
// Indirect return
//
// CHECK-LABEL: define internal { i8*, %swift.refcounted* } @_TPA__TF21partial_apply_generic5split{{.*}}(%V21partial_apply_generic5Spoon* noalias nocapture, %swift.refcounted*)
// CHECK: [[REABSTRACT:%.*]] = bitcast %V21partial_apply_generic5Spoon* %0 to %swift.opaque*
// CHECK: tail call { i8*, %swift.refcounted* } @_TF21partial_apply_generic5split{{.*}}(%swift.opaque* noalias nocapture [[REABSTRACT]],
struct HugeStruct { var a, b, c, d: Int }
struct S {
func hugeStructReturn(h: HugeStruct) -> HugeStruct { return h }
}
let s = S()
var y = s.hugeStructReturn
// CHECK-LABEL: define internal void @_TPA__TFV21partial_apply_generic1S16hugeStructReturnfVS_10HugeStructS1_(%V21partial_apply_generic10HugeStruct* noalias nocapture sret, %V21partial_apply_generic10HugeStruct* noalias nocapture dereferenceable(32), %swift.refcounted*) #0 {
// CHECK: entry:
// CHECK: tail call void @_TFV21partial_apply_generic1S16hugeStructReturnfVS_10HugeStructS1_(%V21partial_apply_generic10HugeStruct* noalias nocapture sret %0, %V21partial_apply_generic10HugeStruct* noalias nocapture dereferenceable(32) %1) #0
// CHECK: ret void
// CHECK: }
//
// Witness method
//
protocol Protein {
static func veganOrNothing() -> Protein?
static func paleoDiet() throws -> Protein
}
enum CarbOverdose : ErrorProtocol {
case Mild
case Severe
}
class Chicken : Protein {
static func veganOrNothing() -> Protein? {
return nil
}
static func paleoDiet() throws -> Protein {
throw CarbOverdose.Severe
}
}
func healthyLunch<T: Protein>(t: T) -> () -> Protein? {
return T.veganOrNothing
}
let f = healthyLunch(Chicken())
func dietaryFad<T: Protein>(t: T) -> () throws -> Protein {
return T.paleoDiet
}
let g = dietaryFad(Chicken())
do {
try g()
} catch {}
| 25.468085 | 275 | 0.703843 |
e9d1aafb9c6f2a4959fb01fe99328b9e2f23e9af | 2,170 | //
// DetailRecipeViewController.swift
// CookBook
//
// Created by Jainam, Himanshu, Ramy on 5/10/21.
//
import UIKit
class DetailRecipeViewController: UIViewController {
var model: dbModel = dbModel.getModelInstance()
var selectedMeal: meal?
@IBOutlet weak var mealImageView: UIImageView!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var ingredientsTextView: UITextView!
@IBOutlet weak var directionsTextView: UITextView!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var prepTimeLabel: UILabel!
func updateView(){
guard let selectedMealObj = self.selectedMeal
else{
return
}
mealNameLabel.text = selectedMealObj.name
descriptionTextView.text = selectedMealObj.description
ingredientsTextView.text = selectedMealObj.ingredients
directionsTextView.text = selectedMealObj.directions
categoryLabel.text = "Category: " + selectedMealObj.category
prepTimeLabel.text = "⏲️: " + selectedMealObj.prepTime
let url: URL? = URL(string: selectedMealObj.imageData)
guard
let defualtUIImg = UIImage(named: "icon1"),
let defaultImg = defualtUIImg.jpegData(compressionQuality: 1)
else {return}
if let url: URL = url {
let data = try? Data(contentsOf: url)
mealImageView.image = UIImage(data: data ?? defaultImg)
} else {
mealImageView.image = UIImage(data: defaultImg)
}
// mealImageView.image = get data from url // copy from cellCiew
}
override func viewDidLoad() {
super.viewDidLoad()
self.selectedMeal = self.model.getSelectedMeal()
updateView()
NotificationCenter.default.addObserver(self, selector: #selector(self.updateSelectedMeals(_:)), name: NSNotification.Name(rawValue: "SelectedMealUpdated"), object: nil)
}
@objc func updateSelectedMeals(_ notification: NSNotification){
self.selectedMeal = self.model.getSelectedMeal()
updateView()
}
}
| 34.444444 | 176 | 0.664516 |
bb6b298471a8c8352cd8645bb3abc6e7261728ec | 12,826 | //
// 🦠 Corona-Warn-App
//
import BackgroundTasks
import UIKit
import HealthCertificateToolkit
import OpenCombine
class TaskExecutionHandler: ENATaskExecutionDelegate {
// MARK: - Init
init(
riskProvider: RiskProvider,
restServiceProvider: RestServiceProviding,
exposureManager: ExposureManager,
plausibleDeniabilityService: PlausibleDeniabilityService,
contactDiaryStore: DiaryStoring,
eventStore: EventStoring,
eventCheckoutService: EventCheckoutService,
store: Store,
exposureSubmissionDependencies: ExposureSubmissionServiceDependencies,
healthCertificateService: HealthCertificateService
) {
self.riskProvider = riskProvider
self.restServiceProvider = restServiceProvider
self.exposureManager = exposureManager
self.plausibleDeniabilityService = plausibleDeniabilityService
self.contactDiaryStore = contactDiaryStore
self.eventStore = eventStore
self.eventCheckoutService = eventCheckoutService
self.store = store
self.dependencies = exposureSubmissionDependencies
self.healthCertificateService = healthCertificateService
}
// MARK: - Protocol ENATaskExecutionDelegate
var plausibleDeniabilityService: PlausibleDeniability
var dependencies: ExposureSubmissionServiceDependencies
var contactDiaryStore: DiaryStoring
/// This method executes the background tasks needed for fetching test results, performing exposure detection
/// and executing plausible deniability fake requests.
///
/// - NOTE: The method explicitly ignores the outcomes of all subtasks (success/failure) and will _always_
/// call completion(true) when the subtasks finished regardless of their individual results.
/// This will set the background task state to _completed_. We only mark the task as incomplete
/// when the OS calls the expiration handler before all tasks were able to finish.
func executeENABackgroundTask(completion: @escaping ((Bool) -> Void)) {
Log.info("Starting background task...", log: .background)
guard store.isOnboarded else {
Log.info("Cancelling background task because user is not onboarded yet.", log: .background)
completion(true)
return
}
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
Log.info("Starting ExposureDetection...", log: .background)
self.executeExposureDetectionRequest { _ in
Log.info("Done detecting Exposures…", log: .background)
/// ExposureDetection should be our highest Priority if we run all other tasks simultaneously we might get killed by the Watchdog while the Detection is running.
/// This could leave us in a dirty state which causes the ExposureDetection to run too often. This will then lead to Error 13. (https://jira-ibs.wbs.net.sap/browse/EXPOSUREAPP-5836)
group.enter()
DispatchQueue.global().async {
Log.info("Trying to submit TEKs...", log: .background)
self.executeSubmitTemporaryExposureKeys { _ in
group.leave()
Log.info("Done submitting TEKs...", log: .background)
}
}
group.enter()
DispatchQueue.global().async {
Log.info("Trying to fetch TestResults...", log: .background)
self.executeFetchTestResults { _ in
group.leave()
Log.info("Done fetching TestResults...", log: .background)
}
}
group.enter()
DispatchQueue.global().async {
Log.info("Starting FakeRequests...", log: .background)
self.plausibleDeniabilityService.executeFakeRequests {
group.leave()
Log.info("Done sending FakeRequests...", log: .background)
}
}
group.enter()
DispatchQueue.global().async {
Log.info("Cleanup contact diary store.", log: .background)
self.contactDiaryStore.cleanup(timeout: 10.0)
Log.info("Done cleaning up contact diary store.", log: .background)
group.leave()
}
group.enter()
DispatchQueue.global().async {
Log.info("Cleanup event store.", log: .background)
self.eventStore.cleanup(timeout: 10.0)
Log.info("Done cleaning up contact event store.", log: .background)
group.leave()
}
group.enter()
DispatchQueue.global().async {
Log.info("Checkout overdue checkins.", log: .background)
self.eventCheckoutService.checkoutOverdueCheckins()
Log.info("Done checkin out overdue checkins.", log: .background)
group.leave()
}
group.enter()
DispatchQueue.global().async {
Log.info("Trigger analytics submission.", log: .background)
self.executeAnalyticsSubmission {
group.leave()
Log.info("Done triggering analytics submission…", log: .background)
}
}
group.enter()
DispatchQueue.global().async {
Log.info("Check for invalid certificates", log: .background)
self.checkCertificateValidityStates {
group.leave()
Log.info("Done checking for invalid certificates.", log: .background)
}
}
group.enter()
DispatchQueue.global().async {
Log.info("Check if DCC wallet infos need to be updated and booster notifications need to be triggered.", log: .background)
self.executeDCCWalletInfoUpdatesAndTriggerBoosterNotificationsIfNeeded {
group.leave()
Log.info("Done checking if DCC wallet infos need to be updated and booster notifications need to be triggered", log: .background)
}
}
group.leave() // Leave from the Exposure detection
}
}
group.notify(queue: .main) {
completion(true)
}
}
// MARK: - Internal
var riskProvider: RiskProvider
var store: Store
// MARK: - Private
private let exposureManager: ExposureManager
private let restServiceProvider: RestServiceProviding
private let backgroundTaskConsumer = RiskConsumer()
private let eventStore: EventStoring
private let eventCheckoutService: EventCheckoutService
private let healthCertificateService: HealthCertificateService
private var subscriptions = Set<AnyCancellable>()
/// This method attempts a submission of temporary exposure keys. The exposure submission service itself checks
/// whether a submission should actually be executed.
private func executeSubmitTemporaryExposureKeys(completion: @escaping ((Bool) -> Void)) {
Log.info("[ENATaskExecutionDelegate] Attempt submission of temporary exposure keys.", log: .api)
let service = ENAExposureSubmissionService(
diagnosisKeysRetrieval: dependencies.exposureManager,
appConfigurationProvider: dependencies.appConfigurationProvider,
client: dependencies.client,
restServiceProvider: restServiceProvider,
store: dependencies.store,
eventStore: dependencies.eventStore,
coronaTestService: dependencies.coronaTestService
)
let group = DispatchGroup()
for coronaTestType in CoronaTestType.allCases {
group.enter()
service.submitExposure(coronaTestType: coronaTestType) { error in
switch error {
case .noCoronaTestOfGivenType:
Analytics.collect(.keySubmissionMetadata(.submittedInBackground(false, coronaTestType)))
Log.info("[ENATaskExecutionDelegate] Submission: no corona test of type \(coronaTestType) registered", log: .api)
case .noSubmissionConsent:
Analytics.collect(.keySubmissionMetadata(.submittedInBackground(false, coronaTestType)))
Log.info("[ENATaskExecutionDelegate] Submission: no consent given", log: .api)
case .noKeysCollected:
Analytics.collect(.keySubmissionMetadata(.submittedInBackground(false, coronaTestType)))
Log.info("[ENATaskExecutionDelegate] Submission: no keys to submit", log: .api)
case .some(let error):
Analytics.collect(.keySubmissionMetadata(.submittedInBackground(false, coronaTestType)))
Log.error("[ENATaskExecutionDelegate] Submission error: \(error.localizedDescription)", log: .api)
case .none:
Analytics.collect(.keySubmissionMetadata(.submittedInBackground(true, coronaTestType)))
Log.info("[ENATaskExecutionDelegate] Submission successful", log: .api)
}
group.leave()
}
}
group.notify(queue: .main) {
completion(true)
}
}
/// This method executes a test result fetch, and if it is successful, and the test result is different from the one that was previously
/// part of the app, a local notification is shown.
private func executeFetchTestResults(completion: @escaping ((Bool) -> Void)) {
// First check if user activated notification setting
UNUserNotificationCenter.current().getNotificationSettings { [weak self] settings in
if settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional {
self?.dependencies.coronaTestService.updateTestResults(force: false, presentNotification: true) { result in
switch result {
case .success:
completion(true)
case .failure:
completion(false)
}
}
} else {
Log.info("[ENATaskExecutionDelegate] Cancel updating test results. User deactivated notification setting.", log: .riskDetection)
completion(false)
}
}
}
/// This method performs a check for the current exposure detection state. Only if the risk level has changed compared to the
/// previous state, a local notification is shown.
private func executeExposureDetectionRequest(completion: @escaping ((Bool) -> Void)) {
Log.info("[ENATaskExecutionDelegate] Execute exposure detection.", log: .riskDetection)
// At this point we are already in background so it is safe to assume background mode is available.
riskProvider.riskProvidingConfiguration.detectionMode = .fromBackgroundStatus(.available)
riskProvider.observeRisk(backgroundTaskConsumer)
backgroundTaskConsumer.didCalculateRisk = { [weak self] risk in
Log.info("[ENATaskExecutionDelegate] Execute exposure detection did calculate risk.", log: .riskDetection)
guard let self = self else { return }
if risk.riskLevelHasChanged {
Log.info("[ENATaskExecutionDelegate] Risk has changed.", log: .riskDetection)
completion(true)
} else {
Log.info("[ENATaskExecutionDelegate] Risk has not changed.", log: .riskDetection)
completion(false)
}
self.riskProvider.removeRisk(self.backgroundTaskConsumer)
}
backgroundTaskConsumer.didFailCalculateRisk = { [weak self] error in
guard let self = self else { return }
// Ignore already running errors.
// In other words: if the RiskProvider is already running, we wait for other callbacks.
guard !error.isAlreadyRunningError else {
Log.info("[ENATaskExecutionDelegate] Ignore already running error.", log: .riskDetection)
return
}
Log.error("[ENATaskExecutionDelegate] Exposure detection failed.", log: .riskDetection, error: error)
switch error {
case .failedRiskDetection(let reason):
if case .wrongDeviceTime = reason {
if !self.dependencies.store.wasDeviceTimeErrorShown {
UNUserNotificationCenter.current().presentNotification(
title: AppStrings.WrongDeviceTime.errorPushNotificationTitle,
body: AppStrings.WrongDeviceTime.errorPushNotificationText,
identifier: ActionableNotificationIdentifier.deviceTimeCheck.identifier
)
self.dependencies.store.wasDeviceTimeErrorShown = true
}
}
default:
break
}
completion(false)
self.riskProvider.removeRisk(self.backgroundTaskConsumer)
}
if exposureManager.exposureManagerState.status == .unknown {
exposureManager.activate { [weak self] error in
if let error = error {
Log.error("[ENATaskExecutionDelegate] Cannot activate the ENManager.", log: .api, error: error)
}
self?.riskProvider.requestRisk(userInitiated: false)
}
} else {
riskProvider.requestRisk(userInitiated: false)
}
}
private func executeAnalyticsSubmission(completion: @escaping () -> Void) {
// update the enf risk exposure metadata and checkin risk exposure metadata if new risk calculations are not done in the meanwhile
Analytics.collect(.riskExposureMetadata(.update))
Analytics.triggerAnalyticsSubmission(completion: { result in
switch result {
case .success:
Log.info("[ENATaskExecutionDelegate] Analytics submission was triggered successfully from background", log: .ppa)
case let .failure(error):
Log.error("[ENATaskExecutionDelegate] Analytics submission was triggered not successfully from background with error: \(error)", log: .ppa, error: error)
}
completion()
})
}
private func executeDCCWalletInfoUpdatesAndTriggerBoosterNotificationsIfNeeded(completion: @escaping () -> Void) {
Log.info("[ENATaskExecutionDelegate] Checking if DCC wallet infos need to be updated and booster notifications need to be triggered...", log: .vaccination)
healthCertificateService.updateDCCWalletInfosIfNeeded(completion: completion)
}
private func checkCertificateValidityStates(completion: @escaping () -> Void) {
healthCertificateService.updateValidityStatesAndNotificationsWithFreshDSCList(completion: completion)
}
}
| 38.286567 | 185 | 0.74388 |
fb29497cc9162915b326c0a781f3546206c69bd7 | 1,059 | import Foundation
import PhoenixShared
/// Represents a displayable currency,
/// which can be either a BitcoinUnit or a FiatCurrency.
///
enum Currency: Hashable {
case bitcoin(BitcoinUnit)
case fiat(FiatCurrency)
var abbrev: String {
switch self {
case .bitcoin(let unit):
return unit.shortName
case .fiat(let currency):
return currency.shortName
}
}
}
extension Currency {
/// A list of all BitcoinUnit's and the currently selected FiatCurrency (IFF we know the exchangeRate).
///
static func displayable(currencyPrefs: CurrencyPrefs) -> [Currency] {
var all = [Currency]()
for bitcoinUnit in BitcoinUnit.default().values {
all.append(Currency.bitcoin(bitcoinUnit))
}
let fiatCurrency = currencyPrefs.fiatCurrency
if let _ = currencyPrefs.fiatExchangeRate(fiatCurrency: fiatCurrency) {
all.append(Currency.fiat(fiatCurrency))
} else {
// We don't have the exchange rate for the user's selected fiat currency.
// So we won't be able to perform conversion to millisatoshi.
}
return all
}
}
| 24.068182 | 104 | 0.721435 |
def234db32892935f5452c2639cb89d5909cdaba | 2,619 | /*
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 XCTest
import Basic
import PackageModel
class SwiftLanguageVersionTests: XCTestCase {
func testBasics() throws {
let validVersions = [
"4" : "4",
"4.0" : "4.0",
"4.2" : "4.2",
"1.0.0" : "1.0.0",
"3.1.0" : "3.1.0",
]
for (version, expected) in validVersions {
guard let swiftVersion = SwiftLanguageVersion(string: version) else {
return XCTFail("Couldn't form a version with string: \(version)")
}
XCTAssertEqual(swiftVersion.rawValue, expected)
XCTAssertEqual(swiftVersion.description, expected)
}
let invalidVersions = [
"1.2.3.4",
"1.2-al..beta.0+bu.uni.ra",
"1.2.33-al..beta.0+bu.uni.ra",
".1.0.0-x.7.z.92",
"1.0.0-alpha.beta+",
"1.0.0beta",
"1.0.0-",
"1.-2.3",
"1.2.3d",
]
for version in invalidVersions {
if let swiftVersion = SwiftLanguageVersion(string: version) {
XCTFail("Formed an invalid version \(swiftVersion) with string: \(version)")
}
}
}
func testComparison() {
XCTAssertTrue(SwiftLanguageVersion(string: "4.0.1")! > SwiftLanguageVersion(string: "4")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.0")! == SwiftLanguageVersion(string: "4")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.1")! > SwiftLanguageVersion(string: "4")!)
XCTAssertTrue(SwiftLanguageVersion(string: "5")! >= SwiftLanguageVersion(string: "4")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.0.1")! < ToolsVersion(string: "4.1")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4")! == ToolsVersion(string: "4.0")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! == ToolsVersion(string: "4.2")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! < ToolsVersion(string: "4.3")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! <= ToolsVersion(string: "4.3")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! <= ToolsVersion(string: "5.0")!)
XCTAssertTrue(SwiftLanguageVersion(string: "4")! < ToolsVersion(string: "5.0")!)
}
}
| 36.887324 | 98 | 0.597174 |
fed84308204f5843408c96eafe4aa53b5eec6dd9 | 14,861 | //
// KeyManager.swift
// Peacemakr-iOS
//
// Created by Yuliia Synytsia on 5/18/19.
// Copyright © 2019 Peacemakr. All rights reserved.
//
import Foundation
import CoreCrypto
class KeyManager {
enum KeyManagerError: Error {
case serializationError
case keygenError
case saveError
case loadError
var localizedDescription: String {
switch self {
case .serializationError:
return "failed to serialize/deserialize"
case .keygenError:
return "keygen failed"
case .saveError:
return "failed to save"
case .loadError:
return "failed to load"
}
}
}
let defaultSymmetricCipher = SymmetricCipher.CHACHA20_POLY1305
let testingMode: Bool
private let persister: Persister
/// MARK: - Initializers
required public init(persister: Persister, testingMode: Bool = false) {
self.persister = persister
self.testingMode = testingMode
}
/// MARK: - Generate New Key Pair
private func parseIntoCipher(keyType: String, keyLen: Int) -> AsymmetricCipher {
if keyType == "ec" {
switch keyLen {
case 256:
return .ECDH_P256
case 384:
return .ECDH_P384
case 521:
return .ECDH_P521
default:
return .ECDH_P256
}
} else if keyType == "rsa" {
switch keyLen {
case 2048:
return .RSA_2048
case 4096:
return .RSA_4096
default:
return .RSA_4096
}
}
return .ECDH_P256
}
func createKeyPair(with rand: RandomDevice, asymm: AsymmetricCipher) throws -> PeacemakrKey {
guard let keyPair = PeacemakrKey(asymmCipher: asymm, symmCipher: defaultSymmetricCipher, rand: rand) else {
throw KeyManagerError.keygenError
}
return keyPair
}
// Generate and Store keypair
func createAndStoreKeyPair(with rand: RandomDevice, keyType: String, keyLen: Int) throws -> (priv: Data, pub: Data) {
let newKeyPair = try createKeyPair(with: rand, asymm: parseIntoCipher(keyType: keyType, keyLen: keyLen))
// Store private key
guard let priv = UnwrapCall(newKeyPair.toPem(isPriv: true), onError: Logger.onError),
self.persister.storeKey(priv, keyID: Constants.privTag) else {
throw KeyManagerError.saveError
}
// Store public key
guard let pub = UnwrapCall(newKeyPair.toPem(isPriv: false), onError: Logger.onError),
self.persister.storeKey(pub, keyID: Constants.pubTag) else {
throw KeyManagerError.saveError
}
// Store key creation time in Unix time
let success = self.persister.storeData(Constants.dataPrefix + Constants.keyCreationTime, val: Date().timeIntervalSince1970)
if !success {
throw KeyManagerError.saveError
}
return (priv, pub)
}
func getKeyID(serialized: Data) throws -> (keyID: String, signKeyID: String) {
guard let serializedAAD = UnwrapCall(CryptoContext.extractUnverifiedAAD(serialized), onError: Logger.onError) else {
throw KeyManagerError.serializationError
}
let aadDict = try JSONSerialization.jsonObject(with: serializedAAD.authenticatableData, options: [])
guard let aad = aadDict as? [String: Any],
let senderKeyID = aad["senderKeyID"] as? String,
let cryptoKeyID = aad["cryptoKeyID"] as? String else {
throw KeyManagerError.serializationError
}
return (cryptoKeyID, senderKeyID)
}
// This edits the plaintext to add the key ID to the message before it gets encrypted and sent out
func getEncryptionKeyId(useDomainName: String) -> (aad: String, cryptoConfig: CoreCrypto.CryptoConfig, keyId: String?)? {
guard let keyIDandCfg = self.selectKey(useDomainName: useDomainName) else {
Logger.error("failed to select a key")
return nil
}
let myPubKeyID = self.getMyPublicKeyID()
let jsonObject: [String: String] = ["cryptoKeyID": keyIDandCfg.keyId, "senderKeyID": myPubKeyID]
guard let aadJSON = try? JSONSerialization.data(withJSONObject: jsonObject, options: []),
let messageAAD = String(data: aadJSON, encoding: .utf8) else {
Logger.error("failed to serialize the key IDs to json")
return nil
}
return (messageAAD, keyIDandCfg.keyConfig, keyIDandCfg.keyId)
}
private func parseDigestAlgorithm(digest: String?) -> MessageDigestAlgorithm {
switch (digest) {
case Constants.Sha224:
return .SHA_224
case Constants.Sha256:
return .SHA_256
case Constants.Sha384:
return .SHA_384
case Constants.Sha512:
return .SHA_512
default:
return .SHA_256
}
}
private func parseEncryptionAlgorithm(algo: String) -> SymmetricCipher {
switch (algo) {
case Constants.Aes128gcm:
return .AES_128_GCM
case Constants.Aes192gcm:
return .AES_192_GCM
case Constants.Aes256gcm:
return .AES_256_GCM
case Constants.Chacha20Poly1305:
return .CHACHA20_POLY1305
default:
return .CHACHA20_POLY1305
}
}
private class func isValidDomainForEncryption(domain: SymmetricKeyUseDomain) -> Bool {
return Int(NSDate().timeIntervalSince1970) <= domain.symmetricKeyEncryptionUseTTL + domain.creationTime
}
func selectKey(useDomainName: String) -> (keyId: String, keyConfig: CoreCrypto.CryptoConfig)? {
if self.testingMode {
return ("my-key-id", CoreCrypto.CryptoConfig(
mode: CoreCrypto.EncryptionMode.SYMMETRIC,
symm_cipher: CoreCrypto.SymmetricCipher.CHACHA20_POLY1305,
asymm_cipher: CoreCrypto.AsymmetricCipher.ASYMMETRIC_UNSPECIFIED,
digest: CoreCrypto.MessageDigestAlgorithm.SHA_256))
}
// Use the string, if it's empty then just use the first one
guard let encodedUseDomains: Data = self.persister.getData(Constants.dataPrefix + Constants.useDomains) else {
Logger.error("Persisted use domains were nil")
return nil
}
guard let useDomains = try? JSONDecoder().decode([SymmetricKeyUseDomain].self, from: encodedUseDomains) else {
Logger.error("failed to decode useDomains")
return nil
}
// If the domain was not explicitly selected, use the first
// valid use domain available.
var useDomainToUse: SymmetricKeyUseDomain? = nil
if useDomainName == "" {
useDomains.forEach { domain in
if KeyManager.isValidDomainForEncryption(domain: domain) {
useDomainToUse = domain
}
}
}
// If we want a specific use domain, then match the names, and
// select the first valid use domain of that name.
useDomains.forEach { domain in
if KeyManager.isValidDomainForEncryption(domain: domain) && domain.name == useDomainName {
useDomainToUse = domain
}
}
guard let domain = useDomainToUse else {
Logger.error("invalid or unavilable use domain")
return nil
}
guard let encryptionKeyID = domain.encryptionKeyIds.randomElement() else {
Logger.error("Invalid encryption key ID")
return nil
}
let keyCfg = CoreCrypto.CryptoConfig(mode: .SYMMETRIC,
symm_cipher: parseEncryptionAlgorithm(algo: domain.symmetricKeyEncryptionAlg),
asymm_cipher: .ASYMMETRIC_UNSPECIFIED,
digest: parseDigestAlgorithm(digest: domain.digestAlgorithm))
return (encryptionKeyID, keyCfg)
}
func getMyKey(priv: Bool) -> PeacemakrKey? {
var tag: String
if priv {
tag = Constants.privTag
} else {
tag = Constants.pubTag
}
// should be base64Encoded? or not?
guard let keyStr = String(data: self.persister.getKey(tag) ?? Data(), encoding: .utf8) else {
return nil
}
return PeacemakrKey(symmCipher: defaultSymmetricCipher, fileContents: keyStr, isPriv: priv)
}
func getMyPublicKeyID() -> String {
guard let pubKeyID: String = self.persister.getData(Constants.dataPrefix + Constants.pubKeyIDTag) else {
return ""
}
return pubKeyID
}
func getPublicKeyByID(keyID: String, completion: (@escaping (PeacemakrKey?) -> Void)) -> Void {
if let keyBytes: String = self.persister.getData(Constants.dataPrefix + keyID) {
return completion(PeacemakrKey(symmCipher: defaultSymmetricCipher, fileContents: keyBytes, isPriv: false))
}
// QUESTION: else? what will happen if we fail to get keyBytes from persister?
// we will request it from server?
let requestBuilder = KeyServiceAPI.getPublicKeyWithRequestBuilder(keyID: keyID)
requestBuilder.execute({ (key, error) in
if error != nil {
Logger.error("failed request public key: " + error!.localizedDescription)
return completion(nil)
}
if let keyStr = key?.body?.key {
if !self.persister.storeData(Constants.dataPrefix + keyID, val: keyStr) {
Logger.error("failed to store key with ID: \(keyID)")
}
return completion(PeacemakrKey(symmCipher: self.defaultSymmetricCipher, fileContents: keyStr, isPriv: false))
} else {
Logger.error("server error")
return completion(nil)
}
})
}
func getLocalKeyByID(keyID: String, cfg: CoreCrypto.CryptoConfig) -> PeacemakrKey? {
if keyID == "my-key-id" {
Logger.error("Using insecure key for local-only testing!")
return PeacemakrKey(symmCipher: cfg.symmCipher, bytes: Data([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]))
}
let tag = Constants.symmTagPrefix + keyID
guard let keyData = self.persister.getKey(tag) else {
return nil
}
return PeacemakrKey(symmCipher: cfg.symmCipher, bytes: keyData)
}
func storeKey(key: [UInt8], keyID: [UInt8]) -> Bool {
guard let keyIDStr = String(bytes: keyID, encoding: .utf8) else {
Logger.error("failed to serialize keyID to string")
return false
}
let tag = Constants.symmTagPrefix + keyIDStr
var keyData: Data? = nil
key.withUnsafeBufferPointer { buf -> Void in
keyData = Data(buffer: buf)
}
return self.persister.storeKey(keyData!, keyID: tag)
}
func rotateClientKeyIfNeeded(rand: RandomDevice, completion: (@escaping (Error?) -> Void)) {
guard let myPub = getMyKey(priv: false) else {
Logger.error("unable to get my public key")
completion(KeyManagerError.loadError)
return
}
let config = myPub.getConfig()
guard let keyType: String = self.persister.getData(Constants.dataPrefix + Constants.clientKeyType),
let keyLen: Int = self.persister.getData(Constants.dataPrefix + Constants.clientKeyLen) else {
completion(KeyManagerError.loadError)
return
}
let cryptoConfigCipher = parseIntoCipher(keyType: keyType, keyLen: keyLen)
guard let keyCreationTime: TimeInterval = self.persister.getData(Constants.dataPrefix + Constants.keyCreationTime) else {
completion(KeyManagerError.loadError)
return
}
guard let keyTTL: Int = self.persister.getData(Constants.dataPrefix + Constants.clientKeyTTL) else {
completion(KeyManagerError.loadError)
return
}
// TimeInterval is always in seconds: https://developer.apple.com/documentation/foundation/timeinterval
let isStale = Int(Date().timeIntervalSince1970 - keyCreationTime) > keyTTL
if !isStale && cryptoConfigCipher == config.asymmCipher {
// No error, but bail early cause no rotation needed
completion(nil)
return
}
Logger.debug("Rotating stale asymmetric keys")
// Might have to roll back changes
guard let prevPriv = getMyKey(priv: true) else {
completion(KeyManagerError.loadError)
return
}
let prevCreationTime = keyCreationTime
let rollback: (Error) -> Error = { (outerError) in
// Store private key
guard let priv = UnwrapCall(prevPriv.toPem(isPriv: true), onError: Logger.onError),
self.persister.storeKey(priv, keyID: Constants.privTag) else {
Logger.error("In recovering from " + outerError.localizedDescription + " another error ocurred")
return KeyManagerError.saveError
}
// Store public key
guard let pub = UnwrapCall(prevPriv.toPem(isPriv: false), onError: Logger.onError),
self.persister.storeKey(pub, keyID: Constants.pubTag) else {
Logger.error("In recovering from " + outerError.localizedDescription + " another error ocurred")
return KeyManagerError.saveError
}
// Store key creation time in Unix time
let success = self.persister.storeData(Constants.dataPrefix + Constants.keyCreationTime, val: prevCreationTime)
if !success {
Logger.error("In recovering from " + outerError.localizedDescription + " another error ocurred")
return KeyManagerError.saveError
}
return outerError
}
// Do the rotation
guard let orgID: String = self.persister.getData(Constants.dataPrefix + Constants.orgID) else {
completion(rollback(KeyManagerError.loadError))
return
}
do {
let keyPair = try createAndStoreKeyPair(with: rand, keyType: keyType, keyLen: keyLen)
let pubKeyToSend = PublicKey(
_id: Metadata.shared.getPubKeyID(persister: self.persister),
creationTime: Int(Date().timeIntervalSince1970),
keyType: keyType,
encoding: "pem",
key: keyPair.pub.toString(),
owningClientId: Metadata.shared.getClientId(persister: self.persister),
owningOrgId: orgID)
let registerClient = Client(
_id: Metadata.shared.getClientId(persister: self.persister),
sdk: Metadata.shared.version,
preferredPublicKeyId: Metadata.shared.getPubKeyID(persister: self.persister),
publicKeys: [pubKeyToSend])
let requestBuilder = ClientAPI.addClientWithRequestBuilder(client: registerClient)
requestBuilder.execute({ (resp, error) in
Logger.info("registration request completed")
if error != nil {
Logger.error("addClient failed with " + error.debugDescription)
completion(rollback(error!))
}
guard let response = resp, let body = response.body else {
Logger.error("server error: response body was nil")
completion(rollback(NSError(domain: "response body was nil", code: -1, userInfo: nil)))
return
}
// Store the new publicKeyID
guard self.persister.storeData(Constants.dataPrefix + Constants.pubKeyIDTag, val: body.publicKeys.first?._id) else {
Logger.error("failed to store key pair")
completion(rollback(NSError(domain: "could not store metadata", code: -2, userInfo: nil)))
return
}
Logger.debug("Rotated client asymmetric keypair")
completion(nil)
})
} catch {
completion(rollback(error))
}
}
}
| 33.097996 | 186 | 0.675594 |
09a6690cb07e08ea19f293f60be34cefeab02a93 | 821 | // DRUNKWATER TEMPLATE(add description and prototypes)
// Question Title and Description on leetcode.com
// Function Declaration and Function Prototypes on leetcode.com
//66. Plus One
//Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
//The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
//You may assume the integer does not contain any leading zero, except the number 0 itself.
//Example 1:
//Input: [1,2,3]
//Output: [1,2,4]
//Explanation: The array represents the integer 123.
//Example 2:
//Input: [4,3,2,1]
//Output: [4,3,2,2]
//Explanation: The array represents the integer 4321.
//class Solution {
// func plusOne(_ digits: [Int]) -> [Int] {
// }
//}
// Time Is Money | 35.695652 | 142 | 0.72229 |
db9a92c00c4e4a04fa77f34a4ee1c1898886307b | 133 |
// THIS-TEST-SHOULD-NOT-COMPILE
f(int x=0, int y=0) {
trace(x, y);
}
// Cannot provide keyword arg before positional
f(y=2, 5);
| 13.3 | 47 | 0.639098 |
465a1bbc536aeb93458cdb1803f8ff48c98b04d0 | 1,244 | /*
* Given a string, find the length of the longest substring without repeating characters.
*/
public func getLongestSubstringWithoutRepeation(input : String) -> String? {
let length = input.characters.count
var uniqueCharacters = Set<String>()
var index = 0, subsequentIndex = 0, longestSubstringWithoutRepeation = ""
while index < length && subsequentIndex < length {
if !uniqueCharacters.contains(input[subsequentIndex]) {
uniqueCharacters.insert(input[subsequentIndex])
subsequentIndex += 1
longestSubstringWithoutRepeation = longestSubstringWithoutRepeation.characters.count > subsequentIndex - index ?
longestSubstringWithoutRepeation : input[index..<subsequentIndex]
}else{
let repeatitionPosition = input.distance(from: input.startIndex, to: input.range(of: input[subsequentIndex])!.lowerBound)
uniqueCharacters.remove(input[index])
index = repeatitionPosition + 1
}
if longestSubstringWithoutRepeation.characters.count > length - index - 1 {
break
}
}
return longestSubstringWithoutRepeation == "" ? nil : longestSubstringWithoutRepeation
}
| 38.875 | 133 | 0.677653 |
292986bc34726a6e4f8a7c69fda9cc381659f0b4 | 16,408 | //
// Service.swift
// Gastos (iOS)
//
// Created by Carlos Andres Chaguendo Sanchez on 30/03/21.
//
import Foundation
import RealmSwift
public class Service {
public static var fileURL = FileManager
.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.com.mayorgafirm.gastos.shared")!
.appendingPathComponent("default.realm")
public static var realm: Realm = {
let fileURL = Service.fileURL
Logger.info("File", Realm.Configuration.defaultConfiguration.fileURL)
let config = Realm.Configuration(
fileURL: fileURL,
schemaVersion: 7,
migrationBlock: { _, oldSchemaVersion in
if oldSchemaVersion < 1 {
}
})
Realm.Configuration.defaultConfiguration = config
Logger.info("File", Realm.Configuration.defaultConfiguration.fileURL)
do {
let realm = try Realm(configuration: Realm.Configuration.defaultConfiguration)
return realm
} catch {
preconditionFailure(error.localizedDescription)
}
}()
private init() {}
static func addItem(_ item: ExpenseItem, notify: Bool = true) {
realm.rwrite {
let local: ExpenseItem = realm.findBy(id: item.id) ?? item
local.value = item.value
local.title = item.title
local.date = item.date
if local.realm == nil {
local.id = UUID().description
}
local.category = realm.findBy(id: item.category.id)
local.wallet = realm.findBy(id: item.wallet.id)
local.tags = realm.findBy(ids: item.tags)
realm.add(local)
}
if notify {
if item.hasId() {
NotificationCenter.default.post(name: .didEditTransaction, object: item.detached())
} else {
NotificationCenter.default.post(name: .didAddNewTransaction, object: item.detached())
}
}
}
@discardableResult
static func addGroup<Group: Entity & ExpensePropertyWithValue>(_ item: Group) -> Group {
realm.rwrite {
let local: Group = realm.findBy(id: item.id) ?? item
local.name = item.name
local.color = item.color
if local.realm == nil {
local.id = UUID().description
}
realm.add(local)
}
return item.detached()
}
@discardableResult
static func addCategory(_ item: Catagory) -> Catagory {
let local: Catagory = realm.findBy(id: item.id) ?? item
realm.rwrite {
local.name = item.name
local.color = item.color
local.sign = item.sign
if local.realm == nil {
local.id = UUID().description
}
realm.add(local)
}
let sender = local.detached()
NotificationCenter.default.post(name: .didEditCategories, object: sender)
return sender
}
@discardableResult
static func removeBudget(for item: Catagory.ID) -> Catagory {
guard let local: Catagory = realm.findBy(id: item) else {
preconditionFailure()
}
realm.rwrite {
local.budget = 0
realm.add(local)
}
let sender = local.detached()
NotificationCenter.default.post(name: .didEditBudget, object: sender)
return sender
}
@discardableResult
static func addBudget(_ item: Catagory) -> Catagory {
guard let local: Catagory = realm.findBy(id: item.id) else {
preconditionFailure()
}
realm.rwrite {
local.budget = item.budget
realm.add(local)
}
let sender = local.detached()
NotificationCenter.default.post(name: .didEditBudget, object: sender)
return sender
}
static func addTag(_ item: Tag) -> Tag {
realm.rwrite {
item.id = UUID().description
realm.add(item)
}
return item
}
@discardableResult
static func addWallet(_ item: Wallet) -> Wallet {
let local: Wallet = realm.findBy(id: item.id) ?? item
realm.rwrite {
local.name = item.name
local.color = item.color
if local.realm == nil {
local.id = UUID().description
}
realm.add(local)
}
let sender = local.detached()
NotificationCenter.default.post(name: .didEditWallet, object: sender)
return sender
}
@discardableResult
static func removeWallet(_ item: Wallet) throws -> Wallet {
guard let local = realm.object(ofType: Wallet.self, forPrimaryKey: item.id) else {
preconditionFailure()
}
let count = realm.objects(ExpenseItem.self)
.filter("wallet.id = %@ ", item.id)
.count
if count > 0 {
throw NSError(domain: "service", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey: ""])
}
let sender = local.detached()
realm.rwrite {
if !local.isInvalidated {
realm.delete(local)
}
Logger.info("Eliminando", local)
}
NotificationCenter.default.post(name: .didEditWallet, object: sender)
return sender
}
@discardableResult
static func removeCategory(_ item: Catagory) throws -> Catagory {
guard let local = realm.object(ofType: Catagory.self, forPrimaryKey: item.id) else {
preconditionFailure()
}
let count = realm.objects(ExpenseItem.self)
.filter("category.id = %@ ", item.id)
.count
if count > 0 {
throw NSError(domain: "service", code: 1, userInfo: [NSLocalizedFailureReasonErrorKey: ""])
}
let sender = local.detached()
realm.rwrite {
if !local.isInvalidated {
realm.delete(local)
}
Logger.info("Eliminando", local)
}
NotificationCenter.default.post(name: .didEditCategories, object: sender)
return sender
}
static func remove(_ item: ExpenseItem) {
guard let local = realm.object(ofType: ExpenseItem.self, forPrimaryKey: item.id) else {
preconditionFailure()
}
realm.rwrite {
if !local.isInvalidated {
realm.delete(local)
}
Logger.info("Eliminando", local)
}
}
/// Retorna todas las fechas que almenos tiene una transaccion
/// - Parameter date: El mes el cual se quiere consultar
/// - Returns: description
static func summaryOf(month date: Date) -> [Date] {
let start = date.withStart(of: .month)
let end = date.withEnd(of: .month)
return realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.map { Calendar.current.dateInterval(of: .day, for: $0.date)!.start }
.uniq
}
/// Cuenta el numero detos por dia
/// - Returns: Numero de gastos por dia en un mes
static func countEventsIn(month date: Date) -> [Date: Int] {
let start = date.withStart(of: .month)
let end = date.withEnd(of: .month)
return realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.map { Calendar.current.dateInterval(of: .day, for: $0.date)!.start }
.countBy { $0 }
}
/// Suma de costos por dia
/// - Parameter date: Fecha
/// - Returns: Dicionario de costos diarios, solo las fechas que tiene datos
static func sumEventsIn(month date: Date) -> [Date: Double] {
let start = date.withStart(of: .month)
let end = date.withEnd(of: .month)
return realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.groupBy { $0.date.withStart(of: .day) }
.mapValues { $0.map { $0.value}.reduce(0, +) }
}
/// Diccionario de gastos por fehca
/// - Parameters:
/// - componet: El rango de consulta , dia, mes, anio
/// - date: la fecha en la cual se requiere buscar
/// - Returns: datos por dia, Zero si en una fecha no hay transaciones
static func expenses(in componet: Calendar.Component, of date: Date) -> [Date: Double] {
let start = date.withStart(of: componet)
let end = date.withEnd(of: componet)
let expensesByDay = realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.groupBy { $0.date.withStart(of: .day) }
.mapValues { $0.map { $0.value}.reduce(0, +) }
let dates = start.enumerate(.day, until: end)
var result: [Date: Double] = [:]
for day in dates {
result[day] = expensesByDay[day, default: 0.0]
}
return result
}
/// Los gastos en un dia
/// - Parameter date: Dia
/// - Returns: las transacciones que se realizaron en un dia especificado
static func getItems(in date: Date) -> [ExpenseItem] {
let start = date.withStart(of: .day)
let end = date.withEnd(of: .day)
return realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.detached
.sorted(by: {$0.id > $1.id })
}
/// Consulta las transacciones por grupo
/// - Parameters:
/// - group: Path para el grupo
/// - category: Valor para filtrar
/// - componet: El rango de consulta month. year
/// - date: la fecha de consulta
/// - Returns: Listato de transaciones segun una categoria en unas fecha especificas
static func transactions<Group: Entity & ExpensePropertyWithValue>( by group: KeyPath<ExpenseItem, Group>,
_ category: Group, in componet: Calendar.Component,
of date: Date
) -> [ExpenseItem] {
let start = date.withStart(of: componet)
let end = date.withEnd(of: componet)
return realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.detached
.filter { $0[keyPath: group].id == category.id }
.sorted(by: {$0.id > $1.id })
}
/// Consulta los gastos por grupo
/// - Parameters:
/// - group: Path para el grupo
/// - componet: Valor para filtrar
/// - date: la fecha de consulta
/// - Returns: Agrupa los gastos en un periodo por grupo
static func expenses<Group: Entity & ExpensePropertyWithValue>(by group: KeyPath<ExpenseItem, Group>,
in componet: Calendar.Component,
of date: Date) -> [Group] {
setColorsIfNeeded(to: Group.self)
let start = date.withStart(of: componet)
let end = date.withEnd(of: componet)
let expenses = realm.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.detached
.groupBy { $0[keyPath: group].id }
let expensesByCategoryId = expenses
.mapValues { $0.map { $0.value }.reduce(0, +) }
let categoriesById = realm.objects(Group.self)
.groupBy { $0.id }
.compactMapValues { $0.first }
return expensesByCategoryId.compactMap { categoriId, value -> Group? in
let category = categoriesById[categoriId]?.detached()
category?.value = value
category?.count = expenses[categoriId]?.count ?? 0
return category
}
.sorted(by: { $0.value > $1.value })
}
static func getBudget( in componet: Calendar.Component = .month,
of date: Date = Date()) -> [Catagory] {
let start = date.withStart(of: componet)
let end = date.withEnd(of: componet)
let expensesByCategoryId = realm
.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.groupBy { $0.category.id }
.mapValues { $0.map { $0.value }.reduce(0, +) }
return realm.objects(Catagory.self)
.detached
.map {
$0.value = expensesByCategoryId[$0.id] ?? 0.0
return $0
}
/// Solo se incluyen las categorias con almenos una transacion o con un [resupuesto configurado
.filter { $0.value > 0.0 || $0.budget > 0.0 }
.sorted { $0.name > $1.name }
}
/// Obtiene todos los elemntos de una entidad
/// - Parameter type: Entidad
/// - Returns: Todos los elementos
static func getAll<Object: Entity>(_ type: Object.Type) -> [Object] {
realm.objects(Object.self)
.detached
}
private static func setColorsIfNeeded<Group: Entity & ExpensePropertyWithValue>(to group: Group.Type) {
let groups = realm.objects(group.self)
.filter { $0.color == 0x000 }
realm.rwrite {
groups.forEach {
$0.color = Int32(ColorSpace.random.toHexInt())
}
}
}
/// Registra la ultima creacion de un a copia de seguridad
public static func registreNewBackup() {
let local = realm.object(ofType: ApplicationData.self, forPrimaryKey: "-1") ?? ApplicationData()
realm.rwrite {
local.lastBackup = Date()
realm.add(local, update: .all)
}
}
static func getApplicationData() -> ApplicationData {
guard let local = realm.object(ofType: ApplicationData.self, forPrimaryKey: "-1") else {
return ApplicationData()
}
return local.detached()
}
static func toggleHidden<Item: Entity & EntityWithName>( value: Item) {
guard let local = realm.object(ofType: Item.self, forPrimaryKey: value.id) else {
preconditionFailure()
}
realm.rwrite {
local.isHidden = !local.isHidden
}
}
static func exportAsCSV(between start: Date, and end: Date) -> URL {
let df = DateFormatter()
.set(\.dateFormat, "dd/MM/yyyy HH:mm:ss")
let items = realm
.objects(ExpenseItem.self)
.filter("date BETWEEN %@ ", [start, end])
.sorted(byKeyPath: "date", ascending: false)
let keys = [
"Date",
"Category",
"Wallet",
"Transaction type",
"Value",
"Description"
]
.map { "\"\(NSLocalizedString($0, comment: $0))\"" }
.joined(separator: ",")
var csvString = "\(keys)\n"
for transaction in items {
csvString.append("\"\(df.string(from: transaction.date))\",")
csvString.append("\"\(transaction.category.name)\",")
csvString.append("\"\(transaction.wallet.name)\",")
csvString.append("\"\(transaction.category.sign <= 0 ? "Expense" : "Revenues")\",")
csvString.append("\"\(NumberFormatter.currency.string(from: NSNumber(value: transaction.value))!)\",")
csvString.append("\"\(transaction.title.replacingOccurrences(of: ",", with: " "))\"")
csvString.append("\n")
}
do {
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
.appendingPathComponent("Gastos.csv")
try csvString.write(to: fileURL, atomically: true, encoding: .utf8)
return fileURL
} catch {
print("error creating file")
preconditionFailure()
}
}
}
| 34.762712 | 123 | 0.537421 |
50792f0108cfd0074766f1fc3a63eb9df8e1f14f | 351 | import Foundation
import CoreLocation
extension CLLocationCoordinate2D {
func distance(from other: CLLocationCoordinate2D) -> CLLocationDistance {
let this = CLLocation(latitude: self.latitude, longitude: self.longitude)
let that = CLLocation(latitude: other.latitude, longitude: other.longitude)
return this.distance(from: that)
}
}
| 31.909091 | 79 | 0.774929 |
487cb154b35101d3104bab7bda47817e4a194f2a | 420 | //
// Extensions.swift
// Lr backup
//
// Created by Karl Persson on 2015-08-12.
// Copyright (c) 2015 Karl Persson. All rights reserved.
//
import Foundation
// Int to bool extension
extension Bool {
init<T : IntegerType>(_ integer: T) {
self.init(integer != 0)
}
}
// Bool to int extension
extension Int {
init<T : BooleanType>(_ bool: T) {
if bool {
self.init(1)
}
else {
self.init(0)
}
}
} | 15 | 57 | 0.62619 |
4a0471aafd272423a7051e874956d30058ff182e | 1,579 | //
// AccountTypeEOA.swift
// CaverSwift
//
// Created by won on 2021/07/30.
//
import Foundation
open class AccountTypeEOA: IAccountType {
public var balance: String
public var humanReadable: Bool
public var key: AccountData
public var nonce: String
private enum CodingKeys: String, CodingKey {
case balance, humanReadable, key, nonce
}
open override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(balance, forKey: .balance)
try container.encode(humanReadable, forKey: .humanReadable)
try container.encode(key, forKey: .key)
try container.encode(nonce, forKey: .nonce)
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.balance = (try? container.decode(String.self, forKey: .balance)) ?? ""
self.humanReadable = (try? container.decode(Bool.self, forKey: .humanReadable)) ?? false
self.key = (try? container.decode(AccountData.self, forKey: .key)) ?? AccountData()
self.nonce = (try? container.decode(String.self, forKey: .nonce)) ?? ""
try super.init(from: decoder)
}
internal init(_ balance: String, _ humanReadable: Bool, _ key: AccountData, _ nonce: String) {
self.balance = balance
self.humanReadable = humanReadable
self.key = key
self.nonce = nonce
super.init()
}
}
| 32.895833 | 98 | 0.649145 |
50e96ef667ead86835a55bd0af0c50c4a4c8eb2c | 885 | //
// Century.swift
// Nomosi_Example
//
// Created by Mario on 07/06/2018.
// Copyright © 2018 Mario Iannotta. All rights reserved.
//
import Foundation
struct Century: Decodable {
private enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case objectCount = "objectcount"
case temporalOrder = "temporalOrder"
case lastUpdate = "lastupdate"
case detail = "contains"
}
struct Detail: Decodable {
let groups: [Group]?
}
let id: Int?
let name: String?
let objectCount, temporalOrder: Int?
let lastUpdate: String?
let detail: Detail?
var formattedDate: String {
lastUpdate?
.split(separator: "T")
.first?
.split(separator: "-")
.reversed()
.joined(separator: "/") ?? ""
}
}
| 21.585366 | 57 | 0.558192 |
64aa48a0b0a19d411a569de64bce6355c7165c44 | 352 | //
// ATEventTriggerCompatible.swift
// iosApp
//
// Created by Steve Kim on 2021/03/15.
// Copyright © 2021 orgName. All rights reserved.
//
import shared
import UIKit
extension ATEventTriggerCompatible {
var eventTrigger: ATEventTrigger<Self> {
ATEventTriggerFactory.Companion().create(owner: self) as! ATEventTrigger<Self>
}
}
| 20.705882 | 86 | 0.71875 |
907b7ea7cfeafdbd729997858d50b34ed928b718 | 1,654 | //
// NewsReducer.swift
// TibiaInfo
//
// Created by Namedix on 28/08/2020.
// Copyright © 2020 Bartłomiej Pichalski. All rights reserved.
//
import ComposableArchitecture
typealias NewsReducer = Reducer<NewsState, NewsAction, NewsEnvironment>
private struct GetNewsEffectId: Hashable {}
let newsReducer = NewsReducer.combine(
newsDetailsReducer.optional().pullback(
state: \.newsDetails,
action: /NewsAction.newsDetails,
environment: { NewsDetailsEnvironment(
mainQueue: $0.mainQueue,
networkClient: $0.networkClient
)
}
),
Reducer { state, action, environment in
switch action {
case .getNews:
state.isLoading = true
return environment.networkClient
.getNews()
.receive(on: environment.mainQueue)
.catchToEffect()
.map(NewsAction.didGetNews)
.cancellable(id: GetNewsEffectId(), cancelInFlight: true)
case .didGetNews(.success(let news)):
state.isLoading = false
state.news = news
return .none
case .didGetNews(.failure(let error)):
state.isLoading = false
return .none
case .selectNews(.some(let newsId)):
state.newsDetails = state.news
.first { $0.id == newsId }
.map { NewsDetailsState(title: $0.news, newsId: $0.id) }
return .none
case .selectNews(.none):
state.newsDetails = nil
return .none
case .newsDetails:
return .none
}
}
)
| 27.566667 | 73 | 0.572551 |
dec10e440daf1f5159aecb8cbff9f056d3737a1a | 474 | import Foundation
import Hitch
struct NullNode: ValueNode {
static let null = NullNode()
static func == (lhs: NullNode, rhs: NullNode) -> Bool {
return true
}
var description: String {
return "null"
}
var typeName: ValueNodeType {
return .null
}
var literalValue: Hitch? {
nil
}
func stringValue() -> String? {
return nil
}
var numericValue: Double? {
return nil
}
}
| 15.290323 | 59 | 0.556962 |
0e9008e2f262fa46592c947296e9ced27e9ab0a4 | 1,806 | //
// ViewController.swift
// XDHelper
//
// Created by dte2mdj on 04/22/2020.
// Copyright (c) 2020 dte2mdj. All rights reserved.
//
import UIKit
import XDHelper
class ViewController: UIViewController {
@UserDefaultsWrapper("is_login", default: false)
var isLogin: Bool
lazy var phoneSpliter: TextInputSpliter = {
let spliter = TextInputSpliter()
spliter.separator = "-"
spliter.splitPattern = [3, 4, 4]
spliter.maxLength = 11
spliter.testValidBlock = { $0.xwg.isMatching("\\d*") }
return spliter
}()
lazy var bankAccountSpliter: TextInputSpliter = {
let spliter = TextInputSpliter()
spliter.separator = " "
spliter.splitPattern = [4]
spliter.maxLength = 20
spliter.testValidBlock = { $0.xwg.isMatching("\\d*") }
return spliter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if isLogin {
isLogin = false
print("退出登录。。。")
} else {
isLogin = true
print("登录。。。")
}
}
}
extension ViewController {
func testTextInputPhone() {
let tf = UITextField()
tf.placeholder = "手机号。。。"
tf.frame = CGRect(x: 10, y: 100, width: view.frame.width - 20, height: 40)
tf.backgroundColor = .cyan
tf.delegate = phoneSpliter
view.addSubview(tf)
}
func testTextInputBankAccount() {
let tf = UITextView()
tf.frame = CGRect(x: 10, y: 200, width: view.frame.width - 20, height: 140)
tf.backgroundColor = .cyan
tf.delegate = bankAccountSpliter
view.addSubview(tf)
}
}
| 25.43662 | 83 | 0.570321 |
1c1d261a76c3b59cf81acdc94fc7d5acae1d1d62 | 181 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{class
case, | 30.166667 | 87 | 0.773481 |
f7419e5309667e6a23dfaadabb9068249288ee3d | 2,290 | import UIKit
struct UIHelper {
//Sean Allen Github-Followers
static func createThreeColumnFlowLayout(in view: UIView) -> UICollectionViewFlowLayout {
let width = view.bounds.width
let padding: CGFloat = 12
let minimumItemSpacing: CGFloat = 10
let availableWidth = width - (padding * 2) - (minimumItemSpacing * 2)
let itemWidth = availableWidth / 3
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth + 40)
return flowLayout
}
//Sean Allen Github-Followers
static func createTwoColumnFlowLayout(in view: UIView) -> UICollectionViewFlowLayout {
let width = view.bounds.width
let padding: CGFloat = 15
let minimumItemSpacing: CGFloat = 12
let availableWidth = width - (padding * 2) - (minimumItemSpacing * 2)
let itemWidth = availableWidth / 2
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth + 20)
return flowLayout
}
//Sean Allen Github-Followers
static func createTwoColumnFlowLayoutForCategories(in view: UIView) -> UICollectionViewFlowLayout {
let width = view.bounds.width
let padding: CGFloat = 15
let minimumItemSpacing: CGFloat = 12
let availableWidth = width - (padding * 2) - (minimumItemSpacing * 2)
let itemWidth = availableWidth / 2
let flowLayout = UICollectionViewFlowLayout()
flowLayout.sectionInset = UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
return flowLayout
}
static func activityIndicatorView() -> UIActivityIndicatorView {
let activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.large)
activityIndicatorView.color = .black
activityIndicatorView.hidesWhenStopped = true
return activityIndicatorView
}
}
| 41.636364 | 108 | 0.690393 |
e626ebf81d4395015a4690661fbf24562e2e2f4c | 5,080 | //
// LKLabelCell.swift
// Lark
//
// Created by Hunt on 2021/3/8.
//
import UIKit
open class NKLabelCell: NKStaticCell {
@IBOutlet weak var detailImageView: UIImageView!
@IBOutlet weak var backView: UIView!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
open var desc: String? {
didSet {
data?.desc = desc
qingFillData()
}
}
open var title: String? {
didSet {
if let titleString = title {
data?.title = titleString
qingFillData()
}
}
}
var hasDesc = false
public override var data: NKCommonCellData? {
didSet {
qingFillData()
}
}
open override func qingFillData() {
super.qingFillData()
if let realData = data {
if let iconString = realData.icon, iconString.isNotEmpty {
if let image = UIImage(named: iconString) {
iconImageView.image = image
} else {
if let url = URL(string: iconString) {
iconImageView.kf.setImage(with: url)
}
}
}
if let desc = realData.desc, desc.isNotEmpty {
hasDesc = true
descLabel.text = desc
} else {
hasDesc = false
descLabel.text = ""
}
let detailImage = NKThemeProvider.shared.isNight() ? UIImage(nkBundleNamed: "nk_cell_arrow_right_white") : UIImage(nkBundleNamed: "nk_cell_arrow_right")
detailImageView.image = detailImage
detailImageView.isHidden = !realData.hasDetail
titleLabel.text = realData.title
setNeedsDisplay()
}
}
open override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setupSubviews()
}
override func setupSubviews() {
super.setupSubviews()
backView.theme_backgroundColor = .tableCellBackgroundColor
titleLabel.theme_textColor = .titleColor
descLabel.theme_textColor = .subTitleColor
}
open override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
open override func layoutSubviews() {
super.layoutSubviews()
let left = 15.0
let right = -12.0
backView.snp.remakeConstraints { make in
make.edges.equalTo(0)
}
if iconImageView.image == nil {
iconImageView.isHidden = true
iconImageView.snp.remakeConstraints { (make) in
make.left.equalTo(0)
make.width.height.equalTo(0)
make.centerY.equalTo(backView.snp.centerY).offset(0)
}
} else {
iconImageView.isHidden = false
iconImageView.snp.remakeConstraints { (make) in
make.width.height.equalTo(25)
make.left.equalTo(17)
make.centerY.equalTo(backView.snp.centerY).offset(0)
}
}
if detailImageView.isHidden {
detailImageView.snp.remakeConstraints { (make) in
make.right.equalTo(0)
make.width.height.equalTo(0)
make.centerY.equalTo(0)
}
} else {
detailImageView.snp.remakeConstraints { (make) in
make.width.height.equalTo(20)
make.right.equalTo(right)
make.centerY.equalTo(backView.snp.centerY).offset(0)
}
}
let titleLeft = iconImageView.isHidden ? left : 5
descLabel.isHidden = !hasDesc
if hasDesc {
titleLabel.font = UIFont.systemFont(ofSize: 15.0)
descLabel.font = UIFont.systemFont(ofSize: 12.0)
titleLabel.snp.remakeConstraints { make in
make.left.equalTo(iconImageView.snp.right).offset(titleLeft)
make.right.equalTo(detailImageView.snp.left).offset(-5)
make.top.equalTo(3)
make.height.equalTo(20)
}
} else {
titleLabel.font = UIFont.systemFont(ofSize: 17.0)
titleLabel.snp.remakeConstraints { make in
make.left.equalTo(iconImageView.snp.right).offset(titleLeft)
make.right.equalTo(detailImageView.snp.left).offset(-5)
make.top.equalTo(0)
make.height.equalTo(backView.height)
}
}
descLabel.snp.remakeConstraints { make in
make.left.equalTo(titleLabel.snp.left).offset(1)
make.right.equalTo(titleLabel.snp.right).offset(0)
make.top.equalTo(titleLabel.snp.bottom).offset(2)
make.height.equalTo(15)
}
}
}
| 31.552795 | 164 | 0.548622 |
2f3796d7c1a9a90bba47d06877a161c566d2ca38 | 60 | struct AmpMediaAnalytics {
var text = "Hello, World!"
}
| 15 | 30 | 0.666667 |
e684353d06af70d5f94c72397552a64997998dc5 | 218 | //
// AnimDataApp.swift
// AnimData
//
// Created by 石玉龙 on 2021/1/7.
//
import SwiftUI
@main
struct AnimDataApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.111111 | 31 | 0.545872 |
fb3829af3ba3b5608329017a1f8ceda58d4f1688 | 3,474 | //
// ControllerReusable.swift
// ifanr
//
// Created by 梁亦明 on 16/7/15.
// Copyright © 2016年 ifanrOrg. All rights reserved.
//
import Foundation
enum ScrollViewDirection {
case none
case down
case up
}
protocol ControllerReusable: class {
}
/**
* 这里是用与下拉刷新回调
*/
protocol ScrollViewControllerReusableDataSource: ControllerReusable {
/**
导航栏
*/
func titleHeaderView() -> MainHeaderView
/**
下拉刷新红线
*/
func redLineView() -> UIView
/**
* 菜单按钮
*/
func menuButton() -> UIButton
/**
首页分类按钮
*/
func classifyButton() -> UIButton
}
protocol ScrollViewControllerReusableDelegate: ControllerReusable {
/**
scrollview滚动时方向改变时调用
*/
func ScrollViewControllerDirectionDidChange(_ direction: ScrollViewDirection)
}
protocol ScrollViewControllerReusable: ControllerReusable, PullToRefreshDataSource {
var tableView: UITableView! { get set }
/// 下拉刷新
var pullToRefresh: PullToRefreshView! { get set }
/// 下拉刷新代理
var scrollViewReusableDataSource: ScrollViewControllerReusableDataSource! { get set }
var scrollViewReusableDelegate: ScrollViewControllerReusableDelegate! { get set }
}
// MARK: - 返回一些下拉刷新的回调
extension ScrollViewControllerReusable where Self: UIViewController {
/**
首页,快讯,玩物志顶部标题
*/
func titleHeaderView() -> MainHeaderView {
return scrollViewReusableDataSource.titleHeaderView()
}
/**
红线
*/
func redLine() -> UIView {
return scrollViewReusableDataSource.redLineView()
}
/**
菜单按钮
*/
func menuButton() -> UIButton {
return scrollViewReusableDataSource.menuButton()
}
func classifyButton() -> UIButton {
return scrollViewReusableDataSource.classifyButton()
}
func scrollView() -> UIScrollView {
return self.tableView
}
}
// MARK: - 扩展一些初始化方法
extension ScrollViewControllerReusable where Self: UIViewController {
/**
初始化tableView
*/
func setupTableView() {
if tableView == nil {
tableView = UITableView()
tableView.backgroundColor = UIColor.white
tableView.origin = CGPoint.zero
tableView.size = CGSize(width: self.view.width, height: self.view.height-UIConstant.UI_MARGIN_20)
tableView.separatorStyle = .none
tableView.sectionFooterHeight = 50
tableView.tableFooterView = pullToRefreshFootView()
self.view.addSubview(tableView)
}
}
/**
初始化下拉刷新控件
*/
func setupPullToRefreshView() {
if pullToRefresh == nil {
pullToRefresh = PullToRefreshView(frame: CGRect(x: 0, y: -sceneHeight, width: self.view.width, height: sceneHeight))
pullToRefresh.dataSource = self
self.tableView.insertSubview(pullToRefresh, at: 0)
}
}
fileprivate func pullToRefreshFootView() -> UIView {
let activityView = ActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 25, height: 25) )
activityView.color = UIConstant.UI_COLOR_GrayTheme
activityView.center = CGPoint(x: self.view.center.x, y: 25)
activityView.startAnimation()
let footView = UIView()
footView.origin = CGPoint.zero
footView.size = CGSize(width: 50, height: 50)
footView.addSubview(activityView)
return footView
}
}
| 25.173913 | 128 | 0.637306 |
724d5aafbcf0864329b2f8b18bf57ca43901abe4 | 551 | //
// AppetisingViewController.swift
// AppetisingCocoa
//
// Created by Alexei Gudimenko on 7/7/17.
// Copyright © 2017 Appetiser. All rights reserved.
//
import UIKit
import BetterBaseClasses
open class AppetisingViewController: BaseViewController {
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 22.04 | 58 | 0.700544 |
bfaec8f8515eaefed1d3c7c65ace196b8802582c | 584 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// AzureReachabilityReportItemProtocol is azure reachability report details for a given provider location.
public protocol AzureReachabilityReportItemProtocol : Codable {
var provider: String? { get set }
var azureLocation: String? { get set }
var latencies: [AzureReachabilityReportLatencyInfoProtocol?]? { get set }
}
| 48.666667 | 107 | 0.760274 |
e0cfe8a80f9bc5e05e7c1afefdd643e6e04e9c8d | 673 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "CodeName",
products: [
.executable(name: "codename", targets: ["CodeName"])
],
dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.0.3")
],
targets: [
.executableTarget(
name: "CodeName",
dependencies: [.product(name: "ArgumentParser", package: "swift-argument-parser")]),
.testTarget(
name: "CodeNameTests",
dependencies: ["CodeName"]),
]
)
| 29.26087 | 96 | 0.609212 |
3370e93fa0121b61711747df1fd54ff4b7fa18b9 | 968 | //
// FiltererTests.swift
// FiltererTests
//
// Created by Ming Gong on 8/18/16.
// Copyright © 2016 Ming Gong. All rights reserved.
//
import XCTest
@testable import Filterer
class FiltererTests: 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.162162 | 111 | 0.631198 |
569cceea3ed61c33ec173250469eda4186d60679 | 385 | @_cdecl("myMain")
public func myMain()
{
// Now the fun can begin!
// <Your Swift code starts here ...>
let four = 2 + 2
// TODO/FIXME: print goes to /dev/null on Android
print("2 + 2 = \(four)")
// Remember to not block the event loop
}
@_cdecl("addTwoNumbers")
public func addTwoNumbers(first: UInt8, second: UInt8) -> UInt8 {
return first + second
}
| 20.263158 | 65 | 0.620779 |
48b5c4307eea89acb35a940b17c42888476cea4f | 2,140 | //
// AppDelegate.swift
// SwiftIAPDemo
//
// Created by Gou Bowen on 15/6/2.
// Copyright (c) 2015年 M.T.F. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.531915 | 285 | 0.752336 |
4ae4a2f0b778d4ac384ed5834464cd46876fc901 | 11,871 | // Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import GoogleCast
/** A key for the URL of the media item's poster (large image). */
let kMediaKeyPosterURL = "posterUrl"
/** A key for the media item's extended description. */
let kMediaKeyDescription = "description"
let kKeyCategories = "categories"
let kKeyHlsBaseURL = "hls"
let kKeyImagesBaseURL = "images"
let kKeyTracksBaseURL = "tracks"
let kKeySources = "sources"
let kKeyVideos = "videos"
let kKeyArtist = "artist"
let kKeyBaseURL = "baseUrl"
let kKeyContentID = "contentId"
let kKeyDescription = "description"
let kKeyID = "id"
let kKeyImageURL = "image-480x270"
let kKeyItems = "items"
let kKeyLanguage = "language"
let kKeyMimeType = "mime"
let kKeyName = "name"
let kKeyPosterURL = "image-780x1200"
let kKeyStreamType = "streamType"
let kKeyStudio = "studio"
let kKeySubtitle = "subtitle"
let kKeySubtype = "subtype"
let kKeyTitle = "title"
let kKeyTracks = "tracks"
let kKeyType = "type"
let kKeyURL = "url"
let kKeyDuration = "duration"
let kDefaultVideoMimeType = "application/x-mpegurl"
let kDefaultTrackMimeType = "text/vtt"
let kTypeAudio = "audio"
let kTypePhoto = "photos"
let kTypeVideo = "videos"
let kTypeLive = "live"
let kThumbnailWidth = 480
let kThumbnailHeight = 720
let kPosterWidth = 780
let kPosterHeight = 1200
/**
* The delegate protocol for receiving notifications from the model.
*/
protocol MediaListModelDelegate: NSObjectProtocol {
/**
* Called when the media list has loaded.
*
* @param list The media list.
*/
func mediaListModelDidLoad(_ list: MediaListModel)
/**
* Called when the media list has failed to load.
*
* @param list The media list.
* @param error The error.
*/
func mediaListModel(_ list: MediaListModel, didFailToLoadWithError error: Error?)
}
/**
* An object representing a hierarchy of media items.
*/
class MediaListModel: NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate {
private var request: URLRequest!
private var connection: NSURLConnection!
private var responseData: Data!
private var responseStatus: Int = 0
private var trackStyle: GCKMediaTextTrackStyle!
/* The root item (top-level group). */
fileprivate(set) var rootItem: MediaItem!
/** A delegate for receiving notifications from the model. */
weak var delegate: MediaListModelDelegate?
/** A flag indicating whether the model has been loaded. */
fileprivate(set) var isLoaded: Bool = false
/** The title of the media list. */
fileprivate(set) var title: String = ""
/** Storage for the list of Media objects. */
var medias = [Any]()
/**
* Begins loading the model from the given URL. The delegate will be messaged
* when the load
* completes or fails.
*
* @param url The URL of the JSON file describing the media hierarchy.
*/
func load(from url: URL) {
rootItem = nil
request = URLRequest(url: url)
connection = NSURLConnection(request: request, delegate: self)
responseData = nil
connection.start()
GCKLogger.sharedInstance().delegate?.logMessage?("loading media list from URL \(url)", at: .debug, fromFunction: #function, location: "MediaListModel.class")
}
override init() {
super.init()
trackStyle = GCKMediaTextTrackStyle.createDefault()
}
func cancelLoad() {
if request != nil {
connection.cancel()
request = nil
connection = nil
responseData = nil
}
}
// MARK: - NSURLConnectionDelegate
func connection(_: NSURLConnection, didFailWithError error: Error) {
request = nil
responseData = nil
connection = nil
GCKLogger.sharedInstance().delegate?.logMessage?("httpRequest failed with \(error)", at: .debug, fromFunction: #function, location: "MediaListModel.class")
delegate?.mediaListModel(self, didFailToLoadWithError: error)
}
// MARK: - NSURLConnectionDataDelegate
internal func connection(_: NSURLConnection, didReceive response: URLResponse) {
if let response = response as? HTTPURLResponse {
responseStatus = response.statusCode
}
}
func connection(_: NSURLConnection, didReceive data: Data) {
if responseData == nil {
responseData = Data()
}
responseData.append(data)
}
func connectionDidFinishLoading(_: NSURLConnection) {
GCKLogger.sharedInstance().delegate?.logMessage?("httpRequest completed with \(responseStatus)", at: .debug, fromFunction: #function, location: "MediaListModel.class")
if responseStatus == 200 {
let jsonData = (try? JSONSerialization.jsonObject(with: responseData,
options: .mutableContainers)) as? NSDictionary
rootItem = decodeMediaTree(fromJSON: jsonData!)
isLoaded = true
delegate?.mediaListModelDidLoad(self)
} else {
let error = NSError(domain: "HTTP", code: responseStatus, userInfo: nil)
delegate?.mediaListModel(self, didFailToLoadWithError: error)
}
}
// MARK: - JSON decoding
func decodeMediaTree(fromJSON json: NSDictionary) -> MediaItem {
let rootItem = MediaItem(title: nil, imageURL: nil, parent: nil)
let categories = json.gck_array(forKey: kKeyCategories)!
for categoryElement in categories {
if !(categoryElement is [AnyHashable: Any]) {
continue
}
let category = (categoryElement as? NSDictionary)
let mediaList = category?.gck_array(forKey: kKeyVideos)
if mediaList != nil {
title = (category?.gck_string(forKey: kKeyName))!
// Pick the MP4 files only
let videosBaseURLString: String? = category?.gck_string(forKey: kKeyHlsBaseURL)
let videosBaseURL = URL(string: videosBaseURLString!)
let imagesBaseURLString: String? = category?.gck_string(forKey: kKeyImagesBaseURL)
let imagesBaseURL = URL(string: imagesBaseURLString!)
let tracksBaseURLString: String? = category?.gck_string(forKey: kKeyTracksBaseURL)
let tracksBaseURL = URL(string: tracksBaseURLString!)
decodeItemList(fromArray: mediaList!, into: rootItem, videoFormat: kKeyHlsBaseURL,
videosBaseURL: videosBaseURL!, imagesBaseURL: imagesBaseURL!, tracksBaseURL: tracksBaseURL!)
break
}
}
return rootItem
}
func buildURL(with string: String?, baseURL: URL) -> URL? {
guard let string = string else { return nil }
if string.hasPrefix("http://") || string.hasPrefix("https://") {
return URL(string: string)!
} else {
return URL(string: string, relativeTo: baseURL)!
}
}
func decodeItemList(fromArray array: [Any], into item: MediaItem, videoFormat: String,
videosBaseURL: URL, imagesBaseURL: URL, tracksBaseURL: URL) {
for element in array {
if let dict = element as? NSDictionary {
let metadata = GCKMediaMetadata(metadataType: .movie)
if let title = dict.gck_string(forKey: kKeyTitle) {
metadata.setString(title, forKey: kGCKMetadataKeyTitle)
}
var mimeType: String?
var url: URL?
let sources: [Any] = dict.gck_array(forKey: kKeySources) ?? []
for sourceElement in sources {
if let sourceDict = sourceElement as? NSDictionary {
let type: String? = sourceDict.gck_string(forKey: kKeyType)
if type == videoFormat {
mimeType = sourceDict.gck_string(forKey: kKeyMimeType)
let urlText: String? = sourceDict.gck_string(forKey: kKeyURL)
url = buildURL(with: urlText, baseURL: videosBaseURL)
break
}
}
}
let imageURLString: String? = dict.gck_string(forKey: kKeyImageURL)
if let imageURL = self.buildURL(with: imageURLString, baseURL: imagesBaseURL) {
metadata.addImage(GCKImage(url: imageURL, width: kThumbnailWidth, height: kThumbnailHeight))
}
let posterURLText: String? = dict.gck_string(forKey: kKeyPosterURL)
if let posterURL = self.buildURL(with: posterURLText, baseURL: imagesBaseURL) {
metadata.setString(posterURL.absoluteString, forKey: kMediaKeyPosterURL)
metadata.addImage(GCKImage(url: posterURL, width: kPosterWidth, height: kPosterHeight))
}
if let description = dict.gck_string(forKey: kKeySubtitle) {
metadata.setString(description, forKey: kMediaKeyDescription)
}
var mediaTracks: [GCKMediaTrack]?
if let studio = dict.gck_string(forKey: kKeyStudio) {
metadata.setString(studio, forKey: kGCKMetadataKeyStudio)
}
let duration: Int? = dict.gck_integer(forKey: kKeyDuration)
mediaTracks = [GCKMediaTrack]()
if let tracks = dict.gck_array(forKey: kKeyTracks) {
for trackElement: Any in tracks {
guard let trackDict = trackElement as? NSDictionary else { continue }
let identifier = trackDict.gck_integer(forKey: kKeyID)
let name: String? = trackDict.gck_string(forKey: kKeyName)
let typeString: String? = trackDict.gck_string(forKey: kKeyType)
let subtypeString: String? = trackDict.gck_string(forKey: kKeySubtype)
let contentID: String? = trackDict.gck_string(forKey: kKeyContentID)
let language: String? = trackDict.gck_string(forKey: kKeyLanguage)
let url = buildURL(with: contentID, baseURL: tracksBaseURL)
let mediaTrack = GCKMediaTrack(identifier: identifier, contentIdentifier: url?.absoluteString,
contentType: kDefaultTrackMimeType, type: trackType(from: typeString!),
textSubtype: textTrackSubtype(from: subtypeString!),
name: name, languageCode: language, customData: nil)
mediaTracks?.append(mediaTrack)
}
}
if mediaTracks?.count == 0 {
mediaTracks = nil
}
let mediaInfoBuilder = GCKMediaInformationBuilder(contentURL: url!)
// TODO: Remove contentID when sample receiver supports using contentURL
mediaInfoBuilder.contentID = url!.absoluteString
mediaInfoBuilder.streamType = .buffered
mediaInfoBuilder.streamDuration = TimeInterval(duration!)
mediaInfoBuilder.contentType = mimeType!
mediaInfoBuilder.metadata = metadata
mediaInfoBuilder.mediaTracks = mediaTracks
mediaInfoBuilder.textTrackStyle = trackStyle
let mediaInfo = mediaInfoBuilder.build()
let childItem = MediaItem(mediaInformation: mediaInfo, parent: item)
item.children.append(childItem)
}
}
}
func trackType(from string: String) -> GCKMediaTrackType {
if string == "audio" {
return .audio
}
if string == "text" {
return .text
}
if string == "video" {
return .video
}
return .unknown
}
func textTrackSubtype(from string: String) -> GCKMediaTextTrackSubtype {
if string == "captions" {
return .captions
}
if string == "chapters" {
return .chapters
}
if string == "descriptions" {
return .descriptions
}
if string == "metadata" {
return .metadata
}
if string == "subtitles" {
return .subtitles
}
return .unknown
}
}
| 37.096875 | 171 | 0.675091 |
f84ed19d288a637db9fad226a8e0594b666bc3ed | 15,180 | //
// StencilSwiftKit
// Copyright © 2021 SwiftGen
// MIT Licence
//
import Foundation
import PathKit
import Stencil
// MARK: - Strings Filters
public extension Filters {
enum Strings {
}
}
public enum RemoveNewlinesModes: String {
case all, leading
}
public enum SwiftIdentifierModes: String {
case normal, pretty
}
// MARK: - String Filters: Boolean filters
public extension Filters.Strings {
/// Checks if the given string contains given substring
///
/// - Parameters:
/// - value: the string value to check if it contains substring
/// - arguments: the arguments to the function; expecting one string argument - substring
/// - Returns: the result whether true or not
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string or
/// if number of arguments is not one or if the given argument isn't a string
static func contains(_ value: Any?, arguments: [Any?]) throws -> Bool {
let string = try Filters.parseString(from: value)
let substring = try Filters.parseStringArgument(from: arguments)
return string.contains(substring)
}
/// Checks if the given string has given prefix
///
/// - Parameters:
/// - value: the string value to check if it has prefix
/// - arguments: the arguments to the function; expecting one string argument - prefix
/// - Returns: the result whether true or not
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string or
/// if number of arguments is not one or if the given argument isn't a string
static func hasPrefix(_ value: Any?, arguments: [Any?]) throws -> Bool {
let string = try Filters.parseString(from: value)
let prefix = try Filters.parseStringArgument(from: arguments)
return string.hasPrefix(prefix)
}
/// Checks if the given string has given suffix
///
/// - Parameters:
/// - value: the string value to check if it has prefix
/// - arguments: the arguments to the function; expecting one string argument - suffix
/// - Returns: the result whether true or not
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string or
/// if number of arguments is not one or if the given argument isn't a string
static func hasSuffix(_ value: Any?, arguments: [Any?]) throws -> Bool {
let string = try Filters.parseString(from: value)
let suffix = try Filters.parseStringArgument(from: arguments)
return string.hasSuffix(suffix)
}
}
// MARK: - String Filters: Lettercase filters
public extension Filters.Strings {
/// Lowers the first letter of the string
/// e.g. "People picker" gives "people picker", "Sports Stats" gives "sports Stats"
static func lowerFirstLetter(_ value: Any?) throws -> Any? {
let string = try Filters.parseString(from: value)
let first = String(string.prefix(1)).lowercased()
let other = String(string.dropFirst(1))
return first + other
}
/// If the string starts with only one uppercase letter, lowercase that first letter
/// If the string starts with multiple uppercase letters, lowercase those first letters
/// up to the one before the last uppercase one, but only if the last one is followed by
/// a lowercase character.
/// e.g. "PeoplePicker" gives "peoplePicker" but "URLChooser" gives "urlChooser"
static func lowerFirstWord(_ value: Any?) throws -> Any? {
let string = try Filters.parseString(from: value)
guard !string.isEmpty else { return "" }
let characterSet = CharacterSet.uppercaseLetters
let scalars = string.unicodeScalars
let start = scalars.startIndex
var idx = start
while idx < scalars.endIndex, let scalar = UnicodeScalar(scalars[idx].value), characterSet.contains(scalar) {
idx = scalars.index(after: idx)
}
if idx > scalars.index(after: start) && idx < scalars.endIndex,
let scalar = UnicodeScalar(scalars[idx].value),
CharacterSet.lowercaseLetters.contains(scalar) {
idx = scalars.index(before: idx)
}
let transformed = String(scalars[start..<idx]).lowercased() + String(scalars[idx..<scalars.endIndex])
return transformed
}
/// Uppers the first letter of the string
/// e.g. "people picker" gives "People picker", "sports Stats" gives "Sports Stats"
///
/// - Parameters:
/// - value: the value to uppercase first letter of
/// - arguments: the arguments to the function; expecting zero
/// - Returns: the string with first letter being uppercased
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func upperFirstLetter(_ value: Any?) throws -> Any? {
let string = try Filters.parseString(from: value)
return upperFirstLetter(string)
}
/// Converts snake_case to camelCase. Takes an optional Bool argument for removing any resulting
/// leading '_' characters, which defaults to false
///
/// - Parameters:
/// - value: the value to be processed
/// - arguments: the arguments to the function; expecting zero or one boolean argument
/// - Returns: the camel case string
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func snakeToCamelCase(_ value: Any?, arguments: [Any?]) throws -> Any? {
let stripLeading = try Filters.parseBool(from: arguments, required: false) ?? false
let string = try Filters.parseString(from: value)
return try snakeToCamelCase(string, stripLeading: stripLeading)
}
/// Converts camelCase to snake_case. Takes an optional Bool argument for making the string lower case,
/// which defaults to true
///
/// - Parameters:
/// - value: the value to be processed
/// - arguments: the arguments to the function; expecting zero or one boolean argument
/// - Returns: the snake case string
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func camelToSnakeCase(_ value: Any?, arguments: [Any?]) throws -> Any? {
let toLower = try Filters.parseBool(from: arguments, required: false) ?? true
let string = try Filters.parseString(from: value)
let snakeCase = try snakecase(string)
if toLower {
return snakeCase.lowercased()
}
return snakeCase
}
/// Converts snake_case to camelCase, stripping prefix underscores if needed
///
/// - Parameters:
/// - string: the value to be processed
/// - stripLeading: if false, will preserve leading underscores
/// - Returns: the camel case string
static func snakeToCamelCase(_ string: String, stripLeading: Bool) throws -> String {
let unprefixed: String
if try containsAnyLowercasedChar(string) {
let comps = string.components(separatedBy: "_")
unprefixed = comps.map { upperFirstLetter($0) }.joined()
} else {
let comps = try snakecase(string).components(separatedBy: "_")
unprefixed = comps.map { $0.capitalized }.joined()
}
// only if passed true, strip the prefix underscores
var prefixUnderscores = ""
var result: String { prefixUnderscores + unprefixed }
if stripLeading {
return result
}
for scalar in string.unicodeScalars {
guard scalar == "_" else { break }
prefixUnderscores += "_"
}
return result
}
}
private extension Filters.Strings {
static func containsAnyLowercasedChar(_ string: String) throws -> Bool {
let lowercaseCharRegex = try NSRegularExpression(pattern: "[a-z]", options: .dotMatchesLineSeparators)
let fullRange = NSRange(location: 0, length: string.unicodeScalars.count)
return lowercaseCharRegex.firstMatch(in: string, options: .reportCompletion, range: fullRange) != nil
}
/// Uppers the first letter of the string
/// e.g. "people picker" gives "People picker", "sports Stats" gives "Sports Stats"
///
/// - Parameters:
/// - value: the value to uppercase first letter of
/// - arguments: the arguments to the function; expecting zero
/// - Returns: the string with first letter being uppercased
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func upperFirstLetter(_ value: String) -> String {
guard let first = value.unicodeScalars.first else { return value }
return String(first).uppercased() + String(value.unicodeScalars.dropFirst())
}
/// This returns the snake cased variant of the string.
///
/// - Parameter string: The string to snake_case
/// - Returns: The string snake cased from either snake_cased or camelCased string.
static func snakecase(_ string: String) throws -> String {
let longUpper = try NSRegularExpression(pattern: "([A-Z\\d]+)([A-Z][a-z])", options: .dotMatchesLineSeparators)
let camelCased = try NSRegularExpression(pattern: "([a-z\\d])([A-Z])", options: .dotMatchesLineSeparators)
let fullRange = NSRange(location: 0, length: string.unicodeScalars.count)
var result = longUpper.stringByReplacingMatches(
in: string,
options: .reportCompletion,
range: fullRange,
withTemplate: "$1_$2"
)
result = camelCased.stringByReplacingMatches(
in: result,
options: .reportCompletion,
range: fullRange,
withTemplate: "$1_$2"
)
return result.replacingOccurrences(of: "-", with: "_")
}
}
// MARK: - String Filters: Mutation filters
public extension Filters.Strings {
static func escapeReservedKeywords(value: Any?) throws -> Any? {
let string = try Filters.parseString(from: value)
return escapeReservedKeywords(in: string)
}
/// Replaces in the given string the given substring with the replacement
/// "people picker", replacing "picker" with "life" gives "people life"
///
/// - Parameters:
/// - value: the value to be processed
/// - arguments: the arguments to the function; expecting two arguments: substring, replacement
/// - Returns: the results string
/// - Throws: FilterError.invalidInputType if the value parameter or argunemts aren't string
static func replace(_ value: Any?, arguments: [Any?]) throws -> Any? {
let source = try Filters.parseString(from: value)
let substring = try Filters.parseStringArgument(from: arguments, at: 0)
let replacement = try Filters.parseStringArgument(from: arguments, at: 1)
return source.replacingOccurrences(of: substring, with: replacement)
}
/// Converts an arbitrary string to a valid swift identifier. Takes an optional Mode argument:
/// - normal (default): uppercase the first character, prefix with an underscore if starting
/// with a number, replace invalid characters by underscores
/// - leading: same as the above, but apply the snaceToCamelCase filter first for a nicer
/// identifier
///
/// - Parameters:
/// - value: the value to be processed
/// - arguments: the arguments to the function; expecting zero or one mode argument
/// - Returns: the identifier string
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func swiftIdentifier(_ value: Any?, arguments: [Any?]) throws -> Any? {
var string = try Filters.parseString(from: value)
let mode = try Filters.parseEnum(from: arguments, default: SwiftIdentifierModes.normal)
switch mode {
case .normal:
return SwiftIdentifier.identifier(from: string, replaceWithUnderscores: true)
case .pretty:
string = SwiftIdentifier.identifier(from: string, replaceWithUnderscores: true)
string = try snakeToCamelCase(string, stripLeading: true)
return SwiftIdentifier.prefixWithUnderscoreIfNeeded(string: string)
}
}
/// Converts a file path to just the filename, stripping any path components before it.
///
/// - Parameter value: the value to be processed
/// - Returns: the basename of the path
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func basename(_ value: Any?) throws -> Any? {
let string = try Filters.parseString(from: value)
return Path(string).lastComponent
}
/// Converts a file path to just the path without the filename.
///
/// - Parameter value: the value to be processed
/// - Returns: the dirname of the path
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func dirname(_ value: Any?) throws -> Any? {
let string = try Filters.parseString(from: value)
return Path(string).parent().normalize().string
}
/// Removes newlines and other whitespace from a string. Takes an optional Mode argument:
/// - all (default): remove all newlines and whitespaces
/// - leading: remove newlines and only leading whitespaces
///
/// - Parameters:
/// - value: the value to be processed
/// - arguments: the arguments to the function; expecting zero or one mode argument
/// - Returns: the trimmed string
/// - Throws: FilterError.invalidInputType if the value parameter isn't a string
static func removeNewlines(_ value: Any?, arguments: [Any?]) throws -> Any? {
let string = try Filters.parseString(from: value)
let mode = try Filters.parseEnum(from: arguments, default: RemoveNewlinesModes.all)
switch mode {
case .all:
return string
.components(separatedBy: .whitespacesAndNewlines)
.joined()
case .leading:
return string
.components(separatedBy: .newlines)
.map(removeLeadingWhitespaces(from:))
.joined()
.trimmingCharacters(in: .whitespaces)
}
}
}
private extension Filters.Strings {
static let reservedKeywords = [
"associatedtype", "class", "deinit", "enum", "extension",
"fileprivate", "func", "import", "init", "inout", "internal",
"let", "open", "operator", "private", "protocol", "public",
"static", "struct", "subscript", "typealias", "var", "break",
"case", "continue", "default", "defer", "do", "else",
"fallthrough", "for", "guard", "if", "in", "repeat", "return",
"switch", "where", "while", "as", "Any", "catch", "false", "is",
"nil", "rethrows", "super", "self", "Self", "throw", "throws",
"true", "try", "_", "#available", "#colorLiteral", "#column",
"#else", "#elseif", "#endif", "#file", "#fileLiteral",
"#function", "#if", "#imageLiteral", "#line", "#selector",
"#sourceLocation", "associativity", "convenience", "dynamic",
"didSet", "final", "get", "infix", "indirect", "lazy", "left",
"mutating", "none", "nonmutating", "optional", "override",
"postfix", "precedence", "prefix", "Protocol", "required",
"right", "set", "Type", "unowned", "weak", "willSet"
]
static func removeLeadingWhitespaces(from string: String) -> String {
let chars = string.unicodeScalars.drop { CharacterSet.whitespaces.contains($0) }
return String(chars)
}
/// Checks if the string is one of the reserved keywords and if so, escapes it using backticks
///
/// - Parameter in: the string to possibly escape
/// - Returns: if the string is a reserved keyword, the escaped string, otherwise the original one
static func escapeReservedKeywords(in string: String) -> String {
guard reservedKeywords.contains(string) else {
return string
}
return "`\(string)`"
}
}
| 42.049861 | 115 | 0.688011 |
7aab50efa9047f44405a9e977a6bad1c688dbada | 1,386 |
open class Session<Peer: Interface, GenericConnection>
where
GenericConnection: Connection<Peer>
{
public private(set) var connections = [GenericConnection]()
public var peers: [Peer] { return connections.map { $0.receiver} }
public let proxy: Peer
public required init(proxy: Peer) {
self.proxy = proxy
}
open func connect(to peer: Peer) {
guard shouldConnect(to: peer) else { return }
let connection = prepare(connection: GenericConnection(receiver: peer).prepare())
connections.append(connection)
}
open func prepare(connection: GenericConnection) -> GenericConnection {
return connection
}
open func disconnect(from peer: Peer) {
guard let index = connections.firstIndex(where: { $0.receiver.identifier == peer.identifier }) else {
return
}
connections.remove(at: index).destroy()
}
public func peer(for identifier: Peer.Identifier) -> Peer? {
return peers.first(where: { $0.identifier == identifier })
}
open func shouldConnect(to peer: Peer) -> Bool {
return !isConnected(to: peer)
}
public func isConnected(to peer: Peer) -> Bool {
guard let _ = index(for: peer) else {
return false
}
return true
}
private func index(for peer: Peer) -> Int? {
return connections.firstIndex(where: { $0.receiver.identifier == peer.identifier })
}
}
| 26.653846 | 109 | 0.66811 |
39d5786d78976c12813f604a300f190641016f3e | 3,082 | //
// main.swift
// AccessControl
//
// Created by iMac on 2017/12/20.
// Copyright © 2017年 iMac. All rights reserved.
//
import Foundation
//访问控制
//在属性、方法或类型声明前面放置修饰符关键字来添加访问控制
protocol Account {
associatedtype Currency
//余额
var balance:Currency{get}
//充值
func deposit(amount:Currency)
//提现
func withdraw(amount:Currency)
}
class BasicAccount: Account {
typealias Currency = Double
private(set) var balance: Double = 0.0
func deposit(amount: Double) {
balance += amount
}
func withdraw(amount: Double) {
if amount <= balance {
balance -= amount
}else{
balance = 0
}
}
}
let account = BasicAccount()
account.deposit(amount: 20000.0)
account.withdraw(amount: 5000.0)
//外部私有
//account.balance = 10000.0
typealias Dollars = Double
class CheckingAccount: BasicAccount {
private let accountNumber = UUID().uuidString
//嵌套类
class Check {
let account: String
var amount: Dollars
//只能在当前作用域访问
private(set) var cashed = false
func cash() {
cashed = true
}
init(amount: Dollars, from account: CheckingAccount) {
self.amount = amount
self.account = account.accountNumber
}
}
func writeCheck(amount: Dollars) -> Check? {
guard balance > amount else {
return nil
}
let check = Check(amount: amount, from: self)
withdraw(amount: check.amount)
return check
}
func deposit(_ check: Check) {
guard !check.cashed else {
return
}
deposit(amount: check.amount)
check.cash()
}
}
//单例
class Logger {
//构造器私有,外部不能访问
private init(){}
//单例
static let sharedInstance = Logger()
func log(_ text:String) {
print(text)
}
}
Logger.sharedInstance.log("Singleton")
//Logger()
//'Logger' initializer is inaccessible due to 'private' protection level
//栈 FIFO
struct Stack<Element> {
private var array:[Element] = []
func peek() -> Element? {
return array.last
}
mutating func push(_ element:Element) {
array.append(element)
}
mutating func pop() ->Element? {
if array.isEmpty {
return nil
}
return array.removeLast()
}
func count() -> Int {
return array.count
}
}
var strings = Stack<String>()
strings.push("Great!")
strings.push("is")
strings.push("Swift")
//strings.elements.removeAll() // The implementation details of `Stack` are hidden.
print(strings.peek() ?? "nil")
while let string = strings.pop() {
Logger.sharedInstance.log(string)
}
//3.
let elf = GameCharacterFactory.make(ofType: .elf)
let giant = GameCharacterFactory.make(ofType: .giant)
let wizard = GameCharacterFactory.make(ofType: .wizard)
battle(elf, vs: giant)
battle(wizard, vs: giant)
battle(wizard, vs: elf)
//4.
let p = Person(first: "张", last: "红波")
print(p.fullName())
class Doctor:ClassPerson{
}
| 19.142857 | 83 | 0.601557 |
d64ee983f15a648642f1a86f4be677ea72ac4029 | 862 | //
// SkeletonUITableViewDataSource.swift
// SkeletonView-iOS
//
// Created by Juanpe Catalán on 06/11/2017.
// Copyright © 2017 SkeletonView. All rights reserved.
//
import UIKit
public protocol SkeletonTableViewDataSource: UITableViewDataSource {
func numSections(in collectionSkeletonView: UITableView) -> Int
func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int
func collectionSkeletonView(_ skeletonView: UITableView, cellIdenfierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier
}
public extension SkeletonTableViewDataSource {
func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int {
return skeletonView.estimatedNumberOfRows
}
func numSections(in collectionSkeletonView: UITableView) -> Int { return 1 }
}
| 34.48 | 129 | 0.774942 |
e2c63c30fd2ac8f64da7676dafae8eacb56ffc14 | 456 | protocol IComponentDispatcher {
var entities: [Entity] { get }
func execute() -> Void
func update() -> Void
}
class ComponentDispatcher<T: Component, U: Component, V: Component> : IComponentDispatcher {
var entities: [Entity] { get { getEntities() }}
func execute() -> Void {
}
func update() -> Void {}
private func getEntities() -> [Entity] {
return EntityPool.default.entities(T.self, U.self, V.self)
}
} | 24 | 92 | 0.625 |
ef489ddd5864b1d3f4b6af5f3bb55f0741d24ac4 | 20,302 | //===----------------------------------------------------------------------===//
//
// This source file is part of the AWSSDKSwift open source project
//
// Copyright (c) 2017-2020 the AWSSDKSwift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT.
import AWSSDKSwiftCore
import Foundation
extension PI {
//MARK: Enums
public enum ServiceType: String, CustomStringConvertible, Codable {
case rds = "RDS"
public var description: String { return self.rawValue }
}
//MARK: Shapes
public struct DataPoint: AWSDecodableShape {
/// The time, in epoch format, associated with a particular Value.
public let timestamp: TimeStamp
/// The actual value associated with a particular Timestamp.
public let value: Double
public init(timestamp: TimeStamp, value: Double) {
self.timestamp = timestamp
self.value = value
}
private enum CodingKeys: String, CodingKey {
case timestamp = "Timestamp"
case value = "Value"
}
}
public struct DescribeDimensionKeysRequest: AWSEncodableShape {
/// The date and time specifying the end of the requested time series data. The value specified is exclusive - data points less than (but not equal to) EndTime will be returned. The value for EndTime must be later than the value for StartTime.
public let endTime: TimeStamp
/// One or more filters to apply in the request. Restrictions: Any number of filters by the same dimension, as specified in the GroupBy or Partition parameters. A single filter for any other dimension in this dimension group.
public let filter: [String: String]?
/// A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.
public let groupBy: DimensionGroup
/// An immutable, AWS Region-unique identifier for a data source. Performance Insights gathers metrics from this data source. To use an Amazon RDS instance as a data source, you specify its DbiResourceId value - for example: db-FAIHNTYBKTGAUSUZQYPDS2GW4A
public let identifier: String
/// The maximum number of items to return in the response. If more items exist than the specified MaxRecords value, a pagination token is included in the response so that the remaining results can be retrieved.
public let maxResults: Int?
/// The name of a Performance Insights metric to be measured. Valid values for Metric are: db.load.avg - a scaled representation of the number of active sessions for the database engine. db.sampledload.avg - the raw number of active sessions for the database engine.
public let metric: String
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
public let nextToken: String?
/// For each dimension specified in GroupBy, specify a secondary dimension to further subdivide the partition keys in the response.
public let partitionBy: DimensionGroup?
/// The granularity, in seconds, of the data points returned from Performance Insights. A period can be as short as one second, or as long as one day (86400 seconds). Valid values are: 1 (one second) 60 (one minute) 300 (five minutes) 3600 (one hour) 86400 (twenty-four hours) If you don't specify PeriodInSeconds, then Performance Insights will choose a value for you, with a goal of returning roughly 100-200 data points in the response.
public let periodInSeconds: Int?
/// The AWS service for which Performance Insights will return metrics. The only valid value for ServiceType is: RDS
public let serviceType: ServiceType
/// The date and time specifying the beginning of the requested time series data. You can't specify a StartTime that's earlier than 7 days ago. The value specified is inclusive - data points equal to or greater than StartTime will be returned. The value for StartTime must be earlier than the value for EndTime.
public let startTime: TimeStamp
public init(endTime: TimeStamp, filter: [String: String]? = nil, groupBy: DimensionGroup, identifier: String, maxResults: Int? = nil, metric: String, nextToken: String? = nil, partitionBy: DimensionGroup? = nil, periodInSeconds: Int? = nil, serviceType: ServiceType, startTime: TimeStamp) {
self.endTime = endTime
self.filter = filter
self.groupBy = groupBy
self.identifier = identifier
self.maxResults = maxResults
self.metric = metric
self.nextToken = nextToken
self.partitionBy = partitionBy
self.periodInSeconds = periodInSeconds
self.serviceType = serviceType
self.startTime = startTime
}
public func validate(name: String) throws {
try self.groupBy.validate(name: "\(name).groupBy")
try validate(self.maxResults, name: "maxResults", parent: name, max: 20)
try validate(self.maxResults, name: "maxResults", parent: name, min: 0)
try self.partitionBy?.validate(name: "\(name).partitionBy")
}
private enum CodingKeys: String, CodingKey {
case endTime = "EndTime"
case filter = "Filter"
case groupBy = "GroupBy"
case identifier = "Identifier"
case maxResults = "MaxResults"
case metric = "Metric"
case nextToken = "NextToken"
case partitionBy = "PartitionBy"
case periodInSeconds = "PeriodInSeconds"
case serviceType = "ServiceType"
case startTime = "StartTime"
}
}
public struct DescribeDimensionKeysResponse: AWSDecodableShape {
/// The end time for the returned dimension keys, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedEndTime will be greater than or equal to the value of the user-specified Endtime.
public let alignedEndTime: TimeStamp?
/// The start time for the returned dimension keys, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedStartTime will be less than or equal to the value of the user-specified StartTime.
public let alignedStartTime: TimeStamp?
/// The dimension keys that were requested.
public let keys: [DimensionKeyDescription]?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
public let nextToken: String?
/// If PartitionBy was present in the request, PartitionKeys contains the breakdown of dimension keys by the specified partitions.
public let partitionKeys: [ResponsePartitionKey]?
public init(alignedEndTime: TimeStamp? = nil, alignedStartTime: TimeStamp? = nil, keys: [DimensionKeyDescription]? = nil, nextToken: String? = nil, partitionKeys: [ResponsePartitionKey]? = nil) {
self.alignedEndTime = alignedEndTime
self.alignedStartTime = alignedStartTime
self.keys = keys
self.nextToken = nextToken
self.partitionKeys = partitionKeys
}
private enum CodingKeys: String, CodingKey {
case alignedEndTime = "AlignedEndTime"
case alignedStartTime = "AlignedStartTime"
case keys = "Keys"
case nextToken = "NextToken"
case partitionKeys = "PartitionKeys"
}
}
public struct DimensionGroup: AWSEncodableShape {
/// A list of specific dimensions from a dimension group. If this parameter is not present, then it signifies that all of the dimensions in the group were requested, or are present in the response. Valid values for elements in the Dimensions array are: db.user.id db.user.name db.host.id db.host.name db.sql.id db.sql.db_id db.sql.statement db.sql.tokenized_id db.sql_tokenized.id db.sql_tokenized.db_id db.sql_tokenized.statement db.wait_event.name db.wait_event.type db.wait_event_type.name
public let dimensions: [String]?
/// The name of the dimension group. Valid values are: db.user db.host db.sql db.sql_tokenized db.wait_event db.wait_event_type
public let group: String
/// The maximum number of items to fetch for this dimension group.
public let limit: Int?
public init(dimensions: [String]? = nil, group: String, limit: Int? = nil) {
self.dimensions = dimensions
self.group = group
self.limit = limit
}
public func validate(name: String) throws {
try validate(self.dimensions, name: "dimensions", parent: name, max: 10)
try validate(self.dimensions, name: "dimensions", parent: name, min: 1)
try validate(self.limit, name: "limit", parent: name, max: 10)
try validate(self.limit, name: "limit", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case dimensions = "Dimensions"
case group = "Group"
case limit = "Limit"
}
}
public struct DimensionKeyDescription: AWSDecodableShape {
/// A map of name-value pairs for the dimensions in the group.
public let dimensions: [String: String]?
/// If PartitionBy was specified, PartitionKeys contains the dimensions that were.
public let partitions: [Double]?
/// The aggregated metric value for the dimension(s), over the requested time range.
public let total: Double?
public init(dimensions: [String: String]? = nil, partitions: [Double]? = nil, total: Double? = nil) {
self.dimensions = dimensions
self.partitions = partitions
self.total = total
}
private enum CodingKeys: String, CodingKey {
case dimensions = "Dimensions"
case partitions = "Partitions"
case total = "Total"
}
}
public struct GetResourceMetricsRequest: AWSEncodableShape {
/// The date and time specifiying the end of the requested time series data. The value specified is exclusive - data points less than (but not equal to) EndTime will be returned. The value for EndTime must be later than the value for StartTime.
public let endTime: TimeStamp
/// An immutable, AWS Region-unique identifier for a data source. Performance Insights gathers metrics from this data source. To use an Amazon RDS instance as a data source, you specify its DbiResourceId value - for example: db-FAIHNTYBKTGAUSUZQYPDS2GW4A
public let identifier: String
/// The maximum number of items to return in the response. If more items exist than the specified MaxRecords value, a pagination token is included in the response so that the remaining results can be retrieved.
public let maxResults: Int?
/// An array of one or more queries to perform. Each query must specify a Performance Insights metric, and can optionally specify aggregation and filtering criteria.
public let metricQueries: [MetricQuery]
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
public let nextToken: String?
/// The granularity, in seconds, of the data points returned from Performance Insights. A period can be as short as one second, or as long as one day (86400 seconds). Valid values are: 1 (one second) 60 (one minute) 300 (five minutes) 3600 (one hour) 86400 (twenty-four hours) If you don't specify PeriodInSeconds, then Performance Insights will choose a value for you, with a goal of returning roughly 100-200 data points in the response.
public let periodInSeconds: Int?
/// The AWS service for which Performance Insights will return metrics. The only valid value for ServiceType is: RDS
public let serviceType: ServiceType
/// The date and time specifying the beginning of the requested time series data. You can't specify a StartTime that's earlier than 7 days ago. The value specified is inclusive - data points equal to or greater than StartTime will be returned. The value for StartTime must be earlier than the value for EndTime.
public let startTime: TimeStamp
public init(endTime: TimeStamp, identifier: String, maxResults: Int? = nil, metricQueries: [MetricQuery], nextToken: String? = nil, periodInSeconds: Int? = nil, serviceType: ServiceType, startTime: TimeStamp) {
self.endTime = endTime
self.identifier = identifier
self.maxResults = maxResults
self.metricQueries = metricQueries
self.nextToken = nextToken
self.periodInSeconds = periodInSeconds
self.serviceType = serviceType
self.startTime = startTime
}
public func validate(name: String) throws {
try validate(self.maxResults, name: "maxResults", parent: name, max: 20)
try validate(self.maxResults, name: "maxResults", parent: name, min: 0)
try self.metricQueries.forEach {
try $0.validate(name: "\(name).metricQueries[]")
}
try validate(self.metricQueries, name: "metricQueries", parent: name, max: 15)
try validate(self.metricQueries, name: "metricQueries", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case endTime = "EndTime"
case identifier = "Identifier"
case maxResults = "MaxResults"
case metricQueries = "MetricQueries"
case nextToken = "NextToken"
case periodInSeconds = "PeriodInSeconds"
case serviceType = "ServiceType"
case startTime = "StartTime"
}
}
public struct GetResourceMetricsResponse: AWSDecodableShape {
/// The end time for the returned metrics, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedEndTime will be greater than or equal to the value of the user-specified Endtime.
public let alignedEndTime: TimeStamp?
/// The start time for the returned metrics, after alignment to a granular boundary (as specified by PeriodInSeconds). AlignedStartTime will be less than or equal to the value of the user-specified StartTime.
public let alignedStartTime: TimeStamp?
/// An immutable, AWS Region-unique identifier for a data source. Performance Insights gathers metrics from this data source. To use an Amazon RDS instance as a data source, you specify its DbiResourceId value - for example: db-FAIHNTYBKTGAUSUZQYPDS2GW4A
public let identifier: String?
/// An array of metric results,, where each array element contains all of the data points for a particular dimension.
public let metricList: [MetricKeyDataPoints]?
/// An optional pagination token provided by a previous request. If this parameter is specified, the response includes only records beyond the token, up to the value specified by MaxRecords.
public let nextToken: String?
public init(alignedEndTime: TimeStamp? = nil, alignedStartTime: TimeStamp? = nil, identifier: String? = nil, metricList: [MetricKeyDataPoints]? = nil, nextToken: String? = nil) {
self.alignedEndTime = alignedEndTime
self.alignedStartTime = alignedStartTime
self.identifier = identifier
self.metricList = metricList
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case alignedEndTime = "AlignedEndTime"
case alignedStartTime = "AlignedStartTime"
case identifier = "Identifier"
case metricList = "MetricList"
case nextToken = "NextToken"
}
}
public struct MetricKeyDataPoints: AWSDecodableShape {
/// An array of timestamp-value pairs, representing measurements over a period of time.
public let dataPoints: [DataPoint]?
/// The dimension(s) to which the data points apply.
public let key: ResponseResourceMetricKey?
public init(dataPoints: [DataPoint]? = nil, key: ResponseResourceMetricKey? = nil) {
self.dataPoints = dataPoints
self.key = key
}
private enum CodingKeys: String, CodingKey {
case dataPoints = "DataPoints"
case key = "Key"
}
}
public struct MetricQuery: AWSEncodableShape {
/// One or more filters to apply in the request. Restrictions: Any number of filters by the same dimension, as specified in the GroupBy parameter. A single filter for any other dimension in this dimension group.
public let filter: [String: String]?
/// A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.
public let groupBy: DimensionGroup?
/// The name of a Performance Insights metric to be measured. Valid values for Metric are: db.load.avg - a scaled representation of the number of active sessions for the database engine. db.sampledload.avg - the raw number of active sessions for the database engine.
public let metric: String
public init(filter: [String: String]? = nil, groupBy: DimensionGroup? = nil, metric: String) {
self.filter = filter
self.groupBy = groupBy
self.metric = metric
}
public func validate(name: String) throws {
try self.groupBy?.validate(name: "\(name).groupBy")
}
private enum CodingKeys: String, CodingKey {
case filter = "Filter"
case groupBy = "GroupBy"
case metric = "Metric"
}
}
public struct ResponsePartitionKey: AWSDecodableShape {
/// A dimension map that contains the dimension(s) for this partition.
public let dimensions: [String: String]
public init(dimensions: [String: String]) {
self.dimensions = dimensions
}
private enum CodingKeys: String, CodingKey {
case dimensions = "Dimensions"
}
}
public struct ResponseResourceMetricKey: AWSDecodableShape {
/// The valid dimensions for the metric.
public let dimensions: [String: String]?
/// The name of a Performance Insights metric to be measured. Valid values for Metric are: db.load.avg - a scaled representation of the number of active sessions for the database engine. db.sampledload.avg - the raw number of active sessions for the database engine.
public let metric: String
public init(dimensions: [String: String]? = nil, metric: String) {
self.dimensions = dimensions
self.metric = metric
}
private enum CodingKeys: String, CodingKey {
case dimensions = "Dimensions"
case metric = "Metric"
}
}
}
| 58.33908 | 530 | 0.674466 |
e00362a5791c73cdb03b3b229022bcefd7b1806a | 2,686 | //
// JPApplePayControllerTest.swift
// JPApplePayServiceTest
//
// Copyright (c) 2020 Alternative Payments Ltd
//
// 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 XCTest
@testable import JudoKit_iOS
class JPApplePayControllerTest: XCTestCase {
private var sut: JPApplePayController!
lazy var amount = JPAmount("0.01", currency: "GBP")
lazy var reference = JPReference(consumerReference: "consumerReference")
lazy var configuration = JPConfiguration(judoID: "123456", amount: amount, reference: reference)
lazy var authBlock: JPApplePayAuthorizationBlock = { _,_ in }
lazy var didFinishBlock: JPApplePayDidFinishBlock = { _ in }
lazy var summaryItems = [JPPaymentSummaryItem(label: "item", amount: 0.15)];
lazy var appleConfig = JPApplePayConfiguration(merchantId: "merchantId",
currency: "GBP",
countryCode: "GB",
paymentSummaryItems: summaryItems)
/**
* GIVEN: Apple Pay should be presented on the screen
*
* WHEN: a valid Apple Pay configuration is passed into the JPConfiguration object
*
* THEN: a configured UIViewController should be returned
*/
func test_WhenValidApplePayConfiguration_ReturnConfiguredUIViewController() {
configuration.applePayConfiguration = appleConfig
sut = JPApplePayController(configuration: configuration)
let controller = sut.applePayViewController(authorizationBlock: authBlock, didFinish: didFinishBlock)
XCTAssertNotNil(controller)
}
}
| 45.525424 | 109 | 0.706255 |
8ad37fa2ce195d83ad69cf4ffbfa867edcddace6 | 757 | import UIKit
import XCTest
import mathKit
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.233333 | 111 | 0.603699 |
69eeda5d069c8c91705cb3bc88a0cb6d0dc5accf | 1,091 | import Foundation
extension NSObject
{
func propertyNames() -> [String] {
return Mirror(reflecting: self).children.compactMap { $0.label }
}
}
/// Unzip an `Array` of key/value tuples.
///
/// - Parameter array: `Array` of key/value tuples.
/// - Returns: A tuple with two arrays, an `Array` of keys and an `Array` of values.
func unzip<K, V>(_ array: [(key: K, value: V)]) -> ([K], [V]) {
var keys = [K]()
var values = [V]()
keys.reserveCapacity(array.count)
values.reserveCapacity(array.count)
array.forEach { key, value in
keys.append(key)
values.append(value)
}
return (keys, values)
}
extension Array {
func scan<T>(initial: T, _ f: (T, Element) -> T) -> [T] {
return self.reduce([initial], { (listSoFar: [T], next: Element) -> [T] in
// because we seeded it with a non-empty
// list, it's easy to prove inductively
// that this unwrapping can't fail
let lastElement = listSoFar.last!
return listSoFar + [f(lastElement, next)]
})
}
}
| 25.97619 | 84 | 0.581118 |
abc54511ddce244aff455b05ffbe151c31997008 | 2,989 |
//MARK: Static constants
public let MARGIN_DEFAULT: CGFloat = 8.0
public let DIMENSION_TOUCHABLE: CGFloat = 44.0
public let DURATION_ANIMATION: TimeInterval = 0.3
public let DURATION_QUICK_ANIMATION: TimeInterval = (DURATION_ANIMATION/2.0)
public let DURATION_SLOW_ANIMATION: TimeInterval = (DURATION_ANIMATION*2.0)
public let DURATION_ONE_SECOND: TimeInterval = 1.0
public let DURATION_QUARTER: TimeInterval = (DURATION_ONE_SECOND/4.0)
public let DURATION_FULL_MINUTE: TimeInterval = (DURATION_ONE_SECOND*60.0)
public let LIMIT_CACHED_OBJ: Int = 1000
public let MAXIMUM_LENGTH_TWEET: Int = 140
//MARK: Closures
public typealias FXDcallback = (_ result: Bool, _ object: Any?) -> Void
//MARK: Protocols
@objc public protocol FXDprotocolObserver {
func observedUIApplicationDidEnterBackground(_ notification: NSNotification)
func observedUIApplicationDidBecomeActive(_ notification: NSNotification)
func observedUIApplicationWillTerminate(_ notification: NSNotification)
func observedUIApplicationDidReceiveMemoryWarning(_ notification: NSNotification)
func observedUIDeviceBatteryLevelDidChange(_ notification: NSNotification)
func observedUIDeviceOrientationDidChange(_ notification: NSNotification)
}
public protocol FXDprotocolAppConfig {
var appStoreID: String { get }
var URIscheme: String { get }
var homeURL: String { get }
var shortHomeURL: String { get }
var facebookURIscheme: String { get }
var twitterName: String { get }
var contactEmail: String { get }
var launchScene: String { get }
var bundledSqliteFile: String { get }
var delayBeforeClearForMemory: TimeInterval { get }
}
public protocol FXDrawRepresentable { //}: RawRepresentable { // until ready to remove ALL ObjC
var stringValue: String { get }
}
public protocol FXDrawString {
func stringValue(for enumCase: Int) -> String?
}
//MARK: Logging
import os.log
public func fxdPrint(_ items: Any..., separator: String = " ", terminator: String = "\n") {
#if DEBUG
for item in items {
if let variable = item as? CVarArg {
os_log("%@", (String(describing: variable) as NSString))
}
}
#endif
}
public func fxd_log(_ prefix: String? = nil, _ suffix: String? = nil, filename: String = #file, function: String = #function, line: Int = #line) {
#if DEBUG
os_log(" ")
os_log("\n\n %@[%@ %@]%@", ((prefix == nil) ? "" : prefix!), (filename as NSString).lastPathComponent, function, ((suffix == nil) ? "" : suffix!))
#endif
}
public func fxd_overridable(_ filename: String = #file, function: String = #function, line: Int = #line) {
#if DEBUG
fxd_log("OVERRIDABLE: ", nil, filename: filename, function: function, line: line)
#endif
}
public func fxd_todo(_ filename: String = #file, function: String = #function, line: Int = #line, message: String? = nil) {
#if DEBUG
let suffix = "\(message ?? "") (at \(line))"
fxd_log("//TODO: ", suffix, filename: filename, function: function, line: line)
#endif
}
| 31.135417 | 150 | 0.723319 |
f908804b26a3247c10a0a762b694d6807a69d13d | 8,541 | //
// SGSegmentedProgressView.swift
// SGSegmentedProgressViewLibrary
//
// Created by Sanjeev Gautam on 07/11/20.
//
import Foundation
import UIKit
public final class SGSegmentedProgressView: UIView {
private weak var delegate: SGSegmentedProgressViewDelegate?
private weak var dataSource: SGSegmentedProgressViewDataSource?
private var numberOfSegments: Int { get { return self.dataSource?.numberOfSegments ?? 0 } }
private var segmentDuration: TimeInterval { get { return self.dataSource?.segmentDuration ?? 5 } }
private var paddingBetweenSegments: CGFloat { get { return self.dataSource?.paddingBetweenSegments ?? 5 } }
private var trackColor: UIColor { get { return self.dataSource?.trackColor ?? UIColor.red.withAlphaComponent(0.3) } }
private var progressColor: UIColor { get { return self.dataSource?.progressColor ?? UIColor.red } }
private var segments = [UIProgressView]()
private var timer: Timer?
private let PROGRESS_SPEED: Double = 1000
private var PROGRESS_INTERVAL: Float {
let value = (self.segmentDuration * PROGRESS_SPEED)
let result = (Float(1/value))
return result
}
private var TIMER_TIMEINTERVAL: Double {
return (1/PROGRESS_SPEED)
}
// MARK:- Properties
public private (set) var isPaused: Bool = false
public private (set) var currentIndex: Int = 0
// MARK:- Initializer
internal required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
public init(frame: CGRect, delegate: SGSegmentedProgressViewDelegate, dataSource: SGSegmentedProgressViewDataSource) {
super.init(frame : frame)
self.delegate = delegate
self.dataSource = dataSource
self.drawSegments()
}
// MARK:- Private
private func drawSegments() {
let remainingWidth = self.frame.size.width - (self.paddingBetweenSegments * CGFloat(self.numberOfSegments-1))
let widthOfSegment = remainingWidth/CGFloat(self.numberOfSegments)
let heightOfSegment = self.frame.size.height
var originX: CGFloat = 0
let originY: CGFloat = 0
for index in 0..<self.numberOfSegments {
originX = (CGFloat(index) * widthOfSegment) + (CGFloat(index) * self.paddingBetweenSegments)
let frame = CGRect(x: originX, y: originY, width: widthOfSegment, height: heightOfSegment)
let progressView = self.createProgressView()
progressView.frame = frame
progressView.transform = CGAffineTransform(scaleX: 1.0, y: heightOfSegment)
self.addSubview(progressView)
self.segments.append(progressView)
if let cornerType = self.dataSource?.roundCornerType {
switch cornerType {
case .roundCornerSegments(let cornerRadious):
progressView.borderAndCorner(cornerRadious: cornerRadious, borderWidth: 0, borderColor: nil)
case .roundCornerBar(let cornerRadious):
if index == 0 {
progressView.roundCorners(corners: [.topLeft, .bottomLeft], radius: cornerRadious)
} else if index == self.numberOfSegments-1 {
progressView.roundCorners(corners: [.topRight, .bottomRight], radius: cornerRadious)
}
case .none:
break
}
}
}
}
private func createProgressView() -> UIProgressView {
let progressView = UIProgressView(progressViewStyle: .bar)
progressView.setProgress(0, animated: false)
progressView.trackTintColor = self.trackColor
progressView.tintColor = self.progressColor
return progressView
}
// MARK:- Timer
private func setUpTimer() {
if self.timer == nil {
self.timer = Timer.scheduledTimer(timeInterval: TIMER_TIMEINTERVAL, target: self, selector: #selector(animationTimerMethod), userInfo: nil, repeats: true)
}
}
@objc private func animationTimerMethod() {
if self.isPaused { return }
self.animateSegment()
}
// MARK:- Animate Segment
private func animateSegment() {
if self.currentIndex < self.segments.count {
let progressView = self.segments[self.currentIndex]
let lastProgress = progressView.progress
let newProgress = lastProgress + PROGRESS_INTERVAL
progressView.setProgress(newProgress, animated: false)
if newProgress >= 1 {
if self.currentIndex == self.numberOfSegments-1 {
self.delegate?.segmentedProgressViewFinished(finishedIndex: self.currentIndex, isLastIndex: true)
} else {
self.delegate?.segmentedProgressViewFinished(finishedIndex: self.currentIndex, isLastIndex: false)
}
if self.currentIndex < self.numberOfSegments-1 {
self.currentIndex = self.currentIndex + 1
let progressView = self.segments[self.currentIndex]
progressView.setProgress(0, animated: false)
} else {
self.timer?.invalidate()
self.timer = nil
}
}
}
}
// MARK:- Actions
public func start() {
self.setUpTimer()
}
public func pause() {
self.isPaused = true
}
public func resume() {
self.isPaused = false
}
public func restart() {
self.reset()
self.start()
}
public func nextSegment() {
if self.currentIndex < self.segments.count-1 {
self.isPaused = true
let progressView = self.segments[self.currentIndex]
progressView.setProgress(1, animated: false)
self.currentIndex = self.currentIndex + 1
self.isPaused = false
if self.timer == nil {
self.start()
} else {
self.animateSegment()
}
}
}
public func previousSegment() {
if self.currentIndex > 0 {
self.isPaused = true
let currentProgressView = self.segments[self.currentIndex]
currentProgressView.setProgress(0, animated: false)
self.currentIndex = self.currentIndex - 1
let progressView = self.segments[self.currentIndex]
progressView.setProgress(0, animated: false)
self.isPaused = false
if self.timer == nil {
self.start()
} else {
self.animateSegment()
}
}
}
public func restartCurrentSegment() {
self.isPaused = true
let currentProgressView = self.segments[self.currentIndex]
currentProgressView.setProgress(0, animated: false)
self.isPaused = false
if self.timer == nil {
self.start()
} else {
self.animateSegment()
}
}
public func reset() {
self.isPaused = true
self.timer?.invalidate()
self.timer = nil
for index in 0..<numberOfSegments {
let progressView = self.segments[index]
progressView.setProgress(0, animated: false)
}
self.currentIndex = 0
self.isPaused = false
}
// MARK:- Set Progress Manually
public func setProgressManually(index: Int, progressPercentage: CGFloat) {
if index < self.segments.count && index >= 0 {
self.timer?.invalidate()
self.timer = nil
self.currentIndex = index
var percentage = progressPercentage
if progressPercentage > 100 {
percentage = 100
}
// converting into 0 to 1 for UIProgressView range
percentage = percentage / 100
let progressView = self.segments[self.currentIndex]
progressView.setProgress(Float(percentage), animated: false)
}
}
}
| 34.027888 | 166 | 0.574874 |
e823ab77a815ea106c86f25fa939d686771af585 | 903 | //
// DebuggableNetworkTransport.swift
// ApolloDeveloperKit
//
// Created by Ryosuke Ito on 6/15/19.
// Copyright © 2019 Ryosuke Ito. All rights reserved.
//
import Apollo
public protocol DebuggableNetworkTransportDelegate: class {
func networkTransport<Operation: GraphQLOperation>(_ networkTransport: NetworkTransport, willSendOperation operation: Operation)
func networkTransport<Operation: GraphQLOperation>(_ networkTransport: NetworkTransport, didSendOperation operation: Operation, result: Result<GraphQLResult<Operation.Data>, Error>)
}
/**
* `DebuggableNetworkTransport` is a bridge between `ApolloDebugServer` and `ApolloClient`.
*
* You should instantiate both `ApolloDebugServer` and `ApolloClient` with the same instance of this class.
*/
public protocol DebuggableNetworkTransport: NetworkTransport {
var delegate: DebuggableNetworkTransportDelegate? { get set }
}
| 37.625 | 185 | 0.791805 |
39f6430836002f99f7071967b4410957a761e357 | 396 | @testable import Server
import XCTVapor
final class AppTests: XCTestCase {
func testHelloWorld() throws {
let app = Application(.testing)
defer { app.shutdown() }
try configure(app)
try app.test(.GET, "hello", afterResponse: { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "Hello, world!")
})
}
}
| 24.75 | 60 | 0.603535 |
76f9f1444bc3e4cbab6dc119aff481f9bba91fd3 | 4,848 | //
// ViewController.swift
// Swiftly-Exercise
//
// Created by Megan Herold on 2/27/20.
// Copyright © 2020 Megan Herold. All rights reserved.
//
import UIKit
class ManagerSpecialsCollectionViewController: UICollectionViewController {
// MARK: - Properties
var layout: ManagerSpecialLayout?
var oneUnit: Int {
guard let layout = layout else { return 0 }
return Int(UIScreen.main.bounds.width) / layout.canvasUnit
}
// MARK: - Override Methods
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(ManagerSpecialItemView.self, forCellWithReuseIdentifier: ManagerSpecialItemView.reuseIdentifier)
collectionView.register(ManagerSpecialsHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: ManagerSpecialsHeaderView.reuseIdentifier)
collectionView.backgroundColor = .systemBackground
requestLayout()
}
// MARK: - Networking
private func requestLayout() {
guard let url = ManagerSpecialLayout.Endpoint.url else {
presentOkAlert(message: "Invalid URL ⁉️")
return
}
URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
if let error = error {
self?.presentOkAlert(for: error)
return
}
if let data = data {
if let decodedLayout = try? JSONDecoder().decode(ManagerSpecialLayout.self, from: data) {
self?.layout = decodedLayout
DispatchQueue.main.async {
self?.collectionView?.reloadData()
}
} else {
self?.presentOkAlert(message: "Failed to decode the layout ☹️")
}
}
}.resume()
}
}
// MARK: - UICollectionDataSource
extension ManagerSpecialsCollectionViewController {
override func numberOfSections(in: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection: Int) -> Int {
return layout?.managerSpecials.count ?? 0
}
override func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: ManagerSpecialsHeaderView.reuseIdentifier,
for: indexPath)
return view
default:
return UICollectionReusableView()
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ManagerSpecialItemView.reuseIdentifier,
for: indexPath) as? ManagerSpecialItemView,
let managerSpecial = managerSpecial(for: indexPath) else {
return UICollectionViewCell()
}
cell.configure(for: managerSpecial)
return cell
}
func managerSpecial(for indexPath: IndexPath) -> ManagerSpecialItem? {
return layout?.managerSpecials[indexPath.row]
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension ManagerSpecialsCollectionViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let item = layout?.managerSpecials[indexPath.row] else { return CGSize.zero }
let width = item.width * oneUnit - Int(ManagerSpecialsCollectionViewLayout.padding)
let height = item.height * oneUnit - Int(ManagerSpecialsCollectionViewLayout.padding)
return CGSize(width: width, height: height)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: Int(UIScreen.main.bounds.width), height: oneUnit * 3)
}
}
| 36.451128 | 134 | 0.604167 |
f8e1203aa3a6580af074c5985964ca25e8790696 | 5,927 | import Foundation
// swiftlint:disable:next identifier_name
public let DefaultDelta = 0.0001
internal func isCloseTo(_ actualValue: NMBDoubleConvertible?,
expectedValue: NMBDoubleConvertible,
delta: Double)
-> PredicateResult {
let errorMessage = "be close to <\(stringify(expectedValue))> (within \(stringify(delta)))"
return PredicateResult(
bool: actualValue != nil &&
abs(actualValue!.doubleValue - expectedValue.doubleValue) < delta,
message: .expectedCustomValueTo(errorMessage, "<\(stringify(actualValue))>")
)
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(_ expectedValue: Double, within delta: Double = DefaultDelta) -> Predicate<Double> {
return Predicate.define { actualExpression in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta)
}
}
/// A Nimble matcher that succeeds when a value is close to another. This is used for floating
/// point values which can have imprecise results when doing arithmetic on them.
///
/// @see equal
public func beCloseTo(_ expectedValue: NMBDoubleConvertible, within delta: Double = DefaultDelta) -> Predicate<NMBDoubleConvertible> {
return Predicate.define { actualExpression in
return isCloseTo(try actualExpression.evaluate(), expectedValue: expectedValue, delta: delta)
}
}
#if canImport(Darwin)
public class NMBObjCBeCloseToMatcher: NSObject, NMBMatcher {
// swiftlint:disable identifier_name
var _expected: NSNumber
var _delta: CDouble
// swiftlint:enable identifier_name
init(expected: NSNumber, within: CDouble) {
_expected = expected
_delta = within
}
@objc public func matches(_ actualExpression: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let predicate = beCloseTo(self._expected, within: self._delta)
do {
let result = try predicate.satisfies(expr)
result.message.update(failureMessage: failureMessage)
return result.toBoolean(expectation: .toMatch)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
}
@objc public func doesNotMatch(_ actualExpression: @escaping () -> NSObject?, failureMessage: FailureMessage, location: SourceLocation) -> Bool {
let actualBlock: () -> NMBDoubleConvertible? = ({
return actualExpression() as? NMBDoubleConvertible
})
let expr = Expression(expression: actualBlock, location: location)
let predicate = beCloseTo(self._expected, within: self._delta)
do {
let result = try predicate.satisfies(expr)
result.message.update(failureMessage: failureMessage)
return result.toBoolean(expectation: .toNotMatch)
} catch let error {
failureMessage.stringValue = "unexpected error thrown: <\(error)>"
return false
}
}
@objc public var within: (CDouble) -> NMBObjCBeCloseToMatcher {
return { delta in
return NMBObjCBeCloseToMatcher(expected: self._expected, within: delta)
}
}
}
extension NMBObjCMatcher {
@objc public class func beCloseToMatcher(_ expected: NSNumber, within: CDouble) -> NMBObjCBeCloseToMatcher {
return NMBObjCBeCloseToMatcher(expected: expected, within: within)
}
}
#endif
public func beCloseTo(_ expectedValues: [Double], within delta: Double = DefaultDelta) -> Predicate<[Double]> {
let errorMessage = "be close to <\(stringify(expectedValues))> (each within \(stringify(delta)))"
return Predicate.simple(errorMessage) { actualExpression in
if let actual = try actualExpression.evaluate() {
if actual.count != expectedValues.count {
return .doesNotMatch
} else {
for (index, actualItem) in actual.enumerated() {
if fabs(actualItem - expectedValues[index]) > delta {
return .doesNotMatch
}
}
return .matches
}
}
return .doesNotMatch
}
}
// MARK: - Operators
infix operator ≈ : ComparisonPrecedence
extension Expectation where T == [Double] {
// swiftlint:disable:next identifier_name
public static func ≈(lhs: Expectation, rhs: [Double]) {
lhs.to(beCloseTo(rhs))
}
}
extension Expectation where T == NMBDoubleConvertible {
// swiftlint:disable:next identifier_name
public static func ≈(lhs: Expectation, rhs: NMBDoubleConvertible) {
lhs.to(beCloseTo(rhs))
}
// swiftlint:disable:next identifier_name
public static func ≈(lhs: Expectation, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
public static func == (lhs: Expectation, rhs: (expected: NMBDoubleConvertible, delta: Double)) {
lhs.to(beCloseTo(rhs.expected, within: rhs.delta))
}
}
// make this higher precedence than exponents so the Doubles either end aren't pulled in
// unexpectantly
precedencegroup PlusMinusOperatorPrecedence {
higherThan: BitwiseShiftPrecedence
}
infix operator ± : PlusMinusOperatorPrecedence
// swiftlint:disable:next identifier_name
public func ±(lhs: NMBDoubleConvertible, rhs: Double) -> (expected: NMBDoubleConvertible, delta: Double) {
return (expected: lhs, delta: rhs)
}
| 38.487013 | 149 | 0.669985 |
505287951236109692053889eceea3227f12b836 | 636 | //
// CoreDataStack.swift
// TodoApp
//
// Created by Keawa Rozet on 4/24/19.
// Copyright © 2019 Keawa Rozet. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
var container: NSPersistentContainer {
let container = NSPersistentContainer(name: "Todos")
container.loadPersistentStores {
(description, error) in
guard error == nil else {
print("Error: \(error!)")
return
}
}
return container
}
var managedContext: NSManagedObjectContext {
return container.viewContext
}
}
| 21.931034 | 60 | 0.595912 |
6a32b83c8d54018487772b1f8c4439be9fdf2ee7 | 5,987 | //
// PageControl.swift
// Wei
//
// Created by Ryosuke Fukuda on 2018/04/30.
// Copyright © 2018 popshoot All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class PageControl: UIControl {
let titles = BehaviorRelay<[String]>(value: [])
let selectedIndex = BehaviorRelay<Int>(value: 0)
let currentContentOffset = BehaviorRelay<CGFloat>(value: 0)
private let disposeBag = DisposeBag()
private let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0.0
layout.minimumLineSpacing = 0.0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.scrollsToTop = false
collectionView.backgroundColor = UIColor.clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.decelerationRate = UIScrollView.DecelerationRate.fast
collectionView.register(Cell.self, forCellWithReuseIdentifier: Cell.reuseIdentifier)
return collectionView
}()
private let selectionIndicatorView: UIView = {
let view: UIView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 2.0))
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 1
view.clipsToBounds = true
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
collectionView.delegate = self
addSubview(collectionView)
selectionIndicatorView.frame.origin.y = frame.height - selectionIndicatorView.frame.height
selectionIndicatorView.autoresizingMask = [.flexibleTopMargin]
addSubview(selectionIndicatorView)
bind()
}
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = bounds
updateSelectionIndicatorViewAnimated(animated: false)
}
private func bind() {
titles.asDriver()
.drive(collectionView.rx.items(cellType: Cell.self))
.disposed(by: disposeBag)
Driver
.combineLatest(titles.asDriver(), selectedIndex.asDriver()) { ($0, $1) }
.drive(onNext: { [weak self] titles, index in
guard !titles.isEmpty else {
return
}
let indexPath = IndexPath(item: index, section: 0)
self?.collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)
})
.disposed(by: disposeBag)
currentContentOffset.asDriver()
.drive(onNext: { [weak self] progress in
guard let strongSelf = self else {
return
}
strongSelf.selectionIndicatorView.frame.origin.x = progress * strongSelf.frame.width
})
.disposed(by: disposeBag)
}
private func updateSelectionIndicatorViewAnimated(animated: Bool) {
guard titles.value.count > 0 else {
return
}
guard
let indexPath = collectionView.indexPathsForSelectedItems?.first,
let attributes = collectionView.layoutAttributesForItem(at: indexPath) else {
selectionIndicatorView.frame.size.width = 0.0
return
}
UIView.animate(withDuration: animated ? 0.1 : 0.0) {
self.selectionIndicatorView.frame.origin.x = attributes.frame.minX - self.collectionView.contentOffset.x
self.selectionIndicatorView.frame.size.width = attributes.frame.width
}
}
}
extension PageControl: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndex.accept(indexPath.row)
sendActions(for: .valueChanged)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(
width: collectionView.frame.width / CGFloat(titles.value.count),
height: collectionView.frame.height
)
}
}
extension PageControl {
class Cell: UICollectionViewCell, InputAppliable {
static let reuseIdentifier = "Cell"
typealias Input = String
func apply(input: String) {
titleLabel.text = input
}
let titleLabel = UILabel()
override var isSelected: Bool {
didSet {
if isSelected {
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont.boldSystemFont(ofSize: 15)
} else {
titleLabel.textColor = UIColor.lightGray
titleLabel.font = UIFont.systemFont(ofSize: 15)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isSelected = false
titleLabel.font = UIFont.systemFont(ofSize: 15.0)
titleLabel.textAlignment = .center
addSubview(titleLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame.size = frame.size
titleLabel.center.x = bounds.midX
titleLabel.center.y = bounds.midY
}
}
}
| 33.077348 | 160 | 0.602806 |
2635e835b748f39f23195b0504358428c041c261 | 37 | import Foundation
enum Cleaning { }
| 9.25 | 17 | 0.756757 |
d5118cdc4bbc79181400b92ba69d25a34b8c498f | 304 | //
// PingExample.swift
// LimeAPIClientTests
//
// Created by Лайм HD on 04.06.2020.
// Copyright © 2020 Лайм HD. All rights reserved.
//
import Foundation
let PingExample = """
{
"result": "pong",
"time": "2020-06-04T09:56:34+03:00",
"version": "v0.2.5",
"hostname": "s011"
}
"""
| 16 | 50 | 0.595395 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.