repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
kstaring/swift | validation-test/compiler_crashers_fixed/00886-swift-tuplepattern-create.swift | 11 | 428 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
(T: [c>()
class b: A {
func d<S : d
| apache-2.0 |
sjchmiela/call-of-beacons | ios/CallOfBeacons/CallOfBeacons/COBNotifier.swift | 1 | 295 | //
// COBNotifier.swift
// CallOfBeacons
//
// Created by Stanisław Chmiela on 06.06.2016.
// Copyright © 2016 Stanisław Chmiela, Rafał Żelazko. All rights reserved.
//
import Foundation
protocol COBNotifier {
func update(gamerState: COBGamerState, beacons: [COBBeacon]) -> Void
} | mit |
Flinesoft/BartyCrouch | Sources/BartyCrouchKit/TaskHandlers/TranslateTaskHandler.swift | 1 | 739 | import BartyCrouchConfiguration
import Foundation
struct TranslateTaskHandler {
let options: TranslateOptions
init(
options: TranslateOptions
) {
self.options = options
}
}
extension TranslateTaskHandler: TaskHandler {
func perform() {
// TODO: add support for multiple APIs (currently not in the parameter list of actOnTranslate)
measure(task: "Translate") {
mungo.do {
CommandLineActor()
.actOnTranslate(
paths: options.paths,
subpathsToIgnore: options.subpathsToIgnore,
override: false,
verbose: GlobalOptions.verbose.value,
secret: options.secret,
locale: options.sourceLocale
)
}
}
}
}
| mit |
fhisa/CocoaStudy | 20150905/LayoutSampleWithCode/LayoutSampleWithCodeTests/LayoutSampleWithCodeTests.swift | 1 | 945 | //
// LayoutSampleWithCodeTests.swift
// LayoutSampleWithCodeTests
//
// Created by fhisa on 2015/09/03.
// Copyright (c) 2015年 Hisakuni Fujimoto. All rights reserved.
//
import UIKit
import XCTest
class LayoutSampleWithCodeTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
TheBasicMind/SlackReporter | Example/Tests/SlackCommandTests.swift | 1 | 7145 | //
// SlackCommandTests.swift
// SlackReporter
//
// Created by Paul Lancefield on 17/01/2016.
// Copyright © 2016 Paul Lancefield. All rights reserved.
//
import XCTest
@testable import SlackReporter
class SlackCommandTests: 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 testBaseClassInitialisationSuccess()
{
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: .Chat_postMessage, requiredArguments: (.Token, "AToken"), (.Channel, "#gen-feedback"), (.Text, "Some Text") )
} catch {
XCTFail("command must be instantiated")
}
XCTAssertNotNil(command, "")
}
func testBaseClassInitialisationSuccess_argumentOrderIrrelevant()
{
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: .Chat_postMessage, requiredArguments: (.Channel, "#gen-feedback"), (.Token, "AToken"), (.Text, "Some Text") )
} catch {
XCTFail("command must be instantiated")
}
XCTAssertNotNil(command, "")
}
func testBaseClassInitialisationFailure_requiredArgumentMissing()
{
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: .Chat_postMessage, requiredArguments: (.Token, "AToken"), (.Channel, "#gen-feedback") )
} catch {
// Early return equals success
print(command)
return
}
XCTFail("Command failure was not caught")
}
func testBaseClassInitialisationFailure_requiredArgMissingArgOrderIrrelevant()
{
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: .Chat_postMessage, requiredArguments: (.Channel, "#gen-feedback"), (.Token, "AToken") )
} catch {
// Early return equals success
print(command)
return
}
XCTFail("Command failure was not caught")
}
func testSlackWebhook()
{
let command = SlackWebhook(webhookID: "AToken")
var request: NSMutableURLRequest
do {
try request = command.URLRequest()
} catch {
XCTFail("\(error)")
return
}
XCTAssertEqual("https://hooks.slack.com/services/AToken", request.URL!.absoluteString)
}
func testSlackMessage()
{
/////////
/////////
///
/// Data
let command = SlackPostMessage(channel: "AChannel", text: "Some Text")
var request: NSMutableURLRequest
///////////
///////////
///
/// Process
do {
try request = command.URLRequest()
} catch {
XCTFail("\(error)")
return
}
//////////
//////////
///
/// Result
let data = request.HTTPBody
guard data != nil else { XCTFail() ; return }
let bodyText = NSString(data: data!, encoding: 4)
XCTAssertTrue(bodyText!.hasPrefix("--Boundary"), "Body text in message command must start with HTML form markup")
XCTAssertEqual("https://slack.com/api/chat.postMessage", request.URL!.absoluteString)
}
func testFormDataWithDictionary()
{
/////////
/////////
///
/// Data
let commandType = CommandType.Chat_postMessage
//let arg1 = (Arg.Token, "AToken" )
//let arg2 = (Arg.Channel, "#gen-feedback")
//let arg3 = (Arg.Text, "Some Text")
///////////
///////////
///
/// Process
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: commandType, requiredArguments: (Arg.Token, "AToken" ), (Arg.Channel, "#gen-feedback"), (Arg.Text, "Some Text") )
} catch {
XCTFail("command must be instantiated")
}
guard command != nil else { XCTAssertNotNil(command); return }
do {
try command!.setOptionalArguments( (.IconUrl, "IconURL"), (.AsUser, true) )
} catch { XCTFail("command must allow optional arguments to be set") }
var request: NSMutableURLRequest
do {
try request = command!.URLRequest()
} catch {
XCTFail("\(error)")
return
}
let data = request.HTTPBody
guard data != nil else { XCTFail() ; return }
let bodyText = NSString(data: data!, encoding: 4)
// Check at least 1 required and 1 optional argument has been encoded
XCTAssertTrue(bodyText!.containsString("Token"), "A required parameter has not been encoded")
XCTAssertTrue(bodyText!.containsString("AToken"), "A required parameter has not been encoded")
XCTAssertTrue(bodyText!.containsString("\"icon_url\""), "A required parameter has not been encoded")
XCTAssertTrue(bodyText!.containsString("AToken"), "A required parameter has not been encoded")
XCTAssertEqual("https://slack.com/api/chat.postMessage", request.URL!.absoluteString)
}
func testWebhookRequestURLSuccess()
{
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: .Chat_postMessage, requiredArguments: (.Token, "AToken"), (.Channel, "#gen-feedback"), (.Text, "Some Text") )
} catch {
XCTFail("command must be instantiated")
}
guard command != nil else { XCTAssertNotNil(command); return }
var request: NSMutableURLRequest
do {
try request = command!.URLRequest()
} catch {
XCTFail("\(error)")
return
}
XCTAssertEqual("https://slack.com/api/chat.postMessage", request.URL!.absoluteString)
}
func testRequestURLSuccess()
{
var command: SlackCommand? = nil
do {
try command = SlackCommand(command: .Chat_postMessage, requiredArguments: (.Token, "AToken"), (.Channel, "#gen-feedback"), (.Text, "Some Text") )
} catch {
XCTFail("command must be instantiated")
}
guard command != nil else { XCTAssertNotNil(command); return }
var request: NSMutableURLRequest
do {
try request = command!.URLRequest()
} catch {
XCTFail("\(error)")
return
}
XCTAssertEqual("https://slack.com/api/chat.postMessage", request.URL!.absoluteString)
}
}
| mit |
koden-km/dialekt-swift | Dialekt/Renderer/RendererProtocol.swift | 1 | 139 | public protocol RendererProtocol {
/// Render an expression to a string.
func render(expression: ExpressionProtocol) -> String!
}
| mit |
Alecrim/AlecrimAsyncKit | Sources/Error+Extensions.swift | 1 | 788 | //
// Errors.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 09/03/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
// MARK: -
extension Error {
internal var isUserCancelled: Bool {
let error = self as NSError
return error.domain == NSCocoaErrorDomain && error.code == NSUserCancelledError
}
}
//extension CustomNSError {
// internal var isUserCancelled: Bool {
// return type(of: self).errorDomain == NSCocoaErrorDomain && self.errorCode == NSUserCancelledError
// }
//}
// MAR: -
fileprivate let _userCancelledError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
extension Error {
internal static var userCancelled: Error { return _userCancelledError }
}
| mit |
casd82/powerup-iOS | PowerupTests/ResultViewControllerTests.swift | 2 | 3069 | import XCTest
@testable import Powerup
class ResultViewControllerTests: XCTestCase {
var resultViewController: ResultsViewController!
// Mock data source for tests (score saving & fetching).
class MockSource: DataSource {
var score: Score
init(score: Score) {
self.score = score
}
override func getScore() -> Score {
return score
}
override func saveScore(score: Score) {
self.score = score
}
}
override func setUp() {
resultViewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "Results View Controller") as! ResultsViewController
resultViewController.loadView()
super.setUp()
}
override func tearDown() {
resultViewController = nil
super.tearDown()
}
/**
- Test that ResultViewController correctly saved and fetched the score
*/
func testScoreFetchingAndSaving() {
let originalScore = Score(karmaPoints: 31, healing: 30, strength: 20, telepathy: 10, invisibility: 40)
// Given
let mockSource = MockSource(score: originalScore)
resultViewController.dataSource = mockSource
// When
resultViewController.gainKarmaPoints()
// Then (score is correctly fetched saved, and showed.)
let showedScore = resultViewController.karmaPointsLabel.text
// Score not nil.
XCTAssertNotNil(showedScore)
// Score is correct.
XCTAssertEqual(Int(showedScore!), originalScore.karmaPoints + resultViewController.karmaGain)
}
/**
- Test that the labels for completed scenario and karma points are accurate
*/
func testLabelsHaveCorrectContent() {
let score = Score(karmaPoints: 10, healing: 10, strength: 10, telepathy: 10, invisibility: 10)
// Given
let mockSource = MockSource(score: score)
resultViewController.dataSource = mockSource
resultViewController.completedScenarioName = "School"
// When
resultViewController.viewDidLoad()
// Then
XCTAssertEqual(resultViewController.scenarioName.text, "Current Scenario: " + resultViewController.completedScenarioName)
XCTAssertEqual(resultViewController.karmaPointsLabel.text, String(score.karmaPoints))
}
/**
- Test that completing a scenario adds 20 karma points to the database.
*/
func testGainKarmaPoints() {
let score = Score(karmaPoints: 0, healing: 15, strength: 20, telepathy: 10, invisibility: 20)
// Given
let mockSource = MockSource(score: score)
resultViewController.dataSource = mockSource
// When
resultViewController.gainKarmaPoints()
// Then
XCTAssertEqual(resultViewController.karmaPointsLabel.text, String(20))
}
}
| gpl-2.0 |
sublimter/Meijiabang | KickYourAss/KickYourAss/ArtistDetailFile/artistdDetailCell/ZXY_ChangeUserSexCell.swift | 3 | 1113 | //
// ZXY_ChangeUserSexCell.swift
// KickYourAss
//
// Created by 宇周 on 15/2/11.
// Copyright (c) 2015年 多思科技. All rights reserved.
//
import UIKit
let ZXY_ChangeUserSexCellID = "ZXY_ChangeUserSexCellID"
typealias ZXY_ChangeUserSexCellBlock = (flag: Int) -> Void
class ZXY_ChangeUserSexCell: UITableViewCell {
@IBOutlet weak var girlFlag: UIImageView!
@IBOutlet weak var boyFlag: UIImageView!
var userSelectBoyOrGirlBlock : ZXY_ChangeUserSexCellBlock!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func selectGirl(sender: AnyObject) {
self.userSelectBoyOrGirlBlock(flag: 2)
girlFlag.hidden = false
boyFlag.hidden = true
}
@IBAction func selectBoy(sender: AnyObject) {
self.userSelectBoyOrGirlBlock(flag: 1)
girlFlag.hidden = true
boyFlag.hidden = false
}
}
| mit |
blcsntb/Utilities | Example/Utilities/AppDelegate.swift | 1 | 271 | //
// AppDelegate.swift
// Utilities
//
// Created by blcsntb on 11/30/2016.
// Copyright (c) 2016 blcsntb. All rights reserved.
//
import UIKit
import Utilities
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| mit |
codesman/toolbox | Sources/VaporToolbox/DockerBuild.swift | 1 | 2085 | import Console
public final class DockerBuild: Command {
public let id = "build"
public let signature: [Argument] = []
public let help: [String] = [
"Builds the Docker application."
]
public let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
public func run(arguments: [String]) throws {
do {
_ = try console.backgroundExecute("which docker")
} catch ConsoleError.subexecute(_, _) {
console.info("Visit https://www.docker.com/products/docker-toolbox")
throw ToolboxError.general("Docker not installed.")
}
do {
let contents = try console.backgroundExecute("ls .")
if !contents.contains("Dockerfile") {
throw ToolboxError.general("No Dockerfile found")
}
} catch ConsoleError.subexecute(_) {
throw ToolboxError.general("Could not check for Dockerfile")
}
let swiftVersion: String
do {
swiftVersion = try console.backgroundExecute("cat .swift-version").trim()
} catch {
throw ToolboxError.general("Could not determine Swift version from .swift-version file.")
}
let buildBar = console.loadingBar(title: "Building Docker image")
buildBar.start()
do {
let imageName = DockerBuild.imageName(version: swiftVersion)
_ = try console.backgroundExecute("docker build --rm -t \(imageName) --build-arg SWIFT_VERSION=\(swiftVersion) .")
buildBar.finish()
} catch ConsoleError.subexecute(_, let message) {
buildBar.fail()
throw ToolboxError.general("Docker build failed: \(message.trim())")
}
if console.confirm("Would you like to run the Docker image now?") {
let build = DockerRun(console: console)
try build.run(arguments: arguments)
}
}
static func imageName(version: String) -> String {
return "qutheory/swift:\(version)"
}
}
| mit |
AttilaTheFun/SwaggerParser | Package.swift | 1 | 552 | // swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "SwaggerParser",
products: [
.library(
name: "SwaggerParser",
type: .static,
targets: ["SwaggerParser"]
),
],
dependencies: [],
targets: [
.target(
name: "SwaggerParser",
dependencies: [],
path: "Sources"
),
.testTarget(
name: "SwaggerParserTests",
dependencies: [],
path: "Tests"
),
]
)
| mit |
RCacheaux/BitbucketKit | Sources/iOS/Private/Remote/Details/Authentication/URLRequestAuthenticator.swift | 1 | 201 | // Copyright © 2016 Atlassian Pty Ltd. All rights reserved.
import Foundation
protocol URLRequestAuthenticator {
func authenticateRequest(request: NSMutableURLRequest) -> NSMutableURLRequest
}
| apache-2.0 |
dzenbot/Iconic | Samples/Tests/ImageIconSnapshotTests.swift | 1 | 2532 | //
// ImageIconSnapshotTests.swift
// Iconic
//
// Copyright © 2019 The Home Assistant Authors
// Licensed under the Apache 2.0 license
// For more information see https://github.com/home-assistant/Iconic
class ImageIconSnapshotTests: BaseSnapshotTestCase {
override func setUp() {
super.setUp()
// Toggle on for recording a new snapshot. Remember to turn it back off to validate the test.
self.recordMode = false
}
func testImageDefaultColor() {
let size = CGSize(width: 60, height: 60)
let image = FontAwesomeIcon.saveIcon.image(ofSize: size, color: nil)
let imageView = UIImageView(image: image)
self.verifyView(imageView, withIdentifier: "")
}
func testImagePatternColor() {
let bundle = Bundle(for: type(of: self))
let size = CGSize(width: 60, height: 60)
if let pattern = UIImage(named: "pattern", in: bundle, compatibleWith: nil) {
let color = UIColor(patternImage: pattern)
let image = FontAwesomeIcon.warningSignIcon.image(ofSize: size, color: color)
let imageView = UIImageView(image: image)
self.verifyView(imageView, withIdentifier: "")
}
}
func testImageSizes() {
let pointSizes = [16, 32, 64, 128, 512]
for pointSize in pointSizes {
let size = CGSize(width: pointSize, height: pointSize)
let image = FontAwesomeIcon.githubAltIcon.image(ofSize: size, color: UIColor.red)
let imageView = UIImageView(image: image)
XCTAssertEqual(image.size, size)
self.verifyView(imageView, withIdentifier: "\(pointSize)_icon")
}
}
func testImagePadding() {
let size = CGSize(width: 88, height: 88)
let expectedSize = CGSize(width: 98, height: 98)
let padding = UIEdgeInsets(top: -5, left: -5, bottom: -5, right: -5)
let image = FontAwesomeIcon.githubIcon.image(ofSize: size, color: nil, edgeInsets: padding)
let imageView = UIImageView(image: image)
XCTAssertEqual(image.size, expectedSize)
self.verifyView(imageView, withIdentifier: "")
}
func testImageNoPadding() {
let size = CGSize(width: 88, height: 88)
let image = FontAwesomeIcon.githubIcon.image(ofSize: size, color: nil, edgeInsets: UIEdgeInsets.zero)
let imageView = UIImageView(image: image)
XCTAssertEqual(image.size, size)
self.verifyView(imageView, withIdentifier: "")
}
}
| mit |
alessiobrozzi/firefox-ios | Client/Frontend/Browser/HomePageHelper.swift | 6 | 2539 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.browserLogger
struct HomePageConstants {
static let HomePageURLPrefKey = "HomePageURLPref"
static let DefaultHomePageURLPrefKey = PrefsKeys.KeyDefaultHomePageURL
static let HomePageButtonIsInMenuPrefKey = PrefsKeys.KeyHomePageButtonIsInMenu
}
class HomePageHelper {
let prefs: Prefs
var currentURL: URL? {
get {
return HomePageAccessors.getHomePage(prefs)
}
set {
if let url = newValue, url.isWebPage(includeDataURIs: false) && !url.isLocal {
prefs.setString(url.absoluteString, forKey: HomePageConstants.HomePageURLPrefKey)
} else {
prefs.removeObjectForKey(HomePageConstants.HomePageURLPrefKey)
}
}
}
var defaultURLString: String? {
return HomePageAccessors.getDefaultHomePageString(prefs)
}
var isHomePageAvailable: Bool { return currentURL != nil }
init(prefs: Prefs) {
self.prefs = prefs
}
func openHomePage(_ tab: Tab) {
guard let url = currentURL else {
// this should probably never happen.
log.error("User requested a homepage that wasn't a valid URL")
return
}
tab.loadRequest(URLRequest(url: url))
}
func openHomePage(inTab tab: Tab, withNavigationController navigationController: UINavigationController?) {
if isHomePageAvailable {
openHomePage(tab)
} else {
setHomePage(toTab: tab, withNavigationController: navigationController)
}
}
func setHomePage(toTab tab: Tab, withNavigationController navigationController: UINavigationController?) {
let alertController = UIAlertController(
title: Strings.SetHomePageDialogTitle,
message: Strings.SetHomePageDialogMessage,
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: Strings.SetHomePageDialogNo, style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: Strings.SetHomePageDialogYes, style: .default) { _ in
self.currentURL = tab.url as URL?
})
navigationController?.present(alertController, animated: true, completion: nil)
}
}
| mpl-2.0 |
wireapp/wire-ios-sync-engine | Tests/Source/Synchronization/Strategies/LabelUpstreamRequestStrategyTests.swift | 1 | 8096 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import WireSyncEngine
class LabelUpstreamRequestStrategyTests: MessagingTest {
var sut: LabelUpstreamRequestStrategy!
var mockSyncStatus: MockSyncStatus!
var mockSyncStateDelegate: MockSyncStateDelegate!
var mockApplicationStatus: MockApplicationStatus!
var conversation1: ZMConversation!
var conversation2: ZMConversation!
override func setUp() {
super.setUp()
mockApplicationStatus = MockApplicationStatus()
mockApplicationStatus.mockSynchronizationState = .online
sut = LabelUpstreamRequestStrategy(withManagedObjectContext: syncMOC, applicationStatus: mockApplicationStatus)
syncMOC.performGroupedBlockAndWait {
self.conversation1 = ZMConversation.insertNewObject(in: self.syncMOC)
self.conversation1.remoteIdentifier = UUID()
self.conversation2 = ZMConversation.insertNewObject(in: self.syncMOC)
self.conversation2.remoteIdentifier = UUID()
}
}
override func tearDown() {
sut = nil
mockSyncStatus = nil
mockApplicationStatus = nil
mockSyncStateDelegate = nil
conversation1 = nil
conversation2 = nil
super.tearDown()
}
func testThatItGeneratesRequestForUpdatingLabels() throws {
let labelUpdate = WireSyncEngine.LabelUpdate(id: Label.fetchFavoriteLabel(in: uiMOC).remoteIdentifier!, type: 1, name: nil, conversations: [conversation1.remoteIdentifier!])
let expectedPayload = WireSyncEngine.LabelPayload(labels: [labelUpdate])
syncMOC.performGroupedBlockAndWait {
// given
let label = Label.fetchFavoriteLabel(in: self.syncMOC)
label.conversations = Set([self.conversation1])
label.modifiedKeys = Set(["conversations"])
self.sut.objectsDidChange(Set([label]))
// when
guard let request = self.sut.nextRequestIfAllowed(for: .v0) else { return XCTFail() }
// then
let payload = try! JSONSerialization.data(withJSONObject: request.payload as Any, options: [])
let decodedPayload = try! JSONDecoder().decode(WireSyncEngine.LabelPayload.self, from: payload)
XCTAssertEqual(request.path, "/properties/labels")
XCTAssertEqual(decodedPayload, expectedPayload)
}
}
func testThatItDoesntUploadLabelsMarkedForDeletion() {
let labelUpdate = WireSyncEngine.LabelUpdate(id: Label.fetchFavoriteLabel(in: uiMOC).remoteIdentifier!, type: 1, name: nil, conversations: [])
let expectedPayload = WireSyncEngine.LabelPayload(labels: [labelUpdate])
syncMOC.performGroupedBlockAndWait {
// given
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: UUID(), create: true, in: self.syncMOC, created: &created)!
label.conversations = Set([self.conversation1])
label.markForDeletion()
label.modifiedKeys = Set(["conversations", "markedForDeletion"])
self.sut.objectsDidChange(Set([label]))
// when
guard let request = self.sut.nextRequestIfAllowed(for: .v0) else { return XCTFail() }
// then
let payload = try! JSONSerialization.data(withJSONObject: request.payload as Any, options: [])
let decodedPayload = try! JSONDecoder().decode(WireSyncEngine.LabelPayload.self, from: payload)
XCTAssertEqual(request.path, "/properties/labels")
XCTAssertEqual(decodedPayload, expectedPayload)
}
}
func testThatItUploadLabels_WhenModifyingConversations() {
// given
syncMOC.performGroupedBlockAndWait {
let label = Label.insertNewObject(in: self.syncMOC)
label.modifiedKeys = Set(["conversations"])
self.sut.objectsDidChange(Set([label]))
}
// then
syncMOC.performGroupedBlockAndWait {
XCTAssertNotNil(self.sut.nextRequestIfAllowed(for: .v0))
}
}
func testThatItUploadLabels_WhenModifyingName() {
// given
syncMOC.performGroupedBlockAndWait {
let label = Label.insertNewObject(in: self.syncMOC)
label.modifiedKeys = Set(["name"])
self.sut.objectsDidChange(Set([label]))
}
// then
syncMOC.performGroupedBlockAndWait {
XCTAssertNotNil(self.sut.nextRequestIfAllowed(for: .v0))
}
}
func testThatItUploadsLabels_WhenModifiedWhileUploadingLabels() {
var label1: Label!
var label2: Label!
// given
syncMOC.performGroupedBlockAndWait {
label1 = Label.insertNewObject(in: self.syncMOC)
label2 = Label.insertNewObject(in: self.syncMOC)
label1.modifiedKeys = Set(["name"])
self.syncMOC.saveOrRollback()
self.sut.objectsDidChange(Set([label1]))
}
// when
syncMOC.performGroupedBlockAndWait {
guard let request = self.sut.nextRequestIfAllowed(for: .v0) else { return XCTFail() }
label2.modifiedKeys = Set(["name"])
self.syncMOC.saveOrRollback()
self.sut.objectsDidChange(Set([label2]))
request.complete(with: ZMTransportResponse(payload: nil, httpStatus: 201, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue))
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
syncMOC.performGroupedBlockAndWait {
XCTAssertNotNil(self.sut.nextRequestIfAllowed(for: .v0))
}
}
func testThatItResetsLocallyModifiedKeys_AfterSuccessfullyUploadingLabels() {
var label: Label!
// given
syncMOC.performGroupedBlockAndWait {
label = Label.insertNewObject(in: self.syncMOC)
label.modifiedKeys = Set(["name"])
self.sut.objectsDidChange(Set([label]))
}
// when
syncMOC.performGroupedBlockAndWait {
guard let request = self.sut.nextRequestIfAllowed(for: .v0) else { return XCTFail() }
request.complete(with: ZMTransportResponse(payload: nil, httpStatus: 201, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue))
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
syncMOC.performGroupedBlockAndWait {
XCTAssertNil(label.modifiedKeys)
}
}
func testThatItDeletesLabelMarkedForDeletion_AfterSuccessfullyUploadingLabels() {
var label: Label!
// given
syncMOC.performGroupedBlockAndWait {
label = Label.insertNewObject(in: self.syncMOC)
label.markForDeletion()
label.modifiedKeys = Set(["markedForDeletion"])
self.sut.objectsDidChange(Set([label]))
}
// when
syncMOC.performGroupedBlockAndWait {
guard let request = self.sut.nextRequestIfAllowed(for: .v0) else { return XCTFail() }
request.complete(with: ZMTransportResponse(payload: nil, httpStatus: 201, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue))
}
XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// then
syncMOC.performGroupedBlockAndWait {
XCTAssertTrue(label.isZombieObject)
}
}
}
| gpl-3.0 |
goldmoment/UIViewStuff | UIViewStuff/Classes/USGradientLayer.swift | 1 | 2523 | //
// USGradientLayer.swift
// UIViewStuff
//
// Created by Vien Van Nguyen on 2/28/17.
//
//
import UIKit
public typealias USGradientPoint = (x: CGPoint, y: CGPoint)
public enum USGradientType {
case leftRight
case rightLeft
case topBottom
case bottomTop
case topLeftBottomRight
case bottomRightTopLeft
case topRightBottomLeft
case bottomLeftTopRight
func draw() -> USGradientPoint {
switch self {
case .leftRight:
return (x: CGPoint(x: 0, y: 0.5), y: CGPoint(x: 1, y: 0.5))
case .rightLeft:
return (x: CGPoint(x: 1, y: 0.5), y: CGPoint(x: 0, y: 0.5))
case .topBottom:
return (x: CGPoint(x: 0.5, y: 0), y: CGPoint(x: 0.5, y: 1))
case .bottomTop:
return (x: CGPoint(x: 0.5, y: 1), y: CGPoint(x: 0.5, y: 0))
case .topLeftBottomRight:
return (x: CGPoint(x: 0, y: 0), y: CGPoint(x: 1, y: 1))
case .bottomRightTopLeft:
return (x: CGPoint(x: 1, y: 1), y: CGPoint(x: 0, y: 0))
case .topRightBottomLeft:
return (x: CGPoint(x: 1, y: 0), y: CGPoint(x: 0, y: 1))
case .bottomLeftTopRight:
return (x: CGPoint(x: 0, y: 1), y: CGPoint(x: 1, y: 0))
}
}
}
public class USGradientLayer : CAGradientLayer {
public var gradientType: USGradientType? {
didSet {
applyPoint()
}
}
public convenience init(_ colors: [Any], gradientType: USGradientType? = .leftRight) {
self.init()
self.colors = colors.map({ (color) -> CGColor in
if let color = color as? Int {
return UIColor.init(UInt(color)).cgColor
}
if let color = color as? UIColor {
return color.cgColor
}
return UIColor.clear.cgColor
})
self.gradientType = gradientType
applyPoint()
}
private func applyPoint() {
if let gradientPoint = gradientType?.draw() {
startPoint = gradientPoint.x
endPoint = gradientPoint.y
}
}
}
public extension UIView {
public func addGradientLayer(_ colors: [Any], gradientType: USGradientType? = .leftRight) -> USGradientLayer {
let gradientLayer = USGradientLayer(colors, gradientType: gradientType)
gradientLayer.frame = self.layer.bounds
self.layer.addSublayer(gradientLayer)
return gradientLayer
}
}
| mit |
alexbasson/swift-experiment | SwiftExperimentTests/Helpers/Mocks/MockJSONClient.swift | 1 | 756 | import Foundation
import SwiftExperiment
class MockJSONClient: JSONClientInterface {
class SendRequestParams {
var request: NSURLRequest!
var closure: JSONClientClosure!
init(request: NSURLRequest, closure: JSONClientClosure) {
self.request = request
self.closure = closure
}
}
var sendRequestInvocation = Invocation(wasReceived: false, params: nil)
func sendRequest(request: NSURLRequest, closure: JSONClientClosure) {
sendRequestInvocation.wasReceived = true
sendRequestInvocation.params = SendRequestParams(request: request, closure: closure)
}
}
extension MockJSONClient: Mockable {
func resetSentMessages() {
sendRequestInvocation.wasReceived = false
sendRequestInvocation.params = nil
}
} | mit |
beryu/DoneHUD | Source/DoneHUD.swift | 2 | 2437 | //
// DoneHUD.swift
// DoneHUD
//
// Created by Ryuta Kibe on 2015/08/23.
// Copyright (c) 2015 blk. All rights reserved.
//
import UIKit
open class DoneHUD: NSObject {
fileprivate static let sharedObject = DoneHUD()
let doneView = DoneView()
public static func showInView(_ view: UIView) {
DoneHUD.sharedObject.showInView(view, message: nil)
}
public static func showInView(_ view: UIView, message: String?) {
DoneHUD.sharedObject.showInView(view, message: message)
}
fileprivate func showInView(_ view: UIView, message: String?) {
// Set size of done view
let doneViewWidth = min(view.frame.width, view.frame.height) / 2
var originX: CGFloat, originY: CGFloat
if (UIDevice.current.systemVersion as NSString).floatValue >= 8.0 {
originX = (view.frame.width - doneViewWidth) / 2
originY = (view.frame.height - doneViewWidth) / 2
} else {
let isLandscape = UIDevice.current.orientation.isLandscape
originX = ((isLandscape ? view.frame.height : view.frame.width) - doneViewWidth) / 2
originY = ((isLandscape ? view.frame.width : view.frame.height) - doneViewWidth) / 2
}
let doneViewFrame = CGRect(
x: originX,
y: originY,
width: doneViewWidth,
height: doneViewWidth)
self.doneView.layer.cornerRadius = 8
self.doneView.frame = doneViewFrame
// Set message
self.doneView.setMessage(message)
// Start animation
self.doneView.alpha = 0
view.addSubview(self.doneView)
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.doneView.alpha = 1
}, completion: { (result: Bool) -> Void in
self.doneView.drawCheck({ () -> Void in
let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.doneView.alpha = 0
}, completion: { (result: Bool) -> Void in
self.doneView.removeFromSuperview()
self.doneView.clear()
})
}
})
})
}
}
| mit |
danielsaidi/KeyboardKit | Sources/KeyboardKit/Input/KeyboardInput.swift | 1 | 2022 | //
// KeyboardInputRow.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-03.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
/**
This struct represents a keyboard input item, with an upper
and a lowercased string.
You can either create an instance with just a string, which
is the regular way of working with input sets. However, the
struct also supports specific casings, which means that you
can use it to create unicode keyboards as well.
*/
public struct KeyboardInput: Equatable {
public init(_ char: String) {
self.neutral = char
self.uppercased = char.uppercased()
self.lowercased = char.lowercased()
}
public init(
neutral: String,
uppercased: String,
lowercased: String) {
self.neutral = neutral
self.uppercased = uppercased
self.lowercased = lowercased
}
public let neutral: String
public let uppercased: String
public let lowercased: String
func character(for casing: KeyboardCasing) -> String {
switch casing {
case .lowercased: return lowercased
case .uppercased, .capsLocked: return uppercased
case .neutral: return neutral
}
}
}
/**
This typealias represents a list of keyboard inputs.
*/
public typealias KeyboardInputRow = [KeyboardInput]
public extension KeyboardInputRow {
init(_ row: [String]) {
self = row.map { KeyboardInput($0) }
}
func characters(for casing: KeyboardCasing = .lowercased) -> [String] {
map { $0.character(for: casing) }
}
}
/**
This typealias represents a list of keyboard input rows.
*/
public typealias KeyboardInputRows = [KeyboardInputRow]
public extension KeyboardInputRows {
init(_ rows: [[String]]) {
self = rows.map { KeyboardInputRow($0) }
}
func characters(for casing: KeyboardCasing = .lowercased) -> [[String]] {
map { $0.characters(for: casing) }
}
}
| mit |
Aster0id/Swift-StudyNotes | Swift-StudyNotes/AppDelegate.swift | 1 | 941 | //
// AppDelegate.swift
// Swift-StudyNotes
//
// Created by 牛萌 on 15/5/14.
// Copyright (c) 2015年 Aster0id.Team. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var l1s1 = Lesson1Section1()
l1s1.run(false)
var l2s1 = Lesson2Section1()
l2s1.run(false)
var l2s2 = Lesson2Section2()
l2s2.run(false)
var l2s3 = Lesson2Section3()
l2s3.run(false)
var l2s4 = Lesson2Section4()
l2s4.run(false)
var l2s5 = Lesson2Section5()
l2s5.run(false)
var l2s6 = Lesson2Section6()
l2s6.run(true)
return true
}
}
| mit |
toymachiner62/myezteam-ios | Myezteam/Myezteam/EventTableViewCell.swift | 1 | 666 | //
// EventTableViewCell.swift
// Myezteam
//
// Created by Caflisch, Thomas J. (Tom) on 11/18/15.
// Copyright (c) 2015 Tom Caflisch. All rights reserved.
//
import UIKit
class EventTableViewCell: UITableViewCell {
// MARK: Properties
@IBOutlet weak var gameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var teamLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit |
thisIsAndrewH/Distractification-iOS | Pods/LicensesKit/LicensesKitTests/LicensesKitTests.swift | 2 | 920 | //
// LicensesKitTests.swift
// LicensesKitTests
//
// Created by Matthew Wyskiel on 9/29/14.
// Copyright (c) 2014 Matthew Wyskiel. All rights reserved.
//
import UIKit
import XCTest
class LicensesKitTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
hoowang/WKRefreshDemo | RefreshToolkit/Other/ScrollViewCategory.swift | 1 | 971 | //
// ScrollViewCategory.swift
// WKRefreshDemo
//
// Created by hooge on 16/4/28.
// Copyright © 2016年 hooge. All rights reserved.
//
import UIKit
public extension UIScrollView{
var wk_InsetTop: CGFloat {
set {
var insets: UIEdgeInsets = self.contentInset
insets.top = newValue
self.contentInset = insets
}
get {
return self.contentInset.top
}
}
var wk_InsetBottom: CGFloat {
set {
var insets: UIEdgeInsets = self.contentInset
insets.bottom = newValue
self.contentInset = insets
}
get {
return self.contentInset.top
}
}
var wk_OffsetY: CGFloat {
set {
var offset: CGPoint = self.contentOffset
offset.y = newValue
self.contentOffset = offset
}
get {
return self.contentOffset.y
}
}
} | mit |
NAHCS/UnityKit | UnityKit/NodeComponent.swift | 1 | 492 | //
// NodeComponent.swift
// UnityKit
//
// Created by Jak Tiano on 1/29/17.
// Copyright © 2017 Creationism. All rights reserved.
//
import GameplayKit
/**
Subclass of `GameComponent` that specifically contains an SKNode to be added to
the scene hierarchy when added to an entity.
*/
open class NodeComponent: GameComponent {
/// An SKNode that will be parented to owning entity.
internal var node: SKNode? // TODO: Determine if this can be seen in subclasses in other modules
}
| mit |
karyjan/KMediaPlayer | KMediaPlayer/VolumeView.swift | 1 | 1691 | //
// VolumeView.swift
// MobilePlayer
//
// Created by Toygar Dündaralp on 25/06/15.
// Copyright (c) 2015 MovieLaLa. All rights reserved.
//
import UIKit
import MediaPlayer
private let defaultIncreaseVolumeTintColor = UIColor.blackColor()
private let defaultReduceVolumeTintColor = UIColor.blackColor()
class VolumeView: UIView {
let volumeSlider = MPVolumeView(frame: CGRect(x: -22, y: 50, width: 110, height: 50))
let increaseVolumeImage = UIImageView(frame: CGRect(x: 10, y: 0, width: 20, height: 20))
let reduceVolumeImage = UIImageView(frame: CGRect(x: 10, y: 130, width: 20, height: 20))
init(
increaseVolumeTintColor: UIColor = defaultIncreaseVolumeTintColor,
reduceVolumeTintColor: UIColor = defaultReduceVolumeTintColor) {
super.init(frame: CGRectZero)
layer.cornerRadius = 5
layer.borderColor = UIColor.grayColor().CGColor
layer.borderWidth = 0.5
layer.masksToBounds = true
backgroundColor = UIColor.whiteColor()
volumeSlider.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
volumeSlider.showsRouteButton = false
addSubview(volumeSlider)
increaseVolumeImage.contentMode = .ScaleAspectFit;
increaseVolumeImage.image = UIImage(named: "MLIncreaseVolume")
increaseVolumeImage.tintColor = increaseVolumeTintColor
addSubview(increaseVolumeImage)
reduceVolumeImage.contentMode = .ScaleAspectFit;
reduceVolumeImage.image = UIImage(named: "MLReduceVolume")
reduceVolumeImage.tintColor = reduceVolumeTintColor
addSubview(reduceVolumeImage)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 |
natecook1000/swift-compiler-crashes | crashes-duplicates/16577-swift-sourcemanager-getmessage.swift | 11 | 222 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
[ h: {
extension Array {
{
}
struct A {
class
case ,
| mit |
swojtyna/starsview | StarsView/StarsView/JSONResult.swift | 1 | 425 | //
// JSONResult.swift
// StarsView
//
// Created by Sebastian Wojtyna on 29/08/16.
// Copyright © 2016 Sebastian Wojtyna. All rights reserved.
//
import Foundation
protocol JSONResult: Result { }
extension JSONResult {
func parseData(data: NSData) -> [String: AnyObject]? {
let result = try? NSJSONSerialization.JSONObjectWithData(data, options: [])
return result as? [String: AnyObject]
}
}
| agpl-3.0 |
Jamol/Nutil | Sources/http/Http1xResponse.swift | 1 | 6473 | //
// Http1xResponse.swift
// Nutil
//
// Created by Jamol Bao on 11/12/16.
// Copyright © 2015 Jamol Bao. All rights reserved.
//
import Foundation
class Http1xResponse : TcpConnection, HttpResponse, HttpParserDelegate, MessageSender {
fileprivate let parser = HttpParser()
fileprivate var version = "HTTP/1.1"
enum State: Int, Comparable {
case idle
case receivingRequest
case waitForResponse
case sendingHeader
case sendingBody
case completed
case error
case closed
}
fileprivate var state = State.idle
fileprivate var cbData: DataCallback?
fileprivate var cbHeader: EventCallback?
fileprivate var cbRequest: EventCallback?
fileprivate var cbReponse: EventCallback?
fileprivate var cbError: ErrorCallback?
fileprivate var cbSend: EventCallback?
fileprivate var message = HttpMessage()
override init() {
super.init()
parser.delegate = self
message.sender = self
}
convenience init(version: String) {
self.init()
self.version = version
}
fileprivate func setState(_ state: State) {
self.state = state
}
fileprivate func cleanup() {
super.close()
}
override func attachFd(_ fd: SOCKET_FD, _ initData: UnsafeRawPointer?, _ initSize: Int) -> KMError {
setState(.receivingRequest)
return super.attachFd(fd, initData, initSize)
}
func addHeader(_ name: String, _ value: String) {
message.addHeader(name, value)
}
func addHeader(_ name: String, _ value: Int) {
message.addHeader(name, value)
}
func sendResponse(_ statusCode: Int, _ desc: String?) -> KMError {
infoTrace("Http1xResponse.sendResponse, status=\(statusCode), state=\(state)")
if state != .waitForResponse {
return .invalidState
}
let rsp = message.buildHeader(statusCode, desc, version)
setState(.sendingHeader)
let ret = send(rsp)
if ret < 0 {
errTrace("Http1xResponse.sendResponse, failed to send response")
setState(.error)
return .sockError
} else if sendBufferEmpty() {
if message.hasBody {
setState(.sendingBody)
socket.async {
self.cbSend?()
}
} else {
setState(.completed)
socket.async {
self.cbReponse?()
}
}
}
return .noError
}
func sendData(_ data: UnsafeRawPointer?, _ len: Int) -> Int {
if !sendBufferEmpty() || state != .sendingBody {
return 0
}
let ret = message.sendData(data, len)
if ret >= 0 {
if message.isCompleted && sendBufferEmpty() {
setState(.completed)
socket.async {
self.cbReponse?()
}
}
} else if ret < 0 {
setState(.error)
}
return ret
}
func sendString(_ str: String) -> Int {
return sendData(UnsafePointer<UInt8>(str), str.utf8.count)
}
override func reset() {
super.reset()
parser.reset()
message.reset()
setState(.receivingRequest)
}
override func close() {
cleanup()
}
override func handleInputData(_ data: UnsafeMutablePointer<UInt8>, _ len: Int) -> Bool {
let ret = parser.parse(data: data, len: len)
if ret != len {
warnTrace("Http1xResponse.handleInputData, ret=\(ret), len=\(len)")
}
return true
}
override func handleOnSend() {
super.handleOnSend()
if state == .sendingHeader {
if message.hasBody {
setState(.sendingBody)
} else {
setState(.completed)
cbReponse?()
return
}
cbSend?()
} else if state == .sendingBody {
if message.isCompleted {
setState(.completed)
cbReponse?()
return
}
cbSend?()
}
}
override func handleOnError(err: KMError) {
infoTrace("Http1xResponse.handleOnError, err=\(err)")
onHttpError(err: err)
}
func onHttpData(data: UnsafeMutableRawPointer, len: Int) {
//infoTrace("onData, len=\(len), total=\(parser.bodyBytesRead)")
cbData?(data, len)
}
func onHttpHeaderComplete() {
infoTrace("Http1xResponse.onHeaderComplete, method=\(parser.method), url=\(parser.urlString)")
cbHeader?()
}
func onHttpComplete() {
infoTrace("Http1xResponse.onRequestComplete, bodyReceived=\(parser.bodyBytesRead)")
setState(.waitForResponse)
cbRequest?()
}
func onHttpError(err: KMError) {
infoTrace("Http1xResponse.onHttpError")
if state < State.completed {
setState(.error)
cbError?(err)
} else {
setState(.closed)
}
}
}
extension Http1xResponse {
@discardableResult func onData(_ cb: @escaping (UnsafeMutableRawPointer, Int) -> Void) -> Self {
cbData = cb
return self
}
@discardableResult func onHeaderComplete(_ cb: @escaping () -> Void) -> Self {
cbHeader = cb
return self
}
@discardableResult func onRequestComplete(_ cb: @escaping () -> Void) -> Self {
cbRequest = cb
return self
}
@discardableResult func onResponseComplete(_ cb: @escaping () -> Void) -> Self {
cbReponse = cb
return self
}
@discardableResult func onError(_ cb: @escaping (KMError) -> Void) -> Self {
cbError = cb
return self
}
@discardableResult func onSend(_ cb: @escaping () -> Void) -> Self {
cbSend = cb
return self
}
func getMethod() -> String {
return parser.method
}
func getPath() -> String {
return parser.url.path
}
func getVersion() -> String {
return parser.version
}
func getHeader(_ name: String) -> String? {
return parser.headers[name]
}
func getParam(_ name: String) -> String? {
return nil
}
}
| mit |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Core/Extensions/NSDictionary+Additions.swift | 1 | 1643 | import Foundation
extension NSDictionary {
func toJsonString() -> String {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
if let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) {
return jsonString
}
return ""
} catch {
return error.localizedDescription
}
}
func parseToQuery() -> String {
if !NSDictionary.isNullOrEmpty(self) {
var parametersString = ""
for (key, value) in self {
if let key = key as? String,
let value = value as? String {
parametersString += key + "=" + value + "&"
}
}
let range = parametersString.index(before: parametersString.endIndex)
parametersString = String(parametersString[..<range])
return parametersString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
} else {
return ""
}
}
func parseToLiteral() -> [String: Any] {
var anyDict = [String: Any]()
for (key, value) in self {
if let keyValue = key as? String {
anyDict[keyValue] = value
}
}
return anyDict
}
static func isNullOrEmpty(_ value: NSDictionary?) -> Bool {
return value == nil || value?.count == 0
}
func isKeyValid(_ dictKey: String) -> Bool {
let dictValue: Any? = self[dictKey]
return (dictValue == nil || dictValue is NSNull) ? false : true
}
}
| mit |
infobip/mobile-messaging-sdk-ios | Classes/Vendor/PSOperations/State.swift | 1 | 1834 | //
// State.swift
// PSOperations
//
// Created by Matt McMurry on 6/23/17.
// Copyright © 2017 Pluralsight. All rights reserved.
//
import Foundation
internal enum State: Int, Comparable {
static func <(lhs: State, rhs: State) -> Bool {
return lhs.rawValue < rhs.rawValue
}
static func ==(lhs: State, rhs: State) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// The initial state of an `Operation`.
case initialized
/// The `Operation` is ready to begin evaluating conditions.
case pending
/// The `Operation` is evaluating conditions.
case evaluatingConditions
/**
The `Operation`'s conditions have all been satisfied, and it is ready
to execute.
*/
case ready
/// The `Operation` is executing.
case executing
/**
Execution of the `Operation` has finished, but it has not yet notified
the queue of this.
*/
case finishing
/// The `Operation` has finished executing.
case finished
func canTransitionToState(_ target: State, operationIsCancelled cancelled: Bool) -> Bool {
switch (self, target) {
case (.initialized, .pending):
return true
case (.pending, .evaluatingConditions):
return true
case (.pending, .finishing) where cancelled:
return true
case (.pending, .ready):
return true
case (.evaluatingConditions, .ready):
return true
case (.ready, .executing):
return true
case (.ready, .finishing):
return true
case (.executing, .finishing):
return true
case (.finishing, .finished):
return true
default:
return false
}
}
}
| apache-2.0 |
ArslanBilal/GesturesDemo | GesturesDemo/GesturesDemo/PinchViewController.swift | 1 | 1666 | //
// PinchViewController.swift
// GesturesDemo
//
// Created by Bilal Arslan on 02/02/15.
// Copyright (c) 2015 Bilal Arslan. All rights reserved.
//
import UIKit
class PinchViewController: UIViewController {
@IBOutlet var testView:UIView!
@IBOutlet var label: UILabel!
override func viewDidLoad() {
/// Tab Changing Swipe Gestures
var leftSwipeGesture = UISwipeGestureRecognizer(target: self, action: "jumpToOtherTab:")
leftSwipeGesture.direction = UISwipeGestureRecognizerDirection.Left
view.addGestureRecognizer(leftSwipeGesture)
var rightSwipeGesture = UISwipeGestureRecognizer(target: self, action: "jumpToOtherTab:")
rightSwipeGesture.direction = UISwipeGestureRecognizerDirection.Right
view.addGestureRecognizer(rightSwipeGesture)
var pinchGesture = UIPinchGestureRecognizer(target: self, action: "handlePinchWithGestureRecognizer:")
testView.addGestureRecognizer(pinchGesture)
}
func handlePinchWithGestureRecognizer(gestureRecognizer: UIPinchGestureRecognizer) -> Void {
self.view.bringSubviewToFront(label)
self.testView.transform = CGAffineTransformScale(self.testView.transform, gestureRecognizer.scale, gestureRecognizer.scale)
gestureRecognizer.scale = 1.0;
}
func jumpToOtherTab(gestureRecognizer: UISwipeGestureRecognizer) -> Void {
if gestureRecognizer.direction == UISwipeGestureRecognizerDirection.Left
{
tabBarController?.selectedIndex = 4
}
else
{
tabBarController?.selectedIndex = 2
}
}
}
| mit |
sarahspins/Loop | WatchApp Extension/Models/WatchContext.swift | 1 | 2846 | //
// WatchContext.swift
// Naterade
//
// Created by Nathan Racklyeft on 11/25/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
final class WatchContext: NSObject, RawRepresentable {
typealias RawValue = [String: AnyObject]
private let version = 2
var preferredGlucoseUnit: HKUnit?
var glucose: HKQuantity?
var glucoseTrend: GlucoseTrend?
var eventualGlucose: HKQuantity?
var glucoseDate: NSDate?
var loopLastRunDate: NSDate?
var lastNetTempBasalDose: Double?
var lastNetTempBasalDate: NSDate?
var recommendedBolusDose: Double?
var COB: Double?
var IOB: Double?
var reservoir: Double?
var reservoirPercentage: Double?
var batteryPercentage: Double?
override init() {
super.init()
}
required init?(rawValue: RawValue) {
super.init()
guard rawValue["v"] as? Int == version else {
return nil
}
if let unitString = rawValue["gu"] as? String {
let unit = HKUnit(fromString: unitString)
preferredGlucoseUnit = unit
if let glucoseValue = rawValue["gv"] as? Double {
glucose = HKQuantity(unit: unit, doubleValue: glucoseValue)
}
if let glucoseValue = rawValue["egv"] as? Double {
eventualGlucose = HKQuantity(unit: unit, doubleValue: glucoseValue)
}
}
if let rawTrend = rawValue["gt"] as? Int {
glucoseTrend = GlucoseTrend(rawValue: rawTrend)
}
glucoseDate = rawValue["gd"] as? NSDate
IOB = rawValue["iob"] as? Double
reservoir = rawValue["r"] as? Double
reservoirPercentage = rawValue["rp"] as? Double
batteryPercentage = rawValue["bp"] as? Double
loopLastRunDate = rawValue["ld"] as? NSDate
lastNetTempBasalDose = rawValue["ba"] as? Double
lastNetTempBasalDate = rawValue["bad"] as? NSDate
recommendedBolusDose = rawValue["rbo"] as? Double
COB = rawValue["cob"] as? Double
}
var rawValue: RawValue {
var raw: [String: AnyObject] = [
"v": version
]
raw["ba"] = lastNetTempBasalDose
raw["bad"] = lastNetTempBasalDate
raw["bp"] = batteryPercentage
raw["cob"] = COB
if let unit = preferredGlucoseUnit {
raw["egv"] = eventualGlucose?.doubleValueForUnit(unit)
raw["gu"] = unit.unitString
raw["gv"] = glucose?.doubleValueForUnit(unit)
}
raw["gt"] = glucoseTrend?.rawValue
raw["gd"] = glucoseDate
raw["iob"] = IOB
raw["ld"] = loopLastRunDate
raw["r"] = reservoir
raw["rbo"] = recommendedBolusDose
raw["rp"] = reservoirPercentage
return raw
}
}
| apache-2.0 |
KalpeshTalkar/KPhotoPickerController | KimagePickerExample/AppDelegate.swift | 1 | 6131 | //
// AppDelegate.swift
// KimagePickerExample
//
// Created by Kalpesh Talkar on 01/01/16.
// Copyright © 2016 Kalpesh Talkar. All rights reserved.
//
import UIKit
import CoreData
@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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.kalpesh.KimagePickerExample" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("KimagePickerExample", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit |
Drakken-Engine/GameEngine | DrakkenEngine/dRenderer.swift | 1 | 3154 | //
// Renderer.swift
// Underground - Survivors
//
// Created by Allison Lindner on 03/09/15.
// Copyright © 2015 Allison Lindner. All rights reserved.
//
import Metal
import MetalKit
internal class dRenderer {
private var _rFactory: dRendererFactory?
private var _cBuffer: MTLCommandBuffer!
private var _rcEncoders: [Int : MTLRenderCommandEncoder] = [:]
private var _nextIndex: Int = 0
internal func startFrame(_ texture: MTLTexture) -> Int {
_cBuffer = dCore.instance.cQueue.makeCommandBuffer()
_cBuffer.enqueue()
if _rFactory == nil {
_rFactory = dRendererFactory()
}
let index = _nextIndex
let encoder = _cBuffer.makeRenderCommandEncoder(descriptor: _rFactory!.buildRenderPassDescriptor(texture))
encoder.setDepthStencilState(_rFactory?.buildDepthStencil())
encoder.setFrontFacing(.counterClockwise)
encoder.setCullMode(.back)
encoder.setFragmentSamplerState(_rFactory?.buildSamplerState(), at: 0)
_rcEncoders[index] = encoder
_nextIndex += 1
return index
}
internal func endFrame(_ id: Int) {
let encoder: MTLRenderCommandEncoder = _rcEncoders[id]!
encoder.endEncoding()
_rcEncoders.remove(at: _rcEncoders.index(forKey: id)!)
}
internal func encoder(withID id: Int) -> MTLRenderCommandEncoder {
return self._rcEncoders[id]!
}
internal func present(_ drawable: CAMetalDrawable) {
_cBuffer.present(drawable)
_cBuffer.commit()
_rcEncoders.removeAll()
}
internal func bind(_ buffer: dBufferable, encoderID: Int) {
if let encoder = _rcEncoders[encoderID] {
switch buffer.bufferType {
case .vertex:
encoder.setVertexBuffer(
buffer.buffer, offset: buffer.offset, at: buffer.index
)
case .fragment:
encoder.setFragmentBuffer(
buffer.buffer, offset: buffer.offset, at: buffer.index
)
}
} else {
fatalError("Invalid Encoder ID")
}
}
internal func bind(_ materialTexture: dMaterialTexture, encoderID: Int) {
if let encoder = _rcEncoders[encoderID] {
encoder.setFragmentTexture(materialTexture.texture.getTexture(), at: materialTexture.index)
} else {
fatalError("Invalid Encoder ID")
}
}
internal func bind(_ material: dMaterialData, encoderID: Int) {
if let encoder = _rcEncoders[encoderID] {
encoder.setRenderPipelineState(material.shader.rpState)
}
for buffer in material.buffers {
self.bind(buffer, encoderID: encoderID)
}
for texture in material.textures {
self.bind(texture, encoderID: encoderID)
}
}
internal func draw(_ mesh: dMeshData, encoderID: Int, modelMatrixBuffer: dBufferable) {
for buffer in mesh.buffers {
self.bind(buffer, encoderID: encoderID)
}
self.bind(modelMatrixBuffer, encoderID: encoderID)
if let encoder = _rcEncoders[encoderID] {
encoder.drawIndexedPrimitives(type: .triangle,
indexCount: mesh.indicesCount!,
indexType: .uint32,
indexBuffer: mesh.indicesBuffer!.buffer,
indexBufferOffset: 0,
instanceCount: modelMatrixBuffer.count)
}
}
}
| gpl-3.0 |
NickChenHao/PhotoBrowser | PhotoBrowser/PhotoBrowser/Classes/Home/CHFlowLayout.swift | 1 | 834 | //
// CHFlowLayout.swift
// PhotoBrowser
//
// Created by nick on 16/4/28.
// Copyright © 2016年 nick. All rights reserved.
//
import UIKit
class CHFlowLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
// 1.定义常量
let cols : CGFloat = 3
let margin : CGFloat = 10
// 2.计算item的WH
let itemWH = (UIScreen.mainScreen().bounds.width - (cols + 1) * margin) / cols
// 3.设置布局内容
itemSize = CGSize(width: itemWH, height: itemWH)
minimumInteritemSpacing = 0
minimumLineSpacing = margin
// 4.设置collectionView的属性
collectionView?.contentInset = UIEdgeInsets(top: margin + 64, left: margin, bottom: margin, right: margin)
}
}
| apache-2.0 |
cbaker6/iOS-csr-swift | CertificateSigningRequest/Classes/CertificateSigningRequestConstants.swift | 3 | 6716 | //
// CertificateSigningRequestConstants.swift
// CertificateSigningRequest
//
// Created by Corey Baker on 10/8/17.
// Copyright © 2017 Network Reconnaissance Lab. All rights reserved.
//
import Foundation
import CommonCrypto
// Use e.g., https://misc.daniel-marschall.de/asn.1/oid-converter/online.php to convert OID (OBJECT IDENTIFIER) to ASN.1 DER hex forms
//Guide to translate OID's to bytes for ANS.1 (Look at comment section on page): https://msdn.microsoft.com/en-us/library/bb540809(v=vs.85).aspx
/* RSA */
let OBJECT_rsaEncryptionNULL:[UInt8] = [0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00]
// See: http://oid-info.com/get/1.2.840.113549.1.1.5
let SEQUENCE_OBJECT_sha1WithRSAEncryption:[UInt8] = [0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 1, 1, 5, 0x05, 0x00]
// See: http://oid-info.com/get/1.2.840.113549.1.1.11
let SEQUENCE_OBJECT_sha256WithRSAEncryption:[UInt8] = [0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 1, 1, 0x0B, 0x05, 0x00]
// See: http://oid-info.com/get/1.2.840.113549.1.1.13
let SEQUENCE_OBJECT_sha512WithRSAEncryption:[UInt8] = [0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 1, 1, 0x0D, 0x05, 0x00]
/* EC */
let OBJECT_ecEncryptionNULL:[UInt8] = [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07]
let OBJECT_ecPubicKey:[UInt8] = [0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01]
let SEQUENCE_OBJECT_sha1WithECEncryption:[UInt8] = [0x30, 0x0A, 0x06, 0x07, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01]
// See: http://www.oid-info.com/get/1.2.840.10045.4.3.2
let SEQUENCE_OBJECT_sha256WithECEncryption:[UInt8] = [0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02]
// See: http://oid-info.com/get/1.2.840.10045.4.3.4
let SEQUENCE_OBJECT_sha512WithECEncryption:[UInt8] = [0x30, 0x0A, 0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04]
//Enums
public enum KeyAlgorithm {
case rsa(signatureType: signature), ec(signatureType: signature)
@available(iOS 10, macCatalyst 13.0, macOS 10.12, *)
public var secKeyAttrType: CFString {
let result: CFString
switch self {
case .rsa: result = kSecAttrKeyTypeRSA
case .ec: result = kSecAttrKeyTypeECSECPrimeRandom
}
return result
}
@available(iOS, deprecated: 10.0)
public var secKeyAttrTypeiOS9: CFString {
let result: CFString
switch self {
case .rsa: result = kSecAttrKeyTypeRSA
case .ec: result = kSecAttrKeyTypeEC
}
return result
}
public var availableKeySizes: [Int] {
let result: [Int]
switch self {
case .rsa: result = [512, 1024, 2048]
case .ec: result = [256]
}
return result
}
public enum signature {
case sha1, sha256, sha512
}
public var type:String{
let result: String
switch self {
case .rsa(signatureType: .sha1), .rsa(signatureType: .sha256), .rsa(signatureType: .sha512):
result = "RSA"
case .ec(signatureType: .sha1), .ec(signatureType: .sha256), .ec(signatureType: .sha512):
result = "EC"
}
return result
}
@available(iOS 10, macCatalyst 13.0, macOS 10.12, *)
public var signatureAlgorithm: SecKeyAlgorithm {
let result: SecKeyAlgorithm
switch self {
case .rsa(signatureType: .sha1):
result = .rsaSignatureMessagePKCS1v15SHA1
case .rsa(signatureType: .sha256):
result = .rsaSignatureMessagePKCS1v15SHA256
case .rsa(signatureType: .sha512):
result = .rsaSignatureMessagePKCS1v15SHA512
case .ec(signatureType: .sha1):
result = .ecdsaSignatureMessageX962SHA1
case .ec(signatureType: .sha256):
result = .ecdsaSignatureMessageX962SHA256
case .ec(signatureType: .sha512):
result = .ecdsaSignatureMessageX962SHA512
}
return result
}
@available(iOS, deprecated: 10.0)
public var digestLength: Int {
let result: Int32
switch self {
//case .rsa(signatureType: .md5), .ec(signatureType: .md5): result = CC_MD5_DIGEST_LENGTH
case .rsa(signatureType: .sha1), .ec(signatureType: .sha1): result = CC_SHA1_DIGEST_LENGTH
//case .rsa(signatureType: .sha224), .ec(signatureType: .sha224): result = CC_SHA224_DIGEST_LENGTH
case .rsa(signatureType: .sha256), .ec(signatureType: .sha256): result = CC_SHA256_DIGEST_LENGTH
//case .rsa(signatureType: .sha384), .ec(signatureType: .sha384): result = CC_SHA384_DIGEST_LENGTH
case .rsa(signatureType: .sha512), .ec(signatureType: .sha512): result = CC_SHA512_DIGEST_LENGTH
}
return Int(result)
}
@available(iOS, deprecated: 10.0)
public var padding: SecPadding {
let result: SecPadding
switch self {
case .rsa(signatureType: .sha1), .ec(signatureType: .sha1):
result = SecPadding.PKCS1SHA1
case .rsa(signatureType: .sha256), .ec(signatureType: .sha256):
result = SecPadding.PKCS1SHA256
case .rsa(signatureType: .sha512), .ec(signatureType: .sha512):
result = SecPadding.PKCS1SHA512
}
return result
}
var sequenceObjectEncryptionType: [UInt8]{
let result:[UInt8]
switch self {
case .rsa(signatureType: .sha1):
result = SEQUENCE_OBJECT_sha1WithRSAEncryption
case .rsa(signatureType: .sha256):
result = SEQUENCE_OBJECT_sha256WithRSAEncryption
case .rsa(signatureType: .sha512):
result = SEQUENCE_OBJECT_sha512WithRSAEncryption
case .ec(signatureType: .sha1):
result = SEQUENCE_OBJECT_sha1WithECEncryption
case .ec(signatureType: .sha256):
result = SEQUENCE_OBJECT_sha256WithECEncryption
case .ec(signatureType: .sha512):
result = SEQUENCE_OBJECT_sha512WithECEncryption
}
return result
}
var objectEncryptionKeyType: [UInt8]{
let result:[UInt8]
switch self {
case .rsa(signatureType: .sha1), .rsa(signatureType: .sha256), .rsa(signatureType: .sha512):
result = OBJECT_rsaEncryptionNULL
case .ec(signatureType: .sha1), .ec(signatureType: .sha256), .ec(signatureType: .sha512):
result = OBJECT_ecEncryptionNULL
}
return result
}
}
| mit |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV1/Models/Configuration.swift | 1 | 3565 | /**
* (C) Copyright IBM Corp. 2016, 2020.
*
* 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
/**
A custom configuration for the environment.
*/
public struct Configuration: Codable, Equatable {
/**
The unique identifier of the configuration.
*/
public var configurationID: String?
/**
The name of the configuration.
*/
public var name: String
/**
The creation date of the configuration in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'.
*/
public var created: Date?
/**
The timestamp of when the configuration was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'.
*/
public var updated: Date?
/**
The description of the configuration, if available.
*/
public var description: String?
/**
Document conversion settings.
*/
public var conversions: Conversions?
/**
An array of document enrichment settings for the configuration.
*/
public var enrichments: [Enrichment]?
/**
Defines operations that can be used to transform the final output JSON into a normalized form. Operations are
executed in the order that they appear in the array.
*/
public var normalizations: [NormalizationOperation]?
/**
Object containing source parameters for the configuration.
*/
public var source: Source?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case configurationID = "configuration_id"
case name = "name"
case created = "created"
case updated = "updated"
case description = "description"
case conversions = "conversions"
case enrichments = "enrichments"
case normalizations = "normalizations"
case source = "source"
}
/**
Initialize a `Configuration` with member variables.
- parameter name: The name of the configuration.
- parameter description: The description of the configuration, if available.
- parameter conversions: Document conversion settings.
- parameter enrichments: An array of document enrichment settings for the configuration.
- parameter normalizations: Defines operations that can be used to transform the final output JSON into a
normalized form. Operations are executed in the order that they appear in the array.
- parameter source: Object containing source parameters for the configuration.
- returns: An initialized `Configuration`.
*/
public init(
name: String,
description: String? = nil,
conversions: Conversions? = nil,
enrichments: [Enrichment]? = nil,
normalizations: [NormalizationOperation]? = nil,
source: Source? = nil
)
{
self.name = name
self.description = description
self.conversions = conversions
self.enrichments = enrichments
self.normalizations = normalizations
self.source = source
}
}
| apache-2.0 |
gengzhenxing/SwiftDemo | MyDemo/MyHomeTableViewController.swift | 1 | 2579 | //
// MyHomeTableViewController.swift
// MyDemo
//
// Created by gengzhenxing on 15/12/27.
// Copyright © 2015年 gengzhenxing. All rights reserved.
//
import UIKit
import Alamofire
class MyHomeTableViewController: UITableViewController {
var result = [HomeInfoModel]()
var myCell:MyHomeTableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
self.getHomeInfo()
self.tableView.tableFooterView = UIView()
myCell = tableView.dequeueReusableCellWithIdentifier("MyHomeTableViewCell") as! MyHomeTableViewCell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - get network info
private func getHomeInfo() {
Alamofire.request(.GET, "http://news-at.zhihu.com/api/4/news/latest", parameters: nil)
.responseJSON { response in
if let JSON = response.result.value {
if let array:[Dictionary<String,AnyObject>] = JSON["stories"] as? [Dictionary<String,AnyObject>] {
self.result = array.map({ (item) -> HomeInfoModel in
let model = HomeInfoModel(dictionary:item)
return model
})
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return result.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:MyHomeTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyHomeTableViewCell", forIndexPath: indexPath) as! MyHomeTableViewCell
cell.configCellWithModel(self.result[indexPath.row])
return cell
}
// MARK: Table view delegate
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let model = result[indexPath.row]
myCell.homeLabel.text = model.title
return myCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height + 1
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
| mit |
ontouchstart/swift3-playground | Shapes.playgroundbook/Contents/Sources/PlaygroundAPI/Grid.swift | 1 | 3908 | //
// Grid.swift
// Drawing
//
// Created by Ken Orr on 4/7/16.
// Copyright © 2016 Apple, Inc. All rights reserved.
//
import UIKit
internal class Grid {
internal var show = false {
didSet {
backingView.isHidden = !show
}
}
internal var backingView = GridView()
private var majorGridColor: Color {
get {
return backingView.majorGridColor
}
set {
backingView.minorGridColor = majorGridColor
}
}
private var minorGridColor: Color {
get {
return backingView.minorGridColor
}
set {
backingView.minorGridColor = minorGridColor
}
}
internal init() {
// make sure the grids visibility matches the show property's default.
backingView.isHidden = !show
}
}
internal class GridView: UIView {
internal var offsetToCenterInScreenPoints = Point(x: 0, y: 0)
internal var gridStrideInPoints = 10.0
private var majorGridColor = Color(white: 0.85, alpha: 1.0) {
didSet {
setNeedsDisplay()
}
}
private var minorGridColor = Color(white: 0.95, alpha: 1.0) {
didSet {
setNeedsDisplay()
}
}
private init() {
super.init(frame: CGRect.zero)
self.isOpaque = false
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
drawGridLinesFor(axis: .x, dirtyRect: rect)
drawGridLinesFor(axis: .y, dirtyRect: rect)
}
private func drawGridLinesFor(axis: Axis, dirtyRect: CGRect) {
let centerPoint: Double
switch axis {
case .x:
centerPoint = offsetToCenterInScreenPoints.x
break
case .y:
centerPoint = offsetToCenterInScreenPoints.y
break
}
let firstStrokeWidth: CGFloat = 3.0
let otherThanFirstStrokeWidth: CGFloat = 1.0
var currentPoint = CGFloat(centerPoint)
var keepGoing = true
var iteration = 0
while (keepGoing) {
if iteration % 10 == 0 || (iteration + 1) % 10 == 0{
majorGridColor.uiColor.set()
} else {
minorGridColor.uiColor.set()
}
let strokeWidth = iteration == 0 ? firstStrokeWidth : otherThanFirstStrokeWidth
let x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat
switch axis {
case .x:
x = currentPoint - strokeWidth/2.0
y = dirtyRect.minY
width = strokeWidth
height = dirtyRect.height
break
case .y:
x = dirtyRect.minX
y = currentPoint - strokeWidth/2.0
width = dirtyRect.width
height = strokeWidth
break
}
UIRectFillUsingBlendMode(CGRect(x: x, y: y, width: width, height: height), .darken)
iteration += 1
let multiplier = iteration % 2 == 0 ? 1.0 : -1.0
currentPoint += CGFloat(gridStrideInPoints * (Double(iteration) * multiplier))
switch axis {
case .x:
keepGoing = dirtyRect.minX <= currentPoint && currentPoint <= dirtyRect.maxX
break
case .y:
keepGoing = dirtyRect.minY <= currentPoint && currentPoint <= dirtyRect.maxY
break
}
}
}
private enum Axis {
case x
case y
}
}
| mit |
turekj/ReactiveTODO | ReactiveTODOTests/DataAccess/Impl/TODONoteDataAccessObjectSpec.swift | 1 | 6702 | @testable import ReactiveTODO
import Nimble
import Quick
import RealmSwift
class TODONoteDataAccessObjectSpec: QuickSpec {
override func spec() {
describe("TODONoteDataAccessObject") {
Realm.Configuration
.defaultConfiguration
.inMemoryIdentifier = self.name
beforeEach {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
}
afterEach {
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
}
let factory = TODONoteFactoryMock()
let sut = TODONoteDataAccessObject(factory: factory)
context("When creating a TODONote") {
it("Should save created note in database") {
let realm = try! Realm()
factory.guid = "FACTORY_GUID"
factory.completed = true
sut.createTODONote(NSDate(timeIntervalSince1970: 444),
note: "Creanote", priority: Priority.Urgent)
expect(realm.objects(TODONote.self).count).to(equal(1))
expect(realm.objects(TODONote.self).first).toNot(beNil())
expect(realm.objects(TODONote.self).first?.guid)
.to(equal("FACTORY_GUID"))
expect(realm.objects(TODONote.self).first?.date)
.to(equal(NSDate(timeIntervalSince1970: 444)))
expect(realm.objects(TODONote.self).first?.note)
.to(equal("Creanote"))
expect(realm.objects(TODONote.self).first?.priority)
.to(equal(Priority.Urgent))
expect(realm.objects(TODONote.self).first?.completed)
.to(beTrue())
}
it("Should return created note") {
factory.guid = "CREATED_GUID"
factory.completed = true
let result = sut.createTODONote(
NSDate(timeIntervalSince1970: 444),
note: "Creanote",
priority: Priority.Urgent)
expect(result.guid).to(equal("CREATED_GUID"))
expect(result.note).to(equal("Creanote"))
expect(result.date).to(
equal(NSDate(timeIntervalSince1970: 444)))
expect(result.priority).to(equal(Priority.Urgent))
expect(result.completed).to(beTrue())
}
}
context("When returning current TODONotes") {
it("Should return notes that are not complete") {
let realm = try! Realm()
let completedNote = TODONote()
completedNote.guid = "AWESOME_UNIQUE_GUID"
completedNote.date = NSDate(timeIntervalSince1970: 1970)
completedNote.note = "Awesome Note"
completedNote.priority = .Urgent
completedNote.completed = true
let notCompletedNote = TODONote()
notCompletedNote.guid = "AWESOME_UNIQUE_GUID_NOT_COMPLETED"
notCompletedNote.date = NSDate(timeIntervalSince1970: 111)
notCompletedNote.note = "Awesome Not Completed Note"
notCompletedNote.priority = .Low
notCompletedNote.completed = false
try! realm.write {
realm.add(completedNote)
realm.add(notCompletedNote)
}
let notes = sut.getCurrentTODONotes()
expect(notes.count).to(equal(1))
expect(notes.first?.guid)
.to(equal("AWESOME_UNIQUE_GUID_NOT_COMPLETED"))
expect(notes.first?.date)
.to(equal(NSDate(timeIntervalSince1970: 111)))
expect(notes.first?.note)
.to(equal("Awesome Not Completed Note"))
expect(notes.first?.priority).to(equal(Priority.Low))
expect(notes.first?.completed).to(beFalse())
}
it("Should order notes by ascending date") {
let realm = try! Realm()
let firstNote = TODONote()
firstNote.guid = "note_1_date"
firstNote.date = NSDate(timeIntervalSince1970: 222)
firstNote.note = "Note One"
firstNote.priority = .Urgent
firstNote.completed = false
let secondNote = TODONote()
secondNote.guid = "note_2_date"
secondNote.date = NSDate(timeIntervalSince1970: 111)
secondNote.note = "Note Two"
secondNote.priority = .Urgent
secondNote.completed = false
try! realm.write {
realm.add(firstNote)
realm.add(secondNote)
}
let notes = sut.getCurrentTODONotes()
expect(notes.count).to(equal(2))
expect(notes.first?.guid)
.to(equal("note_2_date"))
expect(notes.last?.guid)
.to(equal("note_1_date"))
}
}
context("When marking note as completed") {
it("Should set completed flag to true") {
let realm = try! Realm()
let note = TODONote()
note.guid = "completed_test_guid"
note.date = NSDate(timeIntervalSince1970: 222)
note.note = "Note to complete"
note.priority = .Urgent
note.completed = false
try! realm.write {
realm.add(note)
}
sut.completeTODONote("completed_test_guid")
let noteQuery = realm.objects(TODONote.self)
.filter("guid = 'completed_test_guid'")
expect(noteQuery.count).to(equal(1))
expect(noteQuery.first?.guid)
.to(equal("completed_test_guid"))
expect(noteQuery.first?.completed).to(beTrue())
}
}
}
}
}
| mit |
alokc83/mix-ios-tutes | SideBarProject/SideBarProject/LeftMEnuViewController.swift | 1 | 2646 | //
// LeftMEnuViewController.swift
// SideBarProject
//
// Created by Alok Choudhary on 4/6/16.
// Copyright © 2016 Alok Choudhary. All rights reserved.
//
import UIKit
class LeftMEnuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let tableView = UITableView(frame: CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 54*5), style: UITableViewStyle.Plain)
//tableView.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth
tableView.delegate = self
tableView.dataSource = self
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.bounces = true
tableView.scrollsToTop = false
self.view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UItableView Delegate Method
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//
let cellIdentifier = "menuCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
if(cell == nil){
cell = UITableViewCell.init(style: .Default, reuseIdentifier: cellIdentifier)
cell?.backgroundColor = UIColor.clearColor()
//cell?.textLabel?.font = UIFont.fontNamesForFamilyName("HelveticaNeue")
cell?.textLabel?.textColor = UIColor.blackColor()
cell?.textLabel?.highlightedTextColor = UIColor.whiteColor()
cell?.backgroundView = UIView()
}
var titles = ["Home", "Calendar", "Profile", "Settings", "Log Out"]
//var images = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconProfile"]
cell?.textLabel?.text = titles[indexPath.row]
//cell?.imageView?.image = UIImage(named: images[indexPath.row])
return cell!
}
}
extension RESideMenuDelegate {
}
| bsd-3-clause |
kosicki123/eidolon | Kiosk/Bid Fulfillment/RegistrationPostalZipViewController.swift | 1 | 1063 | import UIKit
class RegistrationPostalZipViewController: UIViewController, RegistrationSubController {
@IBOutlet var zipCodeTextField: TextField!
@IBOutlet var confirmButton: ActionButton!
let finishedSignal = RACSubject()
override func viewDidLoad() {
super.viewDidLoad()
if let bidDetails = self.navigationController?.fulfillmentNav().bidDetails {
zipCodeTextField.text = bidDetails.newUser.zipCode
RAC(bidDetails, "newUser.zipCode") <~ zipCodeTextField.rac_textSignal()
let emailIsValidSignal = RACObserve(bidDetails.newUser, "zipCode").map(isZeroLengthString)
RAC(confirmButton, "enabled") <~ emailIsValidSignal.not()
}
zipCodeTextField.returnKeySignal().subscribeNext({ [weak self] (_) -> Void in
self?.finishedSignal.sendCompleted()
return
})
zipCodeTextField.becomeFirstResponder()
}
@IBAction func confirmTapped(sender: AnyObject) {
finishedSignal.sendCompleted()
}
}
| mit |
nicolastinkl/swift | ListerAProductivityAppBuiltinSwift/Lister/ListDocumentsViewController.swift | 1 | 18809 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Handles displaying a list of available documents for users to open.
*/
import UIKit
import ListerKit
class ListDocumentsViewController: UITableViewController, ListViewControllerDelegate, NewListDocumentControllerDelegate {
// MARK: Types
struct MainStoryboard {
struct ViewControllerIdentifiers {
static let listViewController = "listViewController"
static let listViewNavigationController = "listViewNavigationController"
static let emptyViewController = "emptyViewController"
}
struct TableViewCellIdentifiers {
static let listDocumentCell = "listDocumentCell"
}
struct SegueIdentifiers {
static let newListDocument = "newListDocument"
}
}
var listInfos = ListInfo[]()
var documentMetadataQuery: NSMetadataQuery?
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setNeedsStatusBarAppearanceUpdate()
navigationController.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: List.Color.Gray.colorValue
]
ListCoordinator.sharedListCoordinator.updateDocumentStorageContainerURL()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "handleListColorDidChangeNotification:", name: ListViewController.Notifications.ListColorDidChange.name, object: nil)
notificationCenter.addObserver(self, selector: "handleContentSizeCategoryDidChangeNotification:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
// When the desired storage changes, start the query.
notificationCenter.addObserver(self, selector: "startQuery", name: ListCoordinator.Notifications.StorageDidChange.name, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController.navigationBar.titleTextAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline),
NSForegroundColorAttributeName: List.Color.Gray.colorValue
]
navigationController.navigationBar.tintColor = List.Color.Gray.colorValue
navigationController.toolbar.tintColor = List.Color.Gray.colorValue
tableView.tintColor = List.Color.Gray.colorValue
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setupUserStoragePreferences()
}
// MARK: Lifetime
deinit {
let notificationCenter = NSNotificationCenter.defaultCenter()
// Lister notifications.
notificationCenter.removeObserver(self, name: ListViewController.Notifications.ListColorDidChange.name, object: nil)
notificationCenter.removeObserver(self, name: ListCoordinator.Notifications.StorageDidChange.name, object: nil)
// System notifications.
notificationCenter.removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
notificationCenter.removeObserver(self, name: NSMetadataQueryDidFinishGatheringNotification, object: nil)
notificationCenter.removeObserver(self, name: NSMetadataQueryDidUpdateNotification, object: nil)
}
// MARK: Setup
func selectListWithListInfo(listInfo: ListInfo) {
if !splitViewController { return }
// A shared configuration function for list selection.
func configureListViewController(listViewController: ListViewController) {
if listInfo.isLoaded {
listViewController.configureWithListInfo(listInfo)
}
else {
listInfo.fetchInfoWithCompletionHandler {
listViewController.configureWithListInfo(listInfo)
}
}
listViewController.delegate = self
}
if splitViewController.collapsed {
let listViewController = storyboard.instantiateViewControllerWithIdentifier(MainStoryboard.ViewControllerIdentifiers.listViewController) as ListViewController
configureListViewController(listViewController)
showDetailViewController(listViewController, sender: self)
}
else {
let navigationController = storyboard.instantiateViewControllerWithIdentifier(MainStoryboard.ViewControllerIdentifiers.listViewNavigationController) as UINavigationController
let listViewController = navigationController.topViewController as ListViewController
configureListViewController(listViewController)
splitViewController.viewControllers = [splitViewController.viewControllers[0], UIViewController()]
showDetailViewController(navigationController, sender: self)
}
}
func setupUserStoragePreferences() {
let (storageOption, accountDidChange, cloudAvailable) = AppConfiguration.sharedConfiguration.storageState
if accountDidChange {
notifyUserOfAccountChange()
}
if cloudAvailable {
if storageOption == .NotSet {
promptUserForStorageOption()
}
else {
startQuery()
}
}
else {
AppConfiguration.sharedConfiguration.storageOption = .NotSet
}
}
// MARK: UITableViewDataSource
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return listInfos.count
}
override func tableView(_: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.TableViewCellIdentifiers.listDocumentCell, forIndexPath: indexPath) as ListCell
let listInfo = listInfos[indexPath.row]
cell.label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
cell.listColor.backgroundColor = UIColor.clearColor()
// Show an empty string as the text since it may need to load.
cell.text = ""
// Once the list info has been loaded, update the associated cell's properties.
func infoHandler() {
cell.label.text = listInfo.name
cell.listColor.backgroundColor = listInfo.color!.colorValue
}
if listInfo.isLoaded {
infoHandler()
}
else {
listInfo.fetchInfoWithCompletionHandler(infoHandler)
}
return cell
}
// MARK: UITableViewDelegate
override func tableView(_: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let listInfo = listInfos[indexPath.row]
if listInfo.isLoaded {
selectListWithListInfo(listInfo)
}
else {
listInfo.fetchInfoWithCompletionHandler {
self.selectListWithListInfo(listInfo)
}
}
}
override func tableView(_: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func tableView(_: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// MARK: ListViewControllerDelegate
func listViewControllerDidDeleteList(listViewController: ListViewController) {
if !splitViewController.collapsed {
let emptyViewController = storyboard.instantiateViewControllerWithIdentifier(MainStoryboard.ViewControllerIdentifiers.emptyViewController) as UIViewController
splitViewController.showDetailViewController(emptyViewController, sender: nil)
}
// Make sure to deselect the row for the list document that was open, since we are in the process of deleting it.
tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow(), animated: false)
deleteListAtURL(listViewController.documentURL)
}
// MARK: NewListDocumentControllerDelegate
func newListDocumentController(_: NewListDocumentController, didCreateDocumentWithListInfo listInfo: ListInfo) {
if AppConfiguration.sharedConfiguration.storageOption != .Cloud {
insertListInfo(listInfo) { index in
let indexPathForInsertedRow = NSIndexPath(forRow: index, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPathForInsertedRow], withRowAnimation: .Automatic)
}
}
}
// MARK: UIStoryboardSegue Handling
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject) {
if segue.identifier == MainStoryboard.SegueIdentifiers.newListDocument {
let newListController = segue.destinationViewController as NewListDocumentController
newListController.delegate = self
}
}
// MARK: Convenience
func deleteListAtURL(url: NSURL) {
// Delete the requested document asynchronously.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
ListCoordinator.sharedListCoordinator.deleteFileAtURL(url)
}
// Update the document list and remove the row from the table view.
removeListInfoWithProvider(url) { index in
let indexPathForRemoval = NSIndexPath(forRow: index, inSection: 0)
self.tableView.deleteRowsAtIndexPaths([indexPathForRemoval], withRowAnimation: .Automatic)
}
}
// MARK: List Management
func startQuery() {
documentMetadataQuery?.stopQuery()
if AppConfiguration.sharedConfiguration.storageOption == .Cloud {
startMetadataQuery()
}
else {
startLocalQuery()
}
}
func startLocalQuery() {
let documentsDirectory = ListCoordinator.sharedListCoordinator.documentsDirectory
let defaultManager = NSFileManager.defaultManager()
// Fetch the list documents from container documents directory.
let localDocumentURLs = defaultManager.contentsOfDirectoryAtURL(documentsDirectory, includingPropertiesForKeys: nil, options: .SkipsPackageDescendants, error: nil) as NSURL[]
processURLs(localDocumentURLs)
}
func processURLs(urls: NSURL[]) {
let previousListInfos = listInfos
// Processing metadata items doesn't involve much change in the size of the array, so we want to keep the
// same capacity.
listInfos.removeAll(keepCapacity: true)
sort(urls) { $0.lastPathComponent < $1.lastPathComponent }
for url in urls {
if url.pathExtension == AppConfiguration.listerFileExtension {
insertListInfoWithProvider(url)
}
}
processListInfoDifferences(previousListInfos)
}
func processMetadataItems() {
let previousListInfos = listInfos
// Processing metadata items doesn't involve much change in the size of the array, so we want to keep the
// same capacity.
listInfos.removeAll(keepCapacity: true)
let metadataItems = documentMetadataQuery!.results as NSMetadataItem[]
sort(metadataItems) { lhs, rhs in
return (lhs.valueForAttribute(NSMetadataItemFSNameKey) as String) < (rhs.valueForAttribute(NSMetadataItemFSNameKey) as String)
}
for metadataItem in metadataItems {
insertListInfoWithProvider(metadataItem)
}
processListInfoDifferences(previousListInfos)
}
func startMetadataQuery() {
if !documentMetadataQuery {
let metadataQuery = NSMetadataQuery()
documentMetadataQuery = metadataQuery
documentMetadataQuery!.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
documentMetadataQuery!.predicate = NSPredicate(format: "(%K.pathExtension = %@)", argumentArray: [NSMetadataItemFSNameKey, AppConfiguration.listerFileExtension])
// observe the query
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "handleMetadataQueryUpdates:", name: NSMetadataQueryDidFinishGatheringNotification, object: metadataQuery)
notificationCenter.addObserver(self, selector: "handleMetadataQueryUpdates:", name: NSMetadataQueryDidUpdateNotification, object: metadataQuery)
}
documentMetadataQuery!.startQuery()
}
func handleMetadataQueryUpdates(NSNotification) {
documentMetadataQuery!.disableUpdates()
processMetadataItems()
documentMetadataQuery!.enableUpdates()
}
func processListInfoDifferences(previousListInfo: ListInfo[]) {
var insertionRows = NSIndexPath[]()
var deletionRows = NSIndexPath[]()
for (idx, listInfo) in enumerate(listInfos) {
if let found = find(previousListInfo, listInfo) {
listInfos[idx].color = previousListInfo[found].color
listInfos[idx].name = previousListInfo[found].name
} else {
let indexPath = NSIndexPath(forRow: idx, inSection: 0)
insertionRows.append(indexPath)
}
}
for (idx, listInfo) in enumerate(previousListInfo) {
if let found = find(listInfos, listInfo) {
listInfos[found].color = listInfo.color
listInfos[found].name = listInfo.name
} else {
let indexPath = NSIndexPath(forRow: idx, inSection: 0)
deletionRows.append(indexPath)
}
}
self.tableView.beginUpdates()
self.tableView.deleteRowsAtIndexPaths(deletionRows, withRowAnimation: .Automatic)
self.tableView.insertRowsAtIndexPaths(insertionRows, withRowAnimation: .Automatic)
self.tableView.endUpdates()
}
func insertListInfo(listInfo: ListInfo, completionHandler: (Int -> Void)? = nil) {
listInfos.append(listInfo)
sort(listInfos) { $0.name < $1.name }
let indexOfInsertedInfo = find(listInfos, listInfo)!
completionHandler?(indexOfInsertedInfo)
}
func removeListInfo(listInfo: ListInfo, completionHandler: (Int -> Void)? = nil) {
if let index = find(listInfos, listInfo) {
listInfos.removeAtIndex(index)
completionHandler?(index)
}
}
// ListInfoProvider objects are used to allow us to interact naturally with ListInfo objects that may originate from
// local URLs or NSMetadataItems representing document in the cloud.
func insertListInfoWithProvider(provider: ListInfoProvider, completionHandler: (Int -> Void)? = nil) {
let listInfo = ListInfo(provider: provider)
insertListInfo(listInfo, completionHandler: completionHandler)
}
func removeListInfoWithProvider(provider: ListInfoProvider, completionHandler: (Int -> Void)? = nil) {
let listInfo = ListInfo(provider: provider)
removeListInfo(listInfo, completionHandler: completionHandler)
}
// MARK: Notifications
// The color of the list was changed in the ListViewController, so we need to update the color in our list of documents.
func handleListColorDidChangeNotification(notification: NSNotification) {
let userInfo = notification.userInfo
let rawColor = userInfo[ListViewController.Notifications.ListColorDidChange.colorUserInfoKey] as Int
let url = userInfo[ListViewController.Notifications.ListColorDidChange.URLUserInfoKey] as NSURL
let color = List.Color.fromRaw(rawColor)!
let listInfo = ListInfo(provider: url)
if let index = find(listInfos, listInfo) {
listInfos[index].color = color
let indexPathForRow = NSIndexPath(forRow: index, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPathForRow) as ListCell
cell.listColor.backgroundColor = color.colorValue
}
}
func handleContentSizeCategoryDidChangeNotification(_: NSNotification) {
tableView.setNeedsLayout()
}
// MARK: User Storage Preference Related Alerts
func notifyUserOfAccountChange() {
let title = NSLocalizedString("iCloud Sign Out", comment: "")
let message = NSLocalizedString("You have signed out of the iCloud account previously used to store documents. Sign back in to access those documents.", comment: "")
let okActionTitle = NSLocalizedString("OK", comment: "")
let signedOutController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let action = UIAlertAction(title: okActionTitle, style: .Cancel, handler: nil)
signedOutController.addAction(action)
self.presentViewController(signedOutController, animated: true, completion: nil)
}
func promptUserForStorageOption() {
let title = NSLocalizedString("Choose Storage Option", comment: "")
let message = NSLocalizedString("Do you want to store documents in iCloud or only on this device?", comment: "")
let localOnlyActionTitle = NSLocalizedString("Local Only", comment: "")
let cloudActionTitle = NSLocalizedString("iCloud", comment: "")
let storageController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let localOption = UIAlertAction(title: localOnlyActionTitle, style: .Default) { localAction in
AppConfiguration.sharedConfiguration.storageOption = .Local
}
storageController.addAction(localOption)
let cloudOption = UIAlertAction(title: cloudActionTitle, style: .Default) { cloudAction in
AppConfiguration.sharedConfiguration.storageOption = .Cloud
}
storageController.addAction(cloudOption)
presentViewController(storageController, animated: true, completion: nil)
}
}
| mit |
ben-ng/swift | test/stdlib/StringAPI.swift | 14 | 16837 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
//
// Tests for the non-Foundation API of String
//
import StdlibUnittest
#if _runtime(_ObjC)
import Foundation
#endif
var StringTests = TestSuite("StringTests")
struct ComparisonTest {
let expectedUnicodeCollation: ExpectedComparisonResult
let lhs: String
let rhs: String
let loc: SourceLoc
let xfail: TestRunPredicate
init(
_ expectedUnicodeCollation: ExpectedComparisonResult,
_ lhs: String, _ rhs: String,
xfail: TestRunPredicate = .never,
file: String = #file, line: UInt = #line
) {
self.expectedUnicodeCollation = expectedUnicodeCollation
self.lhs = lhs
self.rhs = rhs
self.loc = SourceLoc(file, line, comment: "test data")
self.xfail = xfail
}
func replacingPredicate(_ xfail: TestRunPredicate) -> ComparisonTest {
return ComparisonTest(expectedUnicodeCollation, lhs, rhs,
xfail: xfail, file: loc.file, line: loc.line)
}
}
// List test cases for comparisons and prefix/suffix. Ideally none fail.
let tests = [
ComparisonTest(.eq, "", ""),
ComparisonTest(.lt, "", "a"),
// ASCII cases
ComparisonTest(.lt, "t", "tt"),
ComparisonTest(.gt, "t", "Tt"),
ComparisonTest(.gt, "\u{0}", ""),
ComparisonTest(.eq, "\u{0}", "\u{0}"),
ComparisonTest(.lt, "\r\n", "t"),
ComparisonTest(.gt, "\r\n", "\n"),
ComparisonTest(.lt, "\u{0}", "\u{0}\u{0}"),
// Whitespace
// U+000A LINE FEED (LF)
// U+000B LINE TABULATION
// U+000C FORM FEED (FF)
// U+0085 NEXT LINE (NEL)
// U+2028 LINE SEPARATOR
// U+2029 PARAGRAPH SEPARATOR
ComparisonTest(.gt, "\u{0085}", "\n"),
ComparisonTest(.gt, "\u{000b}", "\n"),
ComparisonTest(.gt, "\u{000c}", "\n"),
ComparisonTest(.gt, "\u{2028}", "\n"),
ComparisonTest(.gt, "\u{2029}", "\n"),
ComparisonTest(.gt, "\r\n\r\n", "\r\n"),
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
ComparisonTest(.eq, "a\u{301}", "\u{e1}"),
ComparisonTest(.lt, "a", "a\u{301}"),
ComparisonTest(.lt, "a", "\u{e1}"),
// U+304B HIRAGANA LETTER KA
// U+304C HIRAGANA LETTER GA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
ComparisonTest(.eq, "\u{304b}", "\u{304b}"),
ComparisonTest(.eq, "\u{304c}", "\u{304c}"),
ComparisonTest(.lt, "\u{304b}", "\u{304c}"),
ComparisonTest(.lt, "\u{304b}", "\u{304c}\u{3099}"),
ComparisonTest(.eq, "\u{304c}", "\u{304b}\u{3099}"),
ComparisonTest(.lt, "\u{304c}", "\u{304c}\u{3099}"),
// U+212B ANGSTROM SIGN
// U+030A COMBINING RING ABOVE
// U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE
ComparisonTest(.eq, "\u{212b}", "A\u{30a}"),
ComparisonTest(.eq, "\u{212b}", "\u{c5}"),
ComparisonTest(.eq, "A\u{30a}", "\u{c5}"),
ComparisonTest(.lt, "A\u{30a}", "a"),
ComparisonTest(.lt, "A", "A\u{30a}"),
// U+2126 OHM SIGN
// U+03A9 GREEK CAPITAL LETTER OMEGA
ComparisonTest(.eq, "\u{2126}", "\u{03a9}"),
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
// U+1E69 LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
ComparisonTest(.eq, "\u{1e69}", "s\u{323}\u{307}"),
ComparisonTest(.eq, "\u{1e69}", "s\u{307}\u{323}"),
ComparisonTest(.eq, "\u{1e69}", "\u{1e63}\u{307}"),
ComparisonTest(.eq, "\u{1e63}", "s\u{323}"),
ComparisonTest(.eq, "\u{1e63}\u{307}", "s\u{323}\u{307}"),
ComparisonTest(.eq, "\u{1e63}\u{307}", "s\u{307}\u{323}"),
ComparisonTest(.lt, "s\u{323}", "\u{1e69}"),
// U+FB01 LATIN SMALL LIGATURE FI
ComparisonTest(.eq, "\u{fb01}", "\u{fb01}"),
ComparisonTest(.lt, "fi", "\u{fb01}"),
// U+1F1E7 REGIONAL INDICATOR SYMBOL LETTER B
// \u{1F1E7}\u{1F1E7} Flag of Barbados
ComparisonTest(.lt, "\u{1F1E7}", "\u{1F1E7}\u{1F1E7}"),
// Test that Unicode collation is performed in deterministic mode.
//
// U+0301 COMBINING ACUTE ACCENT
// U+0341 COMBINING ACUTE TONE MARK
// U+0954 DEVANAGARI ACUTE ACCENT
//
// Collation elements from DUCET:
// 0301 ; [.0000.0024.0002] # COMBINING ACUTE ACCENT
// 0341 ; [.0000.0024.0002] # COMBINING ACUTE TONE MARK
// 0954 ; [.0000.0024.0002] # DEVANAGARI ACUTE ACCENT
//
// U+0301 and U+0954 don't decompose in the canonical decomposition mapping.
// U+0341 has a canonical decomposition mapping of U+0301.
ComparisonTest(.eq, "\u{0301}", "\u{0341}"),
ComparisonTest(.lt, "\u{0301}", "\u{0954}"),
ComparisonTest(.lt, "\u{0341}", "\u{0954}"),
]
func checkStringComparison(
_ expected: ExpectedComparisonResult,
_ lhs: String, _ rhs: String, _ stackTrace: SourceLocStack
) {
// String / String
expectEqual(expected.isEQ(), lhs == rhs, stackTrace: stackTrace)
expectEqual(expected.isNE(), lhs != rhs, stackTrace: stackTrace)
checkHashable(
expectedEqual: expected.isEQ(),
lhs, rhs, stackTrace: stackTrace.withCurrentLoc())
expectEqual(expected.isLT(), lhs < rhs, stackTrace: stackTrace)
expectEqual(expected.isLE(), lhs <= rhs, stackTrace: stackTrace)
expectEqual(expected.isGE(), lhs >= rhs, stackTrace: stackTrace)
expectEqual(expected.isGT(), lhs > rhs, stackTrace: stackTrace)
checkComparable(expected, lhs, rhs, stackTrace: stackTrace.withCurrentLoc())
#if _runtime(_ObjC)
// NSString / NSString
let lhsNSString = lhs as NSString
let rhsNSString = rhs as NSString
let expectedEqualUnicodeScalars =
Array(lhs.unicodeScalars) == Array(rhs.unicodeScalars)
// FIXME: Swift String and NSString comparison may not be equal.
expectEqual(
expectedEqualUnicodeScalars, lhsNSString == rhsNSString,
stackTrace: stackTrace)
expectEqual(
!expectedEqualUnicodeScalars, lhsNSString != rhsNSString,
stackTrace: stackTrace)
checkHashable(
expectedEqual: expectedEqualUnicodeScalars,
lhsNSString, rhsNSString,
stackTrace: stackTrace.withCurrentLoc())
#endif
}
// Mark the test cases that are expected to fail in checkStringComparison
let comparisonTests = tests.map {
(test: ComparisonTest) -> ComparisonTest in
switch (test.expectedUnicodeCollation, test.lhs, test.rhs) {
case (.gt, "t", "Tt"), (.lt, "A\u{30a}", "a"):
return test.replacingPredicate(.nativeRuntime(
"Comparison reversed between ICU and CFString, https://bugs.swift.org/browse/SR-530"))
case (.gt, "\u{0}", ""), (.lt, "\u{0}", "\u{0}\u{0}"):
return test.replacingPredicate(.nativeRuntime(
"Null-related issue: https://bugs.swift.org/browse/SR-630"))
case (.lt, "\u{0301}", "\u{0954}"), (.lt, "\u{0341}", "\u{0954}"):
return test.replacingPredicate(.nativeRuntime(
"Compares as equal with ICU"))
default:
return test
}
}
for test in comparisonTests {
StringTests.test("String.{Equatable,Hashable,Comparable}: line \(test.loc.line)")
.xfail(test.xfail)
.code {
checkStringComparison(
test.expectedUnicodeCollation, test.lhs, test.rhs,
test.loc.withCurrentLoc())
checkStringComparison(
test.expectedUnicodeCollation.flip(), test.rhs, test.lhs,
test.loc.withCurrentLoc())
}
}
func checkCharacterComparison(
_ expected: ExpectedComparisonResult,
_ lhs: Character, _ rhs: Character, _ stackTrace: SourceLocStack
) {
// Character / Character
expectEqual(expected.isEQ(), lhs == rhs, stackTrace: stackTrace)
expectEqual(expected.isNE(), lhs != rhs, stackTrace: stackTrace)
checkHashable(
expectedEqual: expected.isEQ(),
lhs, rhs, stackTrace: stackTrace.withCurrentLoc())
expectEqual(expected.isLT(), lhs < rhs, stackTrace: stackTrace)
expectEqual(expected.isLE(), lhs <= rhs, stackTrace: stackTrace)
expectEqual(expected.isGE(), lhs >= rhs, stackTrace: stackTrace)
expectEqual(expected.isGT(), lhs > rhs, stackTrace: stackTrace)
checkComparable(expected, lhs, rhs, stackTrace: stackTrace.withCurrentLoc())
}
for test in comparisonTests {
if test.lhs.characters.count == 1 && test.rhs.characters.count == 1 {
StringTests.test("Character.{Equatable,Hashable,Comparable}: line \(test.loc.line)")
.xfail(test.xfail)
.code {
let lhsCharacter = Character(test.lhs)
let rhsCharacter = Character(test.rhs)
checkCharacterComparison(
test.expectedUnicodeCollation, lhsCharacter, rhsCharacter,
test.loc.withCurrentLoc())
checkCharacterComparison(
test.expectedUnicodeCollation.flip(), rhsCharacter, lhsCharacter,
test.loc.withCurrentLoc())
}
}
}
func checkHasPrefixHasSuffix(
_ lhs: String, _ rhs: String, _ stackTrace: SourceLocStack
) {
#if _runtime(_ObjC)
if rhs == "" {
expectTrue(lhs.hasPrefix(rhs), stackTrace: stackTrace)
expectTrue(lhs.hasSuffix(rhs), stackTrace: stackTrace)
return
}
if lhs == "" {
expectFalse(lhs.hasPrefix(rhs), stackTrace: stackTrace)
expectFalse(lhs.hasSuffix(rhs), stackTrace: stackTrace)
return
}
// To determine the expected results, compare grapheme clusters,
// scalar-to-scalar, of the NFD form of the strings.
let lhsNFDGraphemeClusters =
lhs.decomposedStringWithCanonicalMapping.characters.map {
Array(String($0).unicodeScalars)
}
let rhsNFDGraphemeClusters =
rhs.decomposedStringWithCanonicalMapping.characters.map {
Array(String($0).unicodeScalars)
}
let expectHasPrefix = lhsNFDGraphemeClusters.starts(
with: rhsNFDGraphemeClusters, by: (==))
let expectHasSuffix = lhsNFDGraphemeClusters.lazy.reversed()
.starts(with: rhsNFDGraphemeClusters.lazy.reversed(), by: (==))
expectEqual(expectHasPrefix, lhs.hasPrefix(rhs), stackTrace: stackTrace)
expectEqual(expectHasSuffix, lhs.hasSuffix(rhs), stackTrace: stackTrace)
#endif
}
StringTests.test("LosslessStringConvertible") {
checkLosslessStringConvertible(comparisonTests.map { $0.lhs })
checkLosslessStringConvertible(comparisonTests.map { $0.rhs })
}
// Mark the test cases that are expected to fail in checkHasPrefixHasSuffix
let substringTests = tests.map {
(test: ComparisonTest) -> ComparisonTest in
switch (test.expectedUnicodeCollation, test.lhs, test.rhs) {
case (.eq, "\u{0}", "\u{0}"):
return test.replacingPredicate(.objCRuntime(
"https://bugs.swift.org/browse/SR-332"))
case (.gt, "\r\n", "\n"):
return test.replacingPredicate(.objCRuntime(
"blocked on rdar://problem/19036555"))
case (.eq, "\u{0301}", "\u{0341}"):
return test.replacingPredicate(.objCRuntime(
"https://bugs.swift.org/browse/SR-243"))
case (.lt, "\u{1F1E7}", "\u{1F1E7}\u{1F1E7}"):
return test.replacingPredicate(.objCRuntime(
"https://bugs.swift.org/browse/SR-367"))
default:
return test
}
}
for test in substringTests {
StringTests.test("hasPrefix,hasSuffix: line \(test.loc.line)")
.skip(.nativeRuntime(
"String.has{Prefix,Suffix} defined when _runtime(_ObjC)"))
.xfail(test.xfail)
.code {
checkHasPrefixHasSuffix(test.lhs, test.rhs, test.loc.withCurrentLoc())
checkHasPrefixHasSuffix(test.rhs, test.lhs, test.loc.withCurrentLoc())
let fragment = "abc"
let combiner = "\u{0301}" // combining acute accent
checkHasPrefixHasSuffix(test.lhs + fragment, test.rhs, test.loc.withCurrentLoc())
checkHasPrefixHasSuffix(fragment + test.lhs, test.rhs, test.loc.withCurrentLoc())
checkHasPrefixHasSuffix(test.lhs + combiner, test.rhs, test.loc.withCurrentLoc())
checkHasPrefixHasSuffix(combiner + test.lhs, test.rhs, test.loc.withCurrentLoc())
}
}
StringTests.test("SameTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
let xs = "\u{1e69}"
expectTrue(xs == "s\u{323}\u{307}")
expectFalse(xs != "s\u{323}\u{307}")
expectTrue("s\u{323}\u{307}" == xs)
expectFalse("s\u{323}\u{307}" != xs)
expectTrue("\u{1e69}" == "s\u{323}\u{307}")
expectFalse("\u{1e69}" != "s\u{323}\u{307}")
expectTrue(xs == xs)
expectFalse(xs != xs)
}
StringTests.test("CompareStringsWithUnpairedSurrogates")
.xfail(
.always("<rdar://problem/18029104> Strings referring to underlying " +
"storage with unpaired surrogates compare unequal"))
.code {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{fffd}\u{1f602}\u{fffd}",
acceptor[
donor.index(donor.startIndex, offsetBy: 1) ..<
donor.index(donor.startIndex, offsetBy: 5)
]
)
}
var CStringTests = TestSuite("CStringTests")
func getNullUTF8() -> UnsafeMutablePointer<UInt8>? {
return nil
}
func getASCIIUTF8() -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) {
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
up[0] = 0x61
up[1] = 0x62
up[2] = 0
return (up, { up.deallocate(capacity: 100) })
}
func getNonASCIIUTF8() -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) {
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
up[0] = 0xd0
up[1] = 0xb0
up[2] = 0xd0
up[3] = 0xb1
up[4] = 0
return (UnsafeMutablePointer(up), { up.deallocate(capacity: 100) })
}
func getIllFormedUTF8String1(
) -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) {
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
up[0] = 0x41
up[1] = 0xed
up[2] = 0xa0
up[3] = 0x80
up[4] = 0x41
up[5] = 0
return (UnsafeMutablePointer(up), { up.deallocate(capacity: 100) })
}
func getIllFormedUTF8String2(
) -> (UnsafeMutablePointer<UInt8>, dealloc: () -> ()) {
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
up[0] = 0x41
up[0] = 0x41
up[1] = 0xed
up[2] = 0xa0
up[3] = 0x81
up[4] = 0x41
up[5] = 0
return (UnsafeMutablePointer(up), { up.deallocate(capacity: 100) })
}
func asCCharArray(_ a: [UInt8]) -> [CChar] {
return a.map { CChar(bitPattern: $0) }
}
func getUTF8Length(_ cString: UnsafePointer<UInt8>) -> Int {
var length = 0
while cString[length] != 0 {
length += 1
}
return length
}
func bindAsCChar(_ utf8: UnsafePointer<UInt8>) -> UnsafePointer<CChar> {
return UnsafeRawPointer(utf8).bindMemory(to: CChar.self,
capacity: getUTF8Length(utf8))
}
func expectEqualCString(_ lhs: UnsafePointer<UInt8>,
_ rhs: UnsafePointer<UInt8>) {
var index = 0
while lhs[index] != 0 {
expectEqual(lhs[index], rhs[index])
index += 1
}
expectEqual(0, rhs[index])
}
func expectEqualCString(_ lhs: UnsafePointer<UInt8>,
_ rhs: ContiguousArray<UInt8>) {
rhs.withUnsafeBufferPointer {
expectEqualCString(lhs, $0.baseAddress!)
}
}
func expectEqualCString(_ lhs: UnsafePointer<UInt8>,
_ rhs: ContiguousArray<CChar>) {
rhs.withUnsafeBufferPointer {
$0.baseAddress!.withMemoryRebound(
to: UInt8.self, capacity: rhs.count) {
expectEqualCString(lhs, $0)
}
}
}
CStringTests.test("String.init(validatingUTF8:)") {
do {
let (s, dealloc) = getASCIIUTF8()
expectOptionalEqual("ab", String(validatingUTF8: bindAsCChar(s)))
dealloc()
}
do {
let (s, dealloc) = getNonASCIIUTF8()
expectOptionalEqual("аб", String(validatingUTF8: bindAsCChar(s)))
dealloc()
}
do {
let (s, dealloc) = getIllFormedUTF8String1()
expectNil(String(validatingUTF8: bindAsCChar(s)))
dealloc()
}
}
CStringTests.test("String(cString:)") {
do {
let (s, dealloc) = getASCIIUTF8()
let result = String(cString: s)
expectEqual("ab", result)
let su = bindAsCChar(s)
expectEqual("ab", String(cString: su))
dealloc()
}
do {
let (s, dealloc) = getNonASCIIUTF8()
let result = String(cString: s)
expectEqual("аб", result)
let su = bindAsCChar(s)
expectEqual("аб", String(cString: su))
dealloc()
}
do {
let (s, dealloc) = getIllFormedUTF8String1()
let result = String(cString: s)
expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result)
let su = bindAsCChar(s)
expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", String(cString: su))
dealloc()
}
}
CStringTests.test("String.decodeCString") {
do {
let s = getNullUTF8()
let result = String.decodeCString(s, as: UTF8.self)
expectNil(result)
}
do { // repairing
let (s, dealloc) = getIllFormedUTF8String1()
if let (result, repairsMade) = String.decodeCString(
s, as: UTF8.self, repairingInvalidCodeUnits: true) {
expectOptionalEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result)
expectTrue(repairsMade)
} else {
expectUnreachable("Expected .some()")
}
dealloc()
}
do { // non repairing
let (s, dealloc) = getIllFormedUTF8String1()
let result = String.decodeCString(
s, as: UTF8.self, repairingInvalidCodeUnits: false)
expectNil(result)
dealloc()
}
}
CStringTests.test("String.utf8CString") {
do {
let (cstr, dealloc) = getASCIIUTF8()
let str = String(cString: cstr)
expectEqualCString(cstr, str.utf8CString)
dealloc()
}
do {
let (cstr, dealloc) = getNonASCIIUTF8()
let str = String(cString: cstr)
expectEqualCString(cstr, str.utf8CString)
dealloc()
}
}
runAllTests()
| apache-2.0 |
bhargavg/Request | Examples/SimpleResponseParsing/main.swift | 1 | 759 | //
// main.swift
// SampleResponseParsing
//
// Created by Gurlanka, Bhargav (Agoda) on 30/06/17.
// Copyright © 2017 Gurlanka, Bhargav (Agoda). All rights reserved.
//
import Foundation
import Result
import Request
do {
let result = post(url: "https://httpbin.org/post", params: {
$0.body = .jsonArray(["foo", "bar"])
}).mapError({ .sessionError($0) })
.flatMap(HTTPBinResponse.from(response:))
print(result.value ?? "Failed with error")
}
do {
let result = get(url: "https://httpbin.org/get", params: {
$0.queryItems = ["bar": "foo"]
$0.headers = ["X-Foo": "Bar"]
}).mapError({ .sessionError($0) })
.flatMap(HTTPBinResponse.from(response:))
print(result.value ?? "Failed with error")
}
| mit |
ufogxl/MySQLTest | Sources/login.swift | 1 | 3186 | //
// Login.swift
// GoodStudent
//
// Created by ufogxl on 16/11/7.
//
//
import Foundation
import PerfectLib
import PerfectHTTP
import MySQL
import ObjectMapper
fileprivate let container = ResponseContainer()
fileprivate let login_user = NSMutableDictionary()
fileprivate let errorContent = ErrorContent()
func login(_ request:HTTPRequest,response:HTTPResponse){
//读取网络请求的参数
let params = request.params()
phaseParams(params: params)
if !paramsValid(){
let errorStr = "参数错误"
errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue
container.message = errorStr
container.data = errorContent
container.result = false
response.appendBody(string:container.toJSONString(prettyPrint: true)!)
response.completed()
return
}
guard let ary = getUser() else{
//数据库错误
return
}
//无此用户
if ary.count < 1{
errorContent.code = ErrCode.NO_SUCH_USER.hashValue
container.data = errorContent
container.result = false
container.message = "用户不存在"
response.appendBody(string:container.toJSONString(prettyPrint: true)!)
response.completed()
return
}
if (login_user as NSDictionary)["password"] as? String == ary.first!.u_pass{
let successstr = "登陆成功"
container.message = successstr
container.result = true
container.data = ary[0]
response.appendBody(string:container.toJSONString(prettyPrint: true)!)
response.completed()
return
}else{
let failstr = "用户名或密码错误"
errorContent.code = ErrCode.PASSWORD_ERROR.hashValue
container.message = failstr
container.data = errorContent
container.result = false
response.appendBody(string:container.toJSONString(prettyPrint: false)!)
response.completed()
return
}
}
//处理参数
fileprivate func phaseParams(params:[(String,String)]){
for i in 0..<params.count{
login_user.setObject(params[i].1, forKey: NSString(string: params[i].0))
}
}
//判断请求的参数是否输入正确
fileprivate func paramsValid() -> Bool{
if (login_user["userName"] == nil)||(login_user["password"] == nil){
return false
}
return true
}
//数据库查询操作
func getUser() -> [User]?{
let connected = mysql.connect(host: db_host, user: db_user, password: db_password, db: database,port:db_port)
guard connected else {
print(mysql.errorMessage())
return nil
}
defer {
mysql.close()
}
let querySuccess = mysql.query(statement: "SELECT id,u_name,u_pass FROM user WHERE u_name=\(login_user["userName"]!)")
guard querySuccess else {
return nil
}
let results = mysql.storeResults()!
var ary = [User]()
while let row = results.next() {
let user = User()
user.id = row[0]!
user.u_name = Int(row[1]!)
user.u_pass = row[2]!
ary.append(user)
}
return ary
}
| apache-2.0 |
softwarenerd/Stately | Stately/Code/State.swift | 1 | 2672 | //
// State.swift
// Stately
//
// Created by Brian Lambert on 10/4/16.
// See the LICENSE.md file in the project root for license information.
//
import Foundation
// State error enumeration.
public enum StateError: Error {
case NameEmpty
}
// Types alias for a state change tuple.
public typealias StateChange = (state: State, object: AnyObject?)
// Type alias for a state enter action.
public typealias StateEnterAction = (AnyObject?) throws -> StateChange?
// State class.
public class State: Hashable {
// Gets the name of the state.
public let name: String
// The optional state enter action.
internal let stateEnterAction: StateEnterAction?
/// Initializes a new instance of the State class.
///
/// - Parameters:
/// - name: The name of the state. Each state must have a unique name.
public convenience init(name nameIn: String) throws {
try self.init(name: nameIn, stateEnterAction: nil)
}
/// Initializes a new instance of the State class.
///
/// - Parameters:
/// - name: The name of the state. Each state must have a unique name.
/// - stateEnterAction: The state enter action.
public convenience init(name nameIn: String, stateEnterAction stateEnterActionIn: @escaping StateEnterAction) throws {
try self.init(name: nameIn, stateEnterAction: StateEnterAction?(stateEnterActionIn))
}
/// Initializes a new instance of the State class.
///
/// - Parameters:
/// - name: The name of the state. Each state must have a unique name.
/// - stateAction: The optional state enter action.
private init(name nameIn: String, stateEnterAction stateEnterActionIn: StateEnterAction?) throws {
// Validate the state name.
if nameIn.isEmpty {
throw StateError.NameEmpty
}
// Initialize.
name = nameIn
stateEnterAction = stateEnterActionIn
}
/// Gets the hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
public var hashValue: Int {
get {
return name.hashValue
}
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: State, rhs: State) -> Bool {
return lhs === rhs
}
}
| mit |
LaudyLaw/FirstSwiftDemo | MyFirstGitSwiftDemo/SecondPlayBallViewController.swift | 1 | 557 | //
// SecondPlayBallViewController.swift
// MyFirstGitSwiftDemo
//
// Created by luosong on 15/5/27.
// Copyright (c) 2015年 Personal. All rights reserved.
//
import UIKit
class SecondPlayBallViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
kfix/MacPin | Sources/MacPinIOS/AppDelegateIOS.swift | 1 | 7070 | import UIKit
import ObjectiveC
import WebKitPrivates
import Darwin
@main
public class MacPinAppDelegateIOS: NSObject, MacPinAppDelegate {
var browserController: BrowserViewController = MobileBrowserViewController() //frame: UIScreen.mainScreen().applicationFrame)
let window = UIWindow(frame: UIScreen.main.bounds) // total pixels w/ rotation
var prompter: Prompter? = nil
func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
warn("`\(url)` -> AppScriptRuntime.shared.jsdelegate.launchURL()")
AppScriptRuntime.shared.emit(.launchURL, url.absoluteString ?? "")
return true //FIXME
}
public func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // state not restored, UI not presented
application.registerUserNotificationSettings(UIUserNotificationSettings(types: [UIUserNotificationType.sound, UIUserNotificationType.alert, UIUserNotificationType.badge], categories: nil))
AppScriptRuntime.shared.setBrowserWindowClass(MobileBrowserViewController.self)
if !AppScriptRuntime.shared.loadMainScript() { // load main.js, if present
self.browserController.extend(AppScriptRuntime.shared.exports) // expose our default browser instance early on, because legacy
MobileBrowserViewController.self.exportSelf(AppScriptRuntime.shared.context.globalObject) // & the type for self-setup
AppScriptRuntime.shared.exports.setObject(MPWebView.self, forKeyedSubscript: "WebView" as NSString) // because legacy
AppScriptRuntime.shared.exports.setObject("", forKeyedSubscript: "launchedWithURL" as NSString)
AppScriptRuntime.shared.loadSiteApp() // load app.js, if present
AppScriptRuntime.shared.emit(.AppFinishedLaunching)
}
AppScriptRuntime.shared.emit(.AppWillFinishLaunching, self) // allow JS to replace our browserController
AppScriptRuntime.shared.context.evaluateScript("eval = null;") // security thru obscurity
return true
}
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { //state restored, but UI not presented yet
// launchOptions: http://nshipster.com/launch-options/
UIApplication.shared.statusBarStyle = .lightContent
window.backgroundColor = UIColor.white // visible behind status bar area when unobscured by page content
window.rootViewController = browserController as! UIViewController //adds the browserView to window.subviews
window.makeKeyAndVisible() // presentation is deferred until after didFinishLaunching
AppScriptRuntime.shared.emit(.AppFinishedLaunching, "FIXME: provide real launch URLs")
// airplay to an external screen on a mac or appletv
// https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/WindowAndScreenGuide/UsingExternalDisplay/UsingExternalDisplay.html#//apple_ref/doc/uid/TP40012555-CH3-SW1
warn(CommandLine.arguments.description)
for (idx, arg) in CommandLine.arguments.enumerated() {
switch (arg) {
case "-i":
//open a JS console on the terminal, if present
if AppScriptRuntime.shared.eventCallbacks[.printToREPL, default: []].isEmpty {
if let repl_js = Bundle.main.url(forResource: "app_repl", withExtension: "js") {
warn("injecting TTY REPL")
AppScriptRuntime.shared.eventCallbacks[.printToREPL] = [
AppScriptRuntime.shared.loadCommonJSScript(repl_js.absoluteString).objectForKeyedSubscript("repl")
]
}
}
prompter = AppScriptRuntime.shared.REPL()
case "-t":
if idx + 1 >= CommandLine.arguments.count { // no arg after this one
prompter = browserController.tabs.first?.REPL() //open a JS console for the first tab WebView on the terminal, if present
break
}
if let tabnum = Int(CommandLine.arguments[idx + 1]), browserController.tabs.count >= tabnum { // next argv should be tab number
prompter = browserController.tabs[tabnum].REPL() // open a JS Console on the requested tab number
// FIXME skip one more arg
} else {
prompter = browserController.tabs.first?.REPL() //open a JS console for the first tab WebView on the terminal, if present
}
case let _ where (arg.hasPrefix("http:") || arg.hasPrefix("https:") || arg.hasPrefix("about:") || arg.hasPrefix("file:")):
warn("\(arg)")
//application(NSApp, openFile: arg) // LS will openFile AND argv.append() fully qualified URLs
default:
if arg != CommandLine.arguments[0] && !arg.hasPrefix("-psn_0_") { // Process Serial Number from LaunchServices open()
warn("unrecognized argv[]: `\(arg)`")
}
}
}
prompter?.start()
return true //FIXME
}
public func applicationDidBecomeActive(_ application: UIApplication) { // UI presented
//if application?.orderedDocuments?.count < 1 { showApplication(self) }
browserController.view.frame = UIScreen.main.bounds
if browserController.tabs.count < 1 { browserController.newTabPrompt() } //don't allow a tabless state
}
// need https://github.com/kemenaran/ios-presentError
// w/ http://nshipster.com/uialertcontroller/
/*
func application(application: NSApplication, willPresentError error: NSError) -> NSError {
//warn("`\(error.localizedDescription)` [\(error.domain)] [\(error.code)] `\(error.localizedFailureReason ?? String())` : \(error.userInfo)")
if error.domain == NSURLErrorDomain {
if let userInfo = error.userInfo {
if let errstr = userInfo[NSLocalizedDescriptionKey] as? String {
if let url = userInfo[NSURLErrorFailingURLStringErrorKey] as? String {
var newUserInfo = userInfo
newUserInfo[NSLocalizedDescriptionKey] = "\(errstr)\n\n\(url)" // add failed url to error message
let newerror = NSError(domain: error.domain, code: error.code, userInfo: newUserInfo)
return newerror
}
}
}
}
return error
}
*/
public func applicationWillTerminate(_ application: UIApplication) {
AppScriptRuntime.shared.emit(.AppShouldTerminate, self) // allow JS to clean up its refs
UserDefaults.standard.synchronize()
}
public func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { return false }
public func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return false }
//func applicationDidReceiveMemoryWarning(application: UIApplication) { close all hung tabs! }
public func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
warn("user clicked notification")
// FIXME should be passing a [:]
if AppScriptRuntime.shared.anyHandled(.handleClickedNotification, [
"title": (notification.alertTitle ?? "") as NSString,
"subtitle": (notification.alertAction ?? "") as NSString,
"body": (notification.alertBody ?? "") as NSString,
]) {
warn("handleClickedNotification fired!")
}
}
//alerts do not display when app is already frontmost, cannot override this like on OSX
}
| gpl-3.0 |
AlbertMontserrat/AMGLanguageManager | Example/Tests/Tests15.swift | 1 | 9110 | import UIKit
import AMGLanguageManager
class Tests15
{
func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample68() {
// This is an example of a functional test case.
}
func testExample67() {
// This is an example of a functional test case.
}
func testExample66() {
// This is an example of a functional test case.
}
func testExample65() {
// This is an example of a functional test case.
}
func testExample64() {
// This is an example of a functional test case.
}
func testExample63() {
// This is an example of a functional test case.
}
func testExample62() {
// This is an example of a functional test case.
}
func testExample61() {
// This is an example of a functional test case.
}
func testExample60() {
// This is an example of a functional test case.
}
func testExample59() {
// This is an example of a functional test case.
}
func testExample58() {
// This is an example of a functional test case.
}
func testExample57() {
// This is an example of a functional test case.
}
func testExample56() {
// This is an example of a functional test case.
}
func testExample55() {
// This is an example of a functional test case.
}
func testExample54() {
// This is an example of a functional test case.
}
func testExample53() {
// This is an example of a functional test case.
}
func testExample52() {
// This is an example of a functional test case.
}
func testExample51() {
// This is an example of a functional test case.
}
func testExample50() {
// This is an example of a functional test case.
}
func testExample49() {
// This is an example of a functional test case.
}
func testExample48() {
// This is an example of a functional test case.
}
func testExample47() {
// This is an example of a functional test case.
}
func testExample46() {
// This is an example of a functional test case.
}
func testExample45() {
// This is an example of a functional test case.
}
func testExample44() {
// This is an example of a functional test case.
}
func testExample43() {
// This is an example of a functional test case.
}
func testExample42() {
// This is an example of a functional test case.
}
func testExample41() {
// This is an example of a functional test case.
}
func testExample40() {
// This is an example of a functional test case.
}
func testExample39() {
// This is an example of a functional test case.
}
func testExample38() {
// This is an example of a functional test case.
}
func testExample37() {
// This is an example of a functional test case.
}
func testExample36() {
// This is an example of a functional test case.
}
func testExample35() {
// This is an example of a functional test case.
}
func testExample34() {
// This is an example of a functional test case.
}
func testExample33() {
// This is an example of a functional test case.
}
func testExample32() {
// This is an example of a functional test case.
}
func testExample31() {
// This is an example of a functional test case.
}
func testExample30() {
// This is an example of a functional test case.
}
func testExample29() {
// This is an example of a functional test case.
}
func testExample28() {
// This is an example of a functional test case.
}
func testExample27() {
// This is an example of a functional test case.
}
func testExample26() {
// This is an example of a functional test case.
}
func testExample25() {
// This is an example of a functional test case.
}
func testExample24() {
// This is an example of a functional test case.
}
func testExample23() {
// This is an example of a functional test case.
}
func testExample22() {
// This is an example of a functional test case.
}
func testExample21() {
// This is an example of a functional test case.
}
func testExample20() {
// This is an example of a functional test case.
}
func testExample19() {
// This is an example of a functional test case.
}
func testExample18() {
// This is an example of a functional test case.
}
func testExample17() {
// This is an example of a functional test case.
}
func testExample16() {
// This is an example of a functional test case.
}
func testExample15() {
// This is an example of a functional test case.
}
func testExample14() {
// This is an example of a functional test case.
}
func testExample13() {
// This is an example of a functional test case.
}
func testExample12() {
// This is an example of a functional test case.
}
func testExample11() {
// This is an example of a functional test case.
}
func testExample10() {
// This is an example of a functional test case.
}
func testExample9() {
// This is an example of a functional test case.
}
func testExample8() {
// This is an example of a functional test case.
}
func testExample7() {
// This is an example of a functional test case.
}
func testExample6() {
// This is an example of a functional test case.
}
func testExample5() {
// This is an example of a functional test case.
}
func testExample4() {
// This is an example of a functional test case.
}
func testExample3() {
// This is an example of a functional test case.
}
func testExample2() {
// This is an example of a functional test case.
}
func testExample1() {
// This is an example of a functional test case.
}
func testPerformanceExample() {
// This is an example of a performance test case.
}
}
| mit |
dn-m/Collections | CollectionsTests/StableSortTests.swift | 1 | 916 | //
// StableSortTests.swift
// Collections
//
// Created by James Bean on 12/23/16.
//
//
import XCTest
import Collections
class StableSortTests: XCTestCase {
struct S {
let a: Int
let b: Int
init(_ a: Int, _ b: Int) {
self.a = a
self.b = b
}
}
func testStableSort() {
let items = [
(2,0), (1,1), (1,2),
(1,0), (0,2), (0,0),
(2,2), (0,1), (2,1)
].map(S.init)
let sortA = items.stableSort { $0.a < $1.a }
XCTAssertEqual(sortA.map { $0.a }, [0,0,0,1,1,1,2,2,2])
let sortB = sortA.stableSort { $0.b < $1.b }
XCTAssertEqual(sortB.map { $0.b }, [0,0,0,1,1,1,2,2,2])
let sortA2 = sortB.stableSort { $0.a < $1.a }
XCTAssertEqual(sortA2.map { $0.a }, [0,0,0,1,1,1,2,2,2])
XCTAssertEqual(sortA2.map { $0.b }, [0,1,2,0,1,2,0,1,2])
}
}
| mit |
czj1127292580/weibo_swift | WeiBo_Swift/WeiBo_Swift/Class/Home/QRCode/QRCodeCardViewController.swift | 1 | 3969 | //
// QRCodeCardViewController.swift
// WeiBo_Swift
//
// Created by 岑志军 on 16/8/24.
// Copyright © 2016年 cen. All rights reserved.
//
import UIKit
class QRCodeCardViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
navigationItem.title = "我的名片"
view.addSubview(iconView)
iconView.xmg_AlignInner(type: XMG_AlignType.Center, referView: view, size: CGSizeMake(200, 200))
let qrcodeImage = createQRCodeImage()
iconView.image = qrcodeImage
}
private func createQRCodeImage() -> UIImage?{
// 1.创建滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
// 2、还原滤镜默认属性
filter?.setDefaults()
// 3、设置需要生成的二维码数据
filter?.setValue("岑志军".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
// 4、从滤镜中取出生成好的图片
let ciImage = filter?.outputImage
// 这个方法生层的图片比较模糊
// return UIImage(CIImage: ciImage!)
let bgImage = createNonInterpolatedUIImageFormCIImage(ciImage!, size: 300)
// 5、创建一个头像
let icon = UIImage(named: "czj.jpg")
// 6、合成图片(将二维码和头像进行合并)
let newImage = createImage(bgImage, iconImage: icon!)
// 7、返回生成好的二维码
return newImage
}
/**
合成图片
- parameter bgImage: 背景图片
- parameter iconImage: 头像
*/
private func createImage(bgImage: UIImage, iconImage: UIImage) -> UIImage {
// 1、开启图片上下文
UIGraphicsBeginImageContext(bgImage.size)
// 2、绘制背景图片
bgImage.drawInRect(CGRect(origin: CGPointZero, size: bgImage.size))
// 3、绘制头像
let width: CGFloat = 50
let height: CGFloat = width
let x = (bgImage.size.width - width) * 0.5
let y = (bgImage.size.height - height) * 0.5
iconImage.drawInRect(CGRect(x: x, y: y, width: width, height: height))
// 4、取出绘制好的图片
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// 5、关闭上下文
UIGraphicsEndImageContext()
// 6、返回合成好的图片
return newImage!
}
/**
根据CIImage生成指定大小的高清UIImage
:param: image 指定CIImage
:param: size 指定大小
:returns: 生成好的图片
*/
private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
let extent: CGRect = CGRectIntegral(image.extent)
let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
// 1.创建bitmap;
let width = CGRectGetWidth(extent) * scale
let height = CGRectGetHeight(extent) * scale
let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()
let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
let context = CIContext(options: nil)
let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)!
CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None)
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到图片
let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
return UIImage(CGImage: scaledImage)
}
// MARK: - 懒加载
private lazy var iconView: UIImageView = UIImageView()
}
| mit |
tkremenek/swift | validation-test/compiler_crashers_2_fixed/0086-sr4301.swift | 51 | 215 | // RUN: not %target-swift-frontend -typecheck -primary-file %s
protocol P {
init()
}
extension P {
public init(x: Int, y: Int? = nil) {
self.init()
}
}
func foo(t: P.Type, a: Int) {
let _ = t(x: a)
}
| apache-2.0 |
andrewdavidmackenzie/cocoa_swift_tutorials | Lesson2/Lesson2/AppDelegate.swift | 1 | 555 | //
// AppDelegate.swift
// Lesson2
//
// Created by Andrew Mackenzie on 20/06/15.
// Copyright (c) 2015 Andrew Mackenzie. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| cc0-1.0 |
srn214/Floral | Floral/Floral/Classes/Module/Community(研究院)/ViewModel/LDRecommendVM.swift | 1 | 3846 | //
// LDRecommendVM.swift
// Floral
//
// Created by LDD on 2019/7/18.
// Copyright © 2019 文刂Rn. All rights reserved.
//
import UIKit
class LDRecommendVM: RefreshViewModel {
struct Input {
let city: String
}
struct Output {
let banners: Driver<[BannerModel]>
let items: Driver<[CourseSectionModel]>
}
}
extension LDRecommendVM: ViewModelProtocol {
func transform(input: LDRecommendVM.Input) -> LDRecommendVM.Output {
let bannerList = BehaviorRelay<[BannerModel]>(value: [])
let itemList = BehaviorRelay<[CourseSectionModel]>(value: [])
var page = 0
/// 上拉刷新
let loadList = refreshOutput
.headerRefreshing
.flatMapLatest { (_) -> SharedSequence<DriverSharingStrategy, ([BannerModel], LDRecommendHotModel, [CourseSectionModel])> in
let loadBranner = RecommendApi
.bannerList
.request()
.mapObject([BannerModel].self)
.asDriver(onErrorJustReturn: [])
let loadHop = RecommendApi
.portalList
.request()
.mapObject(LDRecommendHotModel.self)
.asDriver(onErrorJustReturn: LDRecommendHotModel(limitedTimeFreeList: nil, latestRecommendList: nil))
let loadCategory = RecommendApi
.categoryList(page: page)
.request()
.mapObject([CourseSectionModel].self)
.asDriver(onErrorJustReturn: [])
return Driver.zip(loadBranner, loadHop, loadCategory)
}
/// 下拉刷新
let loadMore = refreshOutput
.footerRefreshing
.then(page += 1)
.flatMapLatest { [unowned self] in
RecommendApi
.categoryList(page: page)
.request()
.mapObject([CourseSectionModel].self)
.trackActivity(self.loading)
.trackError(self.refreshError)
.asDriverOnErrorJustComplete()
}
/// 绑定数据
loadList.drive(onNext: { (arg0) in
let (headerList, hotItem, categoryList) = arg0
bannerList.accept(headerList)
if let limited = hotItem.limitedTimeFreeList {
itemList.append(limited)
}
if let latest = hotItem.latestRecommendList {
itemList.append(latest)
}
itemList.accept(itemList.value + categoryList)
}).disposed(by: disposeBag)
loadMore
.drive(itemList.append)
.disposed(by: disposeBag)
// 头部刷新状态
loadList
.mapTo(false)
.drive(refreshInput.headerRefreshState)
.disposed(by: disposeBag)
// 尾部刷新状态
Driver.merge(
loadList.map { _ in
RxMJRefreshFooterState.default
},
loadMore.map { list in
if list.count > 0 {
return RxMJRefreshFooterState.default
} else {
return RxMJRefreshFooterState.noMoreData
}
})
.startWith(.hidden)
.drive(refreshInput.footerRefreshState)
.disposed(by: disposeBag)
let output = Output(banners: bannerList.asDriver(), items: itemList.asDriver())
return output
}
}
extension LDRecommendVM {
}
| mit |
MarcoSantarossa/SwiftyToggler | Source/FeaturesManager/FeaturesManager.swift | 1 | 7755 | //
// FeaturesManager.swift
//
// Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public final class FeaturesManager {
/// Static instance to use as singleton
public static let shared = FeaturesManager()
var featuresStatus: [FeatureStatus] {
return dict
.flatMap { FeatureStatus(name: $0.key, isEnabled: $0.value.feature.isEnabled) }
.sorted(by: { $0.name < $1.name })
}
fileprivate let featureChangesObserversPool: FeatureChangesObserversPoolProtocol
fileprivate let featuresListCoordinator: FeaturesListCoordinatorProtocol
fileprivate var dict = [String: FeatureProxyProtocol]()
init(featureChangesObserversPool: FeatureChangesObserversPoolProtocol = FeatureChangesObserversPool(),
featuresListCoordinator: FeaturesListCoordinatorProtocol = FeaturesListCoordinator()) {
self.featureChangesObserversPool = featureChangesObserversPool
self.featuresListCoordinator = featuresListCoordinator
}
fileprivate func findFeatureProxy(for name: String) throws -> FeatureProxyProtocol {
guard let proxy = dict[name] else {
throw SwiftyTogglerError.featureNotFound
}
return proxy
}
}
// MARK: - FeaturesManagerProtocol
extension FeaturesManager: FeaturesManagerProtocol {
/// Adds a new features. If the feature name already exists, it will replace the previous one.
/// - parameter feature: It's the feature which you want to add.
/// - parameter name: The feature name associated to the feature to add.
/// - parameter shouldRunWhenEnabled: Flag to run the feature as soon as it's enabled. By default is false.
public func add(feature: FeatureProtocol, name: String, shouldRunWhenEnabled: Bool = false) {
let proxy = FeatureProxy(feature: feature, shouldRunWhenEnabled: shouldRunWhenEnabled)
dict[name] = proxy
}
/// Updates the `shouldRunWhenEnabled` value of a feature. If the feature name doesn't exist, will be thrown an error `SwiftyTogglerError.featureNotFound`.
/// - parameter featureName: Feature name to update.
/// - parameter shouldRunWhenEnabled: Flag to run the feature as soon as it's enabled.
/// - throws: SwiftyTogglerError.featureNotFound if the feature name is not found.
public func update(featureName: String, shouldRunWhenEnabled: Bool) throws {
var proxy = try findFeatureProxy(for: featureName)
proxy.shouldRunWhenEnabled = shouldRunWhenEnabled
}
/// Removes a feature.
/// - parameter featureName: Feature name to remove.
public func remove(featureName: String) {
dict.removeValue(forKey: featureName)
}
/// Removes all the features.
public func removeAll() {
dict.removeAll()
}
/// Runs a feature.
/// - parameter featureName: Feature name to run.
/// - returns: `True` if the feature has been run, `False` if it hasn't been run because it is not enabled.
@discardableResult
public func run(featureName: String) throws -> Bool {
let proxy = try findFeatureProxy(for: featureName)
return proxy.run()
}
/// Checks if a feature is enabled.
/// - parameter featureName: Feature name to check.
/// - returns: `True` if the feature is enabled, `False` if it is not enabled.
public func isEnabled(featureName: String) throws -> Bool {
let proxy = try findFeatureProxy(for: featureName)
return proxy.isFeatureEnable
}
}
// MARK: - FeaturesManagerObserversProtocol
extension FeaturesManager: FeaturesManagerObserversProtocol {
/// Adds an observer for all features changes.
/// - parameter observer: Features changes observer.
public func addChangesObserver(_ observer: FeatureChangesObserver) {
featureChangesObserversPool.addObserver(observer, featureNames: nil)
}
/// Adds an observer for a specific feature changes.
/// - parameter observer: Feature changes observer.
/// - parameter featureName: Feature name to observer.
public func addChangesObserver(_ observer: FeatureChangesObserver, featureName: String) {
featureChangesObserversPool.addObserver(observer, featureNames: [featureName])
}
/// Adds an observer for an array of specific features changes.
/// - parameter observer: Features changes observer.
/// - parameter featureNames: Array of features name to observer.
public func addChangesObserver(_ observer: FeatureChangesObserver, featureNames: [String]) {
featureChangesObserversPool.addObserver(observer, featureNames: featureNames)
}
/// Removes an observer.
/// - parameter observer: Observer to remove.
/// - parameter featureNames: Array of features name to remove. If nil, the observer will be removed for all the features. By default is nil.
public func removeChangesObserver(_ observer: FeatureChangesObserver, featureNames: [String]? = nil) {
featureChangesObserversPool.removeObserver(observer, featureNames: featureNames)
}
}
// MARK: - FeaturesManagerFeaturesListPresenterProtocol
extension FeaturesManager: FeaturesManagerFeaturesListPresenterProtocol {
/// Presents the features list as modal in a new window.
/// - parameter window: Window where to attach the features list. By default, it's a new window created on top of existing ones.
/// - throws: SwiftyTogglerError.modalFeaturesListAlreadyPresented if there is already a modal features list.
public func presentModalFeaturesList(in window: UIWindow = UIWindow(frame: UIScreen.main.bounds)) throws {
try featuresListCoordinator.start(presentingMode: .modal(window))
}
/// Presents the features list inside a parent view controller.
/// - parameter viewController: View controller where to present the features list.
/// - parameter view: View where to present the features list. If nil, the features list will be added in the view controller's main view. By defeault, it's nil.
public func presentFeaturesList(in viewController: UIViewController, view: UIView? = nil) {
try? featuresListCoordinator.start(presentingMode: .inParent(viewController, view))
}
}
extension FeaturesManager: FeaturesManagerTogglerProtocol {
/// Enables/Disables a feature.
/// - parameter isEnabled: New feature value. If `True` the feature will be enabled, if `False` it will be disabled. If the value is `True` and the feature is already enabled or if the value is `False` and the feature is already disabled, this function doesn't do anything.
/// - parameter featureName: Feature name to update.
public func setEnable(_ isEnabled: Bool, featureName: String) throws {
var proxy = try findFeatureProxy(for: featureName)
proxy.isFeatureEnable = isEnabled
featureChangesObserversPool.notify(for: proxy.feature, featureName: featureName)
}
}
| mit |
radex/swift-compiler-crashes | crashes-fuzzing/06531-swift-constraints-constraintsystem-matchtypes.swift | 11 | 236 | // 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 A{
var f=a
class a<H:init(){
protocol A{
typealias e:e
func a | mit |
ohwutup/ReactiveCocoa | ReactiveCocoa/AppKit/NSTextField.swift | 2 | 794 | import ReactiveSwift
import AppKit
import enum Result.NoError
extension Reactive where Base: NSTextField {
private var notifications: Signal<Notification, NoError> {
return NotificationCenter.default
.reactive
.notifications(forName: .NSControlTextDidChange, object: base)
.take(during: lifetime)
}
/// A signal of values in `String` from the text field upon any changes.
public var continuousStringValues: Signal<String, NoError> {
return notifications
.map { ($0.object as! NSTextField).stringValue }
}
/// A signal of values in `NSAttributedString` from the text field upon any
/// changes.
public var continuousAttributedStringValues: Signal<NSAttributedString, NoError> {
return notifications
.map { ($0.object as! NSTextField).attributedStringValue }
}
}
| mit |
prebid/prebid-mobile-ios | PrebidMobileTests/RenderingTests/Mocks/MockLocationManager.swift | 1 | 1481 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import CoreLocation
@testable import PrebidMobile
class MockLocationManagerSuccessful: PBMLocationManager {
static let testCoord = CLLocationCoordinate2D(latitude: 34.149335, longitude: -118.1328249)
static let testCoordsAreValid = true
static let testCity = "Pasadena"
static let testCountry = "USA"
static let testState = "CA"
static let testZipCode = "91601"
override class var shared: MockLocationManagerSuccessful {
return MockLocationManagerSuccessful(thread: Thread.current)
}
override var coordinatesAreValid:Bool {
get {
return MockLocationManagerSuccessful.testCoordsAreValid
}
}
override var coordinates:CLLocationCoordinate2D {
get {
return MockLocationManagerSuccessful.testCoord
}
}
}
class MockLocationManagerUnSuccessful : PBMLocationManager {}
| apache-2.0 |
festrs/Plantinfo | PlantInfo/PlantInfo.swift | 1 | 1166 | //
// PlantInfo.swift
// PlantInfo
//
// Created by Felipe Dias Pereira on 2016-07-30.
// Copyright © 2016 Felipe Dias Pereira. All rights reserved.
//
import UIKit
import ObjectMapper
class PlantInfo: Mappable {
var idPlantInfo:Int?
var commonName:String?
var description:String?
var family:String?
var origin:String?
var poisonPart:String?
var posionDeliveryMode:String?
var scientificName:String?
var severity:String?
var symptoms:String?
var toxicPrinciple:String?
required init?(_ map: Map) {}
// Mappable
func mapping(map: Map) {
idPlantInfo <- map["_id"]
commonName <- map["Common_Name"]
description <- map["Description"]
family <- map["Family"]
origin <- map["Origin"]
poisonPart <- map["Poison_Part"]
posionDeliveryMode <- map["Posion_Delivery_Mode"]
scientificName <- map["Scientific_Name"]
symptoms <- map["Symptoms"]
toxicPrinciple <- map["Toxic_Principle"]
severity <- map["Severity"]
}
} | mit |
lexchou/swallow | stdlib/core/Comparable.swift | 1 | 998 | /// Instances of conforming types can be compared using relational
/// operators, which define a `strict total order
/// <http://en.wikipedia.org/wiki/Total_order#Strict_total_order>`_.
///
/// A type conforming to `Comparable` need only supply the `<` and
/// `==` operators; default implementations of `<=`, `>`, `>=`, and
/// `!=` are supplied by the standard library::
///
/// struct Singular : Comparable {}
/// func ==(x: Singular, y: Singular) -> Bool { return true }
/// func <(x: Singular, y: Singular) -> Bool { return false }
///
/// **Axioms**, in addition to those of `Equatable`:
///
/// - `x == y` implies `x <= y`, `x >= y`, `!(x < y)`, and `!(x > y)`
/// - `x < y` implies `x <= y` and `y > x`
/// - `x > y` implies `x >= y` and `y < x`
/// - `x <= y` implies `y >= x`
/// - `x >= y` implies `y <= x`
protocol Comparable : _Comparable, Equatable {
func <=(lhs: Self, rhs: Self) -> Bool
func >=(lhs: Self, rhs: Self) -> Bool
func >(lhs: Self, rhs: Self) -> Bool
}
| bsd-3-clause |
sclark01/Swifty3Mesh | Meshy/MeshyTests/MeshyTests.swift | 1 | 964 | //
// MeshyTests.swift
// MeshyTests
//
// Created by Cannon Biggs on 10/12/16.
// Copyright © 2016 Cannon Biggs. All rights reserved.
//
import XCTest
@testable import Meshy
class MeshyTests: 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.
}
}
}
| mit |
STMicroelectronics-CentralLabs/BlueSTSDK_iOS | BlueSTSDK/BlueSTSDK/Features/Predictive/BlueSTSDKFeaturePredictiveFrequencyDomainStatus.swift | 1 | 7581 | /*******************************************************************************
* COPYRIGHT(c) 2018 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
import Foundation
public class BlueSTSDKFeaturePredictiveFrequencyDomainStatus : BlueSTSDKFeaturePredictiveStatus{
private static let FEATURE_NAME = "PredictiveFrequencyDomainStatus"
private static func buildAccField(name:String)->BlueSTSDKFeatureField{
return BlueSTSDKFeatureField(name: name, unit: "m/s^2", type: .float,
min: NSNumber(value:0.0),
max: NSNumber(value:Float(1<<16)/10.0))
}
private static func buildFreqField(name:String)->BlueSTSDKFeatureField{
return BlueSTSDKFeatureField(name: name, unit: "Hz", type: .float,
min: NSNumber(value:0.0),
max: NSNumber(value:Float(1<<16)/100.0))
}
private static let FIELDS:[BlueSTSDKFeatureField] = [
BlueSTSDKFeaturePredictiveStatus.buildStatusField(name: "StatusAcc_X"),
BlueSTSDKFeaturePredictiveStatus.buildStatusField(name: "StatusAcc_Y"),
BlueSTSDKFeaturePredictiveStatus.buildStatusField(name: "StatusAcc_Z"),
BlueSTSDKFeaturePredictiveFrequencyDomainStatus.buildFreqField(name: "Freq_X"),
BlueSTSDKFeaturePredictiveFrequencyDomainStatus.buildFreqField(name: "Freq_Y"),
BlueSTSDKFeaturePredictiveFrequencyDomainStatus.buildFreqField(name: "Freq_Z"),
BlueSTSDKFeaturePredictiveFrequencyDomainStatus.buildAccField(name: "MaxAmplitude_X"),
BlueSTSDKFeaturePredictiveFrequencyDomainStatus.buildAccField(name: "MaxAmplitude_Y"),
BlueSTSDKFeaturePredictiveFrequencyDomainStatus.buildAccField(name: "MaxAmplitude_Z")
]
public override func getFieldsDesc() -> [BlueSTSDKFeatureField] {
return BlueSTSDKFeaturePredictiveFrequencyDomainStatus.FIELDS
}
public static func getStatusX(_ sample:BlueSTSDKFeatureSample)->Status{
return sample.extractStatus(index: 0)
}
public static func getStatusY(_ sample:BlueSTSDKFeatureSample)->Status{
return sample.extractStatus(index: 1)
}
public static func getStatusZ(_ sample:BlueSTSDKFeatureSample)->Status{
return sample.extractStatus(index: 2)
}
public static func getWorstXFrequency(_ sample:BlueSTSDKFeatureSample)->Float{
return sample.extractFloat(index: 3)
}
public static func getWorstYFrequency(_ sample:BlueSTSDKFeatureSample)->Float{
return sample.extractFloat(index: 4)
}
public static func getWorstZFrequency(_ sample:BlueSTSDKFeatureSample)->Float{
return sample.extractFloat(index: 5)
}
public static func getWorstXValue(_ sample:BlueSTSDKFeatureSample)->Float{
return sample.extractFloat(index: 6)
}
public static func getWorstYValue(_ sample:BlueSTSDKFeatureSample)->Float{
return sample.extractFloat(index: 7)
}
public static func getWorstZValue(_ sample:BlueSTSDKFeatureSample)->Float{
return sample.extractFloat(index: 8)
}
public static func getWorstXPoint(_ sample:BlueSTSDKFeatureSample)->(Float,Float){
return (getWorstXFrequency(sample),getWorstXValue(sample))
}
public static func getWorstYPoint(_ sample:BlueSTSDKFeatureSample)->(Float,Float){
return (getWorstYFrequency(sample),getWorstYValue(sample))
}
public static func getWorstZPoint(_ sample:BlueSTSDKFeatureSample)->(Float,Float){
return (getWorstZFrequency(sample),getWorstZValue(sample))
}
public override init(whitNode node: BlueSTSDKNode) {
super.init(whitNode: node, name: BlueSTSDKFeaturePredictiveFrequencyDomainStatus.FEATURE_NAME)
}
public override func extractData(_ timestamp: UInt64, data: Data,
dataOffset offset: UInt32) -> BlueSTSDKExtractResult {
let intOffset = Int(offset)
if((data.count-intOffset) < 12){
NSException(name: NSExceptionName(rawValue: "Invalid data"),
reason: "There are no 12 bytes available to read",
userInfo: nil).raise()
return BlueSTSDKExtractResult(whitSample: nil, nReadData: 0)
}
let uintOffset = UInt(offset)
let status = data[intOffset]
let freqX = Float((data as NSData).extractLeUInt16(fromOffset: uintOffset+1))/10.0
let valX = Float((data as NSData).extractLeUInt16(fromOffset: uintOffset+3))/100.0
let freqY = Float((data as NSData).extractLeUInt16(fromOffset: uintOffset+5))/10.0
let valY = Float((data as NSData).extractLeUInt16(fromOffset: uintOffset+7))/100.0
let freqZ = Float((data as NSData).extractLeUInt16(fromOffset: uintOffset+9))/10.0
let valZ = Float((data as NSData).extractLeUInt16(fromOffset: uintOffset+11))/100.0
let sample = BlueSTSDKFeatureSample(timestamp: timestamp,
data: [
BlueSTSDKFeaturePredictiveStatus.extractXStatus(status).toNumber(),
BlueSTSDKFeaturePredictiveStatus.extractYStatus(status).toNumber(),
BlueSTSDKFeaturePredictiveStatus.extractZStatus(status).toNumber(),
NSNumber(value: freqX),
NSNumber(value: freqY),
NSNumber(value: freqZ),
NSNumber(value: valX),
NSNumber(value: valY),
NSNumber(value: valZ) ])
return BlueSTSDKExtractResult(whitSample: sample, nReadData: 12)
}
}
| bsd-3-clause |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/CartLinesRemovePayload.swift | 1 | 4205 | //
// CartLinesRemovePayload.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// Return type for `cartLinesRemove` mutation.
open class CartLinesRemovePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = CartLinesRemovePayload
/// The updated cart.
@discardableResult
open func cart(alias: String? = nil, _ subfields: (CartQuery) -> Void) -> CartLinesRemovePayloadQuery {
let subquery = CartQuery()
subfields(subquery)
addField(field: "cart", aliasSuffix: alias, subfields: subquery)
return self
}
/// The list of errors that occurred from executing the mutation.
@discardableResult
open func userErrors(alias: String? = nil, _ subfields: (CartUserErrorQuery) -> Void) -> CartLinesRemovePayloadQuery {
let subquery = CartUserErrorQuery()
subfields(subquery)
addField(field: "userErrors", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// Return type for `cartLinesRemove` mutation.
open class CartLinesRemovePayload: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = CartLinesRemovePayloadQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "cart":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: CartLinesRemovePayload.self, field: fieldName, value: fieldValue)
}
return try Cart(fields: value)
case "userErrors":
guard let value = value as? [[String: Any]] else {
throw SchemaViolationError(type: CartLinesRemovePayload.self, field: fieldName, value: fieldValue)
}
return try value.map { return try CartUserError(fields: $0) }
default:
throw SchemaViolationError(type: CartLinesRemovePayload.self, field: fieldName, value: fieldValue)
}
}
/// The updated cart.
open var cart: Storefront.Cart? {
return internalGetCart()
}
func internalGetCart(alias: String? = nil) -> Storefront.Cart? {
return field(field: "cart", aliasSuffix: alias) as! Storefront.Cart?
}
/// The list of errors that occurred from executing the mutation.
open var userErrors: [Storefront.CartUserError] {
return internalGetUserErrors()
}
func internalGetUserErrors(alias: String? = nil) -> [Storefront.CartUserError] {
return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.CartUserError]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "cart":
if let value = internalGetCart() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "userErrors":
internalGetUserErrors().forEach {
response.append($0)
response.append(contentsOf: $0.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit |
mparrish91/gifRecipes | framework/OAuth/Token.swift | 2 | 1302 | //
// Token.swift
// reddift
//
// Created by sonson on 2015/05/28.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
/**
Protocol for OAuthToken.
*/
public protocol Token {
/// token
var accessToken: String {get}
/// the type of token
var tokenType: String {get}
var expiresIn: Int {get}
var expiresDate: TimeInterval {get}
var scope: String {get}
var refreshToken: String {get}
/// user name to identifiy token.
var name: String {get}
/// base URL of API
static var baseURL: String {get}
/// vacant token
init()
/// deserials Token from JSON data
init(_ json: JSONDictionary)
}
extension Token {
/**
Returns json object
- returns: Dictinary object containing JSON data.
*/
var JSONObject: JSONDictionary {
let dict: JSONDictionary = [
"name": self.name as AnyObject,
"access_token": self.accessToken as AnyObject,
"token_type": self.tokenType as AnyObject,
"expires_in": self.expiresIn as AnyObject,
"expires_date": self.expiresDate as AnyObject,
"scope": self.scope as AnyObject,
"refresh_token": self.refreshToken as AnyObject
]
return dict
}
}
| mit |
jtbandes/swift-compiler-crashes | crashes-fuzzing/28020-llvm-smallvectorimpl-swift-decl-insert.swift | 2 | 242 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A{let a{class a{var b{class A{class T{enum B{enum A{class b<f:f.c
| mit |
JohnCoates/Aerial | Aerial/Source/Models/Cache/VideoManager.swift | 1 | 6210 | //
// VideoManager.swift
// Aerial
//
// Created by Guillaume Louel on 08/10/2018.
// Copyright © 2018 John Coates. All rights reserved.
//
import Foundation
typealias VideoManagerCallback = (Int, Int) -> Void
typealias VideoProgressCallback = (Int, Int, Double) -> Void
final class VideoManager: NSObject {
static let sharedInstance = VideoManager()
var managerCallbacks = [VideoManagerCallback]()
var progressCallbacks = [VideoProgressCallback]()
/// Dictionary of CheckCellView, keyed by the video.id
private var checkCells = [String: CheckCellView]()
/// List of queued videos, by video.id
private var queuedVideos = [String]()
/// Dictionary of operations, keyed by the video.id
fileprivate var operations = [String: VideoDownloadOperation]()
/// Number of videos that were queued
private var totalQueued = 0
var stopAll = false
// var downloadItems: [VideoDownloadItem]
/// Serial OperationQueue for downloads
private let queue: OperationQueue = {
// swiftlint:disable:next identifier_name
let _queue = OperationQueue()
_queue.name = "videodownload"
_queue.maxConcurrentOperationCount = 1
return _queue
}()
// MARK: Tracking CheckCellView
func addCheckCellView(id: String, checkCellView: CheckCellView) {
checkCells[id] = checkCellView
}
func addCallback(_ callback:@escaping VideoManagerCallback) {
managerCallbacks.append(callback)
}
func addProgressCallback(_ callback:@escaping VideoProgressCallback) {
progressCallbacks.append(callback)
}
func updateAllCheckCellView() {
for view in checkCells {
view.value.adaptIndicators()
}
}
// Is the video queued for download ?
func isVideoQueued(id: String) -> Bool {
if queuedVideos.firstIndex(of: id) != nil {
return true
} else {
return false
}
}
@discardableResult
func queueDownload(_ video: AerialVideo) -> VideoDownloadOperation {
if stopAll {
stopAll = false
}
let operation = VideoDownloadOperation(video: video, delegate: self)
operations[video.id] = operation
queue.addOperation(operation)
queuedVideos.append(video.id) // Our Internal List of queued videos
markAsQueued(id: video.id) // Callback the CheckCellView
totalQueued += 1 // Increment our count
DispatchQueue.main.async {
// Callback the callbacks
for callback in self.managerCallbacks {
callback(self.totalQueued-self.queuedVideos.count, self.totalQueued)
}
}
return operation
}
// Callbacks for Items
func finishedDownload(id: String, success: Bool) {
// Manage our queuedVideo index
if let index = queuedVideos.firstIndex(of: id) {
queuedVideos.remove(at: index)
}
if queuedVideos.isEmpty {
totalQueued = 0
}
DispatchQueue.main.async {
// Callback the callbacks
for callback in self.managerCallbacks {
callback(self.totalQueued-self.queuedVideos.count, self.totalQueued)
}
}
// Then callback the CheckCellView
if let cell = checkCells[id] {
if success {
cell.markAsDownloaded()
} else {
cell.markAsNotDownloaded()
}
}
}
func markAsQueued(id: String) {
// Manage our queuedVideo index
if let cell = checkCells[id] {
cell.markAsQueued()
}
}
func updateProgress(id: String, progress: Double) {
if let cell = checkCells[id] {
cell.updateProgressIndicator(progress: progress)
}
DispatchQueue.main.async {
// Callback the callbacks
for callback in self.progressCallbacks {
callback(self.totalQueued-self.queuedVideos.count, self.totalQueued, progress)
}
}
}
/// Cancel all queued operations
func cancelAll() {
stopAll = true
queue.cancelAllOperations()
}
}
final class VideoDownloadOperation: AsynchronousOperation {
var video: AerialVideo
var download: VideoDownload?
init(video: AerialVideo, delegate: VideoManager) {
debugLog("Video queued \(video.name)")
self.video = video
}
override func main() {
let videoManager = VideoManager.sharedInstance
if videoManager.stopAll {
return
}
debugLog("Starting download for \(video.name)")
DispatchQueue.main.async {
self.download = VideoDownload(video: self.video, delegate: self)
self.download!.startDownload()
}
}
override func cancel() {
defer { finish() }
let videoManager = VideoManager.sharedInstance
if let _ = self.download {
self.download!.cancel()
} else {
videoManager.finishedDownload(id: self.video.id, success: false)
}
self.download = nil
super.cancel()
// finish()
}
}
extension VideoDownloadOperation: VideoDownloadDelegate {
func videoDownload(_ videoDownload: VideoDownload,
finished success: Bool, errorMessage: String?) {
debugLog("Finished")
defer { finish() }
let videoManager = VideoManager.sharedInstance
if success {
// Call up to clean the view
videoManager.finishedDownload(id: videoDownload.video.id, success: true)
} else {
if let _ = errorMessage {
errorLog(errorMessage!)
}
videoManager.finishedDownload(id: videoDownload.video.id, success: false)
}
}
func videoDownload(_ videoDownload: VideoDownload, receivedBytes: Int, progress: Float) {
// Call up to update the view
let videoManager = VideoManager.sharedInstance
videoManager.updateProgress(id: videoDownload.video.id, progress: Double(progress))
}
}
| mit |
whiteshadow-gr/HatForIOS | HAT/Objects/Feed/HATFeed.swift | 1 | 1971 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
// MARK: Struct
public struct HATFeed: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `date` in JSON is `date`
* `source` in JSON is `source`
* `content` in JSON is `content`
* `title` in JSON is `title`
* `types` in JSON is `types`
* `location` in JSON is `location`
*/
private enum CodingKeys: String, CodingKey {
case date
case source
case content
case title
case types
case location
}
// MARK: - Variables
/// The date of the feed object. It includes iso and unix formats
public var date: HATFeedDate = HATFeedDate()
/// The source of the feed item. Can be Facebook, twitter etc
public var source: String = ""
/// The content of the feed item. It includes any media files that may exist in a feed item as well as the main text of the feed item. Optional
public var content: HATFeedContent?
/// The title of the feed item as well as some subtitles if any
public var title: HATFeedTitle = HATFeedTitle()
/// The types of events, for google calendar, eg Event. Optional
public var types: [String]?
/// The location information of the feed item. Can either be a geographical place with name and info for its whereabouts or can be latitude longtitude. Optional
public var location: HATFeedLocation?
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
}
}
| mpl-2.0 |
VincentNarbot/whenTapped | whenTapped/whenTapped.swift | 1 | 559 | //
// whenTapped.swift
// whenTapped
//
// Created by Vincent Narbot on 12/2/16.
// Copyright © 2016 Vincent Narbot. All rights reserved.
//
import UIKit
import ObjectiveC
import AVFoundation
class ClosureWrapper: NSObject, NSCopying {
public func copy(with zone: NSZone? = nil) -> Any {
let wrapper: ClosureWrapper = ClosureWrapper()
wrapper.closure = closure
return wrapper
}
var closure: (() -> Void)?
convenience init(closure: (() -> Void)?) {
self.init()
self.closure = closure
}
}
| mit |
germc/IBM-Ready-App-for-Retail | iOS/ReadyAppRetail/ReadyAppRetail/Views/CarouselCollectionView/CarouselCollectionViewFlowLayout.swift | 2 | 1105 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
class CarouselCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
This method sets up various properties of the carousel collectionview
*/
override func prepareLayout() {
if let collectionView = self.collectionView {
collectionView.pagingEnabled = true
self.scrollDirection = .Horizontal
self.minimumLineSpacing = 0
let viewSize = collectionView.bounds.size
setItemSize(viewSize)
}
}
/**
This method sets the item size for each cell of the carousel collectionview.
:param: viewSize <#viewSize description#>
*/
private func setItemSize(viewSize: CGSize){
let itemSize = CGSize(width: viewSize.width - minimumLineSpacing, height: viewSize.height)
self.itemSize = itemSize
}
}
| epl-1.0 |
openHPI/xikolo-ios | iOS/Extensions/UIAlertViewController+customView.swift | 1 | 2910 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import UIKit
// Heavily inspired by https://stackoverflow.com/a/47925120/7414898
extension UIAlertController {
/// Creates a `UIAlertController` with a custom `UIView` instead the message text.
/// - Note: In case anything goes wrong during replacing the message string with the custom view, a fallback message will
/// be used as normal message string.
///
/// - Parameters:
/// - title: The title text of the alert controller
/// - customView: A `UIView` which will be displayed in place of the message string.
/// - fallbackMessage: An optional fallback message string, which will be displayed in case something went wrong with inserting the custom view.
/// - preferredStyle: The preferred style of the `UIAlertController`.
convenience init(title: String?, customView: UIView, fallbackMessage: String?, preferredStyle: UIAlertController.Style) {
let marker = "__CUSTOM_CONTENT_MARKER__"
self.init(title: title, message: marker, preferredStyle: preferredStyle)
// Try to find the message label in the alert controller's view hierarchy
if let customContentPlaceholder = self.view.findLabel(withText: marker), let customContainer = customContentPlaceholder.superview {
// The message label was found. Add the custom view over it and fix the auto layout...
customContainer.addSubview(customView)
customView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customView.leadingAnchor.constraint(equalTo: customContainer.leadingAnchor),
customView.trailingAnchor.constraint(equalTo: customContainer.trailingAnchor),
customContentPlaceholder.topAnchor.constraint(equalTo: customView.topAnchor, constant: -8),
customContentPlaceholder.heightAnchor.constraint(equalTo: customView.heightAnchor),
])
customContentPlaceholder.text = ""
} else { // In case something fishy is going on, fall back to the standard behaviour and display a fallback message string
self.message = fallbackMessage
}
}
}
private extension UIView {
/// Searches a `UILabel` with the given text in the view's subviews hierarchy.
///
/// - Parameter text: The label text to search
/// - Returns: A `UILabel` in the view's subview hierarchy, containing the searched text or `nil` if no `UILabel` was found.
func findLabel(withText text: String) -> UILabel? {
if let label = self as? UILabel, label.text == text {
return label
}
for subview in self.subviews {
if let found = subview.findLabel(withText: text) {
return found
}
}
return nil
}
}
| gpl-3.0 |
tutao/tutanota | app-ios/tutanota/Sources/Utils/UIColor+utils.swift | 1 | 2282 | import UIKit
public extension UIColor {
/// Convenience constructor to initialize from a hex color string.
/// Supported formats:
/// #RGB
/// #RRGGBB
/// #RRGGBBAA
convenience init?(hex: String) {
var color: UInt32 = 0
if parseColorCode(hex, &color) {
let r = CGFloat(redPart(color)) / 255.0
let g = CGFloat(greenPart(color)) / 255.0
let b = CGFloat(bluePart(color)) / 255.0
let a = CGFloat(alphaPart(color)) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
return nil
}
func isLight() -> Bool {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
let success: Bool = self.getRed(&r, green: &g, blue: &b, alpha: nil)
// lines with assertions are removed in release builds
assert(success, "Invalid UI Color")
// Counting the perceptive luminance
// human eye favors green color...
let lightness = 0.299*r + 0.587*g + 0.114*b
return lightness >= 0.5
}
}
/** Parse a #RGB or #RRGGBB #RRGGBBAA color code into an 0xRRGGBBAA int */
private func parseColorCode(_ code: String, _ rrggbbaa: UnsafeMutablePointer<UInt32>?) -> Bool {
if code.first != "#" || (code.count != 4 && code.count != 7 && code.count != 9) {
return false
}
let start = code.index(code.startIndex, offsetBy: 1)
var hexString = String(code[start...]).uppercased()
// input was #RGB
if hexString.count == 3 {
hexString = expandShortHex(hex: hexString)
}
// input was #RGB or #RRGGBB, set alpha channel to max
if hexString.count != 8 {
hexString += "FF"
}
return Scanner(string: hexString).scanHexInt32(rrggbbaa)
}
private func expandShortHex(hex: String) -> String {
assert(hex.count == 3, "hex string must be exactly 3 characters")
var hexCode = ""
for char in hex {
hexCode += String(repeating: char, count: 2)
}
return hexCode
}
private func redPart(_ rrggbbaa: UInt32) -> UInt8 {
return UInt8((rrggbbaa >> 24) & 0xff)
}
private func greenPart(_ rrggbbaa: UInt32) -> UInt8 {
return UInt8((rrggbbaa >> 16) & 0xff)
}
private func bluePart(_ rrggbbaa: UInt32) -> UInt8 {
return UInt8((rrggbbaa >> 8) & 0xff)
}
private func alphaPart(_ rrggbbaa: UInt32) -> UInt8 {
return UInt8(rrggbbaa & 0xff)
}
| gpl-3.0 |
LibraryLoupe/PhotosPlus | PhotosPlus/PhotosPlus/CGSize_ScreenScaled.swift | 3 | 459 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
extension CGSize {
public func screenScaled(_ screen: UIScreen = UIScreen.main) -> CGSize {
var scaled = self
scaled.width = width * screen.scale
scaled.height = height * screen.scale
return scaled
}
}
#endif
| mit |
apple/swift-async-algorithms | Tests/AsyncAlgorithmsTests/TestManualClock.swift | 1 | 2710 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
import XCTest
import AsyncAlgorithms
final class TestManualClock: XCTestCase {
func test_sleep() async {
let clock = ManualClock()
let start = clock.now
let afterSleep = expectation(description: "after sleep")
let state = ManagedCriticalState(false)
Task {
try await clock.sleep(until: start.advanced(by: .steps(3)))
state.withCriticalRegion { $0 = true }
afterSleep.fulfill()
}
XCTAssertFalse(state.withCriticalRegion { $0 })
clock.advance()
XCTAssertFalse(state.withCriticalRegion { $0 })
clock.advance()
XCTAssertFalse(state.withCriticalRegion { $0 })
clock.advance()
wait(for: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
}
func test_sleep_cancel() async {
let clock = ManualClock()
let start = clock.now
let afterSleep = expectation(description: "after sleep")
let state = ManagedCriticalState(false)
let failure = ManagedCriticalState<Error?>(nil)
let task = Task {
do {
try await clock.sleep(until: start.advanced(by: .steps(3)))
} catch {
failure.withCriticalRegion { $0 = error }
}
state.withCriticalRegion { $0 = true }
afterSleep.fulfill()
}
XCTAssertFalse(state.withCriticalRegion { $0 })
clock.advance()
task.cancel()
wait(for: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
XCTAssertTrue(failure.withCriticalRegion { $0 is CancellationError })
}
func test_sleep_cancel_before_advance() async {
let clock = ManualClock()
let start = clock.now
let afterSleep = expectation(description: "after sleep")
let state = ManagedCriticalState(false)
let failure = ManagedCriticalState<Error?>(nil)
let task = Task {
do {
try await clock.sleep(until: start.advanced(by: .steps(3)))
} catch {
failure.withCriticalRegion { $0 = error }
}
state.withCriticalRegion { $0 = true }
afterSleep.fulfill()
}
XCTAssertFalse(state.withCriticalRegion { $0 })
task.cancel()
wait(for: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
XCTAssertTrue(failure.withCriticalRegion { $0 is CancellationError })
}
}
| apache-2.0 |
material-motion/material-motion-swift | src/interactions/Tossable.swift | 2 | 2993 | /*
Copyright 2016-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
/**
Allows a view to be tossed by a gesture recognizer and animated to a destination using a spring.
Composed of two sub-interactions: Draggable and Spring.
The spring interaction will be disabled while the drag interaction is active. The spring
interaction is enabled once the drag interaction comes to rest.
**Affected properties**
- `view.layer.position`
**Constraints**
CGPoint constraints may be applied to this interaction. Common constraints include:
- `{ $0.xLocked(to: somePosition) }`
- `{ $0.yLocked(to: somePosition) }`
*/
public final class Tossable: Interaction, Stateful {
/**
The interaction governing drag behaviors.
*/
public let draggable: Draggable
/**
The interaction governing the spring animation.
*/
public let spring: Spring<CGPoint>
public init(spring: Spring<CGPoint> = Spring(), draggable: Draggable = Draggable()) {
self.spring = spring
self.draggable = draggable
}
public func add(to view: UIView,
withRuntime runtime: MotionRuntime,
constraints: ConstraintApplicator<CGPoint>? = nil) {
let position = runtime.get(view.layer).position
// Order matters:
//
// 1. When we hand off from the gesture to the spring we want Tossable's state to still be
// "active", so we observe the spring's state first and observe draggable's state last; this
// ensures that the spring interaction is active before the draggable interaction is at rest.
// 2. The spring's initial velocity must be set before it's re-enabled.
// 3. The spring must be registered before draggable in case draggable's gesture is already
// active and will want to immediately read the current state of the position property.
aggregateState.observe(state: spring.state, withRuntime: runtime)
runtime.add(draggable.finalVelocity, to: spring.initialVelocity)
runtime.toggle(spring, inReactionTo: draggable)
runtime.add(spring, to: position, constraints: constraints)
runtime.add(draggable, to: view, constraints: constraints)
aggregateState.observe(state: draggable.state, withRuntime: runtime)
}
/**
The current state of the interaction.
*/
public var state: MotionObservable<MotionState> {
return aggregateState.asStream()
}
let aggregateState = AggregateMotionState()
}
| apache-2.0 |
prajwalabove/LinuxCommandList | linuxcommands/DetailViewController.swift | 1 | 1421 | //
// DetailViewController.swift
// linuxcommands
//
// Created by Prajwal on 10/11/15.
// Copyright © 2015 Above Solutions India Pvt Ltd. All rights reserved.
//
import UIKit
let websearchURL:String = "https://www.google.co.in/#q="
class DetailViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
var searchKey:String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.title = self.searchKey
self.requestWebSearchWithKey(self.searchKey)
}
func requestWebSearchWithKey(searchKey:String) {
let encodedSearchKey = (searchKey+" in linux").stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let searchURLString = websearchURL+encodedSearchKey!
if let url:NSURL = NSURL(string: searchURLString)! {
let requestObj:NSMutableURLRequest = NSMutableURLRequest(URL: url)
self.webView.loadRequest(requestObj)
}
}
// MARK: UIWebViewDelegate
func webViewDidFinishLoad(webView: UIWebView) {
}
}
| mit |
satorun/designPattern | Builder/Builder/ViewController.swift | 1 | 932 | //
// ViewController.swift
// Builder
//
// Created by satorun on 2016/02/03.
// Copyright © 2016年 satorun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let textBuilder = TextBuilder()
let textDirector = Director(builder: textBuilder)
textDirector.construct()
let textResult = textBuilder.getResult()
print(textResult)
let htmlBuilder = HtmlBuilder()
let htmlDirector = Director(builder: htmlBuilder)
htmlDirector.construct()
let htmlResult = htmlBuilder.getResult()
print(htmlResult)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
tschmidt64/EE464D | Music Lamp/ColorPickerViewController.swift | 1 | 2874 | //
// FirstViewController.swift
// Music Lamp
//
// Created by Taylor Schmidt on 1/30/17.
// Copyright © 2017 Taylor Schmidt. All rights reserved.
//
import UIKit
import SwiftHSVColorPicker
//import SwiftHTTP
import SwiftSocket
class ColorPickerViewController: UIViewController {
var selectedColor = UIColor.white
@IBOutlet weak var colorPicker: SwiftHSVColorPicker!
override func viewDidLoad() {
super.viewDidLoad()
colorPicker.setViewColor(selectedColor)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func setLightsButtonPressed(_ sender: Any) {
if let color = colorPicker.color {
sendLightColorRequest(color: color)
} else {
print("ERROR: Couldn't unwrap the color picker's color")
}
}
func sendLightColorRequest(color: UIColor) {
// IP = 192.168.43.26
// Make sure that socket calls are one at a time (synchronous), open and close for each call
let client = TCPClient(address: "192.168.43.26", port: 5001)
let msg = "api_call=add_theme&theme_id=2&special=0&color=0xFF0000&song=song.wav"
switch client.connect(timeout: 10) {
case .success:
switch client.send(string: msg) {
case .success:
guard let data = client.read(1024*10) else { return }
if let response = String(bytes: data, encoding: .utf8) {
print(response)
} else {
print("No response")
}
case .failure(let error):
print(error)
}
case .failure(let error):
print(error)
}
client.close()
}
/*
func sendLightColorRequest(color: UIColor) {
do {
// the url sent will be https://google.com?hello=world¶m2=value2
// let params = ["hello": "world", "param2": "value2"]
// IP = 192.168.43.26
// Make sure that socket calls are one at a time (synchronous), open and close for each call
let params = ["hello": "world", "param2": "value2"]
let boundary = "AaB03x"
let opt = try HTTP.POST("https://google.com", parameters: params)
print("Request:")
print("\(opt)")
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
print("opt finished: \(response.description)")
}
} catch let error {
print("got an error creating the request: \(error)")
}
}
*/
}
| mit |
frtlupsvn/Vietnam-To-Go | Pods/EZSwiftExtensions/Sources/UIViewControllerExtensions.swift | 1 | 6955 | //
// UIViewControllerExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension UIViewController {
// MARK: - Notifications
//TODO: Document this part
public func addNotificationObserver(name: String, selector: Selector) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: selector, name: name, object: nil)
}
public func removeNotificationObserver(name: String) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: name, object: nil)
}
public func removeNotificationObserver() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public func addKeyboardWillShowNotification() {
self.addNotificationObserver(UIKeyboardWillShowNotification, selector: "keyboardWillShowNotification:");
}
public func addKeyboardDidShowNotification() {
self.addNotificationObserver(UIKeyboardDidShowNotification, selector: "keyboardDidShowNotification:");
}
public func addKeyboardWillHideNotification() {
self.addNotificationObserver(UIKeyboardWillHideNotification, selector: "keyboardWillHideNotification:");
}
public func addKeyboardDidHideNotification() {
self.addNotificationObserver(UIKeyboardDidHideNotification, selector: "keyboardDidHideNotification:");
}
public func removeKeyboardWillShowNotification() {
self.removeNotificationObserver(UIKeyboardWillShowNotification);
}
public func removeKeyboardDidShowNotification() {
self.removeNotificationObserver(UIKeyboardDidShowNotification);
}
public func removeKeyboardWillHideNotification() {
self.removeNotificationObserver(UIKeyboardWillHideNotification);
}
public func removeKeyboardDidHideNotification() {
self.removeNotificationObserver(UIKeyboardDidHideNotification);
}
public func keyboardDidShowNotification(notification: NSNotification) {
let nInfo = notification.userInfo as! [String: NSValue]
let value = nInfo[UIKeyboardFrameEndUserInfoKey]
let frame = value?.CGRectValue()
keyboardDidShowWithFrame(frame!)
}
public func keyboardWillShowNotification(notification: NSNotification) {
let nInfo = notification.userInfo as! [String: NSValue]
let value = nInfo[UIKeyboardFrameEndUserInfoKey]
let frame = value?.CGRectValue()
keyboardWillShowWithFrame(frame!)
}
public func keyboardWillHideNotification(notification: NSNotification) {
let nInfo = notification.userInfo as! [String: NSValue]
let value = nInfo[UIKeyboardFrameEndUserInfoKey]
let frame = value?.CGRectValue()
keyboardWillHideWithFrame(frame!)
}
public func keyboardDidHideNotification(notification: NSNotification) {
let nInfo = notification.userInfo as! [String: NSValue]
let value = nInfo[UIKeyboardFrameEndUserInfoKey]
let frame = value?.CGRectValue()
keyboardDidHideWithFrame(frame!)
}
public func keyboardWillShowWithFrame(frame: CGRect) {
}
public func keyboardDidShowWithFrame(frame: CGRect) {
}
public func keyboardWillHideWithFrame(frame: CGRect) {
}
public func keyboardDidHideWithFrame(frame: CGRect) {
}
// MARK: - VC Container
/// EZSwiftExtensions
public var top: CGFloat {
get {
if let me = self as? UINavigationController {
return me.visibleViewController!.top
}
if let nav = self.navigationController {
if nav.navigationBarHidden {
return view.top
} else {
return nav.navigationBar.bottom
}
} else {
return view.top
}
}
}
/// EZSwiftExtensions
public var bottom: CGFloat {
get {
if let me = self as? UINavigationController {
return me.visibleViewController!.bottom
}
if let tab = tabBarController {
if tab.tabBar.hidden {
return view.bottom
} else {
return tab.tabBar.top
}
} else {
return view.bottom
}
}
}
/// EZSwiftExtensions
public var tabBarHeight: CGFloat {
get {
if let me = self as? UINavigationController {
return me.visibleViewController!.tabBarHeight
}
if let tab = self.tabBarController {
return tab.tabBar.frame.size.height
}
return 0
}
}
/// EZSwiftExtensions
public var navigationBarHeight: CGFloat {
get {
if let me = self as? UINavigationController {
return me.visibleViewController!.navigationBarHeight
}
if let nav = self.navigationController {
return nav.navigationBar.h
}
return 0
}
}
/// EZSwiftExtensions
public var navigationBarColor: UIColor? {
get {
if let me = self as? UINavigationController {
return me.visibleViewController!.navigationBarColor
}
return navigationController?.navigationBar.tintColor
} set(value) {
navigationController?.navigationBar.barTintColor = value
}
}
/// EZSwiftExtensions
public var navBar: UINavigationBar? {
get {
return navigationController?.navigationBar
}
}
/// EZSwiftExtensions
public var applicationFrame: CGRect {
get {
return CGRect(x: view.x, y: top, width: view.w, height: bottom - top)
}
}
// MARK: - VC Flow
/// EZSwiftExtensions
public func pushVC(vc: UIViewController) {
navigationController?.pushViewController(vc, animated: true)
}
/// EZSwiftExtensions
public func popVC() {
navigationController?.popViewControllerAnimated(true)
}
/// EZSwiftExtensions
public func presentVC(vc: UIViewController) {
presentViewController(vc, animated: true, completion: nil)
}
/// EZSwiftExtensions
public func dismissVC(completion completion: (() -> Void)? ) {
dismissViewControllerAnimated(true, completion: completion)
}
/// EZSwiftExtensions
public func addAsChildViewController(vc: UIViewController, toView: UIView){
vc.view.frame = toView.frame
toView.addSubview(vc.view)
self.addChildViewController(vc)
vc.didMoveToParentViewController(self)
}
}
| mit |
svenbacia/iTunesSearchAPI | Sources/iTunesSearchAPI/SearchError.swift | 1 | 434 | //
// Error.swift
// iTunesSearchAPI
//
// Created by Sven Bacia on 27.02.16.
// Copyright © 2016 Sven Bacia. All rights reserved.
//
import Foundation
public extension iTunes {
public enum Error: Swift.Error {
case unknown
case invalidSearchTerm
case invalidURL
case invalidServerResponse
case serverError(Int)
case missingData
case invalidJSON(Swift.Error)
}
}
| mit |
ahmad-raza/QDStepsController | Example/QDStepsController/HomeViewController.swift | 1 | 920 | //
// HomeViewController.swift
//
//
// Created by Ahmad Raza on 3/17/16.
// Copyright © 2016 Ahmad Raza. All rights reserved.
//
import UIKit
import QDStepsController
class HomeViewController: QDNavigationController {
override func viewDidLoad() {
super.viewDidLoad()
setStepsCount(4)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
practicalswift/swift | test/Driver/basic_output_file_map.swift | 8 | 1608 | // RUN: echo "{\"%/s\": {\"object\": \"/build/basic_output_file_map.o\"}, \"%/S/Inputs/main.swift\": {\"object\": \"/build/main.o\"}, \"%/S/Inputs/lib.swift\": {\"object\": \"/build/lib.o\"}}" > %t.json
// RUN: %swiftc_driver -driver-print-output-file-map -target x86_64-apple-macosx10.9 -emit-executable %/s %/S/Inputs/main.swift %/S/Inputs/lib.swift -o /build/basic_output_file_map.out -module-name OutputFileMap -output-file-map %t.json 2>&1 | %FileCheck %/s -check-prefix=DUMPOFM
// RUN: %swiftc_driver -driver-print-bindings -target x86_64-apple-macosx10.9 -emit-executable %/s %/S/Inputs/main.swift %/S/Inputs/lib.swift -o /build/basic_output_file_map.out -module-name OutputFileMap -output-file-map %t.json 2>&1 | %FileCheck %/s -check-prefix=BINDINGS
// DUMPOFM: {{.*}}/Inputs/lib.swift -> object: "/build/lib.o"
// DUMPOFM: {{.*}}/Inputs/main.swift -> object: "/build/main.o"
// DUMPOFM: {{.*}}/basic_output_file_map.swift -> object: "/build/basic_output_file_map.o"
// BINDINGS: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}/basic_output_file_map.swift"], output: {object: "/build/basic_output_file_map.o"}
// BINDINGS: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}/Inputs/main.swift"], output: {object: "/build/main.o"}
// BINDINGS: # "x86_64-apple-macosx10.9" - "swift{{c?(\.EXE)?}}", inputs: ["{{.*}}/Inputs/lib.swift"], output: {object: "/build/lib.o"}
// BINDINGS: # "x86_64-apple-macosx10.9" - "ld{{(\.exe)?}}", inputs: ["/build/basic_output_file_map.o", "/build/main.o", "/build/lib.o"], output: {image: "/build/basic_output_file_map.out"}
| apache-2.0 |
practicalswift/swift | validation-test/stdlib/CoreGraphics-execute.swift | 15 | 15274 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
import CoreGraphics
import StdlibUnittest
let CoreGraphicsTests = TestSuite("CoreGraphics")
//===----------------------------------------------------------------------===//
// CGAffineTransform
//===----------------------------------------------------------------------===//
CoreGraphicsTests.test("CGAffineTransform/Equatable") {
checkEquatable([
CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0),
CGAffineTransform.identity,
CGAffineTransform(a: 1, b: 10, c: 10, d: 1, tx: 0, ty: 0),
CGAffineTransform(a: 1, b: 10, c: 10, d: 1, tx: 0, ty: 0),
] as [CGAffineTransform],
oracle: { $0 / 2 == $1 / 2 })
}
//===----------------------------------------------------------------------===//
// CGColor
//===----------------------------------------------------------------------===//
CoreGraphicsTests.test("CGColor/Equatable") {
checkEquatable([
CGColor(red: 1, green: 0, blue: 0, alpha: 1),
CGColor(red: 1, green: 0, blue: 0, alpha: 0),
CGColor(red: 0, green: 1, blue: 0, alpha: 1),
CGColor(red: 0, green: 1, blue: 0, alpha: 0),
CGColor(red: 0, green: 0, blue: 1, alpha: 1),
CGColor(red: 0, green: 0, blue: 1, alpha: 0),
] as [CGColor],
oracle: { $0 == $1 })
}
CoreGraphicsTests.test("CGColor.components") {
let red = CGColor(red: 1, green: 0, blue: 0, alpha: 1)
let components = red.components!
expectEqual(components.count, 4)
expectEqual(components[0], 1)
expectEqual(components[1], 0)
expectEqual(components[2], 0)
expectEqual(components[3], 1)
}
CoreGraphicsTests.test("CGColor/ExpressibleByColorLiteral") {
let colorLit: CGColor = #colorLiteral(red: 0.25, green: 0.5, blue: 0.75,
alpha: 1.0)
let components = colorLit.components!
expectEqual(components.count, 4)
expectEqual(components[0], 0.25)
expectEqual(components[1], 0.50)
expectEqual(components[2], 0.75)
expectEqual(components[3], 1.0)
}
//===----------------------------------------------------------------------===//
// CGPoint
//===----------------------------------------------------------------------===//
CoreGraphicsTests.test("CGPoint/Equatable") {
checkEquatable([
CGPoint(x: 0, y: 0),
CGPoint(x: -1, y: -1),
CGPoint(x: -1, y: 0),
CGPoint(x: 0, y: -1),
CGPoint(x: 1, y: 1),
CGPoint(x: 1, y: 0),
CGPoint(x: 0, y: 1),
CGPoint(x: 1.nextUp, y: 1.nextUp),
CGPoint(x: 1.nextUp, y: 0),
CGPoint(x: 0, y: 1.nextUp),
CGPoint(x: CGFloat.greatestFiniteMagnitude, y: 0),
] as [CGPoint],
oracle: { $0 == $1 })
}
CoreGraphicsTests.test("CGPoint.init(x:y:)") {
var fractional = CGPoint()
fractional.x = 1.25
fractional.y = 2.25
var negativeFractional = CGPoint()
negativeFractional.x = -1.25
negativeFractional.y = -2.25
var integral = CGPoint()
integral.x = 1.0
integral.y = 2.0
var negativeIntegral = CGPoint()
negativeIntegral.x = -1.0
negativeIntegral.y = -2.0
// Initialize from floating point literals.
expectEqual(fractional, CGPoint(x: 1.25, y: 2.25))
expectEqual(negativeFractional, CGPoint(x: -1.25, y: -2.25))
// Initialize from integer literals.
expectEqual(integral, CGPoint(x: 1, y: 2))
expectEqual(negativeIntegral, CGPoint(x: -1, y: -2))
expectEqual(fractional, CGPoint(x: 1.25 as CGFloat, y: 2.25 as CGFloat))
expectEqual(fractional, CGPoint(x: 1.25 as Double, y: 2.25 as Double))
expectEqual(integral, CGPoint(x: 1 as Int, y: 2 as Int))
}
CoreGraphicsTests.test("CGPoint.dictionaryRepresentation, CGPoint.init(dictionaryRepresentation:)") {
let point = CGPoint(x: 1, y: 2)
let dict = point.dictionaryRepresentation
let newPoint = CGPoint(dictionaryRepresentation: dict)
expectEqual(point, newPoint)
}
CoreGraphicsTests.test("CGPoint.zero") {
expectEqual(0.0, CGPoint.zero.x)
expectEqual(0.0, CGPoint.zero.y)
}
//===----------------------------------------------------------------------===//
// CGSize
//===----------------------------------------------------------------------===//
CoreGraphicsTests.test("CGSize/Equatable") {
checkEquatable([
CGSize(width: 0, height: 0),
CGSize(width: -1, height: -1),
CGSize(width: -1, height: 0),
CGSize(width: 0, height: -1),
CGSize(width: 1, height: 1),
CGSize(width: 1, height: 0),
CGSize(width: 0, height: 1),
CGSize(width: 1.nextUp, height: 1.nextUp),
CGSize(width: 1.nextUp, height: 0),
CGSize(width: 0, height: 1.nextUp),
CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0),
] as [CGSize],
oracle: { $0 == $1 })
}
CoreGraphicsTests.test("CGSize.init(width:height:)") {
var fractional = CGSize()
fractional.width = 1.25
fractional.height = 2.25
var negativeFractional = CGSize()
negativeFractional.width = -1.25
negativeFractional.height = -2.25
var integral = CGSize()
integral.width = 1.0
integral.height = 2.0
var negativeIntegral = CGSize()
negativeIntegral.width = -1.0
negativeIntegral.height = -2.0
// Initialize from floating point literals.
expectEqual(fractional, CGSize(width: 1.25, height: 2.25))
expectEqual(negativeFractional, CGSize(width: -1.25, height: -2.25))
// Initialize from integer literals.
expectEqual(integral, CGSize(width: 1, height: 2))
expectEqual(negativeIntegral, CGSize(width: -1, height: -2))
expectEqual(fractional, CGSize(width: 1.25 as CGFloat, height: 2.25 as CGFloat))
expectEqual(fractional, CGSize(width: 1.25 as Double, height: 2.25 as Double))
expectEqual(integral, CGSize(width: 1 as Int, height: 2 as Int))
}
CoreGraphicsTests.test("CGSize.dictionaryRepresentation, CGSize.init(dictionaryRepresentation:)") {
let size = CGSize(width: 3, height: 4)
let dict = size.dictionaryRepresentation
let newSize = CGSize(dictionaryRepresentation: dict)
expectEqual(size, newSize)
}
CoreGraphicsTests.test("CGSize.zero") {
expectEqual(0.0, CGSize.zero.width)
expectEqual(0.0, CGSize.zero.height)
}
//===----------------------------------------------------------------------===//
// CGRect
//===----------------------------------------------------------------------===//
CoreGraphicsTests.test("CGRect/Equatable") {
checkEquatable([
CGRect.null,
CGRect(x: 0, y: 0, width: 0, height: 0),
CGRect(x: 1.25, y: 2.25, width: 3.25, height: 4.25),
CGRect(x: -1.25, y: -2.25, width: -3.25, height: -4.25),
CGRect(x: 1, y: 2, width: 3, height: 4),
CGRect(x: -1, y: -2, width: -3, height: -4),
] as [CGRect],
oracle: { $0 == $1 })
}
CoreGraphicsTests.test("CGRect.init(x:y:width:height:)") {
var fractional = CGRect()
fractional.origin = CGPoint(x: 1.25, y: 2.25)
fractional.size = CGSize(width: 3.25, height: 4.25)
var negativeFractional = CGRect()
negativeFractional.origin = CGPoint(x: -1.25, y: -2.25)
negativeFractional.size = CGSize(width: -3.25, height: -4.25)
var integral = CGRect()
integral.origin = CGPoint(x: 1.0, y: 2.0)
integral.size = CGSize(width: 3.0, height: 4.0)
var negativeIntegral = CGRect()
negativeIntegral.origin = CGPoint(x: -1.0, y: -2.0)
negativeIntegral.size = CGSize(width: -3.0, height: -4.0)
// Initialize from floating point literals.
expectEqual(fractional, CGRect(x: 1.25, y: 2.25, width: 3.25, height: 4.25))
expectEqual(
negativeFractional,
CGRect(x: -1.25, y: -2.25, width: -3.25, height: -4.25))
// Initialize from integer literals.
expectEqual(integral, CGRect(x: 1, y: 2, width: 3, height: 4))
expectEqual(negativeIntegral, CGRect(x: -1, y: -2, width: -3, height: -4))
expectEqual(
fractional,
CGRect(
x: 1.25 as CGFloat, y: 2.25 as CGFloat,
width: 3.25 as CGFloat, height: 4.25 as CGFloat))
expectEqual(
fractional,
CGRect(
x: 1.25 as Double, y: 2.25 as Double,
width: 3.25 as Double, height: 4.25 as Double))
expectEqual(
integral,
CGRect(
x: 1 as Int, y: 2 as Int,
width: 3 as Int, height: 4 as Int))
}
CoreGraphicsTests.test("CGRect.init(origin:size:)") {
let point = CGPoint(x: 1.25, y: 2.25)
let size = CGSize(width: 3.25, height: 4.25)
expectEqual(
CGRect(x: 1.25, y: 2.25, width: 3.25, height: 4.25),
CGRect(origin: point, size: size))
}
CoreGraphicsTests.test("CGRect.dictionaryRepresentation, CGRect.init(dictionaryRepresentation:)") {
let point = CGPoint(x: 1, y: 2)
let size = CGSize(width: 3, height: 4)
let rect = CGRect(origin: point, size: size)
let dict = rect.dictionaryRepresentation
let newRect = CGRect(dictionaryRepresentation: dict)
expectEqual(rect, newRect)
}
CoreGraphicsTests.test("CGRect.isNull") {
expectFalse(CGRect.infinite.isNull)
expectTrue(CGRect.null.isNull)
expectFalse(CGRect.zero.isNull)
expectFalse(CGRect(x: 0, y: 0, width: 10, height: 20).isNull)
}
CoreGraphicsTests.test("CGRect.isEmpty") {
expectFalse(CGRect.infinite.isEmpty)
expectTrue(CGRect.null.isEmpty)
expectTrue(CGRect.zero.isEmpty)
expectFalse(CGRect(x: 0, y: 0, width: 10, height: 20).isEmpty)
}
CoreGraphicsTests.test("CGRect.isInfinite") {
expectTrue(CGRect.infinite.isInfinite)
expectFalse(CGRect.null.isInfinite)
expectFalse(CGRect.zero.isInfinite)
expectFalse(CGRect(x: 0, y: 0, width: 10, height: 20).isInfinite)
}
CoreGraphicsTests.test("CGRect.contains(CGPoint)") {
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
expectTrue(rect.contains(CGPoint(x: 15, y: 25)))
expectFalse(rect.contains(CGPoint(x: -15, y: 25)))
}
CoreGraphicsTests.test("CGRect.contains(CGRect)") {
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102)
expectTrue(bigRect.contains(rect))
expectFalse(rect.contains(bigRect))
}
CoreGraphicsTests.test("CGRect.divided()") {
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
let (slice, remainder) =
rect.divided(atDistance: 5, from: CGRectEdge.minXEdge)
expectEqual(CGRect(x: 11.25, y: 22.25, width: 5.0, height: 44.25), slice)
expectEqual(CGRect(x: 16.25, y: 22.25, width: 28.25, height: 44.25), remainder)
}
CoreGraphicsTests.test("CGRect.standardized") {
var unstandard = CGRect(x: 10, y: 20, width: -30, height: -50)
var standard = unstandard.standardized
expectEqual(CGPoint(x: 10, y: 20), unstandard.origin)
expectEqual(CGPoint(x: -20, y: -30), standard.origin)
expectEqual(CGSize(width: -30, height: -50), unstandard.size)
expectEqual(CGSize(width: 30, height: 50), standard.size)
expectEqual(unstandard, standard)
expectEqual(standard, standard.standardized)
expectEqual(30, unstandard.width)
expectEqual(30, standard.width)
expectEqual(50, unstandard.height)
expectEqual(50, standard.height)
expectEqual(-20, unstandard.minX)
expectEqual(-5, unstandard.midX)
expectEqual(10, unstandard.maxX)
expectEqual(-20, standard.minX)
expectEqual(-5, standard.midX)
expectEqual(10, standard.maxX)
expectEqual(-30, unstandard.minY)
expectEqual(-5, unstandard.midY)
expectEqual(20, unstandard.maxY)
expectEqual(-30, standard.minY)
expectEqual(-5, standard.midY)
expectEqual(20, standard.maxY)
}
CoreGraphicsTests.test("CGRect.insetBy(self:dx:dy:)") {
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
expectEqual(
CGRect(x: 12.25, y: 20.25, width: 31.25, height: 48.25),
rect.insetBy(dx: 1, dy: -2))
}
CoreGraphicsTests.test("CGRect.offsetBy(self:dx:dy:)") {
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
expectEqual(
CGRect(x: 14.25, y: 18.25, width: 33.25, height: 44.25),
rect.offsetBy(dx: 3, dy: -4))
}
CoreGraphicsTests.test("CGRect.integral") {
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
expectEqual(
CGRect(x: 11, y: 22, width: 34, height: 45),
rect.integral)
}
CoreGraphicsTests.test("CGRect.union(_:)") {
let smallRect = CGRect(x: 10, y: 25, width: 5, height: -5)
let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102)
let distantRect = CGRect(x: 1000, y: 2000, width: 1, height: 1)
let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
expectEqual(
CGRect(x: 10.0, y: 20.0, width: 34.5, height: 46.5),
rect.union(smallRect))
expectEqual(
CGRect(x: 1.0, y: 2.0, width: 101.0, height: 102.0),
rect.union(bigRect))
expectEqual(
CGRect(x: 11.25, y: 22.25, width: 989.75, height: 1978.75),
rect.union(distantRect))
expectEqual(
CGRect(x: 1.0, y: 2.0, width: 1000.0, height: 1999.0),
rect.union(smallRect).union(bigRect).union(distantRect))
}
CoreGraphicsTests.test("CGRect.intersection(_:)") {
let smallRect = CGRect(x: 10, y: 25, width: 5, height: -5)
let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102)
let distantRect = CGRect(x: 1000, y: 2000, width: 1, height: 1)
var rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25)
expectTrue(rect.intersects(smallRect))
expectEqual(
CGRect(x: 11.25, y: 22.25, width: 3.75, height: 2.75),
rect.intersection(smallRect))
expectTrue(rect.intersects(bigRect))
expectEqual(
CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25),
rect.intersection(bigRect))
expectFalse(rect.intersects(distantRect))
expectEqual(CGRect.null, rect.intersection(distantRect))
expectFalse(
rect
.intersection(smallRect)
.intersection(bigRect)
.isEmpty)
expectTrue(
rect
.intersection(smallRect)
.intersection(bigRect)
.intersection(distantRect)
.isEmpty)
}
//===----------------------------------------------------------------------===//
// CGVector
//===----------------------------------------------------------------------===//
CoreGraphicsTests.test("CGVector/Equatable") {
checkEquatable([
CGVector(dx: 0, dy: 0),
CGVector(dx: -1, dy: -1),
CGVector(dx: -1, dy: 0),
CGVector(dx: 0, dy: -1),
CGVector(dx: 1, dy: 1),
CGVector(dx: 1, dy: 0),
CGVector(dx: 0, dy: 1),
CGVector(dx: 1.nextUp, dy: 1.nextUp),
CGVector(dx: 1.nextUp, dy: 0),
CGVector(dx: 0, dy: 1.nextUp),
CGVector(dx: CGFloat.greatestFiniteMagnitude, dy: 0),
] as [CGVector],
oracle: { $0 == $1 })
}
CoreGraphicsTests.test("CGVector.init(dx:dy:)") {
var fractional = CGVector()
fractional.dx = 1.25
fractional.dy = 2.25
var negativeFractional = CGVector()
negativeFractional.dx = -1.25
negativeFractional.dy = -2.25
var integral = CGVector()
integral.dx = 1.0
integral.dy = 2.0
var negativeIntegral = CGVector()
negativeIntegral.dx = -1.0
negativeIntegral.dy = -2.0
// Initialize from floating point literals.
expectEqual(fractional, CGVector(dx: 1.25, dy: 2.25))
expectEqual(negativeFractional, CGVector(dx: -1.25, dy: -2.25))
// Initialize from integer literals.
expectEqual(integral, CGVector(dx: 1, dy: 2))
expectEqual(negativeIntegral, CGVector(dx: -1, dy: -2))
expectEqual(fractional, CGVector(dx: 1.25 as CGFloat, dy: 2.25 as CGFloat))
expectEqual(fractional, CGVector(dx: 1.25 as Double, dy: 2.25 as Double))
expectEqual(integral, CGVector(dx: 1 as Int, dy: 2 as Int))
}
CoreGraphicsTests.test("CGVector.zero") {
expectEqual(0.0, CGVector.zero.dx)
expectEqual(0.0, CGVector.zero.dy)
}
runAllTests()
| apache-2.0 |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionDomain/Limits/TransactionLimitsRepositoryAPI.swift | 1 | 831 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import Errors
import MoneyKit
import PlatformKit
/// Use this protocol to fetch limits data specific to an internal use case.
///
/// Implement this protocol in the Data Layer and use it only internally.
/// This IS NOT meant to be used by the `TransactionEngine`s to build a transaction. Use `TransactionLimitsServiceAPI` for that instead!
public protocol TransactionLimitsRepositoryAPI {
func fetchTradeLimits(
sourceCurrency: CurrencyType,
product: TransactionLimitsProduct
) -> AnyPublisher<TradeLimits, NabuNetworkError>
func fetchCrossBorderLimits(
source: LimitsAccount,
destination: LimitsAccount,
limitsCurrency: FiatCurrency
) -> AnyPublisher<CrossBorderLimits, NabuNetworkError>
}
| lgpl-3.0 |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/Community.swift | 1 | 7179 | //
// Community.swift
// AwesomeCore
//
// Created by Leonardo Vinicius Kaminski Ferreira on 30/01/18.
//
import Foundation
public struct CommunityData: Codable {
public let communities: Communities
}
public struct CommunityRootData: Codable {
public let data: CommunityListData
}
public struct CommunityListData: Codable {
public let communities: [Community]
}
public struct Communities: Codable {
public let publicGroups: [Community]
public let tribeMembership: [Community]
public let privateGroups: [Community]
}
public struct Community: Codable {
public let url: String?
public let type: String?
public let productIds: [String]?
public var passphrase: String?
public let name: String?
public let id: String?
public let groupId: String?
public let description: String?
public let backgroundAsset: QuestAsset?
}
// MARK: - Coding keys
//extension Communities {
// private enum CodingKeys: String, CodingKey {
// case publicGroups = "public_pages"
// case tribeMembership = "tribe_memberships"
// case privateGroups = "private_groups"
// }
//}
//
//extension Community {
// private enum CodingKeys: String, CodingKey {
// case id
// case productId = "awc_product_id"
// case groupId = "group_id"
// case imageUrl = "image_url"
// case name
// case passphrase
// case type = "group_type"
// case url
// }
//}
// MARK: - Equatable
extension Communities {
public static func ==(lhs: Communities, rhs: Communities) -> Bool {
if lhs.publicGroups.first?.groupId != rhs.publicGroups.first?.groupId {
return false
}
return true
}
}
// MARK: - Community Swift
//import Foundation
//import RealmSwift
//import Realm
//
//public struct CommunityData: Decodable {
//
// public let communities: Communities
//}
//
//public class Communities: Object, Decodable {
//
// @objc dynamic var id = 0
// public var publicGroups = List<Community>()
// public var tribeMembership = List<Community>()
// public var privateGroups = List<Community>()
//
// // MARK: - Realm
//
// override public static func primaryKey() -> String? {
// return "id"
// }
//
// public convenience init(publicGroups: [Community], tribeMembership: [Community], privateGroups: [Community]) {
// self.init()
//
// self.privateGroups.append(objectsIn: privateGroups)
// self.publicGroups.append(objectsIn: publicGroups)
// self.tribeMembership.append(objectsIn: tribeMembership)
// }
//
// public convenience required init(from decoder: Decoder) throws {
// let container = try decoder.container(keyedBy: CodingKeys.self)
//
// let privateGroups = try container.decode([Community].self, forKey: .privateGroups)
// let publicGroups = try container.decode([Community].self, forKey: .publicGroups)
// let tribeMembership = try container.decode([Community].self, forKey: .tribeMembership)
//
// self.init(publicGroups: publicGroups, tribeMembership: tribeMembership, privateGroups: privateGroups)
// }
//
// public required init() {
// super.init()
// }
//
// public required init(value: Any, schema: RLMSchema) {
// super.init(value: value, schema: schema)
// }
//
// public required init(realm: RLMRealm, schema: RLMObjectSchema) {
// super.init(realm: realm, schema: schema)
// }
//
//}
//
//public class Community: Object, Codable {
//
// @objc dynamic public var id: Int = 0
// @objc dynamic public var productId: String = ""
// @objc dynamic public var groupId: String = ""
// @objc dynamic public var imageUrl: String = ""
// @objc dynamic public var name: String = ""
// @objc dynamic public var passphrase: String = ""
// @objc dynamic public var type: String = ""
// @objc dynamic public var url: String = ""
//
// public convenience init(id: Int, productId: String, groupId: String, imageUrl: String, name: String, passphrase: String, type: String, url: String) {
// self.init()
//
// self.id = id
// self.productId = productId
// self.groupId = groupId
// self.imageUrl = imageUrl
// self.name = name
// self.passphrase = passphrase
// self.type = type
// self.url = url
// }
//
// public convenience required init(from decoder: Decoder) throws {
// let container = try decoder.container(keyedBy: CodingKeys.self)
//
// let id = try container.decode(Int.self, forKey: .id)
// let productId = try container.decode(String.self, forKey: .productId)
// let groupId = try container.decode(String.self, forKey: .groupId)
// let imageUrl = try container.decode(String.self, forKey: .imageUrl)
// let name = try container.decode(String.self, forKey: .name)
// let passphrase = try container.decode(String.self, forKey: .passphrase)
// let type = try container.decode(String.self, forKey: .type)
// let url = try container.decode(String.self, forKey: .url)
//
// self.init(id: id, productId: productId, groupId: groupId, imageUrl: imageUrl, name: name, passphrase: passphrase, type: type, url: url)
// }
//
// // MARK: - Realm
//
// override public static func primaryKey() -> String? {
// return "url"
// }
//
// public required init() {
// super.init()
// }
//
// public required init(value: Any, schema: RLMSchema) {
// super.init(value: value, schema: schema)
// }
//
// public required init(realm: RLMRealm, schema: RLMObjectSchema) {
// super.init(realm: realm, schema: schema)
// }
//
//}
//
//// MARK: - Realm
//extension CommunityData {
// public func save() {
// let realm = try! Realm()
//
// try! realm.write {
// realm.create(Communities.self, value: communities, update: true)
// }
// }
//}
//
//extension Community {
// public static func list() -> Results<Community> {
// let realm = try! Realm()
// return realm.objects(Community.self)
// }
//}
//
//extension Communities {
// public static func list() -> Results<Communities> {
// let realm = try! Realm()
// return realm.objects(Communities.self)
// }
//}
//
//extension Communities {
// private enum CodingKeys: String, CodingKey {
// case publicGroups = "public_pages"
// case tribeMembership = "tribe_memberships"
// case privateGroups = "private_groups"
// }
//}
//
//extension Community {
// private enum CodingKeys: String, CodingKey {
// case id
// case productId = "awc_product_id"
// case groupId = "group_id"
// case imageUrl = "image_url"
// case name
// case passphrase
// case type = "group_type"
// case url
// }
//}
//
//// MARK: - Equatable
//extension Communities {
// public static func ==(lhs: Communities, rhs: Communities) -> Bool {
// if lhs.publicGroups.first?.groupId != rhs.publicGroups.first?.groupId {
// return false
// }
// return true
// }
//}
| mit |
Fitbit/RxBluetoothKit | Source/Characteristic.swift | 1 | 9995 | import Foundation
import RxSwift
import CoreBluetooth
/// Characteristic is a class implementing ReactiveX which wraps CoreBluetooth functions related to interaction with [CBCharacteristic](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/)
public class Characteristic {
/// Intance of CoreBluetooth characteristic class
public let characteristic: CBCharacteristic
/// Service which contains this characteristic
public let service: Service
/// Current value of characteristic. If value is not present - it's `nil`.
public var value: Data? {
return characteristic.value
}
/// The Bluetooth UUID of the `Characteristic` instance.
public var uuid: CBUUID {
return characteristic.uuid
}
/// Flag which is set to true if characteristic is currently notifying
public var isNotifying: Bool {
return characteristic.isNotifying
}
/// Properties of characteristic. For more info about this refer to [CBCharacteristicProperties](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/#//apple_ref/c/tdef/CBCharacteristicProperties)
public var properties: CBCharacteristicProperties {
return characteristic.properties
}
/// Value of this property is an array of `Descriptor` objects. They provide more detailed information about characteristics value.
public var descriptors: [Descriptor]? {
return characteristic.descriptors?.map { Descriptor(descriptor: $0, characteristic: self) }
}
init(characteristic: CBCharacteristic, service: Service) {
self.characteristic = characteristic
self.service = service
}
convenience init(characteristic: CBCharacteristic, peripheral: Peripheral) throws {
let service = Service(peripheral: peripheral, service: try characteristic.unwrapService())
self.init(characteristic: characteristic, service: service)
}
/// Function that triggers descriptors discovery for characteristic.
/// - returns: `Single` that emits `next` with array of `Descriptor` instances, once they're discovered.
///
/// Observable can ends with following errors:
/// * `BluetoothError.descriptorsDiscoveryFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func discoverDescriptors() -> Single<[Descriptor]> {
return service.peripheral.discoverDescriptors(for: self)
}
/// Function that allow to observe writes that happened for characteristic.
/// - Returns: `Observable` that emits `next` with `Characteristic` instance every time when write has happened.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `BluetoothError.characteristicWriteFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func observeWrite() -> Observable<Characteristic> {
return service.peripheral.observeWrite(for: self)
}
/// Function that allows to know the exact time, when isNotyfing value has changed on a characteristic.
///
/// - returns: `Observable` emitting `Characteristic` when isNoytfing value has changed.
///
/// Observable can ends with following errors:
/// * `BluetoothError.characteristicSetNotifyValueFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func observeNotifyValue() -> Observable<Characteristic> {
return service.peripheral.observeNotifyValue(for: self)
}
/// Function that triggers write of data to characteristic. Write is called after subscribtion to `Observable` is made.
/// Behavior of this function strongly depends on [CBCharacteristicWriteType](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheral_Class/#//apple_ref/swift/enum/c:@E@CBCharacteristicWriteType), so be sure to check this out before usage of the method.
/// - parameter data: `Data` that'll be written to the `Characteristic`
/// - parameter type: Type of write operation. Possible values: `.withResponse`, `.withoutResponse`
/// - returns: `Single` whose emission depends on `CBCharacteristicWriteType` passed to the function call.
/// Behavior is following:
///
/// - `withResponse` - `Observable` emits `next` with `Characteristic` instance write was confirmed without any errors.
/// If any problem has happened, errors are emitted.
/// - `withoutResponse` - `Observable` emits `next` with `Characteristic` instance once write was called.
/// Result of this call is not checked, so as a user you are not sure
/// if everything completed successfully. Errors are not emitted
///
/// Observable can ends with following errors:
/// * `BluetoothError.characteristicWriteFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func writeValue(_ data: Data, type: CBCharacteristicWriteType) -> Single<Characteristic> {
return service.peripheral.writeValue(data, for: self, type: type)
}
/// Function that allow to observe value updates for `Characteristic` instance.
/// - Returns: `Observable` that emits `Next` with `Characteristic` instance every time when value has changed.
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `BluetoothError.characteristicReadFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func observeValueUpdate() -> Observable<Characteristic> {
return service.peripheral.observeValueUpdate(for: self)
}
/// Function that triggers read of current value of the `Characteristic` instance.
/// Read is called after subscription to `Observable` is made.
/// - Returns: `Single` which emits `next` with given characteristic when value is ready to read.
///
/// Observable can ends with following errors:
/// * `BluetoothError.characteristicReadFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func readValue() -> Single<Characteristic> {
return service.peripheral.readValue(for: self)
}
/// Setup characteristic notification in order to receive callbacks when given characteristic has been changed.
/// Returned observable will emit `Characteristic` on every notification change.
/// It is possible to setup more observables for the same characteristic and the lifecycle of the notification will be shared among them.
///
/// Notification is automaticaly unregistered once this observable is unsubscribed
///
/// - returns: `Observable` emitting `next` with `Characteristic` when given characteristic has been changed.
///
/// This is **infinite** stream of values.
///
/// Observable can ends with following errors:
/// * `BluetoothError.characteristicReadFailed`
/// * `BluetoothError.peripheralDisconnected`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func observeValueUpdateAndSetNotification() -> Observable<Characteristic> {
return service.peripheral.observeValueUpdateAndSetNotification(for: self)
}
}
extension Characteristic: CustomStringConvertible {
public var description: String {
return "\(type(of: self)) \(uuid)"
}
}
extension Characteristic: Equatable {}
extension Characteristic: UUIDIdentifiable {}
/// Compare two characteristics. Characteristics are the same when their UUIDs are the same.
///
/// - parameter lhs: First characteristic to compare
/// - parameter rhs: Second characteristic to compare
/// - returns: True if both characteristics are the same.
public func == (lhs: Characteristic, rhs: Characteristic) -> Bool {
return lhs.characteristic == rhs.characteristic
}
extension CBCharacteristic {
/// Unwrap the parent service or throw if the service is nil
func unwrapService() throws -> CBService {
guard let cbService = service as CBService? else {
throw BluetoothError.serviceDeallocated
}
return cbService
}
}
| apache-2.0 |
mhmiles/YouTubeInMP3Client | Carthage/Checkouts/Fuzi/FuziTests/DefaultNamespaceXPathTests.swift | 1 | 2651 | // DefaultNamespaceXPathTests.swift
// Copyright (c) 2015 Ce Zheng
//
// 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
import Fuzi
class DefaultNamespaceXPathTests: XCTestCase {
var document: XMLDocument!
override func setUp() {
super.setUp()
let filePath = NSBundle(forClass: DefaultNamespaceXPathTests.self).pathForResource("ocf", ofType: "xml")!
do {
document = try XMLDocument(data: NSData(contentsOfFile: filePath)!)
} catch {
XCTAssertFalse(true, "Error should not be thrown")
}
}
func testAbsoluteXPathWithDefaultNamespace() {
document.definePrefix("ocf", defaultNamespace: "urn:oasis:names:tc:opendocument:xmlns:container")
let xpath = "/ocf:container/ocf:rootfiles/ocf:rootfile"
var count = 0
for element in document.xpath(xpath) {
XCTAssertEqual("rootfile", element.tag, "tag should be `rootfile`")
count += 1
}
XCTAssertEqual(count, 1, "Element should be found at XPath \(xpath)")
}
func testRelativeXPathWithDefaultNamespace() {
document.definePrefix("ocf", defaultNamespace: "urn:oasis:names:tc:opendocument:xmlns:container")
let absoluteXPath = "/ocf:container/ocf:rootfiles"
let relativeXPath = "./ocf:rootfile"
var count = 0
for absoluteElement in document.xpath(absoluteXPath) {
for relativeElement in absoluteElement.xpath(relativeXPath) {
XCTAssertEqual("rootfile", relativeElement.tag, "tag should be rootfile")
count += 1
}
}
XCTAssertEqual(count, 1, "Element should be found at XPath '\(relativeXPath)' relative to XPath '\(absoluteXPath)'")
}
}
| mit |
PrajeetShrestha/ioshubgsheetwrite | ioshubSheets/LoginController.swift | 1 | 1854 | //
// LoginController.swift
// ioshubSheets
//
// Created by Prajeet Shrestha on 8/12/16.
// Copyright © 2016 eeposit. All rights reserved.
//
import UIKit
import GoogleAPIClient
import GTMOAuth2
class LoginController: UIViewController {
private let service = GlobalGTLService.sharedInstance.service
override func viewDidLoad() {
}
@IBAction func login(sender: AnyObject) {
self.presentViewController(createAuthController(), animated: true
, completion: nil)
}
private func createAuthController() -> GTMOAuth2ViewControllerTouch {
let scopeString = kScopes.joinWithSeparator(" ")
return GTMOAuth2ViewControllerTouch(
scope: scopeString,
clientID: kClientID,
clientSecret: nil,
keychainItemName: kKeychainItemName,
delegate: self,
finishedSelector: #selector(viewController(_:finishedWithAuth:error:))
)
}
func viewController(vc : UIViewController,
finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) {
if let error = error {
service.authorizer = nil
showAlert("Authentication Error", message: error.localizedDescription, controller: self)
return
}
service.authorizer = authResult
dismissViewControllerAnimated(true, completion: {
//Navigate to second view controller
if let authorizer = self.service.authorizer,
canAuth = authorizer.canAuthorize where canAuth {
//Navigation Code here
let controller = self.storyboard?.instantiateViewControllerWithIdentifier("tabBarController")
self.showViewController(controller!, sender: nil)
}
})
}
}
| apache-2.0 |
swordmanboy/KeychainGroupBySMB | _Main/DMPKeyChain-For-Master_Main_swift/DMPKeyChain-For-Master_Main_swiftTests/DMPKeyChain_For_Master_Main_swiftTests.swift | 2 | 1073 | //
// DMPKeyChain_For_Master_Main_swiftTests.swift
// DMPKeyChain-For-Master_Main_swiftTests
//
// Created by Apinun Wongintawang on 9/6/17.
// Copyright © 2017 True. All rights reserved.
//
import XCTest
@testable import DMPKeyChain_For_Master_Main_swift
class DMPKeyChain_For_Master_Main_swiftTests: 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.
}
}
}
| mit |
jerrypupu111/LearnDrawingToolSet | SwiftGL/Float.swift | 1 | 1557 | //
// Float.swift
// SwiftGL
//
// Created by Scott Bennett on 2014-06-08.
// Copyright (c) 2014 Scott Bennett. All rights reserved.
//
import Darwin
public let Pi = Float(M_PI)
public func radians(_ degrees: Float) -> Float {return degrees * Pi / 180}
public func degrees(_ radians: Float) -> Float {return radians * 180 / Pi}
public func sign(_ value: Float) -> Float {return (value > 0 ? 1 : (value < 0 ? -1 : 0))}
// Overload some mathematical functions to make them easier to call without having to worry about as many casts
//public func sqrt(value: Float) -> Float {return sqrtf(value);}
public func sin(_ radians: Float) -> Float {return sinf(radians)}
public func cos(_ radians: Float) -> Float {return cosf(radians)}
public func tan(_ radians: Float) -> Float {return tanf(radians)}
public func sin(radians: Float) -> Float {return sinf(radians)}
public func cos(radians: Float) -> Float {return cosf(radians)}
public func tan(radians: Float) -> Float {return tanf(radians)}
public func sin(degrees: Float) -> Float {return sinf(radians(degrees))}
public func cos(degrees: Float) -> Float {return cosf(radians(degrees))}
public func tan(degrees: Float) -> Float {return tanf(radians(degrees))}
public func clamp(_ value: Float, min: Float, max: Float) -> Float {return value < min ? min : (value > max ? max : value)}
public func mix(_ a: Float, b: Float, t: Float) -> Float {return a + (b - a) * t}
public func smoothstep(_ a: Float, b: Float, t: Float) -> Float {return mix(a, b: b, t: clamp(t * t * (3 - 2 * t), min: 0, max: 1))}
| mit |
TransitionKit/Union | Union/Presenter.swift | 1 | 3773 | //
// Presenter.swift
// Union
//
// Created by Hirohisa Kawasaki on 10/7/15.
// Copyright © 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
public class Presenter: NSObject {
let before = AnimationManager()
let present = AnimationManager()
var duration: NSTimeInterval {
return before.duration + present.duration
}
func animate(transitionContext: UIViewControllerContextTransitioning) {
setup(transitionContext)
start(transitionContext)
}
public class func animate() -> UIViewControllerAnimatedTransitioning {
return Presenter()
}
}
extension Presenter: UIViewControllerAnimatedTransitioning {
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
animate(transitionContext)
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
}
extension Presenter {
func setup(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
if let fromViewController = fromViewController, let toViewController = toViewController {
_setup(fromViewController: fromViewController, toViewController: toViewController)
}
}
func start(transitionContext: UIViewControllerContextTransitioning) {
before.completion = { [unowned self] in
self.startTransition(transitionContext)
}
before.start()
}
func startTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let containerView = transitionContext.containerView() else {
transitionContext.completeTransition(true)
return
}
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
if let toView = toViewController?.view, let fromView = fromViewController?.view {
switch transitionContext.presentationStyle() {
case .None:
containerView.insertSubview(toView, aboveSubview: fromView)
default:
// context.containerView() is UIPresentationController.view
if !fromView.isDescendantOfView(containerView) {
containerView.insertSubview(toView, aboveSubview: fromView)
}
break
}
}
present.completion = {
switch transitionContext.presentationStyle() {
case .None:
fromViewController?.view?.removeFromSuperview()
default:
break
}
transitionContext.completeTransition(true)
}
present.start()
}
private func _setup(fromViewController fromViewController: UIViewController, toViewController: UIViewController) {
if let delegate = fromViewController as? Delegate {
before.animations = delegate.animationsBeforeTransition(from: fromViewController, to: toViewController)
}
// present
let fromAnimations: [Animation] = (fromViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
let toAnimations: [Animation] = (toViewController as? Delegate)?.animationsDuringTransition(from: fromViewController, to: toViewController) ?? []
present.animations = fromAnimations + toAnimations
}
} | mit |
Eonil/HomeworkApp1 | Driver/HomeworkApp1/Operators.swift | 1 | 218 | //
// Operators.swift
// HomeworkApp1
//
// Created by Hoon H. on 2015/02/27.
//
//
import Foundation
infix operator ||| {
}
func ||| <T> (left:T?, right:T) -> T {
if let v = left {
return v
}
return right
} | mit |
ryanbaldwin/RealmSwiftFHIR | firekit/firekitTests/classes/PersonTests.swift | 1 | 10134 | //
// PersonTests.swift
// FireKit
//
// Generated from FHIR 1.0.2.7202 on 2017-11-13.
// 2017, SMART Health IT.
//
// Updated for Realm support by Ryan Baldwin on 2017-11-13
// Copyright @ 2017 Bunnyhug. All rights fall under Apache 2
//
import XCTest
import RealmSwift
import FireKit
class PersonTests: XCTestCase, RealmPersistenceTesting {
var realm: Realm!
override func setUp() {
realm = makeRealm()
}
func inflateFrom(filename: String) throws -> FireKit.Person {
return try inflateFrom(data: try readJSONFile(filename))
}
func inflateFrom(data: Data) throws -> FireKit.Person {
// print("Inflating FireKit.Person from data: \(data)")
let instance = try JSONDecoder().decode(FireKit.Person.self, from: data)
XCTAssertNotNil(instance, "Must have instantiated a test instance")
return instance
}
func testPerson1() {
var instance: FireKit.Person?
do {
instance = try runPerson1()
try runPerson1(try JSONEncoder().encode(instance!))
}
catch let error {
XCTAssertTrue(false, "Must instantiate and test Person successfully, but threw: \(error)")
}
testPersonRealm1(instance!)
}
func testPerson1Copying() {
do {
let instance = try runPerson1()
let copy = instance.copy() as? FireKit.Person
XCTAssertNotNil(copy)
XCTAssertNotEqual(instance.pk, copy?.pk)
try runPerson1(try JSONEncoder().encode(copy!))
} catch let error {
XCTAssertTrue(false, "Must copy and test Person successfully, but threw: \(error)")
}
}
func testPerson1Populatability() {
do {
let instance = try runPerson1()
let copy = FireKit.Person()
copy.populate(from: instance)
XCTAssertNotEqual(instance.pk, copy.pk)
try runPerson1(try JSONEncoder().encode(copy))
}
catch let error {
XCTAssertTrue(false, "Must populate an test Person successfully, but threw: \(error)")
}
}
func testPerson1NillingPopulatability() {
do {
let instance = try runPerson1()
try! realm.write { realm.add(instance) }
try! realm.write { instance.populate(from: FireKit.Person()) }
} catch let error {
XCTAssertTrue(false, "Must populate a test Person successfully, but threw: \(error)")
}
}
func testPersonRealm1(_ instance: FireKit.Person) {
// ensure we can write the instance, then fetch it, serialize it to JSON, then deserialize that JSON
// and ensure it passes the all the same tests.
try! realm.write { realm.add(instance) }
try! runPerson1(JSONEncoder().encode(realm.objects(FireKit.Person.self).first!))
// ensure we can update it.
try! realm.write { instance.implicitRules = "Rule #1" }
XCTAssertEqual(1, realm.objects(FireKit.Person.self).count)
XCTAssertEqual("Rule #1", realm.objects(FireKit.Person.self).first!.implicitRules)
// create a new instance with default key, save it, then populate it from instance JSON.
// PK should persist and not be overwritten.
let newInst = FireKit.Person()
try! realm.write { realm.add(newInst) }
// first time updating it should inflate children resources/elements which don't exist
let existing = realm.object(ofType: FireKit.Person.self, forPrimaryKey: newInst.pk)!
try! realm.write { realm.delete(instance) }
XCTAssertEqual(1, realm.objects(FireKit.Person.self).count)
try! realm.write { realm.delete(existing) }
XCTAssertEqual(0, realm.objects(FireKit.Person.self).count)
}
@discardableResult
func runPerson1(_ data: Data? = nil) throws -> FireKit.Person {
let inst = (data != nil) ? try inflateFrom(data: data!) : try inflateFrom(filename: "person-example-f002-ariadne.json")
XCTAssertTrue(inst.active.value ?? false)
XCTAssertEqual(inst.birthDate?.description, "1963")
XCTAssertEqual(inst.gender, "female")
XCTAssertEqual(inst.id, "f002")
XCTAssertEqual(inst.link[0].target?.display, "Ariadne Bor-Jansma")
XCTAssertEqual(inst.link[0].target?.reference, "RelatedPerson/f002")
XCTAssertEqual(inst.name[0].text, "Ariadne Bor-Jansma")
XCTAssertEqual(inst.name[0].use, "usual")
XCTAssertEqual(inst.photo?.contentType, "image/jpeg")
XCTAssertEqual(inst.telecom[0].system, "phone")
XCTAssertEqual(inst.telecom[0].use, "home")
XCTAssertEqual(inst.telecom[0].value, "+31201234567")
XCTAssertEqual(inst.text?.div, "<div>\n Ariadne Bor-Jansma\n </div>")
XCTAssertEqual(inst.text?.status, "generated")
return inst
}
func testPerson2() {
var instance: FireKit.Person?
do {
instance = try runPerson2()
try runPerson2(try JSONEncoder().encode(instance!))
}
catch let error {
XCTAssertTrue(false, "Must instantiate and test Person successfully, but threw: \(error)")
}
testPersonRealm2(instance!)
}
func testPerson2Copying() {
do {
let instance = try runPerson2()
let copy = instance.copy() as? FireKit.Person
XCTAssertNotNil(copy)
XCTAssertNotEqual(instance.pk, copy?.pk)
try runPerson2(try JSONEncoder().encode(copy!))
} catch let error {
XCTAssertTrue(false, "Must copy and test Person successfully, but threw: \(error)")
}
}
func testPerson2Populatability() {
do {
let instance = try runPerson2()
let copy = FireKit.Person()
copy.populate(from: instance)
XCTAssertNotEqual(instance.pk, copy.pk)
try runPerson2(try JSONEncoder().encode(copy))
}
catch let error {
XCTAssertTrue(false, "Must populate an test Person successfully, but threw: \(error)")
}
}
func testPerson2NillingPopulatability() {
do {
let instance = try runPerson2()
try! realm.write { realm.add(instance) }
try! realm.write { instance.populate(from: FireKit.Person()) }
} catch let error {
XCTAssertTrue(false, "Must populate a test Person successfully, but threw: \(error)")
}
}
func testPersonRealm2(_ instance: FireKit.Person) {
// ensure we can write the instance, then fetch it, serialize it to JSON, then deserialize that JSON
// and ensure it passes the all the same tests.
try! realm.write { realm.add(instance) }
try! runPerson2(JSONEncoder().encode(realm.objects(FireKit.Person.self).first!))
// ensure we can update it.
try! realm.write { instance.implicitRules = "Rule #1" }
XCTAssertEqual(1, realm.objects(FireKit.Person.self).count)
XCTAssertEqual("Rule #1", realm.objects(FireKit.Person.self).first!.implicitRules)
// create a new instance with default key, save it, then populate it from instance JSON.
// PK should persist and not be overwritten.
let newInst = FireKit.Person()
try! realm.write { realm.add(newInst) }
// first time updating it should inflate children resources/elements which don't exist
let existing = realm.object(ofType: FireKit.Person.self, forPrimaryKey: newInst.pk)!
try! realm.write { realm.delete(instance) }
XCTAssertEqual(1, realm.objects(FireKit.Person.self).count)
try! realm.write { realm.delete(existing) }
XCTAssertEqual(0, realm.objects(FireKit.Person.self).count)
}
@discardableResult
func runPerson2(_ data: Data? = nil) throws -> FireKit.Person {
let inst = (data != nil) ? try inflateFrom(data: data!) : try inflateFrom(filename: "person-example.json")
XCTAssertTrue(inst.active.value ?? false)
XCTAssertEqual(inst.address[0].city, "PleasantVille")
XCTAssertEqual(inst.address[0].line[0].value, "534 Erewhon St")
XCTAssertEqual(inst.address[0].postalCode, "3999")
XCTAssertEqual(inst.address[0].state, "Vic")
XCTAssertEqual(inst.address[0].use, "home")
XCTAssertEqual(inst.birthDate?.description, "1974-12-25")
XCTAssertEqual(inst.gender, "male")
XCTAssertEqual(inst.id, "example")
XCTAssertEqual(inst.identifier[0].assigner?.display, "Acme Healthcare")
XCTAssertEqual(inst.identifier[0].period?.start?.description, "2001-05-06")
XCTAssertEqual(inst.identifier[0].system, "urn:oid:1.2.36.146.595.217.0.1")
XCTAssertEqual(inst.identifier[0].type?.coding[0].code, "MR")
XCTAssertEqual(inst.identifier[0].type?.coding[0].system, "http://hl7.org/fhir/v2/0203")
XCTAssertEqual(inst.identifier[0].use, "usual")
XCTAssertEqual(inst.identifier[0].value, "12345")
XCTAssertEqual(inst.link[0].target?.display, "Peter Chalmers")
XCTAssertEqual(inst.link[0].target?.reference, "RelatedPerson/peter")
XCTAssertEqual(inst.link[1].target?.display, "Peter Chalmers")
XCTAssertEqual(inst.link[1].target?.reference, "Patient/example")
XCTAssertEqual(inst.name[0].family[0].value, "Chalmers")
XCTAssertEqual(inst.name[0].given[0].value, "Peter")
XCTAssertEqual(inst.name[0].given[1].value, "James")
XCTAssertEqual(inst.name[0].use, "official")
XCTAssertEqual(inst.name[1].given[0].value, "Jim")
XCTAssertEqual(inst.name[1].use, "usual")
XCTAssertEqual(inst.telecom[0].use, "home")
XCTAssertEqual(inst.telecom[1].system, "phone")
XCTAssertEqual(inst.telecom[1].use, "work")
XCTAssertEqual(inst.telecom[1].value, "(03) 5555 6473")
XCTAssertEqual(inst.text?.status, "generated")
return inst
}
} | apache-2.0 |
janicduplessis/buck | test/com/facebook/buck/swift/testdata/swift_on_swift/ios-parent/AppDelegate.swift | 1 | 311 | import UIKit
import iosdep1
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
IosFoo.bar()
return true
}
}
| apache-2.0 |
DanielOYC/Tools | YCEmoticonKeyboard/YCEmoticonKeyboard/YCEmoticonView/ViewModel/String+Emoji.swift | 1 | 656 | //
// String+Emoji.swift
// YCEmoticonKeyboard
//
// Created by daniel on 2017/8/20.
// Copyright © 2017年 daniel. All rights reserved.
//
import Foundation
extension String {
/// 返回当前字符串中 16 进制对应 的 emoji 字符串
var emoji: String {
// 文本扫描器-扫描指定格式的字符串
let scanner = Scanner(string: (self))
// unicode 的值
var value: UInt32 = 0
scanner.scanHexInt32(&value)
// 转换 unicode `字符`
let chr = Character(UnicodeScalar(value)!)
// 转换成字符串
return "\(chr)"
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/17474-swift-sourcemanager-getmessage.swift | 11 | 212 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
case
let {
enum k {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/17472-swift-constraints-constraintsystem-matchtypes.swift | 11 | 216 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
class A {
var d = b
var b = [ [Void{
| mit |
ello/ello-ios | Specs/Model/ExperienceUpdateSpec.swift | 1 | 1022 | ////
/// ExperienceUpdateSpec.swift
//
@testable import Ello
import Quick
import Nimble
class ExperienceUpdateSpec: QuickSpec {
override func spec() {
describe("ExperienceUpdate") {
it("should update post comment counts") {
let post1 = Post.stub(["id": "post1", "commentsCount": 1])
let post2 = Post.stub(["id": "post2", "commentsCount": 1])
let comment = ElloComment.stub([
"parentPost": post1,
"loadedFromPost": post2
])
ElloLinkedStore.shared.setObject(post1, forKey: post1.id, type: .postsType)
ContentChange.updateCommentCount(comment, delta: 1)
expect(post1.commentsCount) == 2
expect(post2.commentsCount) == 2
let storedPost = ElloLinkedStore.shared.getObject(post1.id, type: .postsType)
as! Post
expect(storedPost.commentsCount) == 2
}
}
}
}
| mit |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetryApi/Baggage/EmptyBaggage.swift | 1 | 592 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
/// An immutable implementation of the Baggage that does not contain any entries.
class EmptyBaggage: Baggage {
private init() {}
/// Returns the single instance of the EmptyBaggage class.
static var instance = EmptyBaggage()
static func baggageBuilder() -> BaggageBuilder {
return EmptyBaggageBuilder()
}
func getEntries() -> [Entry] {
return [Entry]()
}
func getEntryValue(key: EntryKey) -> EntryValue? {
return nil
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.