hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
9cf1aa9e922fbe97f9a12521b3d79700b3545b39 | 34,167 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import XCTest
import TSCBasic
@testable import SourceControl
import SPMTestSupport
import enum TSCUtility.Git
class GitRepositoryTests: XCTestCase {
/// Test the basic provider functions.
func testRepositorySpecifier() {
do {
let s1 = RepositorySpecifier(url: URL(string: "a")!)
let s2 = RepositorySpecifier(url: URL(string: "a")!)
let s3 = RepositorySpecifier(url: URL(string: "b")!)
XCTAssertEqual(s1, s1)
XCTAssertEqual(s1, s2)
XCTAssertEqual(Set([s1]), Set([s2]))
XCTAssertNotEqual(s1, s3)
XCTAssertNotEqual(s2, s3)
}
do {
let s1 = RepositorySpecifier(path: .init("/a"))
let s2 = RepositorySpecifier(path: .init("/a"))
let s3 = RepositorySpecifier(path: .init("/b"))
XCTAssertEqual(s1, s1)
XCTAssertEqual(s1, s2)
XCTAssertEqual(Set([s1]), Set([s2]))
XCTAssertNotEqual(s1, s3)
XCTAssertNotEqual(s2, s3)
}
}
/// Test the basic provider functions.
func testProvider() throws {
try testWithTemporaryDirectory { path in
let testRepoPath = path.appending(component: "test-repo")
try! makeDirectories(testRepoPath)
initGitRepo(testRepoPath, tag: "1.2.3")
// Test the provider.
let testCheckoutPath = path.appending(component: "checkout")
let provider = GitRepositoryProvider()
XCTAssertTrue(try provider.workingCopyExists(at: testRepoPath))
let repoSpec = RepositorySpecifier(path: testRepoPath)
try! provider.fetch(repository: repoSpec, to: testCheckoutPath)
// Verify the checkout was made.
XCTAssertDirectoryExists(testCheckoutPath)
// Test the repository interface.
let repository = provider.open(repository: repoSpec, at: testCheckoutPath)
let tags = try repository.getTags()
XCTAssertEqual(try repository.getTags(), ["1.2.3"])
let revision = try repository.resolveRevision(tag: tags.first ?? "<invalid>")
// FIXME: It would be nice if we had a deterministic hash here...
XCTAssertEqual(revision.identifier,
try Process.popen(
args: Git.tool, "-C", testRepoPath.pathString, "rev-parse", "--verify", "1.2.3").utf8Output().spm_chomp())
if let revision = try? repository.resolveRevision(tag: "<invalid>") {
XCTFail("unexpected resolution of invalid tag to \(revision)")
}
let main = try repository.resolveRevision(identifier: "main")
XCTAssertEqual(main.identifier,
try Process.checkNonZeroExit(
args: Git.tool, "-C", testRepoPath.pathString, "rev-parse", "--verify", "main").spm_chomp())
// Check that git hashes resolve to themselves.
let mainIdentifier = try repository.resolveRevision(identifier: main.identifier)
XCTAssertEqual(main.identifier, mainIdentifier.identifier)
// Check that invalid identifier doesn't resolve.
if let revision = try? repository.resolveRevision(identifier: "invalid") {
XCTFail("unexpected resolution of invalid identifier to \(revision)")
}
}
}
/// Check hash validation.
func testGitRepositoryHash() throws {
let validHash = "0123456789012345678901234567890123456789"
XCTAssertNotEqual(GitRepository.Hash(validHash), nil)
let invalidHexHash = validHash + "1"
XCTAssertEqual(GitRepository.Hash(invalidHexHash), nil)
let invalidNonHexHash = "012345678901234567890123456789012345678!"
XCTAssertEqual(GitRepository.Hash(invalidNonHexHash), nil)
}
/// Check raw repository facilities.
///
/// In order to be stable, this test uses a static test git repository in
/// `Inputs`, which has known commit hashes. See the `construct.sh` script
/// contained within it for more information.
func testRawRepository() throws {
try testWithTemporaryDirectory { path in
// Unarchive the static test repository.
let inputArchivePath = AbsolutePath(#file).parentDirectory.appending(components: "Inputs", "TestRepo.tgz")
try systemQuietly(["tar", "-x", "-v", "-C", path.pathString, "-f", inputArchivePath.pathString])
let testRepoPath = path.appending(component: "TestRepo")
// Check hash resolution.
let repo = GitRepository(path: testRepoPath)
XCTAssertEqual(try repo.resolveHash(treeish: "1.0", type: "commit"),
try repo.resolveHash(treeish: "master"))
// Get the initial commit.
let initialCommitHash = try repo.resolveHash(treeish: "a8b9fcb")
XCTAssertEqual(initialCommitHash, GitRepository.Hash("a8b9fcbf893b3b02c0196609059ebae37aeb7f0b"))
// Check commit loading.
let initialCommit = try repo.readCommit(hash: initialCommitHash)
XCTAssertEqual(initialCommit.hash, initialCommitHash)
XCTAssertEqual(initialCommit.tree, GitRepository.Hash("9d463c3b538619448c5d2ecac379e92f075a8976"))
// Check tree loading.
let initialTree = try repo.readTree(hash: initialCommit.tree)
guard case .hash(let initialTreeHash) = initialTree.location else {
return XCTFail("wrong pointer")
}
XCTAssertEqual(initialTreeHash, initialCommit.tree)
XCTAssertEqual(initialTree.contents.count, 1)
guard let readmeEntry = initialTree.contents.first else { return XCTFail() }
guard case .hash(let readmeEntryHash) = readmeEntry.location else {
return XCTFail("wrong pointer")
}
XCTAssertEqual(readmeEntryHash, GitRepository.Hash("92513075b3491a54c45a880be25150d92388e7bc"))
XCTAssertEqual(readmeEntry.type, .blob)
XCTAssertEqual(readmeEntry.name, "README.txt")
// Check loading of odd names.
//
// This is a commit which has a subdirectory 'funny-names' with
// paths with special characters.
let funnyNamesCommit = try repo.readCommit(hash: repo.resolveHash(treeish: "a7b19a7"))
let funnyNamesRoot = try repo.readTree(hash: funnyNamesCommit.tree)
XCTAssertEqual(funnyNamesRoot.contents.map{ $0.name }, ["README.txt", "funny-names", "subdir"])
guard funnyNamesRoot.contents.count == 3 else { return XCTFail() }
// FIXME: This isn't yet supported.
let funnyNamesSubdirEntry = funnyNamesRoot.contents[1]
XCTAssertEqual(funnyNamesSubdirEntry.type, .tree)
if let _ = try? repo.readTree(location: funnyNamesSubdirEntry.location) {
XCTFail("unexpected success reading tree with funny names")
}
}
}
func testSubmoduleRead() throws {
try testWithTemporaryDirectory { path in
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repoPath = path.appending(component: "repo")
try makeDirectories(repoPath)
initGitRepo(repoPath)
try Process.checkNonZeroExit(
args: Git.tool, "-C", repoPath.pathString, "submodule", "add", testRepoPath.pathString)
let repo = GitRepository(path: repoPath)
try repo.stageEverything()
try repo.commit()
// We should be able to read a repo which as a submdoule.
_ = try repo.readTree(hash: try repo.resolveHash(treeish: "main"))
}
}
/// Test the Git file system view.
func testGitFileView() throws {
try testWithTemporaryDirectory { path in
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
// Add a few files and a directory.
let test1FileContents: ByteString = "Hello, world!"
let test2FileContents: ByteString = "Hello, happy world!"
let test3FileContents: ByteString = """
#!/bin/sh
set -e
exit 0
"""
try localFileSystem.writeFileContents(testRepoPath.appending(component: "test-file-1.txt"), bytes: test1FileContents)
try localFileSystem.createDirectory(testRepoPath.appending(component: "subdir"))
try localFileSystem.writeFileContents(testRepoPath.appending(components: "subdir", "test-file-2.txt"), bytes: test2FileContents)
try localFileSystem.writeFileContents(testRepoPath.appending(component: "test-file-3.sh"), bytes: test3FileContents)
try! Process.checkNonZeroExit(args: "chmod", "+x", testRepoPath.appending(component: "test-file-3.sh").pathString)
let testRepo = GitRepository(path: testRepoPath)
try testRepo.stage(files: "test-file-1.txt", "subdir/test-file-2.txt", "test-file-3.sh")
try testRepo.commit()
try testRepo.tag(name: "test-tag")
// Get the the repository via the provider. the provider.
let testClonePath = path.appending(component: "clone")
let provider = GitRepositoryProvider()
let repoSpec = RepositorySpecifier(path: testRepoPath)
try provider.fetch(repository: repoSpec, to: testClonePath)
let repository = provider.open(repository: repoSpec, at: testClonePath)
// Get and test the file system view.
let view = try repository.openFileView(revision: repository.resolveRevision(tag: "test-tag"))
// Check basic predicates.
XCTAssert(view.isDirectory(AbsolutePath("/")))
XCTAssert(view.isDirectory(AbsolutePath("/subdir")))
XCTAssert(!view.isDirectory(AbsolutePath("/does-not-exist")))
XCTAssert(view.exists(AbsolutePath("/test-file-1.txt")))
XCTAssert(!view.exists(AbsolutePath("/does-not-exist")))
XCTAssert(view.isFile(AbsolutePath("/test-file-1.txt")))
XCTAssert(!view.isSymlink(AbsolutePath("/test-file-1.txt")))
XCTAssert(!view.isExecutableFile(AbsolutePath("/does-not-exist")))
XCTAssert(view.isExecutableFile(AbsolutePath("/test-file-3.sh")))
// Check read of a directory.
let subdirPath = AbsolutePath("/subdir")
XCTAssertEqual(try view.getDirectoryContents(AbsolutePath("/")).sorted(), ["file.swift", "subdir", "test-file-1.txt", "test-file-3.sh"])
XCTAssertEqual(try view.getDirectoryContents(subdirPath).sorted(), ["test-file-2.txt"])
XCTAssertThrows(FileSystemError(.isDirectory, subdirPath)) {
_ = try view.readFileContents(subdirPath)
}
// Check read versus root.
XCTAssertThrows(FileSystemError(.isDirectory, .root)) {
_ = try view.readFileContents(.root)
}
// Check read through a non-directory.
let notDirectoryPath1 = AbsolutePath("/test-file-1.txt")
XCTAssertThrows(FileSystemError(.notDirectory, notDirectoryPath1)) {
_ = try view.getDirectoryContents(notDirectoryPath1)
}
let notDirectoryPath2 = AbsolutePath("/test-file-1.txt/thing")
XCTAssertThrows(FileSystemError(.notDirectory, notDirectoryPath2)) {
_ = try view.readFileContents(notDirectoryPath2)
}
// Check read/write into a missing directory.
let noEntryPath1 = AbsolutePath("/does-not-exist")
XCTAssertThrows(FileSystemError(.noEntry, noEntryPath1)) {
_ = try view.getDirectoryContents(noEntryPath1)
}
let noEntryPath2 = AbsolutePath("/does/not/exist")
XCTAssertThrows(FileSystemError(.noEntry, noEntryPath2)) {
_ = try view.readFileContents(noEntryPath2)
}
// Check read of a file.
XCTAssertEqual(try view.readFileContents(AbsolutePath("/test-file-1.txt")), test1FileContents)
XCTAssertEqual(try view.readFileContents(AbsolutePath("/subdir/test-file-2.txt")), test2FileContents)
}
}
/// Test the handling of local checkouts.
func testCheckouts() throws {
try testWithTemporaryDirectory { path in
// Create a test repository.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath, tag: "initial")
let initialRevision = try GitRepository(path: testRepoPath).getCurrentRevision()
// Add a couple files and a directory.
try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi")
let testRepo = GitRepository(path: testRepoPath)
try testRepo.stage(file: "test.txt")
try testRepo.commit()
try testRepo.tag(name: "test-tag")
let currentRevision = try GitRepository(path: testRepoPath).getCurrentRevision()
// Fetch the repository using the provider.
let testClonePath = path.appending(component: "clone")
let provider = GitRepositoryProvider()
let repoSpec = RepositorySpecifier(path: testRepoPath)
try provider.fetch(repository: repoSpec, to: testClonePath)
// Clone off a checkout.
let checkoutPath = path.appending(component: "checkout")
_ = try provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)
// The remote of this checkout should point to the clone.
XCTAssertEqual(try GitRepository(path: checkoutPath).remotes()[0].url, testClonePath.pathString)
let editsPath = path.appending(component: "edit")
_ = try provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: editsPath, editable: true)
// The remote of this checkout should point to the original repo.
XCTAssertEqual(try GitRepository(path: editsPath).remotes()[0].url, testRepoPath.pathString)
// Check the working copies.
for path in [checkoutPath, editsPath] {
let workingCopy = try provider.openWorkingCopy(at: path)
try workingCopy.checkout(tag: "test-tag")
XCTAssertEqual(try workingCopy.getCurrentRevision(), currentRevision)
XCTAssertFileExists(path.appending(component: "test.txt"))
try workingCopy.checkout(tag: "initial")
XCTAssertEqual(try workingCopy.getCurrentRevision(), initialRevision)
XCTAssertNoSuchPath(path.appending(component: "test.txt"))
}
}
}
func testFetch() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath, tag: "1.2.3")
let repo = GitRepository(path: testRepoPath)
XCTAssertEqual(try repo.getTags(), ["1.2.3"])
// Clone it somewhere.
let testClonePath = path.appending(component: "clone")
let provider = GitRepositoryProvider()
let repoSpec = RepositorySpecifier(path: testRepoPath)
try provider.fetch(repository: repoSpec, to: testClonePath)
let clonedRepo = provider.open(repository: repoSpec, at: testClonePath)
XCTAssertEqual(try clonedRepo.getTags(), ["1.2.3"])
// Clone off a checkout.
let checkoutPath = path.appending(component: "checkout")
let checkoutRepo = try provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)
XCTAssertEqual(try checkoutRepo.getTags(), ["1.2.3"])
// Add a new file to original repo.
try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi")
let testRepo = GitRepository(path: testRepoPath)
try testRepo.stage(file: "test.txt")
try testRepo.commit()
try testRepo.tag(name: "2.0.0")
// Update the cloned repo.
try clonedRepo.fetch()
XCTAssertEqual(try clonedRepo.getTags().sorted(), ["1.2.3", "2.0.0"])
// Update the checkout.
try checkoutRepo.fetch()
XCTAssertEqual(try checkoutRepo.getTags().sorted(), ["1.2.3", "2.0.0"])
}
}
func testHasUnpushedCommits() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
// Create a bare clone it somewhere because we want to later push into the repo.
let testBareRepoPath = path.appending(component: "test-repo-bare")
try systemQuietly([Git.tool, "clone", "--bare", testRepoPath.pathString, testBareRepoPath.pathString])
// Clone it somewhere.
let testClonePath = path.appending(component: "clone")
let provider = GitRepositoryProvider()
let repoSpec = RepositorySpecifier(path: testBareRepoPath)
try provider.fetch(repository: repoSpec, to: testClonePath)
// Clone off a checkout.
let checkoutPath = path.appending(component: "checkout")
let checkoutRepo = try provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: true)
XCTAssertFalse(try checkoutRepo.hasUnpushedCommits())
// Add a new file to checkout.
try localFileSystem.writeFileContents(checkoutPath.appending(component: "test.txt"), bytes: "Hi")
let checkoutTestRepo = GitRepository(path: checkoutPath)
try checkoutTestRepo.stage(file: "test.txt")
try checkoutTestRepo.commit()
// We should have commits which are not pushed.
XCTAssert(try checkoutRepo.hasUnpushedCommits())
// Push the changes and check again.
try checkoutTestRepo.push(remote: "origin", branch: "main")
XCTAssertFalse(try checkoutRepo.hasUnpushedCommits())
}
}
func testSetRemote() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repo = GitRepository(path: testRepoPath)
// There should be no remotes currently.
XCTAssert(try repo.remotes().isEmpty)
// Add a remote via git cli.
try systemQuietly([Git.tool, "-C", testRepoPath.pathString, "remote", "add", "origin", "../foo"])
// Test if it was added.
XCTAssertEqual(Dictionary(uniqueKeysWithValues: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../foo"])
// Change remote.
try repo.setURL(remote: "origin", url: "../bar")
XCTAssertEqual(Dictionary(uniqueKeysWithValues: try repo.remotes().map { ($0.0, $0.1) }), ["origin": "../bar"])
// Try changing remote of non-existent remote.
do {
try repo.setURL(remote: "fake", url: "../bar")
XCTFail("unexpected success (shouldn’t have been able to set URL of missing remote)")
}
catch let error as GitRepositoryError {
XCTAssertEqual(error.path, testRepoPath)
XCTAssertNotNil(error.diagnosticLocation)
}
}
}
func testUncommitedChanges() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
// Create a file (which we will modify later).
try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi")
let repo = GitRepository(path: testRepoPath)
XCTAssert(repo.hasUncommittedChanges())
try repo.stage(file: "test.txt")
XCTAssert(repo.hasUncommittedChanges())
try repo.commit()
XCTAssertFalse(repo.hasUncommittedChanges())
// Modify the file in the repo.
try localFileSystem.writeFileContents(repo.path.appending(component: "test.txt"), bytes: "Hello")
XCTAssert(repo.hasUncommittedChanges())
}
}
func testBranchOperations() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repo = GitRepository(path: testRepoPath)
var currentRevision = try repo.getCurrentRevision()
// This is the default branch of a new repo.
XCTAssert(repo.exists(revision: Revision(identifier: "main")))
// Check a non existent revision.
XCTAssertFalse(repo.exists(revision: Revision(identifier: "nonExistent")))
// Checkout a new branch using command line.
try systemQuietly([Git.tool, "-C", testRepoPath.pathString, "checkout", "-b", "TestBranch1"])
XCTAssert(repo.exists(revision: Revision(identifier: "TestBranch1")))
XCTAssertEqual(try repo.getCurrentRevision(), currentRevision)
// Make sure we're on the new branch right now.
XCTAssertEqual(try repo.currentBranch(), "TestBranch1")
// Checkout new branch using our API.
currentRevision = try repo.getCurrentRevision()
try repo.checkout(newBranch: "TestBranch2")
XCTAssert(repo.exists(revision: Revision(identifier: "TestBranch2")))
XCTAssertEqual(try repo.getCurrentRevision(), currentRevision)
XCTAssertEqual(try repo.currentBranch(), "TestBranch2")
}
}
func testCheckoutRevision() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repo = GitRepository(path: testRepoPath)
func createAndStageTestFile() throws {
try localFileSystem.writeFileContents(testRepoPath.appending(component: "test.txt"), bytes: "Hi")
try repo.stage(file: "test.txt")
}
try repo.checkout(revision: Revision(identifier: "main"))
// Current branch must be main.
XCTAssertEqual(try repo.currentBranch(), "main")
// Create a new branch.
try repo.checkout(newBranch: "TestBranch")
XCTAssertEqual(try repo.currentBranch(), "TestBranch")
// Create some random file.
try createAndStageTestFile()
XCTAssert(repo.hasUncommittedChanges())
// Checkout current revision again, the test file should go away.
let currentRevision = try repo.getCurrentRevision()
try repo.checkout(revision: currentRevision)
XCTAssertFalse(repo.hasUncommittedChanges())
// We should be on detached head.
XCTAssertEqual(try repo.currentBranch(), "HEAD")
// Try again and checkout to a previous branch.
try createAndStageTestFile()
XCTAssert(repo.hasUncommittedChanges())
try repo.checkout(revision: Revision(identifier: "TestBranch"))
XCTAssertFalse(repo.hasUncommittedChanges())
XCTAssertEqual(try repo.currentBranch(), "TestBranch")
do {
try repo.checkout(revision: Revision(identifier: "nonExistent"))
XCTFail("Unexpected checkout success on non existent branch")
} catch {}
}
}
func testSubmodules() throws {
try testWithTemporaryDirectory { path in
let provider = GitRepositoryProvider()
// Create repos: foo and bar, foo will have bar as submodule and then later
// the submodule ref will be updated in foo.
let fooPath = path.appending(component: "foo-original")
let fooSpecifier = RepositorySpecifier(path: fooPath)
let fooRepoPath = path.appending(component: "foo-repo")
let fooWorkingPath = path.appending(component: "foo-working")
let barPath = path.appending(component: "bar-original")
let bazPath = path.appending(component: "baz-original")
// Create the repos and add a file.
for path in [fooPath, barPath, bazPath] {
try makeDirectories(path)
initGitRepo(path)
try localFileSystem.writeFileContents(path.appending(component: "hello.txt"), bytes: "hello")
let repo = GitRepository(path: path)
try repo.stageEverything()
try repo.commit()
}
let foo = GitRepository(path: fooPath)
let bar = GitRepository(path: barPath)
// The tag 1.0.0 does not contain the submodule.
try foo.tag(name: "1.0.0")
// Fetch and clone repo foo.
try provider.fetch(repository: fooSpecifier, to: fooRepoPath)
_ = try provider.createWorkingCopy(repository: fooSpecifier, sourcePath: fooRepoPath, at: fooWorkingPath, editable: false)
let fooRepo = GitRepository(path: fooRepoPath, isWorkingRepo: false)
let fooWorkingRepo = GitRepository(path: fooWorkingPath)
// Checkout the first tag which doesn't has submodule.
try fooWorkingRepo.checkout(tag: "1.0.0")
XCTAssertNoSuchPath(fooWorkingPath.appending(component: "bar"))
// Add submodule to foo and tag it as 1.0.1
try foo.checkout(newBranch: "submodule")
try systemQuietly([Git.tool, "-C", fooPath.pathString, "submodule", "add", barPath.pathString, "bar"])
try foo.stageEverything()
try foo.commit()
try foo.tag(name: "1.0.1")
// Update our bare and working repos.
try fooRepo.fetch()
try fooWorkingRepo.fetch()
// Checkout the tag with submodule and expect submodules files to be present.
try fooWorkingRepo.checkout(tag: "1.0.1")
XCTAssertFileExists(fooWorkingPath.appending(components: "bar", "hello.txt"))
// Checkout the tag without submodule and ensure that the submodule files are gone.
try fooWorkingRepo.checkout(tag: "1.0.0")
XCTAssertNoSuchPath(fooWorkingPath.appending(components: "bar"))
// Add something to bar.
try localFileSystem.writeFileContents(barPath.appending(component: "bar.txt"), bytes: "hello")
// Add a submodule too to check for recusive submodules.
try systemQuietly([Git.tool, "-C", barPath.pathString, "submodule", "add", bazPath.pathString, "baz"])
try bar.stageEverything()
try bar.commit()
// Update the ref of bar in foo and tag as 1.0.2
try systemQuietly([Git.tool, "-C", fooPath.appending(component: "bar").pathString, "pull"])
try foo.stageEverything()
try foo.commit()
try foo.tag(name: "1.0.2")
try fooRepo.fetch()
try fooWorkingRepo.fetch()
// We should see the new file we added in the submodule.
try fooWorkingRepo.checkout(tag: "1.0.2")
XCTAssertFileExists(fooWorkingPath.appending(components: "bar", "hello.txt"))
XCTAssertFileExists(fooWorkingPath.appending(components: "bar", "bar.txt"))
XCTAssertFileExists(fooWorkingPath.appending(components: "bar", "baz", "hello.txt"))
// Sanity check.
try fooWorkingRepo.checkout(tag: "1.0.0")
XCTAssertNoSuchPath(fooWorkingPath.appending(components: "bar"))
}
}
func testAlternativeObjectStoreValidation() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath, tag: "1.2.3")
let repo = GitRepository(path: testRepoPath)
XCTAssertEqual(try repo.getTags(), ["1.2.3"])
// Clone it somewhere.
let testClonePath = path.appending(component: "clone")
let provider = GitRepositoryProvider()
let repoSpec = RepositorySpecifier(path: testRepoPath)
try provider.fetch(repository: repoSpec, to: testClonePath)
let clonedRepo = provider.open(repository: repoSpec, at: testClonePath)
XCTAssertEqual(try clonedRepo.getTags(), ["1.2.3"])
// Clone off a checkout.
let checkoutPath = path.appending(component: "checkout")
let checkoutRepo = try provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)
// The object store should be valid.
XCTAssertTrue(checkoutRepo.isAlternateObjectStoreValid())
// Delete the clone (alternative object store).
try localFileSystem.removeFileTree(testClonePath)
XCTAssertFalse(checkoutRepo.isAlternateObjectStoreValid())
}
}
func testAreIgnored() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test_repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repo = GitRepository(path: testRepoPath)
// Add a .gitignore
try localFileSystem.writeFileContents(testRepoPath.appending(component: ".gitignore"), bytes: "ignored_file1\nignored file2")
let ignored = try repo.areIgnored([testRepoPath.appending(component: "ignored_file1"), testRepoPath.appending(component: "ignored file2"), testRepoPath.appending(component: "not ignored")])
XCTAssertTrue(ignored[0])
XCTAssertTrue(ignored[1])
XCTAssertFalse(ignored[2])
let notIgnored = try repo.areIgnored([testRepoPath.appending(component: "not_ignored")])
XCTAssertFalse(notIgnored[0])
}
}
func testAreIgnoredWithSpaceInRepoPath() throws {
try testWithTemporaryDirectory { path in
// Create a repo.
let testRepoPath = path.appending(component: "test repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repo = GitRepository(path: testRepoPath)
// Add a .gitignore
try localFileSystem.writeFileContents(testRepoPath.appending(component: ".gitignore"), bytes: "ignored_file1")
let ignored = try repo.areIgnored([testRepoPath.appending(component: "ignored_file1")])
XCTAssertTrue(ignored[0])
}
}
func testMissingDefaultBranch() throws {
try testWithTemporaryDirectory { path in
// Create a repository.
let testRepoPath = path.appending(component: "test-repo")
try makeDirectories(testRepoPath)
initGitRepo(testRepoPath)
let repo = GitRepository(path: testRepoPath)
// Create a `newMain` branch and remove `main`.
try repo.checkout(newBranch: "newMain")
try systemQuietly([Git.tool, "-C", testRepoPath.pathString, "branch", "-D", "main"])
// Change the branch name to something non-existent.
try systemQuietly([Git.tool, "-C", testRepoPath.pathString, "symbolic-ref", "HEAD", "refs/heads/_non_existent_branch_"])
// Clone it somewhere.
let testClonePath = path.appending(component: "clone")
let provider = GitRepositoryProvider()
let repoSpec = RepositorySpecifier(path: testRepoPath)
try provider.fetch(repository: repoSpec, to: testClonePath)
let clonedRepo = provider.open(repository: repoSpec, at: testClonePath)
XCTAssertEqual(try clonedRepo.getTags(), [])
// Clone off a checkout.
let checkoutPath = path.appending(component: "checkout")
let checkoutRepo = try provider.createWorkingCopy(repository: repoSpec, sourcePath: testClonePath, at: checkoutPath, editable: false)
XCTAssertNoSuchPath(checkoutPath.appending(component: "file.swift"))
// Try to check out the `main` branch.
try checkoutRepo.checkout(revision: Revision(identifier: "newMain"))
XCTAssertFileExists(checkoutPath.appending(component: "file.swift"))
// The following will throw if HEAD was set incorrectly and we didn't do a no-checkout clone.
XCTAssertNoThrow(try checkoutRepo.getCurrentRevision())
}
}
}
| 48.190409 | 201 | 0.626745 |
ef0d7429faac08c99d49bfe2673108936db4a210 | 976 | //
// Healthwatch Tests.swift
// Healthwatch Tests
//
// Created by Caius Durling on 09/11/2016.
// Copyright © 2016 Caius Durling. All rights reserved.
//
import XCTest
@testable import Healthwatch
class HealthwatchTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.111111 | 111 | 0.64959 |
0a10419299134e2bc6f718071881deb8599386d5 | 1,753 | //
// TagListViewModel.swift
// flash
//
// Created by Songwut Maneefun on 13/11/2564 BE.
//
import Foundation
class TagListViewModel: BaseViewModel {
var selectTagId = [Int]()
var tagList = [UGCTagResult]()
var newTagList = [UGCTagResult]()
var isLoadNextPage = false
var nextPage: Int?
var isFirstPage = true
func callAPITagList(complete: @escaping (_ list: [UGCTagResult]) -> ()) {
if !self.isFirstPage, self.nextPage == nil {
//max of items in page
complete(self.tagList)
} else {
let request = FLRequest()
request.apiMethod = .get
request.endPoint = .tagSelectList
var endpointDict = [String: Any]()
endpointDict["page_size"] = 100
if self.isLoadNextPage, let next = self.nextPage {
endpointDict["page"] = next
}
request.endPointParam = EndPointParam(dict: endpointDict)
API.request(request) { (response: ResponseBody?, result: UGCTagPageResult?, isCache, error) in
if let page = result {
self.nextPage = page.next
if self.isFirstPage {
self.newTagList = page.list
self.tagList = page.list
} else {
self.newTagList = page.list
self.tagList.append(contentsOf: page.list)
}
self.isFirstPage = false
}
print("error:\(error?.localizedDescription)")
complete(self.tagList)
}
}
}
}
| 31.303571 | 106 | 0.499144 |
205d7fff970b1fefb3e17b1545fdb78264296288 | 1,524 | //
// HomePresenter.swift
// mooviez
//
// Created by Betül Çalık on 27.02.2022.
//
import Foundation
final class HomePresenter: HomePresenterProtocol {
// MARK: - Variables
unowned var view: HomeViewProtocol?
private let interactor: HomeInteractorProtocol
private let router: HomeRouterProtocol
init(view: HomeViewProtocol?,
interactor: HomeInteractorProtocol,
router: HomeRouterProtocol) {
self.view = view
self.interactor = interactor
self.router = router
self.interactor.delegate = self
}
func load() {
interactor.load()
}
func selectMovie(with movieType: MovieType, at index: Int) {
interactor.selectMovie(with: movieType, at: index)
}
}
// MARK: - Home Interactor Delegate
extension HomePresenter: HomeInteractorDelegate {
func handleOutput(_ output: HomeInteractorOutput) {
switch output {
case .showUpcomingMovies(let upcomingMovieResponse):
view?.handleOutput(.showUpcomingMovies(upcomingMovieResponse))
case .showTopRatedMovies(let topRatedMoviesResponse):
view?.handleOutput(.showTopRatedMovies(topRatedMoviesResponse))
case .showTrendingMovies(let trendingMoviesResponse):
view?.handleOutput(.showTrendingMovies(trendingMoviesResponse))
case .showMovieDetail(let movie):
guard let view = view else { return }
router.navigateToDetail(with: movie, on: view)
}
}
}
| 28.754717 | 75 | 0.67126 |
7a5fbd0604705b0cbefe1fd57b0cb21acf291ad6 | 287 | // RUN: not %target-swift-frontend %s -parse
// 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 Q<d where g:P{class b{class a<T where g:c
class func g:c:struct c
| 35.875 | 87 | 0.749129 |
234a5a0bfe1e5c9287213b2ee8d22e7416a15334 | 1,852 | //
// RepoService.swift
// Repo List
//
// Created by Linus Nyberg on 2017-05-13.
// Copyright © 2017 Linus Nyberg. All rights reserved.
//
import Foundation
import Alamofire
/// Responsible for fetching remote Repos data from Github.
class RepoService {
var authenticator: Authenticator
var store: RepoStore
init(authenticator: Authenticator, store: RepoStore) {
self.authenticator = authenticator
self.store = store
}
func fetchRepos(completion: @escaping ([Repo]?) -> Void) {
authenticator.ensureAuthenticated() { authenticated in
if !authenticated {
print("Authentication failed - abort fetching repos.")
return
}
print("fetching repos!")
Alamofire.request(
URL(string: "https://api.github.com/user/repos")!,
method: .get,
parameters: nil
)
.validate()
.responseJSON { [weak self] (response) -> Void in
guard let strongSelf = self else {
return
}
guard response.result.isSuccess else {
print("Error while fetching remote repos: \(String(describing: response.result.error))")
completion(nil)
return
}
guard let jsonDicts = response.result.value as? NSArray else {
print("UNKNOWN RESPONSE: \(String(describing: response.result.value))")
return
}
//print("RESPONSE: \(jsonDicts)")
// Parse repos and add them to the store:
//---------------------------------------
strongSelf.store.clearRepos()
for jsonDict in jsonDicts {
guard let jsonData = jsonDict as? NSDictionary else {
continue
}
// TODO: Add these to the store in a single operation, to avoid many saves to disk.
_ = strongSelf.store.addRepo(populateValues: { (repo: Repo) in
repo.populateFromJSON(jsonData: jsonData)
})
}
completion(strongSelf.store.loadRepos())
}
}
}
}
| 25.722222 | 94 | 0.646328 |
87d1092f652d8960b49f59cb63d6dd9a4a952b5f | 529 | import BalancingBucketQueue
import Foundation
import Models
import RESTMethods
import RESTServer
public final class JobDeleteEndpoint: RESTEndpoint {
private let jobManipulator: JobManipulator
public init(jobManipulator: JobManipulator) {
self.jobManipulator = jobManipulator
}
public func handle(decodedRequest: JobDeleteRequest) throws -> JobDeleteResponse {
try jobManipulator.delete(jobId: decodedRequest.jobId)
return JobDeleteResponse(jobId: decodedRequest.jobId)
}
}
| 27.842105 | 86 | 0.761815 |
edf6de522ea281b991861bb354fb2a9f6141bdde | 838 | import Foundation
import StdMsgs
import RosTime
extension trajectory_msgs {
public struct JointTrajectory: Message {
public static let md5sum: String = "65b4f94a94d1ed67169da35a02f33d3f"
public static let datatype = "trajectory_msgs/JointTrajectory"
public static let definition = """
Header header
string[] joint_names
JointTrajectoryPoint[] points
"""
public static let hasHeader = true
public var header: std_msgs.Header
public var joint_names: [String]
public var points: [JointTrajectoryPoint]
public init(header: std_msgs.Header, joint_names: [String], points: [JointTrajectoryPoint]) {
self.header = header
self.joint_names = joint_names
self.points = points
}
public init() {
header = std_msgs.Header()
joint_names = [String]()
points = [JointTrajectoryPoint]()
}
}
} | 23.277778 | 95 | 0.732697 |
64c4a96ecbdf8ba9cf881d2c89608e87d573d699 | 2,861 | //
// DDGViewShot.swift
// DDGScreenshot
//
// Created by dudongge on 2018/3/19.
// Copyright © 2018年 dudongge. All rights reserved.
//
import UIKit
let height = UIScreen.main.bounds.size.height
let width = UIScreen.main.bounds.size.width
class DDGViewShot: UIViewController {
var blueView: UIView!
var leftBtn: UIButton!
var logoImageView: UIImageView!
var imageView: UIImageView!
var storeImage: UIImageView! //保存截取的图片
var activity: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
blueView = UIView()
blueView.backgroundColor = UIColor.blue
blueView.center = self.view.center
blueView.frame.size = CGSize(width: 100, height: 100)
self.view.addSubview(blueView)
logoImageView = UIImageView(image: UIImage(named:"logo"))
logoImageView.frame = CGRect(x: 50, y: 100, width: 100, height: 100)
self.view.addSubview(logoImageView)
storeImage = UIImageView()
self.view.addSubview(storeImage)
let leftBtn = UIButton()
leftBtn.backgroundColor = UIColor.yellow
leftBtn.setTitle("截整个屏", for: .normal)
leftBtn.setTitleColor(UIColor.blue, for: .normal)
leftBtn.addTarget(self, action: #selector(DDGViewShot.screenShotAll), for: .touchUpInside)
leftBtn.frame = CGRect(x: 20, y: height - bottomMargint, width: (width - 60) / 2, height: 40)
self.view.addSubview(leftBtn)
let rightBtn = UIButton()
rightBtn.backgroundColor = UIColor.yellow
rightBtn.setTitle("清除", for: .normal)
rightBtn.setTitleColor(UIColor.blue, for: .normal)
rightBtn.addTarget(self, action: #selector(DDGViewShot.clearShotScreen), for: .touchUpInside)
rightBtn.frame = CGRect(x: (width - 60) / 2 + 40, y: height - bottomMargint, width: (width - 60) / 2, height: 40)
self.view.addSubview(rightBtn)
activity = UIActivityIndicatorView()
activity.style = .whiteLarge
activity.frame = CGRect(x:width / 2.0 - 15, y: 70, width: 30, height: 30)
activity.backgroundColor = UIColor.black
activity.hidesWhenStopped = true
self.view.addSubview(activity)
}
@objc func screenShotAll() {
weak var ws = self
self.view.DDGScreenShot { (image) in
ws!.storeImage.image = image
ws!.storeImage.frame.size = CGSize(width: (image?.size.width)! * 0.5, height: (image?.size.height)! * 0.5)
ws!.storeImage.center = ws!.view.center
ws!.view.backgroundColor = UIColor.yellow
}
}
@objc func clearShotScreen() {
self.storeImage.image = UIImage(named:"")
self.view.backgroundColor = UIColor.white
}
}
| 37.155844 | 121 | 0.637889 |
d6805fc4bd54c1890f89dbe65bb12281c51e62d0 | 4,447 | //
// DetailsViewController.swift
// WeatherApp
//
// Created by Jean-Charles Moussé on 22/05/2019.
// Copyright © 2019 Jean-Charles Moussé. All rights reserved.
//
import UIKit
import Lottie
class DetailsViewController : BaseViewController, UITableViewDataSource {
var city: City?
var forecast: Forecast?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var loader: AnimationView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
self.title = city?.name
let loaderAnim = Animation.named("loader")
loader.animation = loaderAnim
loader.loopMode = .loop
fetchWeatherData()
}
private func fetchWeatherData() {
if let _city = city {
setVisibleLoader(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
ApiManager.getWeatherForecast(
city: _city,
onSuccess: { result in
self.forecast = result
if let _only24hForecast = self.forecast?.hourly?.data.prefix(24) {
self.forecast?.hourly?.data = Array(_only24hForecast)
}
self.tableView.reloadData()
self.setVisibleLoader(false)
},
onFail: { error in
self.setVisibleLoader(false)
self.showAlert(error?.localizedDescription ?? "Error during fetch weather data")
}
)
}
}
}
private func setVisibleLoader(_ isVisible: Bool) {
loader.isHidden = !isVisible
if !loader.isHidden && !loader.isAnimationPlaying {
loader.play()
} else if loader.isHidden && loader.isAnimationPlaying {
loader.pause()
}
}
private func getSectionTitle(_ section: Int) -> String {
if section == 1 {
return forecast?.hourly?.summary ?? "Hourly"
}
if section == 2 {
return forecast?.daily?.summary ?? "Daily"
}
if section == 3 {
return "Extra informations"
}
return ""
}
func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 1 + (forecast?.hourly?.data.count ?? 0)
case 2:
return 1 + (forecast?.daily?.data.count ?? 0)
case 3:
return 3
default:
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let _forecast = forecast else {
return UITableViewCell()
}
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsHeaderCell", for: indexPath) as! DetailsHeaderCell
cell.setData(_forecast, city?.name ?? "")
return cell
} else {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsTitleCell", for: indexPath) as! DetailsTitleCell
cell.setTitle(getSectionTitle(indexPath.section))
return cell
}
switch indexPath.section {
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsHourlyCell", for: indexPath) as! DetailsHourlyForecast
cell.setData(hourlyData: _forecast.hourly!.data[indexPath.row - 1])
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsDailyCell", for: indexPath) as! DetailsDailyForecast
cell.setData(_forecast.daily!.data[indexPath.row - 1])
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailsExtraCell", for: indexPath) as! DetailsExtraInfos
cell.setData(_forecast.currently!, indexPath.row)
return cell
default: return UITableViewCell()
}
}
}
}
| 34.742188 | 135 | 0.550483 |
33d56366e91c0db49d8b43be9c022c42d79b2c45 | 534 | import Foundation
import ProcessController
import SimulatorPoolModels
public class XcodebuildSimulatorDestinationArgument: SubprocessArgument, CustomStringConvertible {
private let xcodeDestinationString: String
public init(destinationId: UDID) {
self.xcodeDestinationString = "platform=iOS Simulator,id=\(destinationId.value)"
}
public func stringValue() throws -> String {
return xcodeDestinationString
}
public var description: String {
return xcodeDestinationString
}
}
| 26.7 | 98 | 0.749064 |
72d7d13b2a6bcf668332b292923a5c3fb9687415 | 470 | //
// FormViewController.swift
// Zavala
//
// Created by Maurice Parker on 11/11/20.
//
import UIKit
class FormViewController: UIViewController {
override var keyCommands: [UIKeyCommand]? {
[
UIKeyCommand(action: #selector(cancel(_:)), input: UIKeyCommand.inputEscape),
UIKeyCommand(action: #selector(submit(_:)), input: "\r"),
]
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true)
}
@IBAction func submit(_ sender: Any) {
}
}
| 17.407407 | 80 | 0.676596 |
ff791552d1ee835363820e5b3f6e0123544f874f | 4,586 | //
// MD5.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 06/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
final class MD5 : CryptoSwift.HashBase, _Hash {
var size:Int = 16 // 128 / 8
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,
0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,
0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,
0x6b901122,0xfd987193,0xa679438e,0x49b40821,
0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,
0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,
0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,
0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,
0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,
0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,
0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,
0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,
0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,
0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,
0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,
0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391]
private let h:[UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
func calculate() -> NSData {
var tmpMessage = prepare()
// hash values
var hh = h
// Step 2. Append Length a 64-bit representation of lengthInBits
var lengthInBits = (message.length * 8)
var lengthBytes = lengthInBits.bytes(64 / 8)
tmpMessage.appendBytes(reverse(lengthBytes));
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
var leftMessageBytes = tmpMessage.length
for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) {
let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))
let bytes = tmpMessage.bytes;
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)
let range = NSRange(location:0, length: M.count * sizeof(UInt32))
chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range)
// Initialize hash value for this chunk:
var A:UInt32 = hh[0]
var B:UInt32 = hh[1]
var C:UInt32 = hh[2]
var D:UInt32 = hh[3]
var dTemp:UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F:UInt32 = 0
switch (j) {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft((A &+ F &+ k[j] &+ M[g]), s[j])
A = dTemp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
}
var buf: NSMutableData = NSMutableData();
hh.map({ (item) -> () in
var i:UInt32 = item.littleEndian
buf.appendBytes(&i, length: sizeofValue(i))
})
return buf.copy() as! NSData;
}
}
| 38.537815 | 119 | 0.474051 |
ab1677d53f0eb62823a8b13fc1fce5d8516d43b6 | 1,564 | //
// PropertyGenerator.swift
// ModelsCodeGeneration
//
// Created by Mikhail Monakov on 03/11/2019.
// Copyright © 2019 Surf. All rights reserved.
//
public final class PropertyGenerator {
/**
Method for creating model for NodeKit's templates
*/
public func generateCode(for node: ASTNode, type: ModelType) throws -> PropertyGenerationModel {
guard case let .field(isOptional) = node.token else {
throw GeneratorError.incorrectNodeToken("Property generator couldn't parse incorrect node")
}
guard
let nameNode = node.subNodes.nameNode,
let typeNode = node.subNodes.typeNode,
case let .name(value) = nameNode.token,
case .type = typeNode.token else {
throw GeneratorError.nodeConfiguration("Property generator couldn't parse incorrect subnodes configurations")
}
let nodeType = try TypeNodeParser().detectType(for: typeNode)
return .init(entryName: value,
entityName: value.snakeCaseToCamelCase(),
typeName: TypeNameBuilder().buildString(for: nodeType, isOptional: isOptional, modelType: type),
fromInit: FromDTOBuilder().buildString(for: nodeType, with: value, isOptional: isOptional),
toDTOInit: ToDTOBuilder().buildString(for: nodeType, with: value, isOptional: isOptional),
isPlain: nodeType.isPlain,
description: node.description?.replacingOccurrences(of: "\n", with: " "))
}
}
| 40.102564 | 125 | 0.641944 |
64b1a3ce636ac9b94f10fc45b74c660cbb59ca41 | 447 | //
// LoadingView.swift
// DesignCode
//
// Created by Meng To on 2020-04-01.
// Copyright © 2020 Meng To. All rights reserved.
//
import SwiftUI
struct LoadingView: View {
var body: some View {
VStack {
LottieView(filename: "loading")
.frame(width: 200, height: 200)
}
}
}
struct LoadingView_Previews: PreviewProvider {
static var previews: some View {
LoadingView()
}
}
| 17.88 | 50 | 0.595078 |
d63458805ecbc61dba0e186dce56dec83ce73764 | 8,574 | //
// RSSsupport.swift
// OklasoftRSS
//
// Created by Justin Oakes on 7/8/17.
// Copyright © 2017 Oklasoft LLC. All rights reserved.
//
import Foundation
#if os(OSX)
import OklasoftNetworking
#elseif os(iOS)
import OklasoftNetworking_iOS_
#endif
public class Feed {
let title: String
let url: URL
let canonicalURL: URL?
var favIcon: URL?
var lastUpdated: Date?
let mimeType: mimeTypes
var stories: [Story]
init(title: String, url: URL, canonicalURL: URL?, lastUpdated: Date?, mimeType: mimeTypes, favIcon: URL?) {
self.title = title
self.url = url
self.canonicalURL = canonicalURL
self.lastUpdated = lastUpdated
self.mimeType = mimeType
self.stories = []
self.favIcon = favIcon
NotificationCenter.default.addObserver(self,
selector: #selector(receaveUpdatedStories(anotification:)),
name: .finishedFindingStories,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(receaveUpdatedFavIcon(anotification:)),
name: .foundFavIcon,
object: nil)
requestUpdatedFavIcon()
requestUpdatedStories()
}
func checkBasicFaviconURL(url: URL) {
unowned let unownedSelf: Feed = self
URLSession.shared.getReturnedDataFrom(url: url) { (data, responce, error) in
if let foundError: Error = error {
NotificationCenter.default.post(name: .networkingErrorNotification,
object: nil,
userInfo: [errorInfoKey:foundError])
}
if let headers: URLResponse = responce,
let _: faviconMimeTypes = faviconMimeTypes(rawValue: headers.mimeType ?? ""),
unownedSelf.favIcon == nil {
unownedSelf.favIcon = url
NotificationCenter.default.post(name: .foundFavIcon, object: nil, userInfo: nil)
}
}
}
func requestUpdatedFavIcon() {
guard let baseURL: URL = canonicalURL != nil ? canonicalURL : URL(string:"http://\(url.host ?? "")") else {
return
}
checkBasicFaviconURL(url: baseURL.appendingPathComponent("favicon.ico"))
unowned let unownedSelf: Feed = self
URLSession.shared.getReturnedDataFrom(url: baseURL) { (data, responce, error) in
if let foundError: Error = error {
NotificationCenter.default.post(name: .networkingErrorNotification,
object: nil,
userInfo:errorInfo(error: foundError).toDict())
return
}
guard let validData: Data = data,
let XMLString: String = String(data: validData, encoding: .utf8)
else {
NotificationCenter.default.post(name: .networkingErrorNotification,
object: nil,
userInfo:errorInfo(error: unrecognizableDataError).toDict())
return
}
do {
let xmlDoc: XMLDocument = try XMLDocument(xmlString: XMLString, options: .documentTidyXML)
let parser: XMLParser = XMLParser(data: xmlDoc.xmlData)
parser.parseHTMLforFavIcon(fromSite: unownedSelf.url)
} catch {
NotificationCenter.default.post(name: .errorConvertingHTML,
object: nil,
userInfo: [errorInfoKey:unrecognizableDataError])
return
}
}
}
@objc func receaveUpdatedFavIcon(anotification: Notification) {
guard let userInfo: [AnyHashable:Any] = anotification.userInfo,
let imageLink: URL = userInfo[url] as? URL else {
return
}
favIcon = imageLink
}
func requestUpdatedStories() {
unowned let unownedSelf: Feed = self
URLSession.shared.getReturnedDataFrom(url: url) { (data, respone, error) in
if let foundError: Error = error {
NotificationCenter.default.post(name: .feedIdentificationError,
object: nil,
userInfo: [errorInfoKey:foundError])
return
}
guard let validData: Data = data else {
return
}
let parser: XMLParser = XMLParser(data: validData)
switch unownedSelf.mimeType {
case .atom, .atomXML:
parser.parseAtomFeed(fromParent: unownedSelf.url)
break
case .rss, .rssXML, .simpleRSS:
parser.parseRSSFeed(fromParent: unownedSelf.url)
break
default:
return
}
}
}
@objc func receaveUpdatedStories(anotification: Notification) {
guard let userInfo: [AnyHashable:Any] = anotification.userInfo,
let requester: URL = userInfo.keys.first as? URL,
let newStories: [Story] = (userInfo[requester] as? [Story]) ?? nil
else {
return
}
if requester == url {
stories.insert(contentsOf: newStories.filter({$0.pubdate > lastUpdated ?? Date.init(timeIntervalSinceReferenceDate: 0)}).sorted(by: {$0.pubdate > $1.pubdate}),
at: 0)
lastUpdated = Date()
}
}
}
public protocol Story {
var title: String {get}
var url: URL {get}
var textContent: String {get}
var htmlContent: String {get}
var pubdate: Date {get}
var read: Bool {get set}
var feedURL: URL {get}
var author: String? {get}
}
public struct baseStory: Story {
public let title: String
public let url: URL
public let textContent: String
public let htmlContent: String
public let pubdate: Date
public var read: Bool
public let feedURL: URL
public let author: String?
}
public struct PodCast: Story {
public let title: String
public let url: URL
public let textContent: String
public let htmlContent: String
public let pubdate: Date
public var read: Bool
public let feedURL: URL
public let author: String?
let audioContent: [URL]
let image: URL
init(story: Story, audio: [URL], image: URL) {
self.title = story.title
self.url = story.url
self.textContent = story.textContent
self.htmlContent = story.htmlContent
self.pubdate = story.pubdate
self.read = story.read
self.feedURL = story.feedURL
self.author = story.author
self.audioContent = audio
self.image = image
}
}
public enum mimeTypes: String {
public typealias rawValue = String
case atom = "application/atom"
case atomXML = "application/atom+xml"
case rss = "application/rss"
case rssXML = "application/rss+xml"
case simpleRSS = "text/xml"
case html = "text/html"
}
public enum mediaMimeTypes: String {
public typealias rawValue = String
case m4a = "audio/x-m4a"
case mpegA = "audio/mpeg"
case mpeg3 = "audio/mpeg3"
case xmpeg3 = "audio/x-mpeg-3"
case aac = "audio/aac"
case mp4A = "audio/mp4"
}
enum faviconMimeTypes: String {
typealias rawValue = String
case microsoft = "image/vnd.microsoft.icon"
case icon = "image/x-icon"
}
| 37.938053 | 175 | 0.510613 |
fcc97a3d180757a2836fd6a3c4381c74ac978f26 | 1,284 | //// SYUISelectionPinView.swift
//
// Copyright (c) 2019 Sygic a.s.
//
// 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 class SYUISelectionPinView: SYUIPinView {
public override func shouldShowNormalState() -> Bool {
return false
}
}
| 41.419355 | 80 | 0.753894 |
ebe9f6fbce98eeee9ab66de6f8a4c146532d8353 | 752 | import XCTest
import UserAcquisition
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.931034 | 111 | 0.603723 |
ebac20fa0ed6c8f3e0c05f2a5d62b78ad0ffb088 | 2,941 |
//
// GCDGroupVC.swift
// MyInsight_Swift
//
// Created by SongMenglong on 2019/6/26.
// Copyright © 2019 SongMengLong. All rights reserved.
//
import UIKit
import Alamofire
class GCDGroupVC: UIViewController {
var allArray: Array<Any> = Array()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
//self.datasRequestGroup()
self.gcdGroupHandler()
}
/// 网络请求调度组
private func datasRequestGroup() {
// 创建调度组
let workingGroup = DispatchGroup()
// 创建多列
let workingQueue = DispatchQueue(label: "request_queue")
// 模拟异步发送网络请求 A
// 入组
workingGroup.enter()
workingQueue.async {
Thread.sleep(forTimeInterval: 1)
print("接口 A 数据请求完成")
// 出组
workingGroup.leave()
}
// 模拟异步发送网络请求 B
// 入组
workingGroup.enter()
workingQueue.async {
Thread.sleep(forTimeInterval: 1)
print("接口 B 数据请求完成")
// 出组
workingGroup.leave()
}
print("我是最开始执行的,异步操作里的打印后执行")
// 调度组里的任务都执行完毕
workingGroup.notify(queue: workingQueue) {
print("接口 A 和接口 B 的数据请求都已经完毕!, 开始合并两个接口的数据")
}
}
// MARK: GCD多线程处理
func gcdGroupHandler() -> Void {
// 多线程线组
let gropQueue:DispatchGroup = DispatchGroup.init()
//
let queue:DispatchQueue = DispatchQueue.init(label: "handleDataQueue")
var strName1 = ""
gropQueue.enter()
self.getInfomation(gropQueue: gropQueue) { (strName) in
strName1 = strName
}
gropQueue.notify(queue: DispatchQueue.main) {
self.handleDatas()
//gropQueue.leave()
}
/*进行界面处理*/
gropQueue.notify(queue: queue) {
self.updateUI()
debugPrint("\(strName1)")
}
}
func getInfomation(gropQueue: DispatchGroup, callback: @escaping ((String) -> Void)) -> Void {
let requestUrl:String = "https://www.apiopen.top/novelApi"
Alamofire.request(requestUrl, method: .get).responseJSON { (response) in
if let json = response.result.value {
let jsonDic:Dictionary<String,Any> = json as! Dictionary
let array:Array<Any> = jsonDic["data"] as! Array
self.allArray.append(array)
gropQueue.leave()
callback("123")
} else {
gropQueue.leave()
callback("aaa")
}
}
}
/*刷新总列表*/
func updateUI() -> Void {
//print("更新UI:\(self.allArray)")
}
/*异步线程处理数据*/
func handleDatas() -> Void {
//print("处理数据:\(self.allArray)")
}
}
| 25.136752 | 98 | 0.519891 |
39e0ef6f216f8c8579cdeac414e509203d75c765 | 5,854 | //
// SelectionViewController.swift
//
//
// Created by Guillermo Cique Fernández on 31/3/18.
//
import UIKit
import SpriteKit
import PlaygroundSupport
public class SelectionViewController : UIViewController, PlaygroundLiveViewSafeAreaContainer {
let scene1: PopulationScene
let scene2: PopulationScene
public init(population1: [Creature], population2: [Creature]) {
scene1 = PopulationScene(creatures: population1)
scene2 = PopulationScene(creatures: population2)
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
enum LabelTitles {
static let randomPopulation = NSLocalizedString("Random population", comment: "Describes the population generated randomly")
static let selectedPopulation = NSLocalizedString("Selected population", comment: "Describes the population selected")
}
override public func viewDidLoad() {
super.viewDidLoad()
let randomPopulationView = RoundedVisualEffectView()
randomPopulationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(randomPopulationView)
NSLayoutConstraint.activate([
randomPopulationView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 32),
randomPopulationView.leadingAnchor.constraint(greaterThanOrEqualTo: liveViewSafeAreaGuide.leadingAnchor, constant: 32),
randomPopulationView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0)
])
let randomPopulationLabel = UILabel()
randomPopulationLabel.translatesAutoresizingMaskIntoConstraints = false
randomPopulationLabel.font = UIFont.preferredFont(forTextStyle: .headline)
randomPopulationLabel.textColor = .black
randomPopulationLabel.text = LabelTitles.randomPopulation
view.addSubview(randomPopulationLabel)
NSLayoutConstraint.activate([
randomPopulationLabel.topAnchor.constraint(equalTo: randomPopulationView.topAnchor, constant: 8),
randomPopulationLabel.leadingAnchor.constraint(equalTo: randomPopulationView.leadingAnchor, constant: 16),
randomPopulationLabel.centerYAnchor.constraint(equalTo: randomPopulationView.centerYAnchor, constant: 0),
randomPopulationLabel.centerXAnchor.constraint(equalTo: randomPopulationView.centerXAnchor, constant: 0)
])
let skView1 = SKView()
skView1.backgroundColor = .clear
skView1.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(skView1)
NSLayoutConstraint.activate([
skView1.topAnchor.constraint(equalTo: randomPopulationLabel.bottomAnchor, constant: 16),
skView1.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 32),
skView1.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -32)
])
scene1.backgroundColor = .clear
scene1.scaleMode = .resizeFill
skView1.preferredFramesPerSecond = 60
skView1.presentScene(scene1)
let selectedPopulationView = RoundedVisualEffectView()
selectedPopulationView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(selectedPopulationView)
NSLayoutConstraint.activate([
selectedPopulationView.heightAnchor.constraint(equalTo: randomPopulationView.heightAnchor, constant: 0),
selectedPopulationView.topAnchor.constraint(equalTo: skView1.bottomAnchor, constant: 16),
selectedPopulationView.leadingAnchor.constraint(greaterThanOrEqualTo: liveViewSafeAreaGuide.leadingAnchor, constant: 32),
selectedPopulationView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0)
])
let selectedPopulationLabel = UILabel()
selectedPopulationLabel.translatesAutoresizingMaskIntoConstraints = false
selectedPopulationLabel.font = UIFont.preferredFont(forTextStyle: .headline)
selectedPopulationLabel.textColor = .black
selectedPopulationLabel.text = LabelTitles.selectedPopulation
view.addSubview(selectedPopulationLabel)
NSLayoutConstraint.activate([
selectedPopulationLabel.topAnchor.constraint(equalTo: selectedPopulationView.topAnchor, constant: 8),
selectedPopulationLabel.leadingAnchor.constraint(equalTo: selectedPopulationView.leadingAnchor, constant: 16),
selectedPopulationLabel.centerYAnchor.constraint(equalTo: selectedPopulationView.centerYAnchor, constant: 0),
selectedPopulationLabel.centerXAnchor.constraint(equalTo: selectedPopulationView.centerXAnchor, constant: 0)
])
let skView2 = SKView()
skView2.backgroundColor = .clear
skView2.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(skView2)
NSLayoutConstraint.activate([
skView2.heightAnchor.constraint(equalTo: skView1.heightAnchor, constant: 0),
skView2.topAnchor.constraint(equalTo: selectedPopulationLabel.bottomAnchor, constant: 16),
skView2.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 32),
skView2.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -32),
skView2.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: 0)
])
scene2.backgroundColor = .clear
scene2.scaleMode = .resizeFill
skView2.preferredFramesPerSecond = 60
skView2.presentScene(scene2)
view.backgroundColor = .clear
}
} | 50.034188 | 133 | 0.726853 |
469efab009b8ea172d663894a7ab412965cf8ece | 2,274 | //
// LocalizationSystem.swift
// DebugWindowKit
//
// Created by Ryan Moniz on 3/5/19.
// Copyright © 2019 Ryan Moniz. All rights reserved.
//
import Foundation
public class LocalizationSystem:NSObject {
var bundle: Bundle!
class var sharedInstance: LocalizationSystem {
struct Singleton {
static let instance: LocalizationSystem = LocalizationSystem()
}
return Singleton.instance
}
override init() {
super.init()
bundle = Bundle.main
}
//MARK: - get language & localized image
func localizedStringForKey(key:String, comment:String) -> String {
return bundle.localizedString(forKey: key, value: comment, table: nil)
}
func localizedImagePathForImg(imagename:String, type:String) -> String {
guard let imagePath = bundle.path(forResource: imagename, ofType: type) else {
return ""
}
return imagePath
}
//MARK: - Set Language
//sets the desired language, if language is not supported by app it returns the default OS language.
func setLanguage(languageCode:String) {
#if DEBUG
var appleLanguages = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
appleLanguages.remove(at: 0)
appleLanguages.insert(languageCode, at: 0)
UserDefaults.standard.set(appleLanguages, forKey: "AppleLanguages")
UserDefaults.standard.synchronize()
if let languageDirectoryPath = Bundle.main.path(forResource: languageCode, ofType: "lproj") {
bundle = Bundle.init(path: languageDirectoryPath)
} else {
resetLocalization()
}
#endif
}
//resets to the default OS language
func resetLocalization() {
bundle = Bundle.main
}
//returns the current language of device/app
func getLanguage() -> String {
let appleLanguages = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
let preferredLanguage = appleLanguages[0]
if preferredLanguage.contains("-") {
let array = preferredLanguage.components(separatedBy: "-")
return array[0]
}
return preferredLanguage
}
}
| 30.72973 | 105 | 0.635004 |
eb6c11a4bc8c6bce298e4bf65f6a5bab7d7d2c07 | 17,490 | //
// XCUIElement+XCTestWDAccessibility.swift
// XCTestWD
//
// Created by zhaoy on 29/4/17.
// Copyright © 2017 XCTestWD. All rights reserved.
//
import Foundation
import SwiftyJSON
func firstNonEmptyValue(_ value1:String?, _ value2:String?) -> String? {
if value1 != nil && (value1?.count)! > 0 {
return value1
} else {
return value2
}
}
extension XCUIElement {
func wdValue() -> Any! {
var value = self.value
if self.elementType == XCUIElement.ElementType.staticText {
if self.value != nil {
value = self.value
} else {
value = self.label
}
}
if self.elementType == XCUIElement.ElementType.button {
if let temp = self.value {
if ((temp as? String)?.count) ?? 0 > 0 {
value = self.value
} else {
value = self.isSelected
}
} else {
value = self.isSelected
}
}
if self.elementType == XCUIElement.ElementType.switch {
value = (self.value as! NSString).doubleValue > 0
}
if self.elementType == XCUIElement.ElementType.textField ||
self.elementType == XCUIElement.ElementType.textView ||
self.elementType == XCUIElement.ElementType.secureTextField {
if let temp = self.value {
if let str = temp as? String {
if str.count > 0 {
value = self.value
} else {
value = self.placeholderValue
}
} else {
value = self.value
}
} else {
value = self.placeholderValue
}
}
return value
}
func wdLabel() -> String {
if self.elementType == XCUIElement.ElementType.textField {
return self.label
} else if self.label.count > 0 {
return self.label
} else {
return ""
}
}
func wdName() -> String? {
let name = (firstNonEmptyValue(self.identifier, self.label))
if name?.count == 0 {
return nil
} else {
return name
}
}
func wdType() -> String {
return XCUIElementTypeTransformer.singleton.stringWithElementType(self.elementType)
}
func isWDEnabled() -> Bool {
return self.isEnabled
}
func wdFrame() -> CGRect {
return self.frame.integral
}
func wdRect() -> [String:CGFloat] {
return [
"x":self.frame.minX,
"y":self.frame.minY,
"width":self.frame.width,
"height":self.frame.height]
}
func checkLastSnapShot() -> XCElementSnapshot {
if self.lastSnapshot != nil {
return self.lastSnapshot
}
self.resolve()
return self.lastSnapshot
}
//MARK: element query
func descendantsMatchingXPathQuery(xpathQuery:String, returnAfterFirstMatch:Bool) -> [XCUIElement]? {
let query = xpathQuery.replacingOccurrences(of: "XCUIElementTypeAny", with: "*")
var matchSnapShots = XCTestWDXPath.findMatchesIn(self.lastSnapshot, query)
if matchSnapShots == nil || matchSnapShots!.count == 0 {
return [XCUIElement]()
}
if returnAfterFirstMatch {
matchSnapShots = [matchSnapShots!.first!]
}
var matchingTypes = Set<XCUIElement.ElementType>()
for snapshot in matchSnapShots! {
matchingTypes.insert(XCUIElementTypeTransformer.singleton.elementTypeWithTypeName(snapshot.wdType()))
}
var map = [XCUIElement.ElementType:[XCUIElement]]()
for type in matchingTypes {
let descendantsOfType = self.descendants(matching: type).allElementsBoundByIndex
map[type] = descendantsOfType
}
var matchingElements = [XCUIElement]()
for snapshot in matchSnapShots! {
var elements = map[snapshot.elementType]
if query.contains("last()") {
elements = elements?.reversed()
}
innerLoop: for element in elements! {
if element.checkLastSnapShot()._matchesElement(snapshot) {
matchingElements.append(element)
break innerLoop
}
}
}
return matchingElements
}
func descendantsMatchingIdentifier(accessibilityId:String, returnAfterFirstMatch:Bool) -> [XCUIElement]? {
var result = [XCUIElement]()
if self.identifier == accessibilityId {
result.append(self)
if returnAfterFirstMatch {
return result
}
}
let query = self.descendants(matching: XCUIElement.ElementType.any).matching(identifier: accessibilityId);
result.append(contentsOf: XCUIElement.extractMatchElementFromQuery(query: query, returnAfterFirstMatch: returnAfterFirstMatch))
return result
}
func descendantsMatchingClassName(className:String, returnAfterFirstMatch:Bool) -> [XCUIElement]? {
var result = [XCUIElement]()
let type = XCUIElementTypeTransformer.singleton.elementTypeWithTypeName(className)
if self.elementType == type || type == XCUIElement.ElementType.any {
result.append(self);
if returnAfterFirstMatch {
return result
}
}
let query = self.descendants(matching: type);
result.append(contentsOf: XCUIElement.extractMatchElementFromQuery(query: query, returnAfterFirstMatch: returnAfterFirstMatch))
return result
}
func descendantsMatching(Predicate predicate:NSPredicate, _ returnFirstMatch:Bool) -> [XCUIElement] {
let formattedPredicate = NSPredicate.xctestWDformatSearch(predicate)
var result:[XCUIElement] = []
if formattedPredicate?.evaluate(with: self.lastSnapshot) ?? false {
if returnFirstMatch {
return [self]
}
result.append(self)
}
let query = self.descendants(matching: XCUIElement.ElementType.any).matching(formattedPredicate!)
if returnFirstMatch {
result.append(query.element(boundBy: 0))
} else {
result.append(contentsOf: query.allElementsBoundByIndex)
}
return result
}
static func extractMatchElementFromQuery(query:XCUIElementQuery, returnAfterFirstMatch:Bool) -> [XCUIElement] {
if !returnAfterFirstMatch {
return query.allElementsBoundByIndex
}
let matchedElement = query.element(boundBy: 0)
if query.allElementsBoundByIndex.count == 0{
return [XCUIElement]()
} else {
return [matchedElement]
}
}
open func customValue(forKey key: String) -> Any? {
if key.lowercased().contains("enable") {
return self.isEnabled
} else if key.lowercased().contains("name") {
return self.wdName() ?? ""
} else if key.lowercased().contains("value") {
return self.wdValue()
} else if key.lowercased().contains("label") {
return self.wdLabel()
} else if key.lowercased().contains("type") {
return self.wdType()
} else if key.lowercased().contains("visible") {
if self.lastSnapshot == nil {
self.resolve()
}
return self.lastSnapshot.isWDVisible()
} else if key.lowercased().contains("access") {
if self.lastSnapshot == nil {
self.resolve()
}
return self.lastSnapshot.isAccessibile()
}
return ""
}
open override func value(forUndefinedKey key: String) -> Any? {
return ""
}
//MARK: Commands
func tree() -> [String : AnyObject]? {
if self.lastSnapshot == nil {
self.resolve()
}
return dictionaryForElement(self.lastSnapshot)
}
func digest(windowName : String) -> String {
let description = "\(windowName)_\(self.buttons.count)_\(self.textViews.count)_\(self.textFields.count)_\(self.otherElements.count)_\(self.descendants(matching:.any).count)_\(self.traits())"
return description
}
func accessibilityTree() -> [String : AnyObject]? {
if self.lastSnapshot == nil {
self.resolve()
let _ = self.query
}
return accessibilityInfoForElement(self.lastSnapshot)
}
//MARK: Private Methods
func dictionaryForElement(_ snapshot:XCElementSnapshot) -> [String : AnyObject]? {
var info = [String : AnyObject]()
info["type"] = XCUIElementTypeTransformer.singleton.shortStringWithElementType(snapshot.elementType) as AnyObject?
info["rawIndentifier"] = (snapshot.identifier.count > 0 ? snapshot.identifier : "") as AnyObject
info["name"] = snapshot.wdName() as AnyObject? ?? "" as AnyObject
info["value"] = snapshot.wdValue() as AnyObject? ?? "" as AnyObject
info["label"] = snapshot.wdLabel() as AnyObject? ?? "" as AnyObject
info["rect"] = snapshot.wdRect() as AnyObject
info["frame"] = NSStringFromCGRect(snapshot.wdFrame()) as AnyObject
info["isEnabled"] = snapshot.isWDEnabled() as AnyObject
info["isVisible"] = snapshot.isWDVisible() as AnyObject
info["isHittable"] = snapshot.isHittable() as AnyObject
// If block is not visible, return
if info["isVisible"] as! Bool == false {
return nil;
}
// If block is visible, iterate through all its children
let childrenElements = snapshot.children
if childrenElements != nil && childrenElements!.count > 0 {
var children = [AnyObject]()
for child in childrenElements! {
if let temp = dictionaryForElement(child as! XCElementSnapshot) {
children.append(temp as AnyObject)
}
}
if children.count > 0 {
info["children"] = children as AnyObject
}
}
return info
}
func accessibilityInfoForElement(_ snapshot:XCElementSnapshot) -> [String:AnyObject]? {
let isAccessible = snapshot.isWDAccessible()
let isVisible = snapshot.isWDVisible()
var info = [String: AnyObject]()
if isAccessible {
if isVisible {
info["value"] = snapshot.wdValue as AnyObject
info["label"] = snapshot.wdLabel as AnyObject
}
}
else {
var children = [AnyObject]()
let childrenElements = snapshot.children
for childSnapshot in childrenElements! {
let childInfo: [String: AnyObject] = self.accessibilityInfoForElement(childSnapshot as! XCElementSnapshot)!
if childInfo.keys.count > 0{
children.append(childInfo as AnyObject)
}
}
if children.count > 0 {
info["children"] = children as AnyObject
}
}
return info
}
}
extension XCElementSnapshot {
func wdValue() -> Any? {
var value = self.value
if self.elementType == XCUIElement.ElementType.staticText {
if self.value != nil {
value = self.value
} else {
value = self.label
}
}
if self.elementType == XCUIElement.ElementType.button {
if let temp = self.value {
if ((temp as? String)?.count) ?? 0 > 0 {
value = self.value
} else {
value = self.isSelected
}
} else {
value = self.isSelected
}
}
if self.elementType == XCUIElement.ElementType.switch {
value = (self.value as! NSString).doubleValue > 0
}
if self.elementType == XCUIElement.ElementType.textField ||
self.elementType == XCUIElement.ElementType.textView ||
self.elementType == XCUIElement.ElementType.secureTextField {
if let temp = self.value {
if let str = temp as? String {
if str.count > 0 {
value = self.value
} else {
value = self.placeholderValue
}
} else {
value = self.value
}
} else {
value = self.placeholderValue
}
}
return value
}
func wdLabel() -> String? {
if self.elementType == XCUIElement.ElementType.textField {
return self.label
} else if self.label.count > 0 {
return self.label
} else {
return ""
}
}
func wdName() -> String? {
let name = (firstNonEmptyValue(self.identifier, self.label))
if name?.count == 0 {
return ""
} else {
return name
}
}
func wdType() -> String {
return XCUIElementTypeTransformer.singleton.stringWithElementType(self.elementType)
}
func isWDEnabled() -> Bool {
return self.isEnabled
}
func wdFrame() -> CGRect {
return self.frame.integral
}
func wdRect() -> [String:CGFloat] {
return [
"x":self.frame.minX != CGFloat.infinity ? self.frame.minX : 9999999999,
"y":self.frame.minY != CGFloat.infinity ? self.frame.minY : 9999999999,
"width":self.frame.width,
"height":self.frame.height]
}
func isHittable() -> Bool {
return true;
//check whether self is the current hitelement
let midPoint:CGPoint = ((self.suggestedHitpoints as! NSArray).lastObject as! NSValue).cgPointValue;
if(midPoint.x == CGFloat.infinity || midPoint.y == CGFloat.infinity){
return false;
}
let hitElement1 = self.hitTest(midPoint) ;//as? XCElementSnapshot)! ;
if( hitElement1 is XCElementSnapshot){
let hitElement = hitElement1 as! XCElementSnapshot;
if (self == hitElement || self._allDescendants().contains(hitElement) ) {
return true;
}
}
// check whether hitPoint is in current visible frame
//let fb_hitPoint:CGPoint = self.hitPoint ;
//if ( self.visibleFrame.contains( fb_hitPoint) ) {
// return true;
//}
// get the children's hittable properties
for ele in self.children {
let elementSnapshot = ele as! XCElementSnapshot;
if (elementSnapshot.isHittable() ) {
return true;
}
}
return false;
}
func isWDVisible() -> Bool {
if self.frame.isEmpty || self.visibleFrame.isEmpty {
return false
}
let app: XCElementSnapshot? = rootElement() as! XCElementSnapshot?
let screenSize: CGSize? = MathUtils.adjustDimensionsForApplication((app?.frame.size)!, (XCUIDevice.shared.orientation))
let screenFrame = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat((screenSize?.width)!), height: CGFloat((screenSize?.height)!))
if !visibleFrame.intersects(screenFrame) {
return false;
}
return true
}
//MARK: Accessibility Measurement
func isWDAccessible() -> Bool {
if self.elementType == XCUIElement.ElementType.cell {
if !isAccessibile() {
let containerView: XCElementSnapshot? = children.first as? XCElementSnapshot
if !(containerView?.isAccessibile())! {
return false
}
}
}
else if self.elementType != XCUIElement.ElementType.textField && self.elementType != XCUIElement.ElementType.secureTextField {
if !isAccessibile() {
return false
}
}
var parentSnapshot: XCElementSnapshot? = parent
while (parentSnapshot != nil) {
if ((parentSnapshot?.isAccessibile())! && parentSnapshot?.elementType != XCUIElement.ElementType.table) {
return false;
}
parentSnapshot = parentSnapshot?.parent
}
return true
}
func isAccessibile() -> Bool {
return self.attributeValue(XCAXAIsElementAttribute)?.boolValue ?? false
}
func attributeValue(_ number:NSNumber) -> AnyObject? {
let attributesResult = (XCAXClient_iOS.sharedClient() as! XCAXClient_iOS).attributes(forElementSnapshot: self, attributeList: [number])
return attributesResult as AnyObject?
}
}
| 33.125 | 198 | 0.549285 |
46269a37feab6d1c49411bc388674f41b5b89a62 | 834 | //
// VGSValidationRuleLuhnCheck.swift
// VGSCollectSDK
//
// Created by Dima on 23.06.2020.
// Copyright © 2020 VGS. All rights reserved.
//
import Foundation
#if !COCOAPODS
import VGSPaymentCards
#endif
/**
Validate input in scope of matching Luhn algorithm.
*/
public struct VGSValidationRuleLuhnCheck: VGSValidationRuleProtocol {
/// Validation Error
public var error: VGSValidationError
/// Initialzation
///
/// - Parameters:
/// - error:`VGSValidationError` - error on failed validation relust.
public init(error: VGSValidationError) {
self.error = error
}
}
extension VGSValidationRuleLuhnCheck: VGSRuleValidator {
internal func validate(input: String?) -> Bool {
guard let input = input else {
return false
}
return CheckSumAlgorithmType.luhn.validate(input)
}
}
| 20.85 | 73 | 0.708633 |
4be7b81feca24d27c04bef012e90d44f4e9bffbd | 232 | //
// GuessTheFlagApp.swift
// GuessTheFlag
//
// Created by SUPER on 2021/7/9.
//
import SwiftUI
@main
struct GuessTheFlagApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.888889 | 33 | 0.573276 |
5ddd5b725a0e6da5495290e297d22b2b8de0eb80 | 485 | //
// Misc.swift
// Pods
//
// Created by Zhixuan Lai on 3/1/16.
// Converted to Swift 3 by Tom Kroening 4/11/2017
//
import Foundation
internal extension DispatchTime {
init(timeInterval: TimeInterval) {
let timeVal = timeInterval < TimeInterval(0) ? DispatchTime.distantFuture : DispatchTime.now() + Double(Int64(timeInterval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
self.init(uptimeNanoseconds: timeVal.uptimeNanoseconds)
}
}
| 24.25 | 178 | 0.682474 |
22e373028db0b388325246e0a8077595789f8ce0 | 225 | //
// Created by Elon on 2020/04/26.
// Copyright (c) 2020 Elon. All rights reserved.
//
import Foundation
// MARK: - Name
struct Name:
Codable,
Equatable
{
let title: String
let first: String
let last: String
}
| 12.5 | 48 | 0.662222 |
8789b9ea651785b1ef38733a27685ffc65fbb381 | 496 | //
// Style.swift
// FontAwesomeSwiftUI
//
// Created by khoa on 18/10/2020.
//
import Foundation
public enum FontStyle: String, CaseIterable {
case brand = "FontAwesome5Brands-Regular"
case regular = "FontAwesome5Free-Regular"
case solid = "FontAwesome5Free-Solid"
public var familyName: String {
switch self {
case .brand:
return "Font Awesome 5 Brands"
case .regular, .solid:
return "Font Awesome 5 Free"
}
}
}
| 20.666667 | 45 | 0.620968 |
48ef3bca811f61a9bfa9f782013fdf99785ce638 | 2,427 | //
// WBWelcomeView.swift
// 传智微博
//
// Created by apple on 16/7/3.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
import SDWebImage
/// 欢迎视图
class WBWelcomeView: UIView {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var bottomCons: NSLayoutConstraint!
/// 图标宽度约束
@IBOutlet weak var iconWidthCons: NSLayoutConstraint!
class func welcomeView() -> WBWelcomeView {
let nib = UINib(nibName: "WBWelcomeView", bundle: nil)
let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBWelcomeView
// 从 XIB 加载的视图,默认是 600 * 600 的
v.frame = UIScreen.main.bounds
return v
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// 提示:initWithCode 只是刚刚从 XIB 的二进制文件将视图数据加载完成
// 还没有和代码连线建立起关系,所以开发时,千万不要在这个方法中处理 UI
print("initWithCoder + \(iconView)")
}
/// 从 XIB 加载完成调用
override func awakeFromNib() {
// 3. 设置圆角(iconView的 bounds 还没有设置)
iconView.layer.cornerRadius = iconWidthCons.constant * 0.5
iconView.layer.masksToBounds = true
}
/// 自动布局系统更新完成约束后,会自动调用此方法
/// 通常是对子视图布局进行修改
// override func layoutSubviews() {
//
// }
/// 视图被添加到 window 上,表示视图已经显示
override func didMoveToWindow() {
super.didMoveToWindow()
// 视图是使用自动布局来设置的,只是设置了约束
// - 当视图被添加到窗口上时,根据父视图的大小,计算约束值,更新控件位置
// - layoutIfNeeded 会直接按照当前的约束直接更新控件位置
// - 执行之后,控件所在位置,就是 XIB 中布局的位置
self.layoutIfNeeded()
bottomCons.constant = bounds.size.height - 200
// 如果控件们的 frame 还没有计算好!所有的约束会一起动画!
UIView.animate(withDuration: 1.0,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: [],
animations: {
// 更新约束
self.layoutIfNeeded()
}) { (_) in
UIView.animate(withDuration: 1.0, animations: {
self.tipLabel.alpha = 1
}, completion: { (_) in
self.removeFromSuperview()
})
}
}
}
| 26.966667 | 82 | 0.528636 |
fc1a4ac0d6491168db0a4ab216609478aa3e8774 | 1,134 | //
// UICollectionView+Cells.swift
// ShopApp
//
// Created by Mykola Voronin on 2/9/18.
// Copyright © 2018 RubyGarage. All rights reserved.
//
import UIKit
extension UICollectionView {
func registerNibForCell<T: UICollectionViewCell>(_ cell: T.Type) {
let cellNib = UINib(nibName: T.nameOfClass, bundle: nil)
register(cellNib, forCellWithReuseIdentifier: T.nameOfClass)
}
func registerNibForSupplementaryView<T: UICollectionReusableView>(_ cell: T.Type, of kind: String) {
let cellNib = UINib(nibName: T.nameOfClass, bundle: nil)
register(cellNib, forSupplementaryViewOfKind: kind, withReuseIdentifier: T.nameOfClass)
}
func dequeueReusableCellForIndexPath<T: UICollectionViewCell>(_ indexPath: IndexPath) -> T {
return dequeueReusableCell(withReuseIdentifier: T.nameOfClass, for: indexPath) as! T
}
func dequeueReusableSupplementaryViewForIndexPath<T: UICollectionReusableView>(_ indexPath: IndexPath, of kind: String) -> T {
return dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: T.nameOfClass, for: indexPath) as! T
}
}
| 37.8 | 130 | 0.734568 |
ac21a25dcac46a536c613edbf5551d5617ce4b17 | 2,351 | //
// SceneDelegate.swift
// iTunesSearcher
//
// Created by Boris Sortino on 10/05/2020.
// Copyright © 2020 Boris Sortino. All rights reserved.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard scene as? UIWindowScene != nil else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 47.02 | 147 | 0.716291 |
e0d047d0e685051beaf084cf602e19b3cd291d30 | 788 | //
// StartStop.swift
// MusicXML
//
// Created by James Bean on 5/14/19.
//
/// The start-stop type is used for an attribute of musical elements that can either start or stop,
/// such as tuplets. The values of start and stop refer to how an element appears in musical score
/// order, not in MusicXML document order. An element with a stop attribute may precede the
/// corresponding element with a start attribute within a MusicXML document. This is particularly
/// common in multi-staff music. For example, the stopping point for a tuplet may appear in staff 1
/// before the starting point for the tuplet appears in staff 2 later in the document.
public enum StartStop: String {
case start
case stop
}
extension StartStop: Equatable {}
extension StartStop: Codable {}
| 37.52381 | 99 | 0.746193 |
9b4ded49b3b0f0e0098bb2d0449bfe928ae0a006 | 3,511 | //
// Loadable.swift
// SWKit
//
// Created by huluobo on 2017/11/5.
//
import Foundation
import Hotaru
public protocol LoadingViewType: class {
var isAnimating: Bool { get set }
var isError: Bool { get set }
func startAnimating()
func stopAnimating()
}
public extension LoadingViewType where Self: UIView {
var isError: Bool { return false }
func startAnimating() {
isAnimating = true
}
func stopAnimating() {
isAnimating = false
}
}
public protocol Loadable: class {
associatedtype LoadingView: UIView, LoadingViewType
/// The loading view
var loadingView: LoadingView { get }
/// The presenter
var presenter: UIView? { get set }
func loadData()
}
var loadingViewKey: Void?
var shouldLoadingKey: Void?
public extension Loadable where Self: UIViewController {
public var loadingView: DefaultLoadingView {
if let view = objc_getAssociatedObject(self, &loadingViewKey) as? DefaultLoadingView {
return view
} else {
let view = DefaultLoadingView()
objc_setAssociatedObject(self, &loadingViewKey, view, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return view
}
}
public var presenter: UIView? {
get { return self.view }
set {}
}
// TODO: shouldShowLoading 已经成为无用参数, 介于影响较大, 后期有时间再改.
public func load<T, R>(with resource: Resource<T, R>, shouldShowLoading: Bool = false, completion: ((R?) -> Void)?) {
if objc_getAssociatedObject(self, &shouldLoadingKey) as? Bool == nil {
objc_setAssociatedObject(self, &shouldLoadingKey, false, .OBJC_ASSOCIATION_ASSIGN)
startLoading(autoLoadData: false)
}
Provider(resource.target).request { response in
guard let data = response.data,
let result = resource.parse(data) else {
self.loadingView.isError = true
// self.loadingView.reloadHandler = {
// self.load(with: resource, shouldShowLoading: shouldShowLoading, completion: completion)
// }
self.stopLoading()
return
}
self.loadingView.isError = false
self.stopLoading()
completion?(result)
}.addToCancelBag()
}
/// 处理Merge的网络请求
///
/// - Parameter response: response
/// - Returns: 是否可以继续
func processLoadingEventsForMergeTarget(response: [Response]) ->Bool {
for res in response {
guard res.error == nil else {
self.loadingView.isError = true
return false
}
}
self.loadingView.isError = false
self.stopLoading()
return true
}
public func startLoading(autoLoadData: Bool = true) {
if presenter == nil {
presenter = view
}
if !presenter!.subviews.contains(loadingView) {
presenter!.addSubview(loadingView)
loadingView.snp.makeConstraints({ make in
make.edges.equalToSuperview()
})
}
loadingView.startAnimating()
if autoLoadData {
loadData()
}
}
public func stopLoading() {
loadingView.stopAnimating()
}
public func loadData() {
// load you data
}
}
| 26.598485 | 121 | 0.569069 |
237f65fef0c93089795c812d5e80bb661543657c | 4,064 | //
// CaptureSignatureViewController.swift
// signature
//
// Created by Vignesh on 2/10/16.
// Copyright © 2016 vigneshuvi. All rights reserved.
//
import UIKit
import QuartzCore
protocol CaptureSignatureViewDelegate {
func processCompleted(_ signImage: UIImage)
}
class CaptureSignatureViewController: UIViewController {
@IBOutlet var captureButton: UIButton!
var delegate: CaptureSignatureViewDelegate?
var username : NSString?
var signedDate : NSString?
@IBAction func captureSign(_ sender: AnyObject) {
//Create the AlertController
let alertView: UIAlertController = UIAlertController(title: "Saving signature with name", message: "Please enter your name`", preferredStyle: .alert)
//Add a text field
alertView.addTextField { textField -> Void in
//TextField configuration
textField.textColor = UIColor.black
textField.placeholder = "Name";
}
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "No, thanks", style: .cancel) { action -> Void in
//Do some stuff
alertView.dismiss(animated: true, completion: nil);
}
alertView.addAction(cancelAction)
//Create and an option action
let nextAction: UIAlertAction = UIAlertAction(title: "Yes, please", style: .default) { action -> Void in
//Do some other stuff
//Handel your yes please button action here
let textField:UITextField = (alertView.textFields?[0])!;
self.username = textField.text as NSString?;
let dateFormatter:DateFormatter = DateFormatter();
dateFormatter.dateFormat = "dd/MM/yyyy"
self.signedDate = dateFormatter.string(from: Date()) as NSString?;
if(self.username != nil && !self.username!.isEqual(to: "") && self.signedDate != nil && !self.signedDate!.isEqual(to: ""))
{
alertView.dismiss(animated: true, completion: nil);
if let delegate = self.delegate {
self.signatureView.captureSignature();
let signedImage = self.signatureView.signatureImage(String(format:"By: %@, %@", self.username!, self.signedDate!) as NSString, position: CGPoint(x: self.signatureView.frame.origin.x+10, y: self.signatureView.frame.size.height-25))
delegate.processCompleted(signedImage);
}
if let navController = self.navigationController {
navController.popViewController(animated: true)
}
}
}
alertView.addAction(nextAction)
//Present the AlertController
self.present(alertView, animated: true, completion: nil)
}
@IBOutlet var signatureView: UviSignatureView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let data:Data = UserDefaults.standard.object(forKey: USER_SIGNATURE_PATH) as? Data {
let signPathArray:NSMutableArray = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSMutableArray;
//self.signatureView.pathArray = signPathArray;
self.signatureView.pathArray(signPathArray);
NSLog("Path size : %d", self.signatureView.pathArray.count);
}
self.signatureView.setNeedsDisplay();
}
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.
}
*/
}
| 36.612613 | 250 | 0.634596 |
ef527089e12c8701956dc151cdf81c8b5c05d157 | 2,342 | import UIKit
public extension UIImage {
public func resized(toWidth width: CGFloat) -> UIImage? {
let ratio = size.width / size.height
let newSize = CGSize(width: width, height: width / ratio)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
draw(in: CGRect(origin: .zero, size: CGSize(width: newSize.width, height: newSize.height)))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public func resized(toHeight height: CGFloat) -> UIImage? {
let ratio = size.width / size.height
let newSize = CGSize(width: height * ratio, height: height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
draw(in: CGRect(origin: .zero, size: CGSize(width: newSize.width, height: newSize.height)))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
public var rounded: UIImage? {
let imageView = UIImageView(image: self)
imageView.layer.cornerRadius = min(size.height / 4, size.width / 4)
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
public var circled: UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
let imageView = UIImageView(frame: CGRect(origin: .zero, size: square))
imageView.contentMode = .scaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width / 2
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
| 41.087719 | 102 | 0.667805 |
033684d96d83171d76d3e6539fdc9064520e9344 | 1,015 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS REGENERATED BY EASY BINDINGS, ONLY MODIFY IT WITHIN USER ZONES
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//--- START OF USER ZONE 1
//--- END OF USER ZONE 1
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
func transient_ArtworkFileGenerationParameters_emptyFileExtensionImage (
_ self_fileExtension : String
) -> NSImage {
//--- START OF USER ZONE 2
return self_fileExtension.isEmpty ? NSImage.statusError : NSImage ()
//--- END OF USER ZONE 2
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 40.6 | 120 | 0.285714 |
d51a443fb284dc2bb899e39ad267eb51bb0843fa | 1,141 | //
// CompanyAndMemberProvider.swift
// Spectrum
//
// Created by Derick on 5/6/20.
// Copyright © 2020 DerickDev. All rights reserved.
//
import Alamofire
class CompanyAndMemberProvider {
static var shared = CompanyAndMemberProvider()
typealias companies = [Company]
func getCompanyList(completion: @escaping (companies?, AFError?) -> Void) {
let url = "https://next.json-generator.com/api/json/get/Vk-LhK44U"
let headers: [String: String] = [:]
NetworkProvider.shared.request(url: url, type: .get, headers: headers, body: nil) { data, error in
if let error = error {
AlertWireframe.shared.showOneButtonAlert("Error", message: error.localizedDescription, actionButton: "OK", inViewController: ApplicationCoordinator.shared.window.rootViewController)
completion(nil, error)
return
}
if let data = data, let companies = try? JSONDecoder().decode(companies.self, from: data) {
completion(companies, nil)
return
}
}
}
}
| 32.6 | 197 | 0.609115 |
f7b2f47afdfef6e573b6b24f4ccab7dce30394a1 | 822 | //
// MainViewController.swift
// 190520KakaoLoginExample
//
// Created by 차수연 on 20/05/2019.
// Copyright © 2019 차수연. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet private weak var thumbnailImageView: UIImageView!
@IBOutlet private weak var profileImageView: UIImageView!
@IBOutlet private weak var nickNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction private func logoutButtonDidTap(_ sender: Any) {
KOSession.shared().logoutAndClose { (success, error) -> Void in
if let error = error {
return print(error.localizedDescription)
}
// Logout success
AppDelegate.instance.setupRootViewController()
}
}
}
| 24.176471 | 67 | 0.694647 |
265ed1dc4b0fc6803332e92a722c39f1486dc279 | 2,928 | //
// SharingOption.swift
// goTapAPI
//
// Created by Dennis Pashkov on 7/28/16.
// Copyright © 2016 Tap Payments. All rights reserved.
//
/**
Sharing option enum.
- SMS: SMS.
- Mail: Email.
- Facebook: Facebook.
- FacebookMessenger: Facebook Messenger.
- Twitter: Twitter.
- WhatsApp: WhatsApp.
- Instagram: Instagram.
- Linkedin: LinkedIn.
- GooglePlus: Google Plus.
*/
public class SharingOption: Enum {
public static let SMS = SharingOption(rawValue: 1)
public static let Mail = SharingOption(rawValue: 2)
public static let Facebook = SharingOption(rawValue: 3)
public static let FacebookMessenger = SharingOption(rawValue: 4)
public static let Twitter = SharingOption(rawValue: 5)
public static let WhatsApp = SharingOption(rawValue: 6)
public static let Instagram = SharingOption(rawValue: 7)
public static let Linkedin = SharingOption(rawValue: 8)
public static let GooglePlus = SharingOption(rawValue: 9)
/// Returns string representation of the receiver.
public var stringRepresentation: String {
if self == SharingOption.SMS {
return Constants.Value.SMS
}
else if self == SharingOption.Mail {
return Constants.Value.Mail
}
else if self == SharingOption.Facebook {
return Constants.Value.Facebook
}
else if self == SharingOption.FacebookMessenger {
return Constants.Value.FacebookMessenger
}
else if self == SharingOption.Twitter {
return Constants.Value.Twitter
}
else if self == SharingOption.WhatsApp {
return Constants.Value.Whatsapp
}
else if self == SharingOption.Instagram {
return Constants.Value.Instagram
}
else if self == SharingOption.Linkedin {
return Constants.Value.Linkedin
}
else if self == SharingOption.GooglePlus {
return Constants.Value.GooglePlus
}
else {
return String.tap_empty
}
}
/**
Initializes sharing option with medium string.
- parameter mediumString: Medium string.
- returns: Sharing option created with a medium string.
*/
internal static func with(stringValue: String?) -> SharingOption {
guard let string = stringValue else {
return SharingOption.Mail
}
switch string {
case Constants.Value.SMS:
return SharingOption.SMS
case Constants.Value.Mail:
return SharingOption.Mail
case Constants.Value.Facebook:
return SharingOption.Facebook
case Constants.Value.FacebookMessenger:
return SharingOption.FacebookMessenger
case Constants.Value.Twitter:
return SharingOption.Twitter
case Constants.Value.Whatsapp:
return SharingOption.WhatsApp
case Constants.Value.Instagram:
return SharingOption.Instagram
case Constants.Value.Linkedin:
return SharingOption.Linkedin
case Constants.Value.GooglePlus:
return SharingOption.GooglePlus
default:
return SharingOption.Mail
}
}
}
| 21.372263 | 67 | 0.70765 |
755a07f0d469ce70e33cc1614cafe9f986bf5f6d | 1,424 | //
// DelaySubscription.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DelaySubscriptionSink<ElementType, O: ObserverType, S: SchedulerType where O.E == ElementType>
: Sink<O>
, ObserverType {
typealias Parent = DelaySubscription<ElementType, S>
typealias E = O.E
private let _parent: Parent
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(event: Event<E>) {
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
}
class DelaySubscription<Element, S: SchedulerType>: Producer<Element> {
typealias TimeInterval = S.TimeInterval
private let _source: Observable<Element>
private let _dueTime: TimeInterval
private let _scheduler: S
init(source: Observable<Element>, dueTime: TimeInterval, scheduler: S) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = DelaySubscriptionSink(parent: self, observer: observer)
sink.disposable = _scheduler.scheduleRelative((), dueTime: _dueTime) { _ in
return self._source.subscribe(sink)
}
return sink
}
} | 26.37037 | 100 | 0.639045 |
e488c7668069ee7eceee793f87f446538555f7fa | 1,232 | //
// NewsCell.swift
// covid19
//
// Created by Daniel on 4/22/20.
// Copyright © 2020 dk. All rights reserved.
//
import UIKit
class NewsCell: UICollectionViewCell {
var identifier: String?
var imageSize: CGSize?
let imageView = UIImageView()
let source = UILabel()
let title = UILabel()
let content = UILabel()
let ago = UILabel()
let line = UIView()
override func prepareForReuse() {
super.prepareForReuse()
ago.attributedText = nil
ago.text = nil
content.text = nil
content.attributedText = nil
identifier = nil
imageView.image = nil
source.text = nil
source.attributedText = nil
title.attributedText = nil
title.text = nil
}
var imageSizeUnwrapped: CGSize {
guard let unwrapped = imageSize else { return CGSize.zero }
return unwrapped
}
func configure(_ article: Article) {
identifier = article.identifier
}
func update(image: UIImage?, matchingIdentifier: String?) {
guard identifier == matchingIdentifier else { return }
imageView.image = image
}
}
| 21.241379 | 67 | 0.582792 |
2357d1e563b4e22a21590945a30eaae0eb7a5fd7 | 3,137 | //
// RecommendViewController.swift
// JPLiveDemo
//
// Created by KC on 16/11/21.
// Copyright © 2016年 KC. All rights reserved.
//
import UIKit
private let kCycleViewH : CGFloat = kScreenW * 3 / 8
private let KGameViewH : CGFloat = 90
class RecommendViewController: BaseAnchorViewController {
//MARK: - 懒加载属性
fileprivate lazy var recommendVM: RecommendViewModel = RecommendViewModel()
fileprivate lazy var cycleView: RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + KGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var gameView: RecommendGameView = {
let gameView = RecommendGameView(frame: CGRect(x: 0, y: -KGameViewH, width: kScreenW, height: KGameViewH))
return gameView
}()
}
// MARK:- 设置UI界面内容
extension RecommendViewController {
override func setupUI() {
super.setupUI()
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + KGameViewH, left: 0, bottom: 0, right: 0)
}
}
//MARK: - 数据请求
extension RecommendViewController {
override func loadData() {
baseVM = recommendVM
recommendVM.requestData {
self.collectionView.reloadData()
var anchorGroups = self.recommendVM.anchorGroups
print(anchorGroups)
// 2.1.移除前两组数据
anchorGroups.removeFirst()
anchorGroups.removeFirst()
// 2.2.添加更多组
let moreGroup = AnchorGroupModel()
moreGroup.tag_name = "更多"
anchorGroups.append(moreGroup)
self.gameView.gameModels = anchorGroups
//3.数据请求完成
self.loadDataFinished()
}
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
//MARK: - UICollectionViewFlowLayout
extension RecommendViewController : UICollectionViewDelegateFlowLayout {
//第一组特殊处理
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
prettyCell.anchor = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return prettyCell
}else {
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
}
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
| 30.754902 | 160 | 0.649984 |
226817d7f0fc71c09d73a394884fddf1284e18c1 | 522 | //
// FavoriteCell.swift
// WeatherApp
//
// Created by Joshua Viera on 1/23/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import UIKit
class FavoriteCell: UITableViewCell {
@IBOutlet weak var photo: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.076923 | 65 | 0.664751 |
abe03000b9a38df7638146990c25dc3e388dc22f | 15,019 | //
// UtilsFile.swift
// Plugin
//
// Created by Quéau Jean Pierre on 18/01/2021.
// Copyright © 2021 Max Lynch. All rights reserved.
//
import Foundation
import ZIPFoundation
enum UtilsFileError: Error {
case getFilePathFailed
case copyFileFailed
case renameFileFailed
case deleteFileFailed
case getAssetsDatabasesPathFailed
case getDatabasesPathFailed
case getDatabasesURLFailed
case getApplicationPathFailed
case getApplicationURLFailed
case getLibraryPathFailed
case getLibraryURLFailed
case getFileListFailed
case copyFromAssetToDatabaseFailed(message: String)
case unzipFromAssetToDatabaseFailed(message: String)
case copyFromNamesFailed
}
// swiftlint:disable file_length
// swiftlint:disable type_body_length
class UtilsFile {
// MARK: - IsFileExist
class func isDirExist(dirPath: String) -> Bool {
var isDir: ObjCBool = true
let fileManager = FileManager.default
let exists = fileManager.fileExists(atPath: dirPath, isDirectory: &isDir)
return exists && isDir.boolValue
}
// MARK: - IsFileExist
class func isFileExist(filePath: String) -> Bool {
var ret: Bool = false
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
ret = true
}
return ret
}
class func isFileExist(fileName: String) -> Bool {
var ret: Bool = false
do {
let filePath: String =
try UtilsFile.getFilePath(
fileName: fileName)
ret = UtilsFile.isFileExist(filePath: filePath)
return ret
} catch UtilsFileError.getFilePathFailed {
return false
} catch _ {
return false
}
}
// MARK: - GetFilePath
class func getFilePath(fileName: String) throws -> String {
do {
let url = try getDatabasesUrl()
return url.appendingPathComponent("\(fileName)").path
} catch UtilsFileError.getDatabasesURLFailed {
print("Error: getDatabasesUrl Failed")
throw UtilsFileError.getFilePathFailed
}
}
// MARK: - getDatabasesUrl
class func getDatabasesUrl() throws -> URL {
if let path: String = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first {
return NSURL(fileURLWithPath: path) as URL
} else {
print("Error: getDatabasesURL did not find the document folder")
throw UtilsFileError.getDatabasesURLFailed
}
}
// MARK: - getDatabasesPath
class func getDatabasesPath() throws -> String {
if let path: String = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first {
return path
} else {
print("Error: getDatabasesPath did not find the document folder")
throw UtilsFileError.getDatabasesPathFailed
}
}
// MARK: - getApplicationURL
class func getApplicationURL() throws -> URL {
if let path: String = NSSearchPathForDirectoriesInDomains(
.applicationDirectory, .userDomainMask, true
).first {
return NSURL(fileURLWithPath: path) as URL
} else {
print("Error: getApplicationURL did not find the application folder")
throw UtilsFileError.getApplicationURLFailed
}
}
// MARK: - getApplicationPath
class func getApplicationPath() throws -> String {
if let path: String = NSSearchPathForDirectoriesInDomains(
.applicationDirectory, .userDomainMask, true
).first {
return path
} else {
print("Error: getApplicationPath did not find the application folder")
throw UtilsFileError.getApplicationPathFailed
}
}
// MARK: - getLibraryURL
class func getLibraryURL() throws -> URL {
if let path: String = NSSearchPathForDirectoriesInDomains(
.libraryDirectory, .userDomainMask, true
).first {
return NSURL(fileURLWithPath: path) as URL
} else {
print("Error: getApplicationURL did not find the library folder")
throw UtilsFileError.getLibraryURLFailed
}
}
// MARK: - getLibraryPath
class func getLibraryPath() throws -> String {
if let path: String = NSSearchPathForDirectoriesInDomains(
.libraryDirectory, .userDomainMask, true
).first {
return path
} else {
print("Error: getApplicationPath did not find the library folder")
throw UtilsFileError.getLibraryPathFailed
}
}
// MARK: - GetAssetsDatabasesPath
class func getAssetsDatabasesPath() throws -> URL {
if let appFolder = Bundle.main.resourceURL {
print("getAssetsDatabasesPath appFolder \(appFolder)")
return appFolder.appendingPathComponent("public/assets/databases")
} else {
print("Error: getAssetsDatabasePath did not find app folder")
throw UtilsFileError.getAssetsDatabasesPathFailed
}
}
// MARK: - setPathSuffix
class func setPathSuffix(sDb: String ) -> String {
var toDb: String = sDb
let ext: String = ".db"
if sDb.hasSuffix(ext) {
if !sDb.contains("SQLite.db") {
toDb = sDb.prefix(sDb.count - ext.count) + "SQLite.db"
}
}
return toDb
}
// MARK: - GetFileList
class func getFileList(path: String, ext: String) throws -> [String] {
do {
var dbs: [String] = []
let filenames = try FileManager.default
.contentsOfDirectory(atPath: path)
for file in filenames {
if file.hasSuffix(ext) {
dbs.append(file)
}
}
return dbs
} catch let error {
print("Error: \(error)")
throw UtilsFileError.getFileListFailed
}
}
// MARK: - CopyFromNames
class func copyFromNames(dbPathURL: URL, fromFile: String, databaseURL: URL,
toFile: String) throws {
do {
let uFrom: URL = dbPathURL.appendingPathComponent(fromFile)
let uTo: URL = databaseURL.appendingPathComponent(toFile)
let pFrom: String = uFrom.path
let pTo: String = uTo.path
let bRet: Bool = try copyFile(pathName: pFrom, toPathName: pTo,
overwrite: true)
if bRet {
return
} else {
print("Error: FromNames return false")
throw UtilsFileError.copyFromNamesFailed
}
} catch UtilsFileError.copyFileFailed {
print("Error: copyFile Failed")
throw UtilsFileError.copyFromNamesFailed
}
}
// MARK: - CopyFromAssetToDatabase
class func copyFromAssetToDatabase(fromDb: String, toDb: String,
overwrite: Bool) throws {
do {
let uAsset: URL = try getAssetsDatabasesPath()
.appendingPathComponent(fromDb)
let pAsset: String = uAsset.path
let uDb: URL = try getDatabasesUrl()
.appendingPathComponent(toDb)
let pDb: String = uDb.path
let bRet: Bool = try copyFile(pathName: pAsset, toPathName: pDb,
overwrite: overwrite)
if bRet {
return
} else {
let msg = "Error: copyFile return false"
print("\(msg)")
throw UtilsFileError.copyFromAssetToDatabaseFailed(message: msg)
}
} catch UtilsFileError.getAssetsDatabasesPathFailed {
let msg = "Error: getAssetsDatabasesPath Failed"
print("\(msg)")
throw UtilsFileError.copyFromAssetToDatabaseFailed(message: msg)
} catch UtilsFileError.getDatabasesURLFailed {
let msg = "Error: getDatabasesUrl Failed"
print("\(msg)")
throw UtilsFileError.copyFromAssetToDatabaseFailed(message: msg)
} catch UtilsFileError.copyFileFailed {
let msg = "Error: copyFile Failed"
print("\(msg)")
throw UtilsFileError.copyFromAssetToDatabaseFailed(message: msg)
} catch let error {
let msg = "Error: \(error)"
print("\(msg)")
throw UtilsFileError.copyFromAssetToDatabaseFailed(message: msg)
}
}
class func unzipFromAssetToDatabase(zip: String, overwrite: Bool) throws {
do {
let zipAsset: URL = try getAssetsDatabasesPath()
.appendingPathComponent(zip)
guard let archive = Archive(url: zipAsset, accessMode: .read) else {
let msg = "Error: Read Archive: \(zipAsset) failed"
print("\(msg)")
throw UtilsFileError.unzipFromAssetToDatabaseFailed(message: msg)
}
for entry in archive {
let dbEntry = setPathSuffix(sDb: entry.path)
let zipCopy: URL = try getDatabasesUrl()
.appendingPathComponent(dbEntry)
do {
let isExist: Bool = isFileExist(filePath: zipCopy.path)
if !isExist || overwrite {
if overwrite && isExist {
_ = try deleteFile(filePath: zipCopy.path)
}
_ = try archive.extract(entry, to: zipCopy)
}
} catch {
let msg = "Error: Extracting \(entry.path) from archive failed \(error.localizedDescription)"
print("\(msg)")
throw UtilsFileError.unzipFromAssetToDatabaseFailed(message: msg)
}
}
} catch UtilsFileError.getAssetsDatabasesPathFailed {
let msg = "Error: getAssetsDatabasesPath Failed"
print("\(msg)")
throw UtilsFileError.unzipFromAssetToDatabaseFailed(message: msg)
} catch UtilsFileError.getDatabasesURLFailed {
let msg = "Error: getDatabasesUrl Failed"
print("\(msg)")
throw UtilsFileError.unzipFromAssetToDatabaseFailed(message: msg)
} catch let error {
let msg = "Error: \(error)"
print("\(msg)")
throw UtilsFileError.unzipFromAssetToDatabaseFailed(message: msg)
}
}
// MARK: - CopyFile
class func copyFile(pathName: String, toPathName: String, overwrite: Bool) throws -> Bool {
if pathName.count > 0 && toPathName.count > 0 {
let isPath = isFileExist(filePath: pathName)
if isPath {
do {
let isExist: Bool = isFileExist(filePath: toPathName)
if !isExist || overwrite {
if overwrite && isExist {
_ = try deleteFile(filePath: toPathName)
}
let fileManager = FileManager.default
try fileManager.copyItem(atPath: pathName,
toPath: toPathName)
}
return true
} catch let error {
print("Error: \(error)")
throw UtilsFileError.copyFileFailed
}
} else {
print("Error: CopyFilePath Failed pathName does not exist")
throw UtilsFileError.copyFileFailed
}
} else {
print("Error: CopyFilePath Failed paths count = 0")
throw UtilsFileError.copyFileFailed
}
}
// MARK: - CopyFile
class func copyFile(fileName: String, toFileName: String)
throws -> Bool {
var ret: Bool = false
do {
let fromPath: String = try getFilePath(fileName: fileName)
let toPath: String = try getFilePath(fileName: toFileName)
ret = try copyFile(pathName: fromPath, toPathName: toPath, overwrite: true)
return ret
} catch UtilsFileError.getFilePathFailed {
print("Error: getFilePath Failed")
throw UtilsFileError.copyFileFailed
} catch let error {
print("Error: \(error)")
throw UtilsFileError.copyFileFailed
}
}
// MARK: - DeleteFile
class func deleteFile(filePath: String) throws -> Bool {
var ret: Bool = false
do {
if isFileExist(filePath: filePath) {
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: filePath)
ret = true
} catch let error {
print("Error: \(error)")
throw UtilsFileError.deleteFileFailed
}
}
} catch let error {
print("Error: \(error)")
throw UtilsFileError.deleteFileFailed
}
return ret
}
// MARK: - DeleteFile
class func deleteFile(fileName: String) throws -> Bool {
var ret: Bool = false
do {
let filePath: String = try getFilePath(fileName: fileName)
ret = try deleteFile(filePath: filePath)
} catch let error {
print("Error: \(error)")
throw UtilsFileError.deleteFileFailed
}
return ret
}
// MARK: - DeleteFile
class func deleteFile(dbPathURL: URL, fileName: String) throws -> Bool {
var ret: Bool = false
do {
let uURL: URL = dbPathURL.appendingPathComponent(fileName)
let filePath: String = uURL.path
ret = try deleteFile(filePath: filePath)
} catch UtilsFileError.deleteFileFailed {
throw UtilsFileError.deleteFileFailed
} catch let error {
print("Error: \(error)")
throw UtilsFileError.deleteFileFailed
}
return ret
}
// MARK: - RenameFile
class func renameFile (filePath: String, toFilePath: String)
throws {
let fileManager = FileManager.default
do {
if isFileExist(filePath: toFilePath) {
let fileName = URL(
fileURLWithPath: toFilePath).lastPathComponent
try _ = deleteFile(fileName: fileName)
}
try fileManager.moveItem(atPath: filePath,
toPath: toFilePath)
} catch let error {
print("Error: \(error)")
throw UtilsFileError.renameFileFailed
}
}
}
// swiftlint:enable type_body_length
// swiftlint:enable file_length
| 34.685912 | 113 | 0.567681 |
18ad0c311daf96dfb39ac2fb66aa07c538d27bcb | 1,856 |
import Foundation
import CoreGraphics
extension Mesh {
public func positionForNewChild(_ parent: Node, length: CGFloat) -> CGPoint {
let childEdges = edges.filter { $0.start == parent.id }
if let grandparentedge = edges.filter({ $0.end == parent.id }).first, let grandparent = nodeWithID(grandparentedge.start) {
let baseAngle = angleFrom(start: grandparent.position, end: parent.position)
let childBasedAngle = positionForChildAtIndex(childEdges.count, baseAngle: baseAngle)
let newpoint = pointWithCenter(center: parent.position, radius: length, angle: childBasedAngle)
return newpoint
}
return CGPoint(x: 200, y: 200)
}
/// get angle for n'th child in order delta * 0,1,-1,2,-2
func positionForChildAtIndex(_ index: Int, baseAngle: CGFloat) -> CGFloat {
let jitter = CGFloat.random(in: CGFloat(-1.0)...CGFloat(1.0)) * CGFloat.pi/32.0
guard index > 0 else { return baseAngle + jitter }
let level = (index + 1)/2
let polarity: CGFloat = index % 2 == 0 ? -1.0:1.0
let delta = CGFloat.pi/6.0 + jitter
return baseAngle + polarity * delta * CGFloat(level)
}
/// angle in radians
func pointWithCenter(center: CGPoint, radius: CGFloat, angle: CGFloat) -> CGPoint {
let deltax = radius*cos(angle)
let deltay = radius*sin(angle)
let newpoint = CGPoint(x: center.x + deltax, y: center.y + deltay)
return newpoint
}
func angleFrom(start: CGPoint, end: CGPoint) -> CGFloat {
var deltax = end.x - start.x
let deltay = end.y - start.y
if abs(deltax) < 0.001 {
deltax = 0.001
}
let angle = atan(deltay/abs(deltax))
return deltax > 0 ? angle: CGFloat.pi - angle
}
}
| 39.489362 | 131 | 0.607759 |
2f792e6ffea85a449f782915d24b61b39799ceaf | 609 | //
// ParticipantTableViewCell.swift
// TogetherStream
//
// Created by Daniel Firsht on 3/27/17.
// Copyright © 2017 IBM. All rights reserved.
//
import UIKit
class ParticipantTableViewCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabelView: 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
}
}
| 22.555556 | 65 | 0.686371 |
cc9b9dcc280cd2036eeb2682284b1b3e4170c833 | 17,680 | //
// VideoEditViewController.swift
// windmill
//
// Created by Liam on 2020-05-07.
// Copyright © 2020 Mulugeta Chamasa. All rights reserved.
//
import UIKit
import Photos
import AVKit
import AVFoundation
protocol StickerDelegate {
func viewTapped(view: UIView)
func imageTapped(image: UIImage)
}
class VideoEditViewController: UIViewController, UITabBarControllerDelegate {
// MARK: IVARS
internal var avPlayer: AVPlayer?
internal var avPlayerLayer: AVPlayerLayer!
internal var videoURL: URL!
internal var vSpinner: UIView?
@IBOutlet weak var videoView: UIView!
@IBOutlet weak var tempImageView: UIImageView!
@IBOutlet weak var deleteView: UIView!
@IBOutlet weak var toolbar: UIToolbar!
internal var imageViewToPan: UIImageView?
internal var textColor: UIColor = UIColor.white
internal var lastTextViewTransform: CGAffineTransform?
internal var lastTextViewTransCenter: CGPoint?
internal var lastTextViewFont: UIFont?
internal var activeTextView: UITextView?
internal var lastPanPoint: CGPoint?
let uploadManager = UploadManager()
let postButton = UIView()
internal var screenHeight = UIScreen.main.bounds.size.height
internal var screenWidth = UIScreen.main.bounds.size.width
internal var textButton: UIBarButtonItem!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
setupPlayer()
addLoopObserver()
setupUI()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)
}
override func viewWillAppear(_ animated: Bool) {
}
override func viewWillDisappear(_ animated: Bool) {
removeLoopObserver()
}
// MARK: Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! UploadVideoViewController
vc.videoURL = sender as? URL
vc.prevVC = self
}
// MARK: Setup Player
internal func setupPlayer() {
avPlayer = AVPlayer()
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.frame = view.bounds
avPlayerLayer.videoGravity = .resizeAspectFill
videoView.layer.insertSublayer(avPlayerLayer, at: 0)
let playerItem = AVPlayerItem(url: videoURL as URL)
avPlayer!.replaceCurrentItem(with: playerItem)
avPlayer!.play()
}
// MARK: User Interface
internal func setupUI() {
// Trash Icon
let icon = UIImage(systemName: "trash", withConfiguration: UIImage.SymbolConfiguration(pointSize: 25, weight: .bold))?.withTintColor(.white, renderingMode: .alwaysOriginal)
let imageView = UIImageView(image: icon)
deleteView.addSubview(imageView)
// Back Button Icon
let icon2 = UIImage(systemName: "arrow.left", withConfiguration: UIImage.SymbolConfiguration(pointSize: 25, weight: .bold))?.withTintColor(.white, renderingMode: .alwaysOriginal)
let button = UIButton()
button.frame = CGRect(x:0, y:0, width: 51, height: 31)
button.setImage(icon2, for: .normal)
button.addTarget(self, action: #selector(self.backButtonTapped), for: .touchUpInside)
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.leftBarButtonItem = barButton
// Next Button Icon
let button2 = UIButton()
button2.frame = CGRect(x:0, y:0, width: 70, height: 35)
button2.setTitle("Next", for: .normal)
button2.titleLabel?.font = UIFont(name: "Ubuntu", size: 18)
button2.layer.backgroundColor = UIColor(rgb: 0x00B894).cgColor
button2.layer.cornerRadius = 17.0
button2.addTarget(self, action: #selector(self.nextButtonTapped), for: .touchUpInside)
let barButton2 = UIBarButtonItem()
barButton2.customView = button2
// Text Button Icon
let button3 = UIButton()
let icon3 = UIImage(systemName: "textbox", withConfiguration: UIImage.SymbolConfiguration(pointSize: 25, weight: .bold))?.withTintColor(.white, renderingMode: .alwaysOriginal)
button3.frame = CGRect(x:0, y:0, width: 51, height: 31)
button3.setImage(icon3, for: .normal)
button3.addTarget(self, action: #selector(self.addTextButtonTapped), for: .touchUpInside)
let barButton3 = UIBarButtonItem()
barButton3.customView = button3
textButton = barButton3
// Toolbar Setup
toolbar.setBackgroundImage(UIImage(),
forToolbarPosition: .any,
barMetrics: .default)
toolbar.setShadowImage(UIImage(), forToolbarPosition: .any)
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.setItems([barButton3, flexibleSpace, barButton2], animated: false)
}
// MARK: User Interaction
@objc internal func addTextButtonTapped() {
let textView = UITextView(frame: CGRect(x: 0, y: tempImageView.center.y,
width: UIScreen.main.bounds.width, height: 30))
textView.textAlignment = .center
textView.font = UIFont(name: "Helvetica", size: 40)
textView.textColor = textColor
textView.layer.shadowColor = UIColor.black.cgColor
textView.layer.shadowOffset = CGSize(width: 1.0, height: 0.0)
textView.layer.shadowOpacity = 0.2
textView.layer.shadowRadius = 1.0
textView.layer.backgroundColor = UIColor.clear.cgColor
textView.autocorrectionType = .no
textView.isScrollEnabled = false
textView.delegate = self
self.tempImageView.addSubview(textView)
addGestures(view: textView)
textView.becomeFirstResponder()
}
@objc internal func backButtonTapped() {
navigationController?.popViewController(animated: true)
}
@objc internal func nextButtonTapped() {
convertVideo(videoURL: videoURL!)
}
@objc internal func dismissKeyboard() {
view.endEditing(true)
tempImageView.isUserInteractionEnabled = true
}
// MARK: Observers
internal func addLoopObserver() {
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.avPlayer!.currentItem, queue: .main) { [weak self] _ in
self?.avPlayer!.seek(to: CMTime.zero)
self?.avPlayer!.play()
}
}
internal func removeLoopObserver() {
NotificationCenter.default.removeObserver(self)
if avPlayer != nil {
avPlayer?.replaceCurrentItem(with: nil)
avPlayer = nil
}
}
// MARK: Video Functions
internal func convertVideo(videoURL: URL) {
self.showSpinner(onView: self.videoView)
let temp = randomString(length: 10)
let filePathName = randomString(length: 10)
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let myDocumentPath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent(temp+".mp4").absoluteString
_ = NSURL(fileURLWithPath: myDocumentPath)
let documentsDirectory2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
let filePath = documentsDirectory2.appendingPathComponent(filePathName+".mp4")
deleteFile(filePath: filePath as NSURL)
if FileManager.default.fileExists(atPath: myDocumentPath) {
do { try FileManager.default.removeItem(atPath: myDocumentPath)
} catch let error { print(error) }
}
let asset = AVURLAsset(url: videoURL as URL)
let composition = AVMutableComposition.init()
composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)
let clipVideoTrack = asset.tracks(withMediaType: AVMediaType.video)[0]
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
let videoTransform: CGAffineTransform = clipVideoTrack.preferredTransform
var videoAssetOrientation_ = UIImage.Orientation.up
var isVideoAssetPortrait_ = false
if videoTransform.a == 0 && videoTransform.b == 1.0 && videoTransform.c == -1.0 && videoTransform.d == 0 {
videoAssetOrientation_ = UIImage.Orientation.right
isVideoAssetPortrait_ = true
}
if videoTransform.a == 0 && videoTransform.b == -1.0 && videoTransform.c == 1.0 && videoTransform.d == 0 {
videoAssetOrientation_ = UIImage.Orientation.left
isVideoAssetPortrait_ = true
}
if videoTransform.a == 1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == 1.0 {
videoAssetOrientation_ = UIImage.Orientation.up
}
if videoTransform.a == -1.0 && videoTransform.b == 0 && videoTransform.c == 0 && videoTransform.d == -1.0 {
videoAssetOrientation_ = UIImage.Orientation.down;
}
transformer.setTransform(clipVideoTrack.preferredTransform, at: CMTime.zero)
transformer.setOpacity(0.0, at: asset.duration)
var naturalSize: CGSize
if(isVideoAssetPortrait_){
naturalSize = CGSize(width: clipVideoTrack.naturalSize.height, height: clipVideoTrack.naturalSize.width)
} else {
naturalSize = clipVideoTrack.naturalSize;
}
var renderWidth: CGFloat!
var renderHeight: CGFloat!
renderWidth = naturalSize.width
renderHeight = naturalSize.height
let parentlayer = CALayer()
let videoLayer = CALayer()
let watermarkLayer = CALayer()
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = CGSize(width: renderWidth, height: renderHeight)
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
videoComposition.renderScale = 1.0
watermarkLayer.contents = tempImageView.asImage().cgImage
parentlayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: naturalSize)
videoLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: naturalSize)
watermarkLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: naturalSize)
parentlayer.addSublayer(videoLayer)
parentlayer.addSublayer(watermarkLayer)
videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayers: [videoLayer], in: parentlayer)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: CMTimeMakeWithSeconds(60, preferredTimescale: 30))
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
let exporter = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetHighestQuality)
exporter?.outputFileType = AVFileType.mov
exporter?.outputURL = filePath
exporter?.videoComposition = videoComposition
exporter!.exportAsynchronously(completionHandler: {() -> Void in
if exporter?.status == .completed {
let outputURL: URL? = exporter?.outputURL
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: outputURL!)
}) { saved, error in
if saved {
let fetchOptions = PHFetchOptions()
let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).lastObject
PHImageManager().requestAVAsset(forVideo: fetchResult!, options: nil, resultHandler: { (avurlAsset, audioMix, dict) in
let newObj = avurlAsset as! AVURLAsset
DispatchQueue.main.async(execute: {
print(newObj.url)
self.performSegue(withIdentifier: "postVideo", sender: newObj.url)
self.removeSpinner()
})
})
}
}
}
})
}
func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
}
func deleteFile(filePath:NSURL) {
guard FileManager.default.fileExists(atPath: filePath.path!) else {
return
}
do { try FileManager.default.removeItem(atPath: filePath.path!)
} catch { fatalError("Unable to delete file: \(error)") }
}
internal func showSpinner(onView: UIView) {
let spinnerView = UIView.init(frame: onView.bounds)
let ai = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.large)
ai.color = .white
ai.startAnimating()
ai.center = spinnerView.center
spinnerView.addSubview(ai)
onView.addSubview(spinnerView)
vSpinner = spinnerView
}
internal func removeSpinner() {
vSpinner?.removeFromSuperview()
vSpinner = nil
}
// MARK: Tab Bar Controller Delegate Functions
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
let tabBarIndex = tabBarController.selectedIndex
if tabBarIndex != 2 {
navigationController?.popViewController(animated: false)
}
}
}
// MARK: Text View Delegate
extension VideoEditViewController: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
let rotation = atan2(textView.transform.b, textView.transform.a)
if rotation == 0 {
let oldFrame = textView.frame
let sizeToFit = textView.sizeThatFits(CGSize(width: oldFrame.width, height:CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: oldFrame.width, height: sizeToFit.height)
}
}
public func textViewDidBeginEditing(_ textView: UITextView) {
lastTextViewTransform = textView.transform
lastTextViewTransCenter = textView.center
lastTextViewFont = textView.font!
activeTextView = textView
textView.superview?.bringSubviewToFront(textView)
textView.font = UIFont(name: "Helvetica", size: 40)
UIView.animate(withDuration: 0.3,
animations: {
textView.transform = CGAffineTransform.identity
textView.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 100)
}, completion: nil)
}
public func textViewDidEndEditing(_ textView: UITextView) {
guard lastTextViewTransform != nil && lastTextViewTransCenter != nil && lastTextViewFont != nil
else {
return
}
activeTextView = nil
textView.font = self.lastTextViewFont!
UIView.animate(withDuration: 0.3,
animations: {
textView.transform = self.lastTextViewTransform!
textView.center = self.lastTextViewTransCenter!
}, completion: nil)
}
}
// MARK: Sticker Delegate
extension VideoEditViewController: StickerDelegate {
func viewTapped(view: UIView) {
view.center = tempImageView.center
self.tempImageView.addSubview(view)
addGestures(view: view)
}
func imageTapped(image: UIImage) {
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
imageView.frame.size = CGSize(width: 150, height: 150)
imageView.center = tempImageView.center
self.tempImageView.addSubview(imageView)
addGestures(view: imageView)
}
func addGestures(view: UIView) {
view.isUserInteractionEnabled = true
let panGesture = UIPanGestureRecognizer(target: self,
action: #selector(VideoEditViewController.panGesture))
panGesture.minimumNumberOfTouches = 1
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
view.addGestureRecognizer(panGesture)
let pinchGesture = UIPinchGestureRecognizer(target: self,
action: #selector(VideoEditViewController.pinchGesture))
pinchGesture.delegate = self
view.addGestureRecognizer(pinchGesture)
let rotationGestureRecognizer = UIRotationGestureRecognizer(target: self,
action:#selector(VideoEditViewController.rotationGesture) )
rotationGestureRecognizer.delegate = self
view.addGestureRecognizer(rotationGestureRecognizer)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(VideoEditViewController.tapGesture))
view.addGestureRecognizer(tapGesture)
}
}
| 39.028698 | 186 | 0.641968 |
1e516c349a06e9c95426f4b1d376e79a2b3964b7 | 3,918 | //
// HTTPClient.swift
// CCAnalyzer
//
// Created by Sviatoslav Belmeha on 8/11/17.
//
import Foundation
public typealias JSON = [String: Any]
public typealias HTTPResponse = (body: JSON, headers: [String: String])
public enum HTTPMethod: String { case GET, POST }
public enum HTTPError: Error {
case serverError
case clientError(code: Int, details: JSON?)
case timeOut
case unknownError
}
private enum ServiceError: Error {
case cannotMakeRequest
case cannotParse
}
private enum HTTPCodeStatus {
case successful, clientError, serverError, unknown
}
public enum Result<T> {
case success(response: T)
case fail(error: Error)
}
public class HTTPClient {
private let baseURL: URL
public init(baseURL: URL) {
self.baseURL = baseURL
}
// MARK: API
public func GET(path: String, parameters: [String: String]? = nil, completion: @escaping (Result<HTTPResponse>) -> Void) {
let request = createRequest(withMethod: .GET, path: path, parameters: parameters)
send(request: request, completion: completion)
}
// MARK: Requests
public func createRequest(withMethod method: HTTPMethod, path: String, parameters: [String: String]?) -> URLRequest? {
guard var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: true) else {
return nil
}
let parm = parameters?.map({ URLQueryItem(name: $0.key, value: $0.value) })
urlComponents.path = path
urlComponents.queryItems = parm
guard let url = urlComponents.url else { return nil }
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
return request
}
private func send(request: URLRequest?, completion: @escaping (Result<HTTPResponse>) -> Void) {
guard let request = request else {
completion(.fail(error: ServiceError.cannotMakeRequest))
return
}
let task = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data, let response = response as? HTTPURLResponse else {
completion(.fail(error: HTTPError.serverError))
return
}
do {
let statusCode = response.statusCode
let headers = response.allHeaderFields as! [String: String]
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? JSON {
switch self.status(fromCode: statusCode) {
case .successful:
completion(.success(response: (body: json, headers: headers)))
case .clientError:
completion(.fail(error: HTTPError.clientError(code: statusCode, details: json)))
case .serverError:
completion(.fail(error: HTTPError.serverError))
default:
completion(.fail(error: HTTPError.unknownError))
}
} else {
completion(.fail(error: ServiceError.cannotParse))
}
} catch {
completion(.fail(error: error))
return
}
}
task.resume()
}
private lazy var session: URLSession = {
var config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
return URLSession(configuration: config)
}()
private func status(fromCode code: Int) -> HTTPCodeStatus {
switch code {
case 200 ..< 300:
return .successful
case 400 ..< 500:
return .clientError
case 500 ..< 600:
return .serverError
default:
return .unknown
}
}
}
| 32.114754 | 126 | 0.586013 |
ccbd6b33fc19f05f2b63c855fe2fb1b7798188ad | 1,279 | //
// RoomView.swift
// DouYuDemo
//
// Created by 也许、 on 16/10/15.
// Copyright © 2016年 K. All rights reserved.
//
import UIKit
class RoomView: UIView {
lazy var roomVM : RoomViewModel = RoomViewModel()
var anchor:Anchor? {
didSet {
// 1.显示虚化的背景图片
let url = URL(string: anchor!.vertical_src)
self.bgImg.sd_setImage(with: url!)
// 2.请求视频流地址
roomVM.loadData(roomId: anchor!.room_id) {
}
}
}
// 虚化背景图
lazy var bgImg:UIImageView = {
let imageView:UIImageView = UIImageView(frame: self.bounds)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let visualEffectView = UIVisualEffectView(effect: blurEffect)
visualEffectView.frame = imageView.bounds
imageView.insertSubview(visualEffectView, at: 1)
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension RoomView {
func initUI() {
self.addSubview(bgImg)
}
}
| 20.301587 | 69 | 0.558249 |
7ab472e8ddb1a46326deb00e077fe769286748ff | 66,743 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#if canImport(Combine)
import Combine
import Realm.Private
// MARK: - Identifiable
/// A protocol which defines a default identity for Realm Objects
///
/// Declaraing your Object subclass as conforming to this protocol will supply
/// a default implemention for `Identifiable`'s `id` which works for Realm
/// Objects:
///
/// // Automatically conforms to `Identifiable`
/// class MyObjectType: Object, ObjectKeyIdentifiable {
/// // ...
/// }
///
/// You can also manually conform to `Identifiable` if you wish, but note that
/// using the object's memory address does *not* work for managed objects.
public protocol ObjectKeyIdentifiable: Identifiable, Object {
/// The stable identity of the entity associated with `self`.
var id: UInt64 { get }
}
/// :nodoc:
@available(*, deprecated, renamed: "ObjectKeyIdentifiable")
public typealias ObjectKeyIdentifable = ObjectKeyIdentifiable
extension ObjectKeyIdentifiable {
/// A stable identifier for this object. For managed Realm objects, this
/// value will be the same for all object instances which refer to the same
/// object (i.e. for which `Object.isSameObject(as:)` returns true).
public var id: UInt64 {
RLMObjectBaseGetCombineId(self)
}
}
// MARK: - Combine
/// A type which can be passed to `valuePublisher()` or `changesetPublisher()`.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public protocol RealmSubscribable {
// swiftlint:disable identifier_name
/// :nodoc:
func _observe<S>(on queue: DispatchQueue?, _ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Self, S.Failure == Error
/// :nodoc:
func _observe<S>(_ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Void, S.Failure == Never
// swiftlint:enable identifier_name
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher {
/// Freezes all Realm objects and collections emitted by the upstream publisher
///
/// Freezing a Realm object makes it no longer live-update when writes are
/// made to the Realm and makes it safe to pass freely between threads
/// without using `.threadSafeReference()`.
///
/// ```
/// // Get a publisher for a Results
/// let cancellable = myResults.publisher
/// // Convert to frozen Results
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { frozenResults in
/// // Do something with the frozen Results
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the objects which the upstream publisher publishes.
public func freeze<T>() -> Publishers.Map<Self, T> where Output: ThreadConfined, T == Output {
return map { $0.freeze() }
}
/// Freezes all Realm object changesets emitted by the upstream publisher.
///
/// Freezing a Realm object changeset makes the included object reference
/// no longer live-update when writes are made to the Realm and makes it
/// safe to pass freely between threads without using
/// `.threadSafeReference()`. It also guarantees that the frozen object
/// contained in the changset will always match the property changes, which
/// is not always the case when using thread-safe references.
///
/// ```
/// // Get a changeset publisher for an object
/// let cancellable = changesetPublisher(object)
/// // Convert to frozen changesets
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { changeset in
/// // Do something with the frozen changeset
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the changesets
/// which the upstream publisher publishes.
public func freeze<T: Object>() -> Publishers.Map<Self, ObjectChange<T>> where Output == ObjectChange<T> {
return map {
if case .change(let object, let properties) = $0 {
return .change(object.freeze(), properties)
}
return $0
}
}
/// Freezes all Realm collection changesets from the upstream publisher.
///
/// Freezing a Realm collection changeset makes the included collection
/// reference no longer live-update when writes are made to the Realm and
/// makes it safe to pass freely between threads without using
/// `.threadSafeReference()`. It also guarantees that the frozen collection
/// contained in the changset will always match the change information,
/// which is not always the case when using thread-safe references.
///
/// ```
/// // Get a changeset publisher for a collection
/// let cancellable = myList.changesetPublisher
/// // Convert to frozen changesets
/// .freeze()
/// // Unlike live objects, frozen objects can be sent to a concurrent queue
/// .receive(on: DispatchQueue.global())
/// .sink { changeset in
/// // Do something with the frozen changeset
/// }
/// ```
///
/// - returns: A publisher that publishes frozen copies of the changesets
/// which the upstream publisher publishes.
public func freeze<T: RealmCollection>()
-> Publishers.Map<Self, RealmCollectionChange<T>> where Output == RealmCollectionChange<T> {
return map {
switch $0 {
case .initial(let collection):
return .initial(collection.freeze())
case .update(let collection, deletions: let deletions, insertions: let insertions, modifications: let modifications):
return .update(collection.freeze(), deletions: deletions, insertions: insertions, modifications: modifications)
case .error(let error):
return .error(error)
}
}
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher where Output: ThreadConfined {
/// Enables passing thread-confined objects to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`.The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the object to the main thread you can do:
///
/// let cancellable = publisher(myObject)
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { object in
/// // Do things with the object on the main thread
/// }
///
/// Calling this function on a publisher which emits frozen or unmanaged
/// objects is unneccesary but is allowed.
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference() -> RealmPublishers.MakeThreadSafe<Self> {
RealmPublishers.MakeThreadSafe(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Publisher {
/// Enables passing object changesets to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`. The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the object changeset to the main thread you can do:
///
/// let cancellable = changesetPublisher(myObject)
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { objectChange in
/// // Do things with the object on the main thread
/// }
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference<T: Object>()
-> RealmPublishers.MakeThreadSafeObjectChangeset<Self, T> where Output == ObjectChange<T> {
RealmPublishers.MakeThreadSafeObjectChangeset(self)
}
/// Enables passing Realm collection changesets to a different dispatch queue.
///
/// Each call to `receive(on:)` on a publisher which emits Realm
/// thread-confined objects must be proceeded by a call to
/// `.threadSafeReference()`. The returned publisher handles the required
/// logic to pass the thread-confined object to the new queue. Only serial
/// dispatch queues are supported and using other schedulers will result in
/// a fatal error.
///
/// For example, to subscribe on a background thread, do some work there,
/// then pass the collection changeset to the main thread you can do:
///
/// let cancellable = myCollection.changesetPublisher
/// .subscribe(on: DispatchQueue(label: "background queue")
/// .print()
/// .threadSafeReference()
/// .receive(on: DispatchQueue.main)
/// .sink { collectionChange in
/// // Do things with the collection on the main thread
/// }
///
/// - returns: A publisher that supports `receive(on:)` for thread-confined objects.
public func threadSafeReference<T: RealmCollection>()
-> RealmPublishers.MakeThreadSafeCollectionChangeset<Self, T> where Output == RealmCollectionChange<T> {
RealmPublishers.MakeThreadSafeCollectionChangeset(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension RealmCollection where Self: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Self> {
RealmPublishers.WillChange(self)
}
/// :nodoc:
@available(*, deprecated, renamed: "collectionPublisher")
public var publisher: RealmPublishers.Value<Self> {
RealmPublishers.Value(self)
}
/// A publisher that emits the collection each time the collection changes.
public var collectionPublisher: RealmPublishers.Value<Self> {
RealmPublishers.Value(self)
}
/// A publisher that emits a collection changeset each time the collection changes.
public var changesetPublisher: RealmPublishers.CollectionChangeset<Self> {
RealmPublishers.CollectionChangeset(self)
}
}
/// Creates a publisher that emits the object each time the object changes.
///
/// - precondition: The object must be a managed object which has not been invalidated.
/// - parameter object: A managed object to observe.
/// - returns: A publisher that emits the object each time it changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func valuePublisher<T: Object>(_ object: T) -> RealmPublishers.Value<T> {
RealmPublishers.Value<T>(object)
}
/// Creates a publisher that emits the collection each time the collection changes.
///
/// - precondition: The collection must be a managed collection which has not been invalidated.
/// - parameter object: A managed collection to observe.
/// - returns: A publisher that emits the collection each time it changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func valuePublisher<T: RealmCollection>(_ collection: T) -> RealmPublishers.Value<T> {
RealmPublishers.Value<T>(collection)
}
/// Creates a publisher that emits an object changeset each time the object changes.
///
/// - precondition: The object must be a managed object which has not been invalidated.
/// - parameter object: A managed object to observe.
/// - returns: A publisher that emits an object changeset each time the object changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func changesetPublisher<T: Object>(_ object: T) -> RealmPublishers.ObjectChangeset<T> {
RealmPublishers.ObjectChangeset<T>(object)
}
/// Creates a publisher that emits a collection changeset each time the collection changes.
///
/// - precondition: The collection must be a managed collection which has not been invalidated.
/// - parameter object: A managed collection to observe.
/// - returns: A publisher that emits a collection changeset each time the collection changes.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public func changesetPublisher<T: RealmCollection>(_ collection: T) -> RealmPublishers.CollectionChangeset<T> {
RealmPublishers.CollectionChangeset<T>(collection)
}
// MARK: - Realm
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Realm {
/// A publisher that emits Void each time the object changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.RealmWillChange {
return RealmPublishers.RealmWillChange(self)
}
}
// MARK: - Object
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Object: ObservableObject {
/// A publisher that emits Void each time the object changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Object> {
return RealmPublishers.WillChange(self)
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Object: RealmSubscribable {
/// :nodoc:
// swiftlint:disable:next identifier_name
public func _observe<S: Subscriber>(on queue: DispatchQueue?, _ subscriber: S)
-> NotificationToken where S.Input: Object, S.Failure == Error {
return observe(on: queue) { (change: ObjectChange<S.Input>) in
switch change {
case .change(let object, _):
_ = subscriber.receive(object)
case .deleted:
subscriber.receive(completion: .finished)
case .error(let error):
subscriber.receive(completion: .failure(error))
}
}
}
/// :nodoc:
public func _observe<S: Subscriber>(_ subscriber: S) -> NotificationToken where S.Input == Void, S.Failure == Never {
return observe { _ in _ = subscriber.receive() }
}
}
// MARK: - List
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension List: ObservableObject, RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<List> {
RealmPublishers.WillChange(self)
}
}
// MARK: - LinkingObjects
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension LinkingObjects: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<LinkingObjects> {
RealmPublishers.WillChange(self)
}
}
// MARK: - Results
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension Results: RealmSubscribable {
/// A publisher that emits Void each time the collection changes.
///
/// Despite the name, this actually emits *after* the collection has changed.
public var objectWillChange: RealmPublishers.WillChange<Results> {
RealmPublishers.WillChange(self)
}
}
// MARK: RealmCollection
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension RealmCollection {
/// :nodoc:
// swiftlint:disable:next identifier_name
public func _observe<S>(on queue: DispatchQueue? = nil, _ subscriber: S)
-> NotificationToken where S: Subscriber, S.Input == Self, S.Failure == Error {
// FIXME: we could skip some pointless work in converting the changeset to the Swift type here
return observe(on: queue) { change in
switch change {
case .initial(let collection):
_ = subscriber.receive(collection)
case .update(let collection, deletions: _, insertions: _, modifications: _):
_ = subscriber.receive(collection)
case .error(let error):
subscriber.receive(completion: .failure(error))
}
}
}
/// :nodoc:
public func _observe<S: Subscriber>(_ subscriber: S) -> NotificationToken where S.Input == Void, S.Failure == Never {
return observe(on: nil) { _ in _ = subscriber.receive() }
}
}
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
extension AnyRealmCollection: RealmSubscribable {
}
// MARK: Subscriptions
/// A subscription which wraps a Realm notification.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
@frozen public struct ObservationSubscription: Subscription {
private var token: NotificationToken
internal init(token: NotificationToken) {
self.token = token
}
/// A unique identifier for identifying publisher streams.
public var combineIdentifier: CombineIdentifier {
return CombineIdentifier(token)
}
/// This function is not implemented.
///
/// Realm publishers do not support backpressure and so this function does nothing.
public func request(_ demand: Subscribers.Demand) {
}
/// Stop emitting values on this subscription.
public func cancel() {
token.invalidate()
}
}
// MARK: Publishers
/// Combine publishers for Realm types.
///
/// You normally should not create any of these types directly, and should
/// instead use the extension methods which create them.
@available(OSX 10.15, watchOS 6.0, iOS 13.0, iOSApplicationExtension 13.0, OSXApplicationExtension 10.15, tvOS 13.0, *)
public enum RealmPublishers {
static private func realm<S: Scheduler>(_ config: RLMRealmConfiguration, _ scheduler: S) -> Realm? {
try? Realm(RLMRealm(configuration: config, queue: scheduler as? DispatchQueue))
}
/// A publisher which emits Void each time the Realm is refreshed.
///
/// Despite the name, this actually emits *after* the Realm is refreshed.
@frozen public struct RealmWillChange: Publisher {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
private let realm: Realm
internal init(_ realm: Realm) {
self.realm = realm
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `RealmWillChangeWithToken` Publisher.
public func saveToken<T>(on object: T, for keyPath: WritableKeyPath<T, NotificationToken?>) -> RealmWillChangeWithToken<T> {
return RealmWillChangeWithToken<T>(realm, object, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.realm.observe { _, _ in
_ = subscriber.receive()
}
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// :nodoc:
public class RealmWillChangeWithToken<T>: Publisher {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private let realm: Realm
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
internal init(_ realm: Realm,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
self.realm = realm
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.realm.observe { _, _ in
_ = subscriber.receive()
}
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// A publisher which emits Void each time the object is mutated.
///
/// Despite the name, this actually emits *after* the collection has changed.
@frozen public struct WillChange<Collection: RealmSubscribable>: Publisher where Collection: ThreadConfined {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
private let collection: Collection
internal init(_ collection: Collection) {
self.collection = collection
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `WillChangeWithToken` Publisher.
public func saveToken<T>(on object: T, at keyPath: WritableKeyPath<T, NotificationToken?>) -> WillChangeWithToken<Collection, T> {
return WillChangeWithToken<Collection, T>(collection, object, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.collection._observe(subscriber)
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// A publisher which emits Void each time the object is mutated.
///
/// Despite the name, this actually emits *after* the collection has changed.
public class WillChangeWithToken<Collection: RealmSubscribable, T>: Publisher where Collection: ThreadConfined {
/// This publisher cannot fail.
public typealias Failure = Never
/// This publisher emits Void.
public typealias Output = Void
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private let object: Collection
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
internal init(_ object: Collection,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
self.object = object
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.object._observe(subscriber)
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
}
/// A publisher which emits an object or collection each time that object is mutated.
@frozen public struct Value<Subscribable: RealmSubscribable>: Publisher where Subscribable: ThreadConfined {
/// This publisher can only fail due to resource exhaustion when
/// creating the worker thread used for change notifications.
public typealias Failure = Error
/// This publisher emits the object or collection which it is publishing.
public typealias Output = Subscribable
private let subscribable: Subscribable
private let queue: DispatchQueue?
internal init(_ subscribable: Subscribable, queue: DispatchQueue? = nil) {
precondition(subscribable.realm != nil, "Only managed objects can be published")
self.subscribable = subscribable
self.queue = queue
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `ValueWithToken` Publisher.
public func saveToken<T>(on object: T, at keyPath: WritableKeyPath<T, NotificationToken?>) -> ValueWithToken<Subscribable, T> {
return ValueWithToken<Subscribable, T>(subscribable, queue, object, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, Output == S.Input {
subscriber.receive(subscription: ObservationSubscription(token: self.subscribable._observe(on: queue, subscriber)))
}
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// For Realm Publishers, this determines which queue the underlying
/// change notifications are sent to. If `receive(on:)` is not used
/// subsequently, it also will determine which queue elements received
/// from the publisher are evaluated on. Currently only serial dispatch
/// queues are supported, and the `options:` parameter is not
/// supported.
///
/// - parameter scheduler: The serial dispatch queue to perform the subscription on.
/// - returns: A publisher which subscribes on the given scheduler.
public func subscribe<S: Scheduler>(on scheduler: S) -> Value<Subscribable> {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return Value(subscribable, queue: queue)
}
/// Specifies the scheduler on which to perform downstream operations.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`.
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> RealmPublishers.Handover<Self, S> {
return Handover(self, scheduler, self.subscribable.realm!)
}
}
/// A publisher which emits an object or collection each time that object is mutated.
public class ValueWithToken<Subscribable: RealmSubscribable, T>: Publisher where Subscribable: ThreadConfined {
/// This publisher can only fail due to resource exhaustion when
/// creating the worker thread used for change notifications.
public typealias Failure = Error
/// This publisher emits the object or collection which it is publishing.
public typealias Output = Subscribable
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private let object: Subscribable
private let queue: DispatchQueue?
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
internal init(_ object: Subscribable,
_ queue: DispatchQueue? = nil,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
precondition(object.realm != nil, "Only managed objects can be published")
self.object = object
self.queue = queue
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, Output == S.Input {
let token = self.object._observe(on: queue, subscriber)
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// For Realm Publishers, this determines which queue the underlying
/// change notifications are sent to. If `receive(on:)` is not used
/// subsequently, it also will determine which queue elements received
/// from the publisher are evaluated on. Currently only serial dispatch
/// queues are supported, and the `options:` parameter is not
/// supported.
///
/// - parameter scheduler: The serial dispatch queue to perform the subscription on.
/// - returns: A publisher which subscribes on the given scheduler.
public func subscribe<S: Scheduler>(on scheduler: S) -> ValueWithToken<Subscribable, T> {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return ValueWithToken(object, queue, tokenParent, tokenKeyPath)
}
/// Specifies the scheduler on which to perform downstream operations.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`.
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> Handover<ValueWithToken, S> {
return Handover(self, scheduler, self.object.realm!)
}
}
/// A helper publisher used to support `receive(on:)` on Realm publishers.
@frozen public struct Handover<Upstream: Publisher, S: Scheduler>: Publisher where Upstream.Output: ThreadConfined {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let config: RLMRealmConfiguration
private let upstream: Upstream
private let scheduler: S
internal init(_ upstream: Upstream, _ scheduler: S, _ realm: Realm) {
self.config = realm.rlmRealm.configuration
self.upstream = upstream
self.scheduler = scheduler
}
/// :nodoc:
public func receive<Sub>(subscriber: Sub) where Sub: Subscriber, Sub.Failure == Failure, Output == Sub.Input {
let scheduler = self.scheduler
let config = self.config
self.upstream
.map { ThreadSafeReference(to: $0) }
.receive(on: scheduler)
.compactMap { realm(config, scheduler)?.resolve($0) }
.receive(subscriber: subscriber)
}
}
/// A publisher which makes `receive(on:)` work for streams of thread-confined objects
///
/// Create using .threadSafeReference()
@frozen public struct MakeThreadSafe<Upstream: Publisher>: Publisher where Upstream.Output: ThreadConfined {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let upstream: Upstream
internal init(_ upstream: Upstream) {
self.upstream = upstream
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, Output == S.Input {
self.upstream.receive(subscriber: subscriber)
}
/// Specifies the scheduler on which to receive elements from the publisher.
///
/// This publisher converts each value emitted by the upstream
/// publisher to a `ThreadSafeReference`, passes it to the target
/// scheduler, and then converts back to the original type.
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandover<Upstream, S> {
DeferredHandover(self.upstream, scheduler)
}
}
/// A publisher which delivers thread-confined values to a serial dispatch queue.
///
/// Create using `.threadSafeReference().receive(on: queue)` on a publisher
/// that emits thread-confined objects.
@frozen public struct DeferredHandover<Upstream: Publisher, S: Scheduler>: Publisher where Upstream.Output: ThreadConfined {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let upstream: Upstream
private let scheduler: S
internal init(_ upstream: Upstream, _ scheduler: S) {
self.upstream = upstream
self.scheduler = scheduler
}
private enum Handover {
case object(_ object: Output)
case tsr(_ tsr: ThreadSafeReference<Output>, config: RLMRealmConfiguration)
}
/// :nodoc:
public func receive<Sub>(subscriber: Sub) where Sub: Subscriber, Sub.Failure == Failure, Output == Sub.Input {
let scheduler = self.scheduler
self.upstream
.map { (obj: Output) -> Handover in
guard let realm = obj.realm, !realm.isFrozen else { return .object(obj) }
return .tsr(ThreadSafeReference(to: obj), config: realm.rlmRealm.configuration)
}
.receive(on: scheduler)
.compactMap { (handover: Handover) -> Output? in
switch handover {
case .object(let obj):
return obj
case .tsr(let tsr, let config):
return realm(config, scheduler)?.resolve(tsr)
}
}
.receive(subscriber: subscriber)
}
}
/// A publisher which emits ObjectChange<T> each time the observed object is modified
///
/// `receive(on:)` and `subscribe(on:)` can be called directly on this
/// publisher, and calling `.threadSafeReference()` is only required if
/// there is an intermediate transform. If `subscribe(on:)` is used, it
/// should always be the first operation in the pipeline.
///
/// Create this publisher using the `objectChangeset()` function.
@frozen public struct ObjectChangeset<O: Object>: Publisher {
/// This publisher emits a ObjectChange<T> indicating which object and
/// which properties of that object have changed each time a Realm is
/// refreshed after a write transaction which modifies the observed
/// object.
public typealias Output = ObjectChange<O>
/// This publisher reports error via the `.error` case of ObjectChange.
public typealias Failure = Never
private let object: O
private let queue: DispatchQueue?
internal init(_ object: O, queue: DispatchQueue? = nil) {
precondition(object.realm != nil, "Only managed objects can be published")
precondition(!object.isInvalidated, "Object is invalidated or deleted")
self.object = object
self.queue = queue
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `ObjectChangesetWithToken` Publisher.
public func saveToken<T>(on tokenParent: T, at keyPath: WritableKeyPath<T, NotificationToken?>) -> ObjectChangesetWithToken<O, T> {
return ObjectChangesetWithToken<O, T>(object, queue, tokenParent, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.object.observe(on: self.queue) { change in
switch change {
case .change(let o, let properties):
_ = subscriber.receive(.change(o as! O, properties))
case .error(let error):
_ = subscriber.receive(.error(error))
case .deleted:
subscriber.receive(completion: .finished)
}
}
subscriber.receive(subscription: ObservationSubscription(token: token))
}
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// For Realm Publishers, this determines which queue the underlying
/// change notifications are sent to. If `receive(on:)` is not used
/// subsequently, it also will determine which queue elements received
/// from the publisher are evaluated on. Currently only serial dispatch
/// queues are supported, and the `options:` parameter is not
/// supported.
///
/// - parameter scheduler: The serial dispatch queue to perform the subscription on.
/// - returns: A publisher which subscribes on the given scheduler.
public func subscribe<S: Scheduler>(on scheduler: S) -> ObjectChangeset<O> {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return ObjectChangeset(object, queue: queue)
}
/// Specifies the scheduler on which to perform downstream operations.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandoverObjectChangeset<Self, O, S> {
DeferredHandoverObjectChangeset(self, scheduler)
}
}
/// A publisher which emits ObjectChange<T> each time the observed object is modified
///
/// `receive(on:)` and `subscribe(on:)` can be called directly on this
/// publisher, and calling `.threadSafeReference()` is only required if
/// there is an intermediate transform. If `subscribe(on:)` is used, it
/// should always be the first operation in the pipeline.
///
/// Create this publisher using the `objectChangeset()` function.
public class ObjectChangesetWithToken<O: Object, T>: Publisher {
/// This publisher emits a ObjectChange<T> indicating which object and
/// which properties of that object have changed each time a Realm is
/// refreshed after a write transaction which modifies the observed
/// object.
public typealias Output = ObjectChange<O>
/// This publisher reports error via the `.error` case of ObjectChange.
public typealias Failure = Never
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
private let object: O
private let queue: DispatchQueue?
internal init(_ object: O,
_ queue: DispatchQueue? = nil,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
precondition(object.realm != nil, "Only managed objects can be published")
precondition(!object.isInvalidated, "Object is invalidated or deleted")
self.object = object
self.queue = queue
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.object.observe(on: self.queue) { change in
switch change {
case .change(let o, let properties):
_ = subscriber.receive(.change(o as! O, properties))
case .error(let error):
_ = subscriber.receive(.error(error))
case .deleted:
subscriber.receive(completion: .finished)
}
}
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// For Realm Publishers, this determines which queue the underlying
/// change notifications are sent to. If `receive(on:)` is not used
/// subsequently, it also will determine which queue elements received
/// from the publisher are evaluated on. Currently only serial dispatch
/// queues are supported, and the `options:` parameter is not
/// supported.
///
/// - parameter scheduler: The serial dispatch queue to perform the subscription on.
/// - returns: A publisher which subscribes on the given scheduler.
public func subscribe<S: Scheduler>(on scheduler: S) -> ObjectChangesetWithToken<O, T> {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return ObjectChangesetWithToken(object, queue, tokenParent, tokenKeyPath)
}
/// Specifies the scheduler on which to perform downstream operations.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandoverObjectChangeset<ObjectChangesetWithToken, T, S> {
DeferredHandoverObjectChangeset(self, scheduler)
}
}
/// A helper publisher created by calling `.threadSafeReference()` on a publisher which emits thread-confined values.
@frozen public struct MakeThreadSafeObjectChangeset<Upstream: Publisher, T: Object>: Publisher where Upstream.Output == ObjectChange<T> {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let upstream: Upstream
internal init(_ upstream: Upstream) {
self.upstream = upstream
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, Output == S.Input {
self.upstream.receive(subscriber: subscriber)
}
/// Specifies the scheduler to deliver object changesets to.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`.
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandoverObjectChangeset<Upstream, T, S> {
DeferredHandoverObjectChangeset(self.upstream, scheduler)
}
}
/// A publisher which delivers thread-confined object changesets to a serial dispatch queue.
///
/// Create using `.threadSafeReference().receive(on: queue)` on a publisher
/// that emits `ObjectChange`.
@frozen public struct DeferredHandoverObjectChangeset<Upstream: Publisher, T: Object, S: Scheduler>: Publisher where Upstream.Output == ObjectChange<T> {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let upstream: Upstream
private let scheduler: S
internal init(_ upstream: Upstream, _ scheduler: S) {
self.upstream = upstream
self.scheduler = scheduler
}
private enum Handover {
case passthrough(_ change: ObjectChange<T>)
case tsr(_ tsr: ThreadSafeReference<T>, _ properties: [PropertyChange], config: RLMRealmConfiguration)
}
/// :nodoc:
public func receive<Sub>(subscriber: Sub) where Sub: Subscriber, Sub.Failure == Failure, Output == Sub.Input {
let scheduler = self.scheduler
self.upstream
.map { (change: Output) -> Handover in
guard case .change(let obj, let properties) = change else { return .passthrough(change) }
guard let realm = obj.realm, !realm.isFrozen else { return .passthrough(change) }
return .tsr(ThreadSafeReference(to: obj), properties, config: realm.rlmRealm.configuration)
}
.receive(on: scheduler)
.compactMap { (handover: Handover) -> Output? in
switch handover {
case .passthrough(let change):
return change
case .tsr(let tsr, let properties, let config):
if let resolved = realm(config, scheduler)?.resolve(tsr) {
return .change(resolved, properties)
}
return nil
}
}
.receive(subscriber: subscriber)
}
}
/// A publisher which emits RealmCollectionChange<T> each time the observed object is modified
///
/// `receive(on:)` and `subscribe(on:)` can be called directly on this
/// publisher, and calling `.threadSafeReference()` is only required if
/// there is an intermediate transform. If `subscribe(on:)` is used, it
/// should always be the first operation in the pipeline.
///
/// Create this publisher using the `changesetPublisher` property on RealmCollection..
@frozen public struct CollectionChangeset<Collection: RealmCollection>: Publisher {
public typealias Output = RealmCollectionChange<Collection>
/// This publisher reports error via the `.error` case of RealmCollectionChange..
public typealias Failure = Never
private let collection: Collection
private let queue: DispatchQueue?
internal init(_ collection: Collection, queue: DispatchQueue? = nil) {
precondition(collection.realm != nil, "Only managed collections can be published")
self.collection = collection
self.queue = queue
}
/// Captures the `NotificationToken` produced by observing a Realm Collection.
///
/// This allows you to do notification skipping when performing a `Realm.write(withoutNotifying:)`. You should use this call if you
/// require to write to the Realm database and ignore this specific observation chain.
/// The `NotificationToken` will be saved on the specified `KeyPath`from the observation block set up in `receive(subscriber:)`.
///
/// - Parameters:
/// - object: The object which the `NotificationToken` is written to.
/// - keyPath: The KeyPath which the `NotificationToken` is written to.
/// - Returns: A `CollectionChangesetWithToken` Publisher.
public func saveToken<T>(on object: T, at keyPath: WritableKeyPath<T, NotificationToken?>) -> CollectionChangesetWithToken<Collection, T> {
return CollectionChangesetWithToken<Collection, T>(collection, queue, object, keyPath)
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.collection.observe(on: self.queue) { change in
_ = subscriber.receive(change)
}
subscriber.receive(subscription: ObservationSubscription(token: token))
}
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// For Realm Publishers, this determines which queue the underlying
/// change notifications are sent to. If `receive(on:)` is not used
/// subsequently, it also will determine which queue elements received
/// from the publisher are evaluated on. Currently only serial dispatch
/// queues are supported, and the `options:` parameter is not
/// supported.
///
/// - parameter scheduler: The serial dispatch queue to perform the subscription on.
/// - returns: A publisher which subscribes on the given scheduler.
public func subscribe<S: Scheduler>(on scheduler: S) -> CollectionChangeset<Collection> {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return CollectionChangeset(collection, queue: queue)
}
/// Specifies the scheduler on which to perform downstream operations.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandoverCollectionChangeset<Self, Collection, S> {
DeferredHandoverCollectionChangeset(self, scheduler)
}
}
/// A publisher which emits RealmCollectionChange<T> each time the observed object is modified
///
/// `receive(on:)` and `subscribe(on:)` can be called directly on this
/// publisher, and calling `.threadSafeReference()` is only required if
/// there is an intermediate transform. If `subscribe(on:)` is used, it
/// should always be the first operation in the pipeline.
///
/// Create this publisher using the `changesetPublisher` property on RealmCollection..
public class CollectionChangesetWithToken<Collection: RealmCollection, T>: Publisher {
public typealias Output = RealmCollectionChange<Collection>
/// This publisher reports error via the `.error` case of RealmCollectionChange..
public typealias Failure = Never
internal typealias TokenParent = T
internal typealias TokenKeyPath = WritableKeyPath<T, NotificationToken?>
private var tokenParent: TokenParent
private var tokenKeyPath: TokenKeyPath
private let collection: Collection
private let queue: DispatchQueue?
internal init(_ collection: Collection,
_ queue: DispatchQueue? = nil,
_ tokenParent: TokenParent,
_ tokenKeyPath: TokenKeyPath) {
precondition(collection.realm != nil, "Only managed collections can be published")
self.collection = collection
self.queue = queue
self.tokenParent = tokenParent
self.tokenKeyPath = tokenKeyPath
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Never, Output == S.Input {
let token = self.collection.observe(on: self.queue) { change in
_ = subscriber.receive(change)
}
tokenParent[keyPath: tokenKeyPath] = token
subscriber.receive(subscription: ObservationSubscription(token: token))
}
/// Specifies the scheduler on which to perform subscribe, cancel, and request operations.
///
/// For Realm Publishers, this determines which queue the underlying
/// change notifications are sent to. If `receive(on:)` is not used
/// subsequently, it also will determine which queue elements received
/// from the publisher are evaluated on. Currently only serial dispatch
/// queues are supported, and the `options:` parameter is not
/// supported.
///
/// - parameter scheduler: The serial dispatch queue to perform the subscription on.
/// - returns: A publisher which subscribes on the given scheduler.
public func subscribe<S: Scheduler>(on scheduler: S) -> CollectionChangesetWithToken<Collection, T> {
guard let queue = scheduler as? DispatchQueue else {
fatalError("Cannot subscribe on scheduler \(scheduler): only serial dispatch queues are currently implemented.")
}
return CollectionChangesetWithToken(collection, queue, tokenParent, tokenKeyPath)
}
/// Specifies the scheduler on which to perform downstream operations.
///
/// This differs from `subscribe(on:)` in how it is integrated with the
/// autorefresh cycle. When using `subscribe(on:)`, the subscription is
/// performed on the target scheduler and the publisher will emit the
/// collection during the refresh. When using `receive(on:)`, the
/// collection is then converted to a `ThreadSafeReference` and
/// delivered to the target scheduler with no integration into the
/// autorefresh cycle, meaning it may arrive some time after the
/// refresh occurs.
///
/// When in doubt, you probably want `subscribe(on:)`
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandoverCollectionChangeset<CollectionChangesetWithToken, Collection, S> {
DeferredHandoverCollectionChangeset(self, scheduler)
}
}
/// A helper publisher created by calling `.threadSafeReference()` on a
/// publisher which emits `RealmCollectionChange`.
@frozen public struct MakeThreadSafeCollectionChangeset<Upstream: Publisher, T: RealmCollection>: Publisher where Upstream.Output == RealmCollectionChange<T> {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let upstream: Upstream
internal init(_ upstream: Upstream) {
self.upstream = upstream
}
/// :nodoc:
public func receive<S>(subscriber: S) where S: Subscriber, S.Failure == Failure, Output == S.Input {
self.upstream.receive(subscriber: subscriber)
}
/// Specifies the scheduler on which to receive elements from the publisher.
///
/// This publisher converts each value emitted by the upstream
/// publisher to a `ThreadSafeReference`, passes it to the target
/// scheduler, and then converts back to the original type.
///
/// - parameter scheduler: The serial dispatch queue to receive values on.
/// - returns: A publisher which delivers values to the given scheduler.
public func receive<S: Scheduler>(on scheduler: S) -> DeferredHandoverCollectionChangeset<Upstream, T, S> {
DeferredHandoverCollectionChangeset(self.upstream, scheduler)
}
}
/// A publisher which delivers thread-confined collection changesets to a
/// serial dispatch queue.
///
/// Create using `.threadSafeReference().receive(on: queue)` on a publisher
/// that emits `RealmCollectionChange`.
@frozen public struct DeferredHandoverCollectionChangeset<Upstream: Publisher, T: RealmCollection, S: Scheduler>: Publisher where Upstream.Output == RealmCollectionChange<T> {
/// :nodoc:
public typealias Failure = Upstream.Failure
/// :nodoc:
public typealias Output = Upstream.Output
private let upstream: Upstream
private let scheduler: S
internal init(_ upstream: Upstream, _ scheduler: S) {
self.upstream = upstream
self.scheduler = scheduler
}
private enum Handover {
case passthrough(_ change: RealmCollectionChange<T>)
case initial(_ tsr: ThreadSafeReference<T>, config: RLMRealmConfiguration)
case update(_ tsr: ThreadSafeReference<T>, deletions: [Int], insertions: [Int], modifications: [Int], config: RLMRealmConfiguration)
}
/// :nodoc:
public func receive<Sub>(subscriber: Sub) where Sub: Subscriber, Sub.Failure == Failure, Output == Sub.Input {
let scheduler = self.scheduler
self.upstream
.map { (change: Output) -> Handover in
switch change {
case .initial(let collection):
guard let realm = collection.realm, !realm.isFrozen else { return .passthrough(change) }
return .initial(ThreadSafeReference(to: collection), config: realm.rlmRealm.configuration)
case .update(let collection, deletions: let deletions, insertions: let insertions, modifications: let modifications):
guard let realm = collection.realm, !realm.isFrozen else { return .passthrough(change) }
return .update(ThreadSafeReference(to: collection), deletions: deletions, insertions: insertions, modifications: modifications, config: realm.rlmRealm.configuration)
case .error:
return .passthrough(change)
}
}
.receive(on: scheduler)
.compactMap { (handover: Handover) -> Output? in
switch handover {
case .passthrough(let change):
return change
case .initial(let tsr, config: let config):
if let resolved = realm(config, scheduler)?.resolve(tsr) {
return .initial(resolved)
}
return nil
case .update(let tsr, deletions: let deletions, insertions: let insertions, modifications: let modifications, config: let config):
if let resolved = realm(config, scheduler)?.resolve(tsr) {
return .update(resolved, deletions: deletions, insertions: insertions, modifications: modifications)
}
return nil
}
}
.receive(subscriber: subscriber)
}
}
}
#endif // canImport(Combine)
| 48.294501 | 189 | 0.643903 |
dd9b4ac66d9c19711893e25a8bfa50a176d19b2b | 517 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -import-objc-header %S/Inputs/attr-objc_subclassing_restricted.h %s -swift-version 5 -verify
// No errors in Swift 3 and 4 modes.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -import-objc-header %S/Inputs/attr-objc_subclassing_restricted.h %s -swift-version 4
// REQUIRES: objc_interop
class Sub: Restricted { // expected-error {{cannot inherit from non-open class 'Restricted' outside of its defining module}}
}
| 51.7 | 165 | 0.760155 |
e663b16754e02bf3fe5c072916f9a391dac71338 | 1,578 | //
// API.swift
// Notes-gRPC-App
//
// Created by Tim Mewe on 14.12.19.
// Copyright © 2019 Tim Mewe. All rights reserved.
//
import Combine
import Foundation
import Grebe_Framework
import Grebe_Generated
import GRPC
typealias Note = NoteProto
extension NoteProto: Identifiable {}
class API {
private let client = GClient<NotesServiceServiceClient>(
target: .hostAndPort("localhost", 55214)
)
func createNote(_ note: Note) -> AnyPublisher<CreateNoteResponse, GRPCStatus> {
var request = CreateNoteRequest()
request.note = note
return client.service.createNote(request: request)
}
func getNotes() -> AnyPublisher<GetNotesResponse, GRPCStatus> {
client.service.getNotes(request: GetNotesRequest())
}
func deleteNotes(_ notes: [Note]) -> AnyPublisher<DeleteNotesResponse, GRPCStatus> {
let requests = Publishers.Sequence<[DeleteNotesRequest], Error>(
sequence: notes.map { note in DeleteNotesRequest.with { $0.note = note } }
).eraseToAnyPublisher()
return client.service.deleteNotes(request: requests)
}
func switchTitleContent(notes: [Note]) -> AnyPublisher<SwitchTitleContentResponse, GRPCStatus> {
let requests = Publishers
.Sequence<[SwitchTitleContentRequest], Error>(
sequence: notes.map { note in
SwitchTitleContentRequest.with { $0.note = note }
}
).eraseToAnyPublisher()
return client.service.switchTitleContent(request: requests)
}
}
| 31.56 | 100 | 0.662864 |
69c0dad5fcc69fdd318b12ced4083864a74fb0e7 | 4,126 | //
// ViewController.swift
// FMDBLibrary
//
// Created by monstar on 2018/7/18.
// Copyright © 2018年 monstar. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var addkid: UITextField!
@IBOutlet weak var addname: UITextField!
@IBOutlet weak var addage: UITextField!
@IBOutlet weak var selectkid: UITextField!
@IBOutlet weak var selectname: UITextField!
@IBOutlet weak var selectage: UITextField!
@IBAction func add(_ sender: Any) {
var updateParmas = [String: Any]()
if let pkid = addkid.text {
if pkid != "" {
updateParmas["pkid"] = Int(pkid)
}
}
if let name = addname.text {
if name != "" {
updateParmas["name"] = name
}
}
if let age = addage.text {
if age != "" {
updateParmas["age"] = Int(age)
}
}
let insertFlag = FMDBManager.shared.insertTable(tableName: "tableone", params: updateParmas)
print("插入结果\(insertFlag)")
}
@IBAction func del(_ sender: Any) {
var parmas = [String: Any]()
if let pkid = selectkid.text {
if pkid != "" {
parmas["pkid"] = Int(pkid)
}
}
if let name = selectname.text {
if name != "" {
parmas["name"] = name
}
}
if let age = selectage.text {
if age != "" {
parmas["age"] = Int(age)
}
}
let deleteFlag = FMDBManager.shared.deleteTable(tableName: "tableone", whereDictionary: parmas)
print("删除结果\(deleteFlag)")
}
@IBAction func sel(_ sender: Any) {
var parmas = [String: Any]()
if let pkid = selectkid.text {
if pkid != "" {
parmas["pkid"] = Int(pkid)
}
}
if let name = selectname.text {
if name != "" {
parmas["name"] = name
}
}
if let age = selectage.text {
if age != "" {
parmas["age"] = Int(age)
}
}
if let selectArray = FMDBManager.shared.selectTable(tableName: "tableone", params: nil, whereDictionary: parmas) {
print("查询结果\(selectArray)")
}
}
@IBAction func upd(_ sender: Any) {
var parmas = [String: Any]()
var updateParmas = [String: Any]()
if let pkid = selectkid.text {
if pkid != "" {
parmas["pkid"] = Int(pkid)
}
}
if let name = selectname.text {
if name != "" {
parmas["name"] = name
}
}
if let age = selectage.text {
if age != "" {
parmas["age"] = Int(age)
}
}
if let pkid = addkid.text {
if pkid != "" {
updateParmas["pkid"] = Int(pkid)
}
}
if let name = addname.text {
if name != "" {
updateParmas["name"] = name
}
}
if let age = addage.text {
if age != "" {
updateParmas["age"] = Int(age)
}
}
let updateFlag = FMDBManager.shared.updateTable(tableName: "tableone", params: updateParmas, whereDictionary: parmas)
print("修改结果\(updateFlag)")
}
override func viewDidLoad() {
super.viewDidLoad()
_ = FMDBManager.shared.shareDataBase()
let creatFlag = FMDBManager.shared.createTableWithDictionary(tableName: "tableone", params: ["name": "TEXT", "age": "INT"])
print(creatFlag)
let columnArray = FMDBManager.shared.getColumnArray(tableName: "tableone", db: FMDBManager.shared.db!)
print(columnArray)
// 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.
}
}
| 28.068027 | 131 | 0.499031 |
e543edd7d2c87ea2600881005a853cc4ce99366c | 4,544 | //
// MDDataNumberCodable.swift
//
// The MIT License
// Copyright (c) 2021 - 2022 O2ter Limited. 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.
//
extension MDData.Number: Encodable {
@inlinable
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .signed(number): try container.encode(number)
case let .unsigned(number): try container.encode(number)
case let .number(number): try container.encode(number)
case let .decimal(number):
if "\(type(of: encoder))" == "_BSONEncoder" {
try container.encode(BSON(number))
} else {
try container.encode(number)
}
}
}
}
extension MDData.Number: Decodable {
@inlinable
static func _decode_number(_ value: BSON) -> MDData.Number? {
switch value {
case let .int32(value): return .signed(Int64(value))
case let .int64(value): return .signed(value)
case let .double(value): return .number(value)
case let .decimal128(value):
let str = value.description
switch str {
case "Infinity": return .number(.infinity)
case "-Infinity": return .number(-.infinity)
case "NaN": return .number(.nan)
default:
guard let decimal = Decimal(string: str, locale: Locale(identifier: "en_US")) else { return nil }
return .decimal(decimal)
}
default: return nil
}
}
@inlinable
static func _decode_number(_ container: SingleValueDecodingContainer) -> MDData.Number? {
if let double = try? container.decode(Double.self) {
if let uint64 = try? container.decode(UInt64.self), Double(uint64) == double {
return .unsigned(uint64)
} else if let int64 = try? container.decode(Int64.self), Double(int64) == double {
return .signed(int64)
} else if let decimal = try? container.decode(Decimal.self), decimal.doubleValue == double {
return .decimal(decimal)
} else {
return .number(double)
}
}
if let uint64 = try? container.decode(UInt64.self) {
return .unsigned(uint64)
}
if let int64 = try? container.decode(Int64.self) {
return .signed(int64)
}
if let decimal = try? container.decode(Decimal.self) {
return .decimal(decimal)
}
return nil
}
@inlinable
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if "\(type(of: decoder))" == "_BSONDecoder",
let value = try? container.decode(BSON.self),
let number = MDData.Number._decode_number(value) {
self = number
return
}
guard let number = MDData.Number._decode_number(container) else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Attempted to decode MDData.Number from unknown structure.")
)
}
self = number
}
}
| 35.5 | 113 | 0.59485 |
1a50590ebc311cd93234a388c2897099e55913e2 | 253 | //
// CDArticle+CoreDataClass.swift
// NYTimes
//
// Created by Waseem Akram on 01/08/20.
// Copyright © 2020 Waseem Akram. All rights reserved.
//
//
import Foundation
import CoreData
@objc(CDArticle)
public class CDArticle: NSManagedObject {
}
| 14.882353 | 55 | 0.715415 |
219c5450f9ac39baabf34b6b7491469b1a95a312 | 1,654 | //
// testUITests.swift
// testUITests
//
// Created by xdf on 14/04/2017.
// Copyright © 2017 xdf. All rights reserved.
//
import XCTest
import Swifter
import XCTestWD
public class XCTextWDRunner: XCTestWDFailureProofTest {
var server: XCTestWDServer?
var monkey: XCTestWDMonkey?
override public func setUp() {
super.setUp()
continueAfterFailure = false
XCTestWDSessionManager.singleton.clearAll()
XCUIDevice.shared.press(XCUIDevice.Button.home)
sleep(2)
NotificationCenter.default.addObserver(self,
selector: #selector(terminate(notification:)),
name: NSNotification.Name(rawValue: "XCTestWDSessionShutDown"),
object: nil)
}
override public func tearDown() {
super.tearDown()
XCUIDevice.shared.press(XCUIDevice.Button.home)
XCUIDevice.shared.press(XCUIDevice.Button.home)
XCTestWDSessionManager.singleton.clearAll()
}
func testRunner() {
self.monkey = XCTestWDMonkey()
_ = self.monkey?.startMonkey()
}
// func testMultipleApps() {
//
// let settingsApp = XCUIApplication(bundleIdentifier: "com.bytedance.ee.microapp.demo")
// settingsApp.launch()
// sleep(5)
// settingsApp.terminate()
//
// print("lalalalalala:\(settingsApp.state)")
//
// }
@objc func terminate(notification: NSNotification) {
self.server?.stopServer();
NSLog("XCTestWDTearDown->Session Reset")
assert(false, "")
}
}
| 28.033898 | 110 | 0.600363 |
72894548cbf5d75ecfbfec60a618b6bf504352b4 | 4,237 | //
// UserDream.swift
// Mongsil
//
// Created by Chanwoo Cho on 2022/05/10.
//
import Foundation
public struct UserDream: Codable, Equatable, Hashable {
public let id: String
public let dreamID: String
public let registerDate: Date
public let title: String
public let description: String
public let categoryList: [Category]
public enum CodingKeys: String, CodingKey {
case id, registerDate, title, description, categoryList
case dreamID = "dreamId"
}
public init(
id: String,
dreamID: String,
registerDate: Date,
title: String,
description: String,
categoryList: [Category]
) {
self.id = id
self.dreamID = dreamID
self.registerDate = registerDate
self.title = title
self.description = description
self.categoryList = categoryList
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.dreamID = try container.decode(String.self, forKey: .dreamID)
self.registerDate = try container.decode(Date.self, forKey: .registerDate)
self.title = try container.decode(String.self, forKey: .title)
self.description = try container.decode(String.self, forKey: .description)
self.categoryList = try container.decode([Category].self, forKey: .categoryList)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(dreamID, forKey: .dreamID)
try container.encode(registerDate, forKey: .registerDate)
try container.encode(title, forKey: .title)
try container.encode(description, forKey: .description)
try container.encode(categoryList, forKey: .categoryList)
}
}
extension UserDream {
public enum Stub {
public static let userDream1 = UserDream(
id: "1",
dreamID: "1",
registerDate: Date(),
title: "호랑이한테 물리는 꿈",
description: "정말로 호랑이한테 물릴 수 있으니 야생에 가면 안됩니다.",
categoryList: [
.Stub.category1,
.Stub.category2
]
)
public static let userDream2 = UserDream(
id: "2",
dreamID: "2",
registerDate: Date(),
title: "호랑이를 죽이는 꿈",
description: "직장이나 학교에서 큰 성취감을 얻을 수 있는 꿈입니다.",
categoryList: [.Stub.category1]
)
public static let userDream3 = UserDream(
id: "3",
dreamID: "3",
registerDate: Date(),
title: "호랑이한테 잡혀가는 꿈",
description: "호랑이한테 물려가도 정신만 차리면 사는것처럼 항상 정신을 챙겨야합니다.",
categoryList: [.Stub.category1]
)
public static let userDream4 = UserDream(
id: "4",
dreamID: "4",
registerDate: Date(),
title: "사자를 죽이는 꿈",
description: "라이언킹을 죽였으니 이제 당신이 야생의 주인입니다.",
categoryList: [.Stub.category2]
)
public static let userDream5 = UserDream(
id: "5",
dreamID: "5",
registerDate: Date(),
title: "사자한테 물리는 꿈",
description: "사자는 호랑이보다 약하니 조금 덜 조심해도 됩니다.",
categoryList: [.Stub.category2]
)
public static let userDream6 = UserDream(
id: "6",
dreamID: "6",
registerDate: Date(),
title: "사자한테 잡혀가는 꿈",
description: "사자한테 잡혀가면 호랑이와 달리 무리 생활을 하기에 그냥 죽은것입니다.",
categoryList: [.Stub.category2]
)
public static let userDream7 = UserDream(
id: "7",
dreamID: "7",
registerDate: Date(),
title: "머리가 터지는 꿈",
description: "머리가 너무 아픈일의 연속이 일어나게 됩니다.",
categoryList: [.Stub.category3]
)
public static let userDream8 = UserDream(
id: "8",
dreamID: "8",
registerDate: Date(),
title: "머리를 자르는 꿈",
description: "시험이나 승진에서 좌절하게 됩니다.",
categoryList: [.Stub.category3]
)
public static let userDream9 = UserDream(
id: "9",
dreamID: "9",
registerDate: Date(),
title: "눈이 안보이는 꿈",
description: "루테인을 많이 챙겨 드셔야 합니다.",
categoryList: [.Stub.category4]
)
public static let userDream10 = UserDream(
id: "10",
dreamID: "10",
registerDate: Date(),
title: "눈이 떠지는 꿈",
description: "못보던 세상을 볼 수 있는 선구안을 가지게 됩니다.",
categoryList: [.Stub.category4]
)
}
}
| 28.436242 | 84 | 0.630163 |
e0efb6f7fa52e84e7edb75031801257fcbbebc2f | 221 | //
// TestDecodingError.swift
// Tests
//
// Copyright © 2021 Bottle Rocket Studios. All rights reserved.
//
import Foundation
enum TestDecodingError: Error, Equatable {
case keyNotFound
case invalidValue
}
| 14.733333 | 64 | 0.714932 |
e81ee46598fd458236ba255bea554e3420cc913b | 3,104 | //
// ResultViewController.swift
// HouseBalance
//
// Created by s-tanaka on 2017/04/30.
// Copyright © 2017年 s-tanaka. All rights reserved.
//
import GoogleMobileAds
import RxCocoa
import RxSwift
import UIKit
class ResultViewController: UIViewController {
@IBOutlet weak var bannerView: GADBannerView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var helpButton: UIButton!
private let viewModel: ResultViewModelType = ResultViewModel()
private let disposeBag = DisposeBag()
static func instantiate() -> ResultViewController {
return Storyboard.result.instantiate(ResultViewController.self)
}
override func viewDidLoad() {
super.viewDidLoad()
bindViewModel()
bindStyles()
if !Secrets.isOSS {
self.bannerView.setUp(adUnitId: Secrets.Firebase.adUnitIDResult,
rootViewController: self)
}
self.helpButton.rx.tap
.subscribe(onNext: {
self.viewModel.inputs.helpButtonPressed()
})
.disposed(by: disposeBag)
self.closeButton.rx.tap
.subscribe(onNext: {
self.viewModel.inputs.closeButtonPressed()
})
.disposed(by: disposeBag)
}
private func bindViewModel() {
self.viewModel.outputs.expenses
.bind(to: self.tableView.rx.items(cellIdentifier: "ResultCell")) { (row, element, cell) in
guard let cell = cell as? ResultCell else {
fatalError("想定外のCellが指定されている")
}
cell.setUp(salary: AppEnvironment.settings.salary, expense: element)
cell.backgroundColor = row % 2 == 0 ? UIColor.gray100 : UIColor.gray200
}
.disposed(by: disposeBag)
self.viewModel.outputs.helpViewShown
.filter { $0 }
.subscribe(onNext: { [weak self] _ in
let hvc = HelpViewController.instantiate()
hvc.transitioningDelegate = self
hvc.modalPresentationStyle = .custom
self?.present(hvc, animated: true)
})
.disposed(by: self.disposeBag)
self.viewModel.outputs.dismiss
.subscribe(onNext: { [weak self] in
self?.dismiss(animated: true)
})
.disposed(by: self.disposeBag)
}
private func bindStyles() {
self.view.backgroundColor = UIColor.background
}
}
extension ResultViewController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
return PopupPresentationController(presentedViewController: presented, presenting: presenting,
size: CGSize(width: 300, height: 154))
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PopupTransition()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PopupTransition()
}
}
| 30.732673 | 112 | 0.685889 |
5005ffa82c281234fd0af0b470610c268abb989e | 1,448 | //
// Utils.swift
// LogsManager
//
// Created by Anton Plebanovich on 3/20/21.
// Copyright © 2021 Anton Plebanovich. All rights reserved.
//
import Foundation
final class Utils {
/// Method to normalize error.
static func normalizeError(_ error: Any?) -> String? {
guard let error = error else { return nil }
return String(describing: error)
}
static func localizedDescription(_ error: Any?) -> String? {
guard let error = error as? Error else { return nil }
return error.localizedDescription
}
static func debugDescription(_ error: Any?) -> String? {
guard let error = error, let error = error as? CustomDebugStringConvertible else { return nil }
return error.debugDescription
}
/// Method to normalize data.
static func normalizeData(_ data: [String: Any?]?) -> [String: String]? {
guard let data = data else { return nil }
var normalizedData = [String: String]()
for (key, value) in data {
let description: String
if let value = value as? Data {
description = value.asString
} else if let value = value {
description = String(describing: value)
} else {
description = "nil"
}
normalizedData[key] = description
}
return normalizedData
}
}
| 28.96 | 103 | 0.574586 |
9b291b2a5a258bace2222eb81e3fa381767ff4c2 | 462 | //
// URIExtensions.swift
// VaporJsonApi
//
// Created by Koray Koska on 03/05/2017.
//
//
import URI
extension URI {
func baseUrl() -> String {
var portString = ""
if let port = port, let defaultPort = defaultPort, port != defaultPort {
portString = ":\(String(port))"
} else if let port = port {
portString = ":\(String(port))"
}
return "\(scheme)://\(hostname)\(portString)"
}
}
| 19.25 | 80 | 0.541126 |
5d90a4000076f7bf2ff60143c6ad17f3f919a258 | 4,652 | //
// MyPageDetailCommentTableViewCell.swift
// Bungsegwon
//
// Created by 성단빈 on 2020/12/28.
//
import UIKit
class MyPageDetailCommentTableViewCell: UITableViewCell {
// MARK: - Properties
static let identifier = "MyPageDetailCommentTableViewCell"
private let containerView = UIView()
private let titleImageView = UIImageView()
private let titleMenuLabel = UILabel()
private let dateLabel = UILabel()
private let commentLabel = UILabel()
let deleteBtn = UIButton()
// MARK: - View LifeCycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setUI()
self.setLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
self.containerView.layer.cornerRadius = 8
self.containerView.layer.masksToBounds = false
}
// MARK: - SetUI
private func setUI() {
[
self.containerView
].forEach {
self.contentView.addSubview($0)
}
self.containerView.backgroundColor = .white
[
self.titleImageView,
self.titleMenuLabel,
self.dateLabel,
self.commentLabel,
self.deleteBtn
].forEach {
self.containerView.addSubview($0)
}
self.contentView.backgroundColor = UIColor(
red: 0.957,
green: 0.957,
blue: 0.957,
alpha: 1
)
self.titleImageView.contentMode = .scaleAspectFit
self.titleMenuLabel.textColor = .black
self.titleMenuLabel.font = UIFont(
name: "AppleSDGothicNeo-Bold",
size: 14
)
self.dateLabel.textColor = UIColor(
red: 0.769,
green: 0.769,
blue: 0.769,
alpha: 1
)
self.dateLabel.font = UIFont(
name: "AppleSDGothicNeo-Regular",
size: 13
)
self.dateLabel.setContentCompressionResistancePriority(UILayoutPriority(751), for: .horizontal)
self.dateLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .horizontal)
self.commentLabel.textColor = .black
self.commentLabel.font = UIFont(
name: "AppleSDGothicNeo-Regular",
size: 14
)
self.commentLabel.textAlignment = .left
self.commentLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 250), for: .horizontal)
self.deleteBtn.setImage(
UIImage(named: "DeleteImage"),
for: .normal
)
}
// MARK: - SetLayout
private func setLayout() {
self.containerView.snp.makeConstraints {
$0.top.equalToSuperview()
$0.leading.equalToSuperview().offset(16)
$0.trailing.equalToSuperview().offset(-16)
$0.bottom.equalToSuperview().offset(-8)
}
self.titleImageView.snp.makeConstraints {
$0.top.equalToSuperview().offset(5)
$0.leading.equalToSuperview().offset(16)
$0.width.height.equalTo(36)
}
self.titleMenuLabel.snp.makeConstraints {
$0.centerY.equalTo(self.titleImageView.snp.centerY)
$0.leading.equalTo(self.titleImageView.snp.trailing).offset(8)
}
self.dateLabel.snp.makeConstraints {
$0.top.equalTo(self.titleImageView.snp.bottom).offset(6)
$0.leading.equalToSuperview().offset(16)
$0.bottom.equalToSuperview().offset(-18)
}
self.commentLabel.snp.makeConstraints {
$0.centerY.equalTo(self.dateLabel.snp.centerY)
$0.leading.equalTo(self.dateLabel.snp.trailing).offset(12)
$0.trailing.equalToSuperview().offset(-16)
}
self.deleteBtn.snp.makeConstraints {
$0.top.equalToSuperview().offset(4)
$0.trailing.equalToSuperview().offset(-4)
}
}
// MARK: - Configuer
func configuer(mainMenu: String, comment: String, createdDate: String) {
self.commentLabel.text = comment
self.titleMenuLabel.text = mainMenu
self.dateLabel.text = createdDate
let image = UIImage(named: "Menu\(self.setImage(imageName: mainMenu))")
self.titleImageView.image = image
}
private func setImage(imageName: String) -> String {
switch imageName {
case "붕어/잉어빵":
return "붕어잉어빵"
case "국화/옛날풀빵":
return "국화옛날풀빵"
case "호두과자":
return "호두과자"
case "땅콩빵":
return "땅콩빵"
case "계란빵":
return "계란빵"
case "바나나빵":
return "바나나빵"
case "타코야키":
return "타코야키"
case "호떡":
return "호떡"
case "떡볶이":
return "떡볶이"
case "튀김":
return "튀김"
case "순대":
return "순대"
case "어묵":
return "어묵"
default:
break
}
return ""
}
// MARK: - Action Button
}
// MARK: - Extension
| 24.877005 | 99 | 0.642304 |
4653ef823c0c1cf8236736fdba31bdb44427f1a7 | 2,039 | //
// AppDelegate.swift
// VirtualLocation
//
// Created by Watanabe Toshinori on 2020/05/30.
// Copyright © 2020 Watanabe Toshinori. All rights reserved.
//
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
let location = Location()
// BLEクライアントを開始
BLEClient.shared.initialize(with: location)
// タイトルバーアクセサリに表示するSwiftUIのビューを作成
let accessoryHostingView = NSHostingView(rootView: AccessoryView(viewModel: .init(location)))
accessoryHostingView.frame.size = accessoryHostingView.fittingSize
let titlebarAccessoryViewController = NSTitlebarAccessoryViewController()
titlebarAccessoryViewController.view = accessoryHostingView
titlebarAccessoryViewController.layoutAttribute = .top
// ウィンドウコンテンツに表示するSwiftUIのビューを作成
let contentView = ContentView(viewModel: .init(location))
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 480),
styleMask: [.titled,
.closable,
.miniaturizable,
.resizable,
.fullSizeContentView,
.unifiedTitleAndToolbar],
backing: .buffered, defer: false)
window.title = "Virtual Cycling"
window.titleVisibility = .hidden
window.center()
window.setFrameAutosaveName("Main Window")
window.toolbar = NSToolbar()
window.addTitlebarAccessoryViewController(titlebarAccessoryViewController)
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
}
// MARK: - UISceneSession ライフサイクル
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
// ウィンドウを閉じたらアプリを終了する
return true
}
}
| 32.887097 | 101 | 0.665032 |
b9d5666536dbc30b0e82f30b02ab65cd2b100aa2 | 3,014 | //
// MqttDecodeUnsubAck.swift
// CocoaMQTT
//
// Created by liwei wang on 2021/8/16.
//
import Foundation
public class MqttDecodeUnsubAck: NSObject {
var totalCount = 0
var dataIndex = 0
var propertyLength: Int = 0
public var reasonCodes: [CocoaMQTTUNSUBACKReasonCode] = []
public var msgid: UInt16 = 0
public var reasonString: String?
public var userProperty: [String: String]?
public func decodeUnSubAck(fixedHeader: UInt8, pubAckData: [UInt8]){
totalCount = pubAckData.count
dataIndex = 0
//msgid
let msgidResult = integerCompute(data: pubAckData, formatType: formatInt.formatUint16.rawValue, offset: dataIndex)
msgid = UInt16(msgidResult!.res)
dataIndex = msgidResult!.newOffset
// 3.11.2.1 UNSUBACK Properties
// 3.11.2.1.1 Property Length
let propertyLengthVariableByteInteger = decodeVariableByteInteger(data: pubAckData, offset: dataIndex)
propertyLength = propertyLengthVariableByteInteger.res
dataIndex = propertyLengthVariableByteInteger.newOffset
let occupyIndex = dataIndex
while dataIndex < occupyIndex + propertyLength {
let resVariableByteInteger = decodeVariableByteInteger(data: pubAckData, offset: dataIndex)
dataIndex = resVariableByteInteger.newOffset
let propertyNameByte = resVariableByteInteger.res
guard let propertyName = CocoaMQTTPropertyName(rawValue: UInt8(propertyNameByte)) else {
break
}
switch propertyName.rawValue {
// 3.11.2.1.2 Reason String
case CocoaMQTTPropertyName.reasonString.rawValue:
guard let result = unsignedByteToString(data: pubAckData, offset: dataIndex) else {
break
}
reasonString = result.resStr
dataIndex = result.newOffset
// 3.11.2.1.3 User Property
case CocoaMQTTPropertyName.userProperty.rawValue:
var key:String?
var value:String?
guard let keyRes = unsignedByteToString(data: pubAckData, offset: dataIndex) else {
break
}
key = keyRes.resStr
dataIndex = keyRes.newOffset
guard let valRes = unsignedByteToString(data: pubAckData, offset: dataIndex) else {
break
}
value = valRes.resStr
dataIndex = valRes.newOffset
userProperty![key!] = value
default:
return
}
}
if dataIndex < totalCount {
while dataIndex < totalCount {
guard let reasonCode = CocoaMQTTUNSUBACKReasonCode(rawValue: pubAckData[dataIndex]) else {
return
}
reasonCodes.append(reasonCode)
dataIndex += 1
}
}
}
}
| 30.14 | 122 | 0.593895 |
335dfe1a353c948b17cbffedd6b7e5088810cbc0 | 305 | //: Playground - noun: a place where people can play
import UIKit
let monet1 = RGBAImage(image: UIImage(named: "monet1")!)!
let monet2 = RGBAImage(image: UIImage(named: "monet2")!)!
let tiger = RGBAImage(image: UIImage(named: "tiger")!)!
ImageProcess.blending(monet1, tiger, alpha: 0.5).toUIImage()
| 25.416667 | 60 | 0.711475 |
4a5be6efc2ab57f7d05fb678b786197bba078673 | 921 | //
// NetworkServiceMock.swift
// RussellTests
//
// Created by Yunfan Cui on 2018/12/25.
// Copyright © 2018 LLS. All rights reserved.
//
@testable import Russell
final class MockCancellable: Cancellable {
func cancel() {}
}
final class NetworkServiceMock: NetworkService {
var json: JSONFile?
@discardableResult func request<Value>(api: API<Value>, extraErrorMapping: [RussellError.ErrorMapping], decoder: @escaping (Data) throws -> Value, completion: @escaping (RussellResult<Value>) -> Void) -> Cancellable {
guard let json = json else {
return MockCancellable()
}
DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) {
if let response: Value = json.loadData().flatMap({ try? decoder($0) }) {
completion(.success(response))
} else {
completion(.failure(RussellError.Common.networkError))
}
}
return MockCancellable()
}
}
| 26.314286 | 219 | 0.666667 |
91bf1f5543dabd73b7dced6886b861351f4c6dc0 | 173 | import Foundation
var isOdd = { (number: Int) -> Bool in
if number % 2 != 0 {
return true
}else {
return false
}
}
isOdd(10)
isOdd(5)
| 12.357143 | 38 | 0.50289 |
f7e0dddb62440c7dc99a2605fa63dab0145b02c6 | 257 | //
// TeamList.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Foundation
public struct TeamList: Codable {
public var teams: [Team]?
public init(teams: [Team]? = nil) {
self.teams = teams
}
}
| 13.526316 | 39 | 0.63035 |
09ffa2a98cd3d504c4d8a7825e4d73512e1c1249 | 2,461 | //
// TabmanBar+Indicator.swift
// Tabman
//
// Created by Merrick Sapsford on 15/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import Pageboy
// MARK: - TabmanBar Indicator creation and mutation
extension TabmanBar {
/// Remove a scroll indicator from the bar.
internal func clear(indicator: TabmanIndicator?) {
self.indicatorMaskView.frame = .zero // reset mask
indicator?.removeFromSuperview()
indicator?.removeConstraints(indicator?.constraints ?? [])
}
/// Create a new indicator for a style.
///
/// - Parameter style: The style.
/// - Returns: The new indicator.
internal func create(indicatorForStyle style: TabmanIndicator.Style) -> TabmanIndicator? {
if let indicatorType = style.rawType {
return indicatorType.init()
}
return nil
}
/// Update the current indicator for a preferred style.
///
/// - Parameter preferredStyle: The new preferred style.
internal func updateIndicator(forPreferredStyle preferredStyle: TabmanIndicator.Style?) {
guard let preferredIndicatorStyle = self.preferredIndicatorStyle else {
// restore default if no preferred style
self.indicator = self.create(indicatorForStyle: self.defaultIndicatorStyle())
guard let indicator = self.indicator else {
return
}
add(indicator: indicator, to: contentView)
self.updateForCurrentPosition()
return
}
guard self.usePreferredIndicatorStyle() else {
return
}
// return nil if same type as current indicator
if let indicator = self.indicator {
guard type(of: indicator) != preferredStyle?.rawType else {
return
}
}
// Create new preferred style indicator.
self.indicator = self.create(indicatorForStyle: preferredIndicatorStyle)
guard let indicator = self.indicator else {
return
}
// disable progressive indicator if indicator does not support it.
if self.indicator?.isProgressiveCapable == false && self.indicatorIsProgressive {
self.indicatorIsProgressive = false
}
add(indicator: indicator, to: contentView)
self.updateForCurrentPosition()
}
}
| 32.381579 | 94 | 0.619667 |
1df35116d87210288aeb0929e77b618cba8bd883 | 1,293 | //
// Fortune_Cookie_MonsterUITests.swift
// Fortune Cookie MonsterUITests
//
// Created by Jonathan Rothwell on 04/06/2018.
// Copyright © 2018 Zuhlke UK. All rights reserved.
//
import XCTest
class Fortune_Cookie_MonsterUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.945946 | 182 | 0.673627 |
efc5a7dca45f0637375fec293039fd0012673065 | 4,487 | // Copyright SIX DAY LLC. All rights reserved.
import BigInt
import Foundation
import APIKit
import JSONRPCKit
import PromiseKit
import Result
class SendTransactionCoordinator {
private let keystore: Keystore
private let session: WalletSession
private let confirmType: ConfirmType
private let config: Config
init(
session: WalletSession,
keystore: Keystore,
confirmType: ConfirmType,
config: Config
) {
self.session = session
self.keystore = keystore
self.confirmType = confirmType
self.config = config
}
func send(rawTransaction: String) -> Promise<ConfirmResult> {
let rawRequest = SendRawTransactionRequest(signedTransaction: rawTransaction.add0x)
let request = EtherServiceRequest(rpcURL: rpcURL, batch: BatchFactory().create(rawRequest))
return firstly {
Session.send(request)
}.map { transactionID in
.sentRawTransaction(id: transactionID, original: rawTransaction)
}
}
private func appendNonce(to: UnsignedTransaction, currentNonce: Int) -> UnsignedTransaction {
return UnsignedTransaction(
value: to.value,
account: to.account,
to: to.to,
nonce: currentNonce,
data: to.data,
gasPrice: to.gasPrice,
gasLimit: to.gasLimit,
server: to.server,
transactionType: to.transactionType
)
}
func send(transaction: UnsignedTransaction) -> Promise<ConfirmResult> {
if transaction.nonce >= 0 {
return signAndSend(transaction: transaction)
} else {
return firstly {
resolveNextNonce(for: transaction)
}.then { transaction -> Promise<ConfirmResult> in
return self.signAndSend(transaction: transaction)
}
}
}
private func resolveNextNonce(for transaction: UnsignedTransaction) -> Promise<UnsignedTransaction> {
firstly {
GetNextNonce(server: session.server, wallet: session.account.address).promise()
}.map { nonce -> UnsignedTransaction in
let transaction = self.appendNonce(to: transaction, currentNonce: nonce)
return transaction
}
}
private func signAndSend(transaction: UnsignedTransaction) -> Promise<ConfirmResult> {
firstly {
keystore.signTransactionPromise(transaction)
}.then { data -> Promise<ConfirmResult> in
switch self.confirmType {
case .sign:
return .value(.signedTransaction(data))
case .signThenSend:
return self.sendTransactionRequest(transaction: transaction, data: data)
}
}
}
private func sendTransactionRequest(transaction: UnsignedTransaction, data: Data) -> Promise<ConfirmResult> {
let rawTransaction = SendRawTransactionRequest(signedTransaction: data.hexEncoded)
let request = EtherServiceRequest(rpcURL: rpcURL, batch: BatchFactory().create(rawTransaction))
return firstly {
Session.send(request)
}.map { transactionID in
.sentTransaction(SentTransaction(id: transactionID, original: transaction))
}
}
private var rpcURL: URL {
session.server.rpcURLReplaceMainWithTaichiIfNeeded(config: config)
}
}
fileprivate extension RPCServer {
func rpcURLReplaceMainWithTaichiIfNeeded(config: Config) -> URL {
switch self {
case .main where config.useTaiChiNetwork:
if let url = config.taichiPrivateRpcUrl {
return url
} else {
return rpcURL
}
case .xDai, .kovan, .ropsten, .rinkeby, .poa, .sokol, .classic, .callisto, .goerli, .artis_sigma1, .artis_tau1, .binance_smart_chain, .binance_smart_chain_testnet, .custom, .heco, .heco_testnet, .main, .fantom, .fantom_testnet, .avalanche, .avalanche_testnet, .polygon, .mumbai_testnet, .optimistic, .optimisticKovan:
return self.rpcURL
}
}
}
extension Keystore {
func signTransactionPromise(_ transaction: UnsignedTransaction) -> Promise<Data> {
return Promise { seal in
switch signTransaction(transaction) {
case .success(let data):
seal.fulfill(data)
case .failure(let error):
seal.reject(error)
}
}
}
}
| 34.515385 | 325 | 0.631825 |
fefa5837f51f684336133a10790dda1b7dffae44 | 12,596 | #if canImport(Combine)
import Combine
import CombineRex
import SwiftRex
import XCTest
struct TestState: Equatable {
var value = UUID()
var name = "Initial State"
}
enum Event: Equatable {
case event1(Event1)
case event2(Event2)
}
struct Event1: Equatable {
var value = UUID()
var name = "e1"
}
struct Event2: Equatable {
var value = UUID()
var name = "e2"
}
indirect enum Action: Equatable {
case action1(Action1)
case action2(Action2)
case middlewareAction(Action)
case middlewareActionAfterReducer(Action)
var name: String {
switch self {
case let .action1(action): return action.name
case let .action2(action): return action.name
case let .middlewareAction(action): return action.name
case let .middlewareActionAfterReducer(action): return action.name
}
}
}
struct Action1: Equatable {
var value = UUID()
var name = "a1"
let event: Event1
}
struct Action2: Equatable {
var value = UUID()
var name = "a2"
let event: Event2
}
class MiddlewareTest: Middleware {
var getState: (() -> TestState)?
var output: AnyActionHandler<Action>?
func receiveContext(getState: @escaping GetState<TestState>, output: AnyActionHandler<Action>) {
self.getState = getState
self.output = output
}
func handle(action: Action, from dispatcher: ActionSource, afterReducer: inout AfterReducer) {
switch action {
case .middlewareAction, .middlewareActionAfterReducer:
afterReducer = .doNothing()
default:
break
}
output?.dispatch(.middlewareAction(action), from: .here())
afterReducer = .do {
self.output?.dispatch(.middlewareActionAfterReducer(action), from: .here())
}
}
}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
class ObservableViewModelTests: XCTestCase {
let reducerTest = Reducer<Action, TestState> { action, state in
switch action {
case let .action1(action):
return .init(value: UUID(), name: state.name + "_" + action.name)
case let .action2(action):
return .init(value: UUID(), name: state.name + "_" + action.name)
case let .middlewareAction(action):
return .init(value: UUID(), name: state.name + "_ma:" + action.name)
case let .middlewareActionAfterReducer(action):
return .init(value: UUID(), name: state.name + "_maar:" + action.name)
}
}
var statePublisher: CurrentValueSubject<TestState, Never>!
let middlewareTest = MiddlewareTest()
var viewModel: ObservableViewModel<Event, String>!
override func setUp() {
super.setUp()
statePublisher = .init(TestState())
viewModel = ReduxStoreBase(
subject: .init(currentValueSubject: statePublisher),
reducer: reducerTest,
middleware: middlewareTest,
emitsValue: .whenDifferent
).projection(
action: { event in
switch event {
case let .event1(event1): return Action.action1(.init(event: event1))
case let .event2(event2): return Action.action2(.init(event: event2))
}
},
state: { (state: TestState) -> String in
"name: \(state.name)"
}
).asObservableViewModel(initialState: "")
}
func testInitialState() {
XCTAssertEqual("name: Initial State", viewModel.state)
}
func testSubscribeDoNotTriggerWillChangeNotifyIntegrationTest() {
let subscription = viewModel.objectWillChange.sink { _ in
XCTFail("On subscribe this notification should never be triggered")
}
XCTAssertNotNil(subscription)
}
func testStatePublisherNotifyOnSubscribeIntegrationTest() {
let shouldBeNotified = expectation(description: "should be notified by state publisher")
// Can't test objectWillChange Publisher because it happens before the mutation
let subscription = viewModel.statePublisher.sink { state in
XCTAssertEqual("name: Initial State", state)
shouldBeNotified.fulfill()
}
wait(for: [shouldBeNotified], timeout: 1)
XCTAssertNotNil(subscription)
}
func testStatePublisherNotifyOnChangeIntegrationTest() {
let shouldBeNotified = expectation(description: "should be notified by state publisher")
var count = 0
// Can't test objectWillChange Publisher because it happens before the mutation
let subscription = viewModel.statePublisher.sink { [unowned self] state in
switch count {
case 0:
XCTAssertEqual("name: Initial State", state)
case 1:
XCTAssertEqual("name: Initial State_a1", state)
case 2:
XCTAssertEqual("name: Initial State_a1_ma:a1", state)
case 3:
XCTAssertEqual("name: Initial State_a1_ma:a1_maar:a1", state)
shouldBeNotified.fulfill()
default:
XCTFail("Unexpected notification: \(self.viewModel.state)")
}
count += 1
}
viewModel.dispatch(.event1(Event1()), from: .here())
wait(for: [shouldBeNotified], timeout: 1)
XCTAssertNotNil(subscription)
}
func testWillChangeNotifyOnChangeIntegrationTest() {
let shouldBeNotifiedByWillChangePublisher = expectation(description: "should be notified by will change publisher")
var count = 0
let subscription = viewModel.objectWillChange.sink { [unowned self] _ in
switch count {
// expected one notification less (only changes, not initial state) and always with the previous value
// not yet the one being set.
case 0:
XCTAssertEqual("name: Initial State", self.viewModel.state)
case 1:
XCTAssertEqual("name: Initial State_a1", self.viewModel.state)
case 2:
XCTAssertEqual("name: Initial State_a1_ma:a1", self.viewModel.state)
shouldBeNotifiedByWillChangePublisher.fulfill()
default:
XCTFail("Unexpected notification: \(self.viewModel.state)")
}
count += 1
}
viewModel.dispatch(.event1(Event1()), from: .here())
wait(for: [shouldBeNotifiedByWillChangePublisher], timeout: 1)
XCTAssertNotNil(subscription)
}
func testObservableViewModelShouldNotLeak() {
weak var obVMWeakRef: ObservableViewModel<String, String>?
weak var storeWeakRef: ReduxStoreBase<String, String>?
autoreleasepool {
let store = ReduxStoreBase(
subject: .combine(initialValue: ""),
reducer: Reducer<String, String>.identity,
middleware: IdentityMiddleware<String, String, String>(),
emitsValue: .whenDifferent
)
storeWeakRef = store
let obVMStrongRef = store.asObservableViewModel(initialState: "")
obVMWeakRef = obVMStrongRef
XCTAssertNotNil(obVMWeakRef)
}
XCTAssertNil(storeWeakRef)
XCTAssertNil(obVMWeakRef, "middleware should be freed")
}
// func testWillChangePublisherCanHaveMultipleSubscriptions() {
// let shouldBeNotifiedByWillChangePublisher3 = expectation(description: "should be notified by will change publisher 1")
// let shouldBeNotifiedByWillChangePublisher4 = expectation(description: "should be notified by will change publisher 2")
// let subscription1 = viewModel.objectWillChange.sink { _ in
// XCTFail("On subscribe this notification should never be triggered")
// }
// subscription1.cancel()
//
// let subscription2 = viewModel.objectWillChange.sink { _ in
// XCTFail("On subscribe this notification should never be triggered")
// }
// subscription2.cancel()
//
// var countSub3 = 0
// let subscription3 = viewModel.objectWillChange.sink { [unowned self] _ in
// switch countSub3 {
// // expected one notification less (only changes, not initial state) and always with the previous value
// // not yet the one being set.
// case 0:
// XCTAssertEqual("name: Initial State", self.viewModel.state)
// case 1:
// XCTAssertEqual("name: Initial State_a1", self.viewModel.state)
// case 2:
// XCTAssertEqual("name: Initial State_a1_ma:a1", self.viewModel.state)
// shouldBeNotifiedByWillChangePublisher3.fulfill()
// default:
// XCTFail("Unexpected notification: \(self.viewModel.state)")
// }
// countSub3 += 1
// }
//
// var countSub4 = 0
// let subscription4 = viewModel.objectWillChange.sink { [unowned self] _ in
// switch countSub4 {
// // expected one notification less (only changes, not initial state) and always with the previous value
// // not yet the one being set.
// case 0:
// XCTAssertEqual("name: Initial State", self.viewModel.state)
// case 1:
// XCTAssertEqual("name: Initial State_a1", self.viewModel.state)
// case 2:
// XCTAssertEqual("name: Initial State_a1_ma:a1", self.viewModel.state)
// shouldBeNotifiedByWillChangePublisher3.fulfill()
// default:
// XCTFail("Unexpected notification: \(self.viewModel.state)")
// }
// countSub4 += 1
// }
//
// viewModel.dispatch(.event1(Event1()))
//
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
// subscription3.cancel()
// }
//
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
// self.viewModel.dispatch(.event2(Event2()))
// }
//
// wait(for: [shouldBeNotifiedByWillChangePublisher3, shouldBeNotifiedByWillChangePublisher4], timeout: 5)
// XCTAssertNotNil(subscription4)
// }
//
// func testStatePublisherCanHaveMultipleSubscriptions() {
// let shouldBeNotifiedByStatePublisher1 = expectation(description: "should be notified by state publisher")
// let shouldBeNotifiedByStatePublisher2 = expectation(description: "should be notified by state publisher")
// let subscription1 = store.statePublisher.sink { [unowned self] value in
// XCTAssertEqual("Initial State", self.store.state.name)
// XCTAssertEqual("Initial State", value.name)
// }
// subscription1.cancel()
//
// let subscription2 = store.statePublisher.sink { [unowned self] value in
// XCTAssertEqual("Initial State", self.store.state.name)
// XCTAssertEqual("Initial State", value.name)
// }
// subscription2.cancel()
//
// var time1 = 0
// let subscription3 = store.statePublisher.sink { [unowned self] value in
// switch time1 {
// case 0:
// XCTAssertEqual("Initial State", self.store.state.name)
// XCTAssertEqual("Initial State", value.name)
// case 1:
// XCTAssertEqual("Initial State_a1", self.store.state.name)
// XCTAssertEqual("Initial State_a1", value.name)
// shouldBeNotifiedByStatePublisher1.fulfill()
// default:
// XCTFail("Too many calls")
// }
// time1 += 1
// }
//
// var time2 = 0
// let subscription4 = store.statePublisher.sink { [unowned self] value in
// switch time2 {
// case 0:
// XCTAssertEqual("Initial State", self.store.state.name)
// XCTAssertEqual("Initial State", value.name)
// case 1:
// XCTAssertEqual("Initial State_a1", self.store.state.name)
// XCTAssertEqual("Initial State_a1", value.name)
// shouldBeNotifiedByStatePublisher2.fulfill()
// default:
// XCTFail("Too many calls")
// }
// time2 += 1
// }
//
// store.eventHandler.dispatch(Event1())
//
// wait(for: [shouldBeNotifiedByStatePublisher1, shouldBeNotifiedByStatePublisher2], timeout: 1)
// XCTAssertNotNil(subscription3)
// XCTAssertNotNil(subscription4)
// }
}
#endif
| 37.6 | 128 | 0.608447 |
e92325e1c25c0a9be7fdbf953b5f3f5bb240cc61 | 385 | //
// IIdentifiableReducer.swift
// OSKit
//
// Created by Brody Robertson.
// Copyright © 2020 Outside Source. All rights reserved.
//
public typealias IdentifiableReduce = (_ action: IAction, _ state: IIdentifiableState) -> IIdentifiableState
public protocol IIdentifiableReducer {
static func reduce(_ action: IAction, _ state: IIdentifiableState) -> IIdentifiableState
}
| 27.5 | 108 | 0.755844 |
0e7061bfee9518e40f869974f1ce34a3df6af757 | 241 | //
// NavigationItem.swift
// Game-of-Thrones-SwiftUI
//
// Created by Christian Elies on 22.07.20.
// Copyright © 2020 Christian Elies. All rights reserved.
//
enum NavigationItem {
case houses
case characters
case books
}
| 17.214286 | 58 | 0.684647 |
768839ec502d53f33f449a7e385fbfbce3db1061 | 5,698 | //
// PreviewLivePhotoViewCell.swift
// HXPHPicker
//
// Created by Slience on 2021/3/12.
//
import UIKit
class PreviewLivePhotoViewCell: PhotoPreviewViewCell, PhotoPreviewContentViewDelete {
var livePhotoPlayType: PhotoPreviewViewController.PlayType = .once {
didSet {
scrollContentView.livePhotoPlayType = livePhotoPlayType
}
}
lazy var liveMarkView: UIVisualEffectView = {
let effect = UIBlurEffect(style: .light)
let view = UIVisualEffectView(effect: effect)
if let nav = UIViewController.topViewController?.navigationController, !nav.navigationBar.isHidden {
view.y = nav.navigationBar.frame.maxY + 5
}else {
if UIApplication.shared.isStatusBarHidden {
view.y = UIDevice.navigationBarHeight + UIDevice.generalStatusBarHeight + 5
}else {
view.y = UIDevice.navigationBarHeight + 5
}
}
view.x = 5
view.height = 24
view.layer.cornerRadius = 3
view.layer.masksToBounds = true
let imageView = UIImageView(image: "hx_picker_livePhoto".image?.withRenderingMode(.alwaysTemplate))
imageView.tintColor = "#666666".color
imageView.size = imageView.image?.size ?? .zero
imageView.centerY = view.height * 0.5
imageView.x = 5
view.contentView.addSubview(imageView)
let label = UILabel()
label.text = "Live"
label.textColor = "#666666".color
label.textAlignment = .center
label.font = .regularPingFang(ofSize: 15)
label.x = imageView.frame.maxX + 5
label.height = view.height
label.width = label.textWidth
view.width = label.frame.maxX + 5
view.contentView.addSubview(label)
return view
}()
var liveMarkConfig: PreviewViewConfiguration.LivePhotoMark? {
didSet {
configLiveMark()
}
}
override var photoAsset: PhotoAsset! {
didSet {
#if HXPICKER_ENABLE_EDITOR
if photoAsset.photoEdit != nil {
liveMarkView.isHidden = true
}
else {
if liveMarkConfig?.allowShow == true {
liveMarkView.isHidden = false
}
}
#else
if liveMarkConfig?.allowShow == true {
liveMarkView.isHidden = false
}
#endif
}
}
func configLiveMark() {
guard let liveMarkConfig = liveMarkConfig else {
liveMarkView.isHidden = true
return
}
if !liveMarkConfig.allowShow {
liveMarkView.isHidden = true
return
}
liveMarkView.effect = UIBlurEffect(
style: PhotoManager.isDark ? liveMarkConfig.blurDarkStyle : liveMarkConfig.blurStyle
)
let imageView = liveMarkView.contentView.subviews.first as? UIImageView
imageView?.tintColor = PhotoManager.isDark ? liveMarkConfig.imageDarkColor : liveMarkConfig.imageColor
let label = liveMarkView.contentView.subviews.last as? UILabel
label?.textColor = PhotoManager.isDark ? liveMarkConfig.textDarkColor : liveMarkConfig.textColor
}
override init(frame: CGRect) {
super.init(frame: frame)
scrollContentView = PhotoPreviewContentView(type: .livePhoto)
scrollContentView.delegate = self
initView()
addSubview(liveMarkView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func contentView(requestSucceed contentView: PhotoPreviewContentView) {
delegate?.cell(requestSucceed: self)
}
func contentView(requestFailed contentView: PhotoPreviewContentView) {
delegate?.cell(requestFailed: self)
}
func contentView(livePhotoWillBeginPlayback contentView: PhotoPreviewContentView) {
hideMark()
}
func contentView(livePhotoDidEndPlayback contentView: PhotoPreviewContentView) {
showMark()
}
func showMark() {
guard let liveMarkConfig = liveMarkConfig else {
return
}
#if HXPICKER_ENABLE_EDITOR
if photoAsset.photoEdit != nil {
return
}
#endif
if !liveMarkConfig.allowShow {
return
}
if scrollContentView.livePhotoIsAnimating ||
scrollContentView.isBacking ||
statusBarShouldBeHidden { return }
if !liveMarkView.isHidden && liveMarkView.alpha == 1 { return }
liveMarkView.isHidden = false
UIView.animate(withDuration: 0.25) {
self.liveMarkView.alpha = 1
}
}
func hideMark() {
guard let liveMarkConfig = liveMarkConfig else {
return
}
#if HXPICKER_ENABLE_EDITOR
if photoAsset.photoEdit != nil {
return
}
#endif
if !liveMarkConfig.allowShow {
return
}
if liveMarkView.isHidden { return }
UIView.animate(withDuration: 0.25) {
self.liveMarkView.alpha = 0
} completion: { _ in
if self.liveMarkView.alpha == 0 {
self.liveMarkView.isHidden = true
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13.0, *) {
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
configLiveMark()
}
}
}
}
| 33.321637 | 110 | 0.6053 |
16a73ce3c7d63ec009fb91d82dff8c471c610961 | 2,163 | //
// AppDelegate.swift
// Example
//
// Created by Joon on 07/11/2017.
// Copyright © 2017 MNISTKit. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.021277 | 285 | 0.75497 |
fb9f0e81d718087b3836c409558dae02a455a918 | 966 | import Foundation
import Utils
// let input = try Utils.getInput(bundle: Bundle.module, file: "test")
let input = try Utils.getInput(bundle: Bundle.module)
let items = input
.components(separatedBy: CharacterSet(charactersIn: ", \n"))
.map { (item) -> Int? in
Int(item)
}
.compactMap { $0 }
func part1(items: [Int]) -> Int {
let length = items.count
for entry in items {
for index in 1 ... length - 1 where entry + items[index] == 2020 {
return entry * items[index]
}
}
return -1
}
print("Part 1: \(part1(items: items))")
func part2(items: [Int]) -> Int {
let length = items.count
for entry in items {
for index in 1 ... length - 1 {
for index2 in 2 ... length - 1 where entry + items[index] + items[index2] == 2020 {
return entry * items[index] * items[index2]
}
}
}
return -1
}
print("Part 2: \(part2(items: items))")
| 24.769231 | 95 | 0.566253 |
0181552e4fcd2432fe3881e2e9be79738afcef21 | 7,642 | public func until(_ tags: [String]) -> ((TokenParser, Token) -> Bool) {
return { parser, token in
if let name = token.components.first {
for tag in tags where name == tag {
return true
}
}
return false
}
}
/// A class for parsing an array of tokens and converts them into a collection of Node's
public class TokenParser {
public typealias TagParser = (TokenParser, Token) throws -> NodeType
fileprivate var tokens: [Token]
fileprivate let environment: Environment
public init(tokens: [Token], environment: Environment) {
self.tokens = tokens
self.environment = environment
}
/// Parse the given tokens into nodes
public func parse() throws -> [NodeType] {
return try parse(nil)
}
public func parse(_ parseUntil: ((_ parser: TokenParser, _ token: Token) -> (Bool))?) throws -> [NodeType] {
var nodes = [NodeType]()
while !tokens.isEmpty {
guard let token = nextToken() else { break }
switch token.kind {
case .text:
nodes.append(TextNode(text: token.contents))
case .variable:
try nodes.append(VariableNode.parse(self, token: token))
case .block:
if let parseUntil = parseUntil, parseUntil(self, token) {
prependToken(token)
return nodes
}
if let tag = token.components.first {
do {
let parser = try environment.findTag(name: tag)
let node = try parser(self, token)
nodes.append(node)
} catch {
throw error.withToken(token)
}
}
case .comment:
continue
}
}
return nodes
}
public func nextToken() -> Token? {
if !tokens.isEmpty {
return tokens.remove(at: 0)
}
return nil
}
public func prependToken(_ token: Token) {
tokens.insert(token, at: 0)
}
/// Create filter expression from a string contained in provided token
public func compileFilter(_ filterToken: String, containedIn token: Token) throws -> Resolvable {
return try environment.compileFilter(filterToken, containedIn: token)
}
/// Create boolean expression from components contained in provided token
public func compileExpression(components: [String], token: Token) throws -> Expression {
return try environment.compileExpression(components: components, containedIn: token)
}
/// Create resolvable (i.e. range variable or filter expression) from a string contained in provided token
public func compileResolvable(_ token: String, containedIn containingToken: Token) throws -> Resolvable {
return try environment.compileResolvable(token, containedIn: containingToken)
}
}
extension Environment {
func findTag(name: String) throws -> Extension.TagParser {
for ext in extensions {
if let filter = ext.tags[name] {
return filter
}
}
throw TemplateSyntaxError("Unknown template tag '\(name)'")
}
func findFilter(_ name: String) throws -> FilterType {
for ext in extensions {
if let filter = ext.filters[name] {
return filter
}
}
let suggestedFilters = self.suggestedFilters(for: name)
if suggestedFilters.isEmpty {
throw TemplateSyntaxError("Unknown filter '\(name)'.")
} else {
throw TemplateSyntaxError("""
Unknown filter '\(name)'. \
Found similar filters: \(suggestedFilters.map { "'\($0)'" }.joined(separator: ", ")).
""")
}
}
private func suggestedFilters(for name: String) -> [String] {
let allFilters = extensions.flatMap { $0.filters.keys }
let filtersWithDistance = allFilters
.map { (filterName: $0, distance: $0.levenshteinDistance(name)) }
// do not suggest filters which names are shorter than the distance
.filter { $0.filterName.count > $0.distance }
guard let minDistance = filtersWithDistance.min(by: { $0.distance < $1.distance })?.distance else {
return []
}
// suggest all filters with the same distance
return filtersWithDistance.filter { $0.distance == minDistance }.map { $0.filterName }
}
/// Create filter expression from a string
public func compileFilter(_ token: String) throws -> Resolvable {
return try FilterExpression(token: token, environment: self)
}
/// Create filter expression from a string contained in provided token
public func compileFilter(_ filterToken: String, containedIn containingToken: Token) throws -> Resolvable {
do {
return try FilterExpression(token: filterToken, environment: self)
} catch {
guard var syntaxError = error as? TemplateSyntaxError, syntaxError.token == nil else {
throw error
}
// find offset of filter in the containing token so that only filter is highligted, not the whole token
if let filterTokenRange = containingToken.contents.range(of: filterToken) {
var location = containingToken.sourceMap.location
location.lineOffset += containingToken.contents.distance(
from: containingToken.contents.startIndex,
to: filterTokenRange.lowerBound
)
syntaxError.token = .variable(
value: filterToken,
at: SourceMap(filename: containingToken.sourceMap.filename, location: location)
)
} else {
syntaxError.token = containingToken
}
throw syntaxError
}
}
/// Create resolvable (i.e. range variable or filter expression) from a string
public func compileResolvable(_ token: String) throws -> Resolvable {
return try RangeVariable(token, environment: self)
?? compileFilter(token)
}
/// Create resolvable (i.e. range variable or filter expression) from a string contained in provided token
public func compileResolvable(_ token: String, containedIn containingToken: Token) throws -> Resolvable {
return try RangeVariable(token, environment: self, containedIn: containingToken)
?? compileFilter(token, containedIn: containingToken)
}
/// Create boolean expression from components contained in provided token
public func compileExpression(components: [String], containedIn token: Token) throws -> Expression {
return try IfExpressionParser.parser(components: components, environment: self, token: token).parse()
}
}
// https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows
extension String {
subscript(_ index: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: index)]
}
func levenshteinDistance(_ target: String) -> Int {
// create two work vectors of integer distances
var last, current: [Int]
// initialize v0 (the previous row of distances)
// this row is A[0][i]: edit distance for an empty s
// the distance is just the number of characters to delete from t
last = [Int](0...target.count)
current = [Int](repeating: 0, count: target.count + 1)
for selfIndex in 0..<self.count {
// calculate v1 (current row distances) from the previous row v0
// first element of v1 is A[i+1][0]
// edit distance is delete (i+1) chars from s to match empty t
current[0] = selfIndex + 1
// use formula to fill in the rest of the row
for targetIndex in 0..<target.count {
current[targetIndex + 1] = Swift.min(
last[targetIndex + 1] + 1,
current[targetIndex] + 1,
last[targetIndex] + (self[selfIndex] == target[targetIndex] ? 0 : 1)
)
}
// copy v1 (current row) to v0 (previous row) for next iteration
last = current
}
return current[target.count]
}
}
| 34.269058 | 110 | 0.663308 |
abe8e402b7e8dab740fe47883a329abe2a4a3998 | 1,068 | //
// LogViewController.swift
// Odyssey
//
// Created by CoolStar on 7/1/20.
// Copyright © 2020 coolstar. All rights reserved.
//
import UIKit
class LogViewController: UIViewController {
@IBOutlet var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
isModalInPresentation = true
NotificationCenter.default.addObserver(self, selector: #selector(LogViewController.reload), name: LogStream.shared.reloadNotification, object: nil)
self.reload()
}
@objc func reload() {
guard let log = LogStream.shared.outputString.copy() as? NSAttributedString else {
return
}
ObjcTryCatch {
self.textView.attributedText = log
self.textView.font = UIFont.monospacedSystemFont(ofSize: 0, weight: .regular)
if log.string.count > 1 {
self.textView.scrollRangeToVisible(NSRange(location: log.string.count - 1, length: 1))
}
self.textView.setNeedsDisplay()
}
}
}
| 29.666667 | 155 | 0.626404 |
2ffc99d8b0c73f8165868cc9eeee5f30cbc7b098 | 17,638 | //
// Copyright (c) 2015 Max Sokolov https://twitter.com/max_sokolov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
/**
Responsible for table view's datasource and delegate.
*/
open class TableDirector: NSObject, UITableViewDataSource, UITableViewDelegate {
open private(set) weak var tableView: UITableView?
open fileprivate(set) var sections = [TableSection]()
private weak var scrollDelegate: UIScrollViewDelegate?
private var cellRegisterer: TableCellRegisterer?
public private(set) var rowHeightCalculator: RowHeightCalculator?
private var sectionsIndexTitlesIndexes: [Int]?
@available(*, deprecated, message: "Produced incorrect behaviour")
open var shouldUsePrototypeCellHeightCalculation: Bool = false {
didSet {
if shouldUsePrototypeCellHeightCalculation {
rowHeightCalculator = TablePrototypeCellHeightCalculator(tableView: tableView)
} else {
rowHeightCalculator = nil
}
}
}
open var isEmpty: Bool {
return sections.isEmpty
}
public init(
tableView: UITableView,
scrollDelegate: UIScrollViewDelegate? = nil,
shouldUseAutomaticCellRegistration: Bool = true,
cellHeightCalculator: RowHeightCalculator?)
{
super.init()
if shouldUseAutomaticCellRegistration {
self.cellRegisterer = TableCellRegisterer(tableView: tableView)
}
self.rowHeightCalculator = cellHeightCalculator
self.scrollDelegate = scrollDelegate
self.tableView = tableView
self.tableView?.delegate = self
self.tableView?.dataSource = self
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveAction), name: NSNotification.Name(rawValue: TableKitNotifications.CellAction), object: nil)
}
public convenience init(
tableView: UITableView,
scrollDelegate: UIScrollViewDelegate? = nil,
shouldUseAutomaticCellRegistration: Bool = true,
shouldUsePrototypeCellHeightCalculation: Bool = false)
{
let heightCalculator: TablePrototypeCellHeightCalculator? = shouldUsePrototypeCellHeightCalculation
? TablePrototypeCellHeightCalculator(tableView: tableView)
: nil
self.init(
tableView: tableView,
scrollDelegate: scrollDelegate,
shouldUseAutomaticCellRegistration: shouldUseAutomaticCellRegistration,
cellHeightCalculator: heightCalculator
)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open func reload() {
tableView?.reloadData()
}
// MARK: - Private
private func row(at indexPath: IndexPath) -> Row? {
if indexPath.section < sections.count && indexPath.row < sections[indexPath.section].rows.count {
return sections[indexPath.section].rows[indexPath.row]
}
return nil
}
// MARK: Public
@discardableResult
open func invoke(
action: TableRowActionType,
cell: UITableViewCell?, indexPath: IndexPath,
userInfo: [AnyHashable: Any]? = nil) -> Any?
{
guard let row = row(at: indexPath) else { return nil }
return row.invoke(
action: action,
cell: cell,
path: indexPath,
userInfo: userInfo
)
}
open override func responds(to selector: Selector) -> Bool {
return super.responds(to: selector) || scrollDelegate?.responds(to: selector) == true
}
open override func forwardingTarget(for selector: Selector) -> Any? {
return scrollDelegate?.responds(to: selector) == true
? scrollDelegate
: super.forwardingTarget(for: selector)
}
// MARK: - Internal
func hasAction(_ action: TableRowActionType, atIndexPath indexPath: IndexPath) -> Bool {
guard let row = row(at: indexPath) else { return false }
return row.has(action: action)
}
@objc
func didReceiveAction(_ notification: Notification) {
guard let action = notification.object as? TableCellAction, let indexPath = tableView?.indexPath(for: action.cell) else { return }
invoke(action: .custom(action.key), cell: action.cell, indexPath: indexPath, userInfo: notification.userInfo)
}
// MARK: - Height
open func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let row = sections[indexPath.section].rows[indexPath.row]
if rowHeightCalculator != nil {
cellRegisterer?.register(cellType: row.cellType, forCellReuseIdentifier: row.reuseIdentifier)
}
return row.defaultHeight
?? row.estimatedHeight
?? rowHeightCalculator?.estimatedHeight(forRow: row, at: indexPath)
?? UITableView.automaticDimension
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = sections[indexPath.section].rows[indexPath.row]
if rowHeightCalculator != nil {
cellRegisterer?.register(cellType: row.cellType, forCellReuseIdentifier: row.reuseIdentifier)
}
let rowHeight = invoke(action: .height, cell: nil, indexPath: indexPath) as? CGFloat
return rowHeight
?? row.defaultHeight
?? rowHeightCalculator?.height(forRow: row, at: indexPath)
?? UITableView.automaticDimension
}
// MARK: UITableViewDataSource - configuration
open func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section < sections.count else { return 0 }
return sections[section].numberOfRows
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = sections[indexPath.section].rows[indexPath.row]
cellRegisterer?.register(cellType: row.cellType, forCellReuseIdentifier: row.reuseIdentifier)
let cell = tableView.dequeueReusableCell(withIdentifier: row.reuseIdentifier, for: indexPath)
if cell.frame.size.width != tableView.frame.size.width {
cell.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: cell.frame.size.height)
cell.layoutIfNeeded()
}
row.configure(cell)
invoke(action: .configure, cell: cell, indexPath: indexPath)
return cell
}
// MARK: UITableViewDataSource - section setup
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard section < sections.count else { return nil }
return sections[section].headerTitle
}
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard section < sections.count else { return nil }
return sections[section].footerTitle
}
// MARK: UITableViewDelegate - section setup
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard section < sections.count else { return nil }
return sections[section].headerView
}
open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard section < sections.count else { return nil }
return sections[section].footerView
}
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section < sections.count else { return 0 }
let section = sections[section]
return section.headerHeight ?? section.headerView?.frame.size.height ?? UITableView.automaticDimension
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard section < sections.count else { return 0 }
let section = sections[section]
return section.footerHeight
?? section.footerView?.frame.size.height
?? UITableView.automaticDimension
}
// MARK: UITableViewDataSource - Index
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
var indexTitles = [String]()
var indexTitlesIndexes = [Int]()
sections.enumerated().forEach { index, section in
if let title = section.indexTitle {
indexTitles.append(title)
indexTitlesIndexes.append(index)
}
}
if !indexTitles.isEmpty {
sectionsIndexTitlesIndexes = indexTitlesIndexes
return indexTitles
}
sectionsIndexTitlesIndexes = nil
return nil
}
public func tableView(
_ tableView: UITableView,
sectionForSectionIndexTitle title: String,
at index: Int) -> Int
{
return sectionsIndexTitlesIndexes?[index] ?? 0
}
// MARK: UITableViewDelegate - actions
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if invoke(action: .click, cell: cell, indexPath: indexPath) != nil {
tableView.deselectRow(at: indexPath, animated: true)
} else {
invoke(action: .select, cell: cell, indexPath: indexPath)
}
}
open func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
invoke(action: .deselect, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath)
}
open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
invoke(action: .willDisplay, cell: cell, indexPath: indexPath)
}
public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
invoke(action: .didEndDisplaying, cell: cell, indexPath: indexPath)
}
open func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return invoke(action: .shouldHighlight, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? true
}
open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if hasAction(.willSelect, atIndexPath: indexPath) {
return invoke(action: .willSelect, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? IndexPath
}
return indexPath
}
open func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
if hasAction(.willDeselect, atIndexPath: indexPath) {
return invoke(action: .willDeselect, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? IndexPath
}
return indexPath
}
@available(iOS 13.0, *)
open func tableView(
_ tableView: UITableView,
shouldBeginMultipleSelectionInteractionAt indexPath: IndexPath) -> Bool
{
invoke(action: .shouldBeginMultipleSelection, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? false
}
@available(iOS 13.0, *)
open func tableView(
_ tableView: UITableView,
didBeginMultipleSelectionInteractionAt indexPath: IndexPath)
{
invoke(action: .didBeginMultipleSelection, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath)
}
@available(iOS 13.0, *)
open func tableView(
_ tableView: UITableView,
contextMenuConfigurationForRowAt indexPath: IndexPath,
point: CGPoint) -> UIContextMenuConfiguration?
{
invoke(action: .showContextMenu, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath, userInfo: [TableKitUserInfoKeys.ContextMenuInvokePoint: point]) as? UIContextMenuConfiguration
}
// MARK: - Row editing
open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return sections[indexPath.section].rows[indexPath.row].isEditingAllowed(forIndexPath: indexPath)
}
open func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return sections[indexPath.section].rows[indexPath.row].editingActions
}
open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if invoke(action: .canDelete, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? false {
return UITableViewCell.EditingStyle.delete
}
return UITableViewCell.EditingStyle.none
}
public func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
public func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
return invoke(action: .canMoveTo, cell: tableView.cellForRow(at: sourceIndexPath), indexPath: sourceIndexPath, userInfo: [TableKitUserInfoKeys.CellCanMoveProposedIndexPath: proposedDestinationIndexPath]) as? IndexPath ?? proposedDestinationIndexPath
}
open func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
invoke(action: .clickDelete, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath)
}
}
open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return invoke(action: .canMove, cell: tableView.cellForRow(at: indexPath), indexPath: indexPath) as? Bool ?? false
}
open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
invoke(action: .move, cell: tableView.cellForRow(at: sourceIndexPath), indexPath: sourceIndexPath, userInfo: [TableKitUserInfoKeys.CellMoveDestinationIndexPath: destinationIndexPath])
}
open func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
invoke(action: .accessoryButtonTap, cell: cell, indexPath: indexPath)
}
}
// MARK: - Sections manipulation
extension TableDirector {
@discardableResult
open func append(section: TableSection) -> Self {
append(sections: [section])
return self
}
@discardableResult
open func append(sections: [TableSection]) -> Self {
self.sections.append(contentsOf: sections)
return self
}
@discardableResult
open func append(rows: [Row]) -> Self {
append(section: TableSection(rows: rows))
return self
}
@discardableResult
open func insert(section: TableSection, atIndex index: Int) -> Self {
sections.insert(section, at: index)
return self
}
@discardableResult
open func replaceSection(at index: Int, with section: TableSection) -> Self {
if index < sections.count {
sections[index] = section
}
return self
}
@discardableResult
open func delete(sectionAt index: Int) -> Self {
sections.remove(at: index)
return self
}
@discardableResult
open func remove(sectionAt index: Int) -> Self {
return delete(sectionAt: index)
}
@discardableResult
open func clear() -> Self {
rowHeightCalculator?.invalidate()
sections.removeAll()
return self
}
// MARK: - deprecated methods
@available(*, deprecated, message: "Use 'delete(sectionAt:)' method instead")
@discardableResult
open func delete(index: Int) -> Self {
sections.remove(at: index)
return self
}
}
| 38.343478 | 257 | 0.663907 |
1cfd643689079fb0978fb8de5ceac57ab85914aa | 1,263 | //
// ResultCard.swift
// Index
//
// Created by Pao Yu on 2020-07-31.
//
import SwiftUI
struct ResultCard: View {
@EnvironmentObject var model: IndexModel
var body: some View {
ZStack {
CardBackground()
VStack {
CardLabel(title: "Result", caption: "Your Body Mass Index is")
VStack {
Text(String(format: "%0.1f", model.resultBMI))
.font(.largeTitle)
.fontWeight(.bold)
.foregroundColor(Color(.systemGreen))
Text("kg / m^2")
.font(.caption)
.padding(.top, 20)
.foregroundColor(Color(.systemGray))
Text("\(model.message)")
.font(.caption)
.fontWeight(.bold)
.padding(.top, 10)
.foregroundColor(Color(.systemGray))
}
}
} .frame(width: 300, height: 500)
// End of ZStack
}
}
| 25.77551 | 78 | 0.375297 |
e68aca9629b48f46411ba70a6876390e797a9fae | 2,616 | //
// MIT License
//
// Copyright (c) 2018-2019 Open Zesame (https://github.com/OpenZesame)
//
// 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
import RxSwift
import RxCocoa
// MARK: - User action and navigation steps
enum ConfirmWalletRemovalUserAction {
case /*user did*/cancel, confirm
}
// MARK: - ConfirmWalletRemovalViewModel
private typealias € = L10n.Scene.ConfirmWalletRemoval
final class ConfirmWalletRemovalViewModel: BaseViewModel<
ConfirmWalletRemovalUserAction,
ConfirmWalletRemovalViewModel.InputFromView,
ConfirmWalletRemovalViewModel.Output
> {
private let useCase: WalletUseCase
init(useCase: WalletUseCase) {
self.useCase = useCase
}
override func transform(input: Input) -> Output {
func userDid(_ userAction: NavigationStep) {
navigator.next(userAction)
}
// MARK: Navigate
bag <~ [
input.fromController.leftBarButtonTrigger
.do(onNext: { userDid(.cancel) })
.drive(),
input.fromView.confirmTrigger
.do(onNext: { userDid(.confirm) })
.drive()
]
// MARK: Return output
return Output(
isConfirmButtonEnabled: input.fromView.isWalletBackedUpCheckboxChecked
)
}
}
extension ConfirmWalletRemovalViewModel {
struct InputFromView {
let confirmTrigger: Driver<Void>
let isWalletBackedUpCheckboxChecked: Driver<Bool>
}
struct Output {
let isConfirmButtonEnabled: Driver<Bool>
}
}
| 31.902439 | 82 | 0.698777 |
08ee73e335e9b9cf1135be2060727706899c4d37 | 7,528 | //
// Models.swift
// GraphJS
//
// Created by CAMOBAP on 9/1/18.
// Copyright © 2018 Pho Networks. All rights reserved.
//
import Foundation
enum FeedType: String {
case wall = "wall"
case timeline = "timeline"
}
struct UserProfile: Codable {
let username: String
let email: String
let joinTime: Date?
let avatar: URL?
let birthday: Date?
let about: String?
let followerCount: Int
let followingCount: Int
let membershipCount: Int
init(username: String, email: String, joinTime: Date? = nil, avatar: URL? = nil, birthday: Date? = nil, about: String? = nil, followerCount: Int = 0, followingCount: Int = 0, membershipCount: Int = 0) {
self.username = username
self.email = email
self.joinTime = joinTime
self.avatar = avatar
self.birthday = birthday
self.about = about
self.followerCount = followerCount
self.followingCount = followingCount
self.membershipCount = membershipCount
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.username = try values.decode(String.self, forKey: .username)
self.email = try values.decode(String.self, forKey: .email)
self.joinTime = try values.decode(Date.self, forKey: .joinTime)
self.avatar = URL(string: try values.decodeIfPresent(String.self, forKey: .avatar) ?? "")
self.about = try values.decodeIfPresent(String.self, forKey: .about)
self.followerCount = try values.decodeIfPresent(Int.self, forKey: .followerCount) ?? 0
self.followingCount = try values.decodeIfPresent(Int.self, forKey: .followingCount) ?? 0
self.membershipCount = try values.decodeIfPresent(Int.self, forKey: .membershipCount) ?? 0
let birthDayString = try values.decode(String.self, forKey: .birthday)
let birthdayFormatter = DateFormatter()
birthdayFormatter.dateFormat = "MM/dd/yyyy"
birthdayFormatter.locale = Locale(identifier: "en_US_POSIX")
self.birthday = birthdayFormatter.date(from: birthDayString)
}
enum CodingKeys: String, CodingKey {
case username
case email
case joinTime = "jointime"
case avatar
case birthday
case about
case followerCount = "follower_count"
case followingCount = "following_count"
case membershipCount = "membership_count"
}
}
struct ForumThread: Codable {
let id: String
let title: String
let authorId: String
let createdAt: Date?
let contributors: [String: UserProfile]
init(id: String, title: String, authorId: String, createdAt: Date, contributors: [String: UserProfile]) {
self.id = id
self.title = title
self.authorId = authorId
self.createdAt = createdAt
self.contributors = contributors
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.id = try values.decode(String.self, forKey: .id)
self.title = try values.decode(String.self, forKey: .title)
self.authorId = try values.decode(String.self, forKey: .authorId)
self.contributors = try values.decode([String: UserProfile].self, forKey: .contributors)
if let createdAt = TimeInterval(try values.decode(String.self, forKey: .createdAt)) {
self.createdAt = Date(timeIntervalSince1970: createdAt)
} else {
self.createdAt = nil
}
}
enum CodingKeys: String, CodingKey {
case id
case title
case authorId = "author"
case createdAt = "timestamp"
case contributors
}
}
struct Member: Codable {
let username: String
let avatar: URL?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.username = try values.decode(String.self, forKey: .username)
self.avatar = URL(string: try values.decode(String.self, forKey: .avatar))
}
enum CodingKeys: String, CodingKey {
case username
case avatar
}
}
struct ThreadMessage: Codable {
let id: String
let authorId: String
let content: String
let createdAt: Date?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.id = try values.decode(String.self, forKey: .id)
self.authorId = try values.decode(String.self, forKey: .authorId)
self.content = try values.decode(String.self, forKey: .content)
if let createdAt = TimeInterval(try values.decode(String.self, forKey: .createdAt)) {
self.createdAt = Date(timeIntervalSince1970: createdAt)
} else {
self.createdAt = nil
}
}
enum CodingKeys: String, CodingKey {
case id
case authorId = "author"
case content
case createdAt = "timestamp"
}
}
struct DirectMessage: Codable {
/// may be empty for outgoing
let fromUserId: String?
/// may be empty for incoming
let toUserId: String?
let content: String?
let isRead: Bool
let sentTime: Date?
init(fromUserId: String? = nil, toUserId: String? = nil, content: String? = nil, isRead: Bool = false, sentTime: Date? = nil) {
self.fromUserId = fromUserId
self.toUserId = toUserId
self.content = content
self.isRead = isRead
self.sentTime = sentTime
}
enum CodingKeys: String, CodingKey {
case fromUserId = "from"
case toUserId = "to"
case content = "message"
case isRead = "is_read"
case sentTime = "timestamp"
}
}
struct Group: Codable {
let id: String
let title: String
let description: String
let creatorId: String
let cover: URL?
let membersCounter: Int
let memberIds: [String]
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.id = try values.decode(String.self, forKey: .id)
self.title = try values.decode(String.self, forKey: .title)
self.description = try values.decode(String.self, forKey: .description)
self.creatorId = try values.decode(String.self, forKey: .creatorId)
self.cover = URL(string: try values.decode(String.self, forKey: .cover))
self.membersCounter = Int(try values.decode(String.self, forKey: .membersCounter)) ?? 0
self.memberIds = try values.decodeIfPresent([String].self, forKey: .memberIds) ?? []
}
enum CodingKeys: String, CodingKey {
case id
case title
case description
case creatorId = "creator"
case cover
case membersCounter = "count"
case memberIds = "members"
}
}
struct StarsStatEntry: Codable {
let title: String
let stars: Int
init(title: String, stars: Int = 0) {
self.title = title
self.stars = stars
}
enum CodingKeys: String, CodingKey {
case title
case stars = "star_count"
}
}
struct ContentComment: Codable {
let content: String
let createTime: Date
let authorId: String
init(content: String, createTime: Date, authorId: String) {
self.content = content
self.createTime = createTime
self.authorId = authorId
}
enum CodingKeys: String, CodingKey {
case content
case createTime
case authorId = "author"
}
}
| 30.979424 | 206 | 0.640011 |
20211e38f9c49029cd58743a6a4590d7f88bf5a9 | 11,673 | //
// MovieCollectionViewController.swift
//
//
// Created by Nghia Nguyen on 5/13/17.
//
//
import UIKit
import AlamofireImage
import MBProgressHUD
import AFNetworking
class MovieCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate, UIScrollViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var networkErrButton : UIButton?
var movies : [[String:Any]] = []
var filterMovies : [[String:Any]] = []
let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed"
let searchBar = UISearchBar()
var endPoint: String?
var isMoreDataLoading = false
var requestedPage = 1
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
collectionView.dataSource = self
collectionView.delegate = self
collectionView.frame = self.view.frame
searchBar.delegate = self
searchBar.placeholder = "Search movie"
self.navigationItem.titleView = searchBar
// Network error button
networkErrButton = UIButton(frame: CGRect(x: collectionView.bounds.origin.x, y: collectionView.bounds.origin.y, width: collectionView.bounds.width, height: searchBar.bounds.height+30))
networkErrButton?.backgroundColor = UIColor.gray
networkErrButton?.setTitle("Network Error!", for: .normal)
networkErrButton?.isEnabled = true
networkErrButton?.isHidden = true
networkErrButton?.addTarget(self, action: #selector(fetch_data), for: UIControlEvents.touchUpInside)
collectionView.addSubview(networkErrButton!)
// Initialize a UIRefreshControl
let refreshControl = UIRefreshControl()
let attributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 14)]
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh", attributes: attributes)
refreshControl.addTarget(self, action: #selector(update_data(_:)), for: UIControlEvents.valueChanged)
// add refresh control to collection view
collectionView.insertSubview(refreshControl, at: 0)
networkErrButton?.isHidden = false
// fetch_data()
}
override func viewWillAppear(_ animated: Bool) {
if networkErrButton?.isHidden == false {
fetch_data()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Collection View Data Source
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filterMovies.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
searchBar.resignFirstResponder()
}
// func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// print("yo header")
// let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerCollectionView", for: indexPath)
// let label = UILabel(frame: headerView.frame)
// label.textColor = UIColor.white
// label.text = "Test"
// headerView.addSubview(label)
// return headerView
// }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "movieCell", for: indexPath) as! MovieCell
cell.frame = CGRect(x: cell.frame.origin.x, y: cell.frame.origin.y, width: collectionView.frame.size.width/2, height: 250)
cell.movieImage.frame.size = cell.frame.size
let movie = self.filterMovies[indexPath.row]
if let poster_path = movie["poster_path"] as? String {
let base_url = "https://image.tmdb.org/t/p/w500/"
let poster_url = URL(string: base_url + poster_path)
let imageRequest = URLRequest(url: poster_url!)
cell.movieImage.setImageWith(imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in
if imageResponse != nil {
cell.movieImage.alpha = 0.0
cell.movieImage.image = image
UIView.animate(withDuration: 0.4, animations: { () -> Void in
cell.movieImage.alpha = 1.0
})
} else {
cell.movieImage.image = image
}
}, failure: { (imageRequest, imageResponse, error) -> Void in
//handle err
})
} else {
cell.movieImage.image = nil
}
return cell
}
// MARK: - Search Bar
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print("change")
filterMovies = searchText.isEmpty ? movies : movies.filter {
(item: [String: Any]) -> Bool in
let title = item["title"] as! String
return title.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil
}
collectionView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
if searchBar.text != "" {
collectionView.reloadData()
}
searchBar.text = ""
searchBar.showsCancelButton = false
searchBar.resignFirstResponder()
filterMovies = movies
}
// MARK: - Scroll View
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (!isMoreDataLoading) {
// Condition to request data bottom of view up 300
let scrollViewContentHeight = collectionView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - collectionView.bounds.size.height - 300
// When the user has scrolled past the threshold, start requesting
if (scrollView.contentOffset.y > scrollOffsetThreshold && collectionView.isDragging) {
isMoreDataLoading = true
// load more data
loadMoreData()
}
}
}
// MARK: - Network call
func update_data(_ refreshControl: UIRefreshControl) {
let url = URL(string: "https://api.themoviedb.org/3/movie/\(self.endPoint!)?api_key=\(self.apiKey)")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
// Hide HUD once the network request comes back (must be done on main UI thread)
if let data = data {
if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// print(dataDictionary)
self.movies = dataDictionary["results"] as! [[String:Any]]
self.filterMovies = self.movies
// print(self.movies)
self.collectionView.reloadData()
self.networkErrButton?.isHidden = true
}
} else {
print("Error here")
self.networkErrButton?.isHidden = false
}
refreshControl.endRefreshing()
}
task.resume()
}
func fetch_data() {
let url = URL(string: "https://api.themoviedb.org/3/movie/\(self.endPoint!)?api_key=\(self.apiKey)")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
// Display HUD right before the request is made
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.mode = MBProgressHUDMode.indeterminate
hud.label.text = "Loading..."
let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
// Hide HUD once the network request comes back (must be done on main UI thread)
if let data = data {
if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// print(dataDictionary)
self.movies = dataDictionary["results"] as! [[String:Any]]
self.filterMovies = self.movies
// print(self.movies)
self.collectionView.reloadData()
self.networkErrButton?.isHidden = true
}
} else {
self.networkErrButton?.isHidden = false
}
MBProgressHUD.hide(for: self.view, animated: true)
}
task.resume()
}
func loadMoreData() {
requestedPage += 1
let url = URL(string: "https://api.themoviedb.org/3/movie/\(self.endPoint!)?api_key=\(self.apiKey)&page=\(requestedPage)")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
// Hide HUD once the network request comes back (must be done on main UI thread)
if let data = data {
if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
// print(dataDictionary)
self.movies.append(contentsOf: dataDictionary["results"] as! [[String:Any]])
self.filterMovies = self.movies
self.collectionView.reloadData()
self.networkErrButton?.isHidden = true
self.isMoreDataLoading = false
}
} else {
self.networkErrButton?.isHidden = false
}
}
task.resume()
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "detailMovie" {
let cell = sender as! MovieCell
let indexPath = collectionView.indexPath(for: cell)
let movie = filterMovies[(indexPath!.row)]
print(movie)
let destVC = segue.destination as! DetailMovieViewController
destVC.movie = movie
}
}
}
| 44.215909 | 192 | 0.617579 |
ffe336ef9684f1497ea6d88ab83ea981cb8bf449 | 993 | //
// HeaderRecomderReusableView.swift
// ZW-DouYu-Swift3.0
//
// Created by xuxichen on 2017/1/23.
// Copyright © 2017年 xxc. All rights reserved.
//
import UIKit
class HeaderRecomderReusableView: UICollectionReusableView {
// MARK- 控件属性
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var moreBtn: UIButton!
// MARK - 定义模型
var group: AnchorGroup? {
didSet {
titleLabel.text = group?.tag_name
iconImageView.image = UIImage(named: group?.icon_name ?? "home_header_normal")
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
// MARK:- 从Xib中快速创建的类方法
extension HeaderRecomderReusableView {
class func collectionHeaderView() -> HeaderRecomderReusableView {
return Bundle.main.loadNibNamed("HeaderRecomderReusableView", owner: nil, options: nil)?.first as! HeaderRecomderReusableView
}
}
| 26.837838 | 133 | 0.677744 |
1cc9c5b74faa50ceea39dbb31fad13bf61aa064b | 4,598 | //
// AppDelegate.swift
// EmployeeData
//
// Created by Yunyan Shi on 10/31/19.
// Copyright © 2019 Yunyan Shi. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "EmployeeData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 48.914894 | 285 | 0.687255 |
1d614eb1e4769b4d18e4f7b8b3f4da8d3d249a2c | 20,350 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// Source file delete_identity.proto
import Foundation
public extension Services.User.Actions{ public struct DeleteIdentity { }}
public func == (lhs: Services.User.Actions.DeleteIdentity.RequestV1, rhs: Services.User.Actions.DeleteIdentity.RequestV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = fieldCheck && (lhs.hasIdentity == rhs.hasIdentity) && (!lhs.hasIdentity || lhs.identity == rhs.identity)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public func == (lhs: Services.User.Actions.DeleteIdentity.ResponseV1, rhs: Services.User.Actions.DeleteIdentity.ResponseV1) -> Bool {
if (lhs === rhs) {
return true
}
var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)
fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields))
return fieldCheck
}
public extension Services.User.Actions.DeleteIdentity {
public struct DeleteIdentityRoot {
public static var sharedInstance : DeleteIdentityRoot {
struct Static {
static let instance : DeleteIdentityRoot = DeleteIdentityRoot()
}
return Static.instance
}
public var extensionRegistry:ExtensionRegistry
init() {
extensionRegistry = ExtensionRegistry()
registerAllExtensions(extensionRegistry)
Services.User.Containers.ContainersRoot.sharedInstance.registerAllExtensions(extensionRegistry)
}
public func registerAllExtensions(registry:ExtensionRegistry) {
}
}
final public class RequestV1 : GeneratedMessage, GeneratedMessageProtocol {
public private(set) var hasIdentity:Bool = false
public private(set) var identity:Services.User.Containers.IdentityV1!
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
if hasIdentity {
try output.writeMessage(1, value:identity)
}
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
if hasIdentity {
if let varSizeidentity = identity?.computeMessageSize(1) {
serialize_size += varSizeidentity
}
}
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.User.Actions.DeleteIdentity.RequestV1> {
var mergedArray = Array<Services.User.Actions.DeleteIdentity.RequestV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.User.Actions.DeleteIdentity.RequestV1? {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFromData(data, extensionRegistry:Services.User.Actions.DeleteIdentity.DeleteIdentityRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
return Services.User.Actions.DeleteIdentity.RequestV1.classBuilder() as! Services.User.Actions.DeleteIdentity.RequestV1.Builder
}
public func getBuilder() -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
return classBuilder() as! Services.User.Actions.DeleteIdentity.RequestV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.User.Actions.DeleteIdentity.RequestV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.User.Actions.DeleteIdentity.RequestV1.Builder()
}
public func toBuilder() throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
return try Services.User.Actions.DeleteIdentity.RequestV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.User.Actions.DeleteIdentity.RequestV1) throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
return try Services.User.Actions.DeleteIdentity.RequestV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
if hasIdentity {
output += "\(indent) identity {\n"
try identity?.writeDescriptionTo(&output, indent:"\(indent) ")
output += "\(indent) }\n"
}
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
if hasIdentity {
if let hashValueidentity = identity?.hashValue {
hashCode = (hashCode &* 31) &+ hashValueidentity
}
}
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.User.Actions.DeleteIdentity.RequestV1"
}
override public func className() -> String {
return "Services.User.Actions.DeleteIdentity.RequestV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.User.Actions.DeleteIdentity.RequestV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.User.Actions.DeleteIdentity.RequestV1 = Services.User.Actions.DeleteIdentity.RequestV1()
public func getMessage() -> Services.User.Actions.DeleteIdentity.RequestV1 {
return builderResult
}
required override public init () {
super.init()
}
public var hasIdentity:Bool {
get {
return builderResult.hasIdentity
}
}
public var identity:Services.User.Containers.IdentityV1! {
get {
if identityBuilder_ != nil {
builderResult.identity = identityBuilder_.getMessage()
}
return builderResult.identity
}
set (value) {
builderResult.hasIdentity = true
builderResult.identity = value
}
}
private var identityBuilder_:Services.User.Containers.IdentityV1.Builder! {
didSet {
builderResult.hasIdentity = true
}
}
public func getIdentityBuilder() -> Services.User.Containers.IdentityV1.Builder {
if identityBuilder_ == nil {
identityBuilder_ = Services.User.Containers.IdentityV1.Builder()
builderResult.identity = identityBuilder_.getMessage()
if identity != nil {
try! identityBuilder_.mergeFrom(identity)
}
}
return identityBuilder_
}
public func setIdentity(value:Services.User.Containers.IdentityV1!) -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
self.identity = value
return self
}
public func mergeIdentity(value:Services.User.Containers.IdentityV1) throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
if builderResult.hasIdentity {
builderResult.identity = try Services.User.Containers.IdentityV1.builderWithPrototype(builderResult.identity).mergeFrom(value).buildPartial()
} else {
builderResult.identity = value
}
builderResult.hasIdentity = true
return self
}
public func clearIdentity() -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
identityBuilder_ = nil
builderResult.hasIdentity = false
builderResult.identity = nil
return self
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
builderResult = Services.User.Actions.DeleteIdentity.RequestV1()
return self
}
public override func clone() throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
return try Services.User.Actions.DeleteIdentity.RequestV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.User.Actions.DeleteIdentity.RequestV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.User.Actions.DeleteIdentity.RequestV1 {
let returnMe:Services.User.Actions.DeleteIdentity.RequestV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.User.Actions.DeleteIdentity.RequestV1) throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
if other == Services.User.Actions.DeleteIdentity.RequestV1() {
return self
}
if (other.hasIdentity) {
try mergeIdentity(other.identity)
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.RequestV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
case 10 :
let subBuilder:Services.User.Containers.IdentityV1.Builder = Services.User.Containers.IdentityV1.Builder()
if hasIdentity {
try subBuilder.mergeFrom(identity)
}
try input.readMessage(subBuilder, extensionRegistry:extensionRegistry)
identity = subBuilder.buildPartial()
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
final public class ResponseV1 : GeneratedMessage, GeneratedMessageProtocol {
required public init() {
super.init()
}
override public func isInitialized() -> Bool {
return true
}
override public func writeToCodedOutputStream(output:CodedOutputStream) throws {
try unknownFields.writeToCodedOutputStream(output)
}
override public func serializedSize() -> Int32 {
var serialize_size:Int32 = memoizedSerializedSize
if serialize_size != -1 {
return serialize_size
}
serialize_size = 0
serialize_size += unknownFields.serializedSize()
memoizedSerializedSize = serialize_size
return serialize_size
}
public class func parseArrayDelimitedFromInputStream(input:NSInputStream) throws -> Array<Services.User.Actions.DeleteIdentity.ResponseV1> {
var mergedArray = Array<Services.User.Actions.DeleteIdentity.ResponseV1>()
while let value = try parseFromDelimitedFromInputStream(input) {
mergedArray += [value]
}
return mergedArray
}
public class func parseFromDelimitedFromInputStream(input:NSInputStream) throws -> Services.User.Actions.DeleteIdentity.ResponseV1? {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeDelimitedFromInputStream(input)?.build()
}
public class func parseFromData(data:NSData) throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFromData(data, extensionRegistry:Services.User.Actions.DeleteIdentity.DeleteIdentityRoot.sharedInstance.extensionRegistry).build()
}
public class func parseFromData(data:NSData, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()
}
public class func parseFromInputStream(input:NSInputStream) throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFromInputStream(input).build()
}
public class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream) throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFromCodedInputStream(input).build()
}
public class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()
}
public class func getBuilder() -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
return Services.User.Actions.DeleteIdentity.ResponseV1.classBuilder() as! Services.User.Actions.DeleteIdentity.ResponseV1.Builder
}
public func getBuilder() -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
return classBuilder() as! Services.User.Actions.DeleteIdentity.ResponseV1.Builder
}
public override class func classBuilder() -> MessageBuilder {
return Services.User.Actions.DeleteIdentity.ResponseV1.Builder()
}
public override func classBuilder() -> MessageBuilder {
return Services.User.Actions.DeleteIdentity.ResponseV1.Builder()
}
public func toBuilder() throws -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
return try Services.User.Actions.DeleteIdentity.ResponseV1.builderWithPrototype(self)
}
public class func builderWithPrototype(prototype:Services.User.Actions.DeleteIdentity.ResponseV1) throws -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
return try Services.User.Actions.DeleteIdentity.ResponseV1.Builder().mergeFrom(prototype)
}
override public func writeDescriptionTo(inout output:String, indent:String) throws {
unknownFields.writeDescriptionTo(&output, indent:indent)
}
override public var hashValue:Int {
get {
var hashCode:Int = 7
hashCode = (hashCode &* 31) &+ unknownFields.hashValue
return hashCode
}
}
//Meta information declaration start
override public class func className() -> String {
return "Services.User.Actions.DeleteIdentity.ResponseV1"
}
override public func className() -> String {
return "Services.User.Actions.DeleteIdentity.ResponseV1"
}
override public func classMetaType() -> GeneratedMessage.Type {
return Services.User.Actions.DeleteIdentity.ResponseV1.self
}
//Meta information declaration end
final public class Builder : GeneratedMessageBuilder {
private var builderResult:Services.User.Actions.DeleteIdentity.ResponseV1 = Services.User.Actions.DeleteIdentity.ResponseV1()
public func getMessage() -> Services.User.Actions.DeleteIdentity.ResponseV1 {
return builderResult
}
required override public init () {
super.init()
}
override public var internalGetResult:GeneratedMessage {
get {
return builderResult
}
}
public override func clear() -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
builderResult = Services.User.Actions.DeleteIdentity.ResponseV1()
return self
}
public override func clone() throws -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
return try Services.User.Actions.DeleteIdentity.ResponseV1.builderWithPrototype(builderResult)
}
public override func build() throws -> Services.User.Actions.DeleteIdentity.ResponseV1 {
try checkInitialized()
return buildPartial()
}
public func buildPartial() -> Services.User.Actions.DeleteIdentity.ResponseV1 {
let returnMe:Services.User.Actions.DeleteIdentity.ResponseV1 = builderResult
return returnMe
}
public func mergeFrom(other:Services.User.Actions.DeleteIdentity.ResponseV1) throws -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
if other == Services.User.Actions.DeleteIdentity.ResponseV1() {
return self
}
try mergeUnknownFields(other.unknownFields)
return self
}
public override func mergeFromCodedInputStream(input:CodedInputStream) throws -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
return try mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())
}
public override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Services.User.Actions.DeleteIdentity.ResponseV1.Builder {
let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(self.unknownFields)
while (true) {
let tag = try input.readTag()
switch tag {
case 0:
self.unknownFields = try unknownFieldsBuilder.build()
return self
default:
if (!(try parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag))) {
unknownFields = try unknownFieldsBuilder.build()
return self
}
}
}
}
}
}
}
// @@protoc_insertion_point(global_scope)
| 46.781609 | 210 | 0.712285 |
fcad940e564cd089a45efb997c5510369220a432 | 609 | //
// NearByTableViewCell.swift
// EmmaGuide
//
// Created by Emma Arfelt Kock on 30/07/2017.
// Copyright © 2017 Emma Arfelt. All rights reserved.
//
import UIKit
class NearByTableViewCell: UITableViewCell {
@IBOutlet var arrow: UIImageView!
@IBOutlet var entityName: UILabel!
var entity: Entity!
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
}
}
| 21 | 65 | 0.669951 |
3a8732d3d8bebed2bfe9a3be16c66079a6a71865 | 1,492 | //
// ViewController.swift
// Popover
//
// Created by Tobioka on 2017/10/14.
// Copyright © 2017年 tnantoka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onTap(_ sender: UIButton) {
/// [marker1]
let alertController = UIAlertController(
title: "アクションシート",
message: nil,
preferredStyle: .actionSheet
)
alertController.addAction(
UIAlertAction(
title: "キャンセル",
style: .cancel,
handler: nil
)
)
alertController.addAction(
UIAlertAction(
title: "OK",
style: .default,
handler: nil
)
)
present(alertController, animated: true, completion: nil)
/// [marker1]
/// [marker2]
alertController.popoverPresentationController?.sourceView = sender
alertController.popoverPresentationController?.sourceRect = sender.bounds
alertController.popoverPresentationController?.permittedArrowDirections = [.up]
/// [marker2]
}
}
| 25.724138 | 87 | 0.572386 |
11f897f1f91329973ff3f6ef7f478a66d0060acb | 2,158 | //
// AppDelegate.swift
// JYAVPlayer
//
// Created by 张冬 on 2019/8/19.
// Copyright © 2019 张冬. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.914894 | 285 | 0.753939 |
ff62bab79d7a20dde086c89400c6c6149ba2d31f | 28,493 | //
// WSTagsField.swift
// Whitesmith
//
// Created by Ricardo Pereira on 12/05/16.
// Copyright © 2016 Whitesmith. All rights reserved.
//
import UIKit
public struct WSTagAcceptOption: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let `return` = WSTagAcceptOption(rawValue: 1 << 0)
public static let comma = WSTagAcceptOption(rawValue: 1 << 1)
public static let space = WSTagAcceptOption(rawValue: 1 << 2)
}
@IBDesignable
open class WSTagsField: UIScrollView {
public let textField = BackspaceDetectingTextField()
/// Dedicated text field delegate.
open weak var textDelegate: UITextFieldDelegate?
/// Background color for tag view in normal (non-selected) state.
@IBInspectable open override var tintColor: UIColor! {
didSet {
tagViews.forEach { $0.tintColor = self.tintColor }
}
}
/// Text color for tag view in normal (non-selected) state.
@IBInspectable open var textColor: UIColor? {
didSet {
tagViews.forEach { $0.textColor = self.textColor }
}
}
/// Background color for tag view in normal (selected) state.
@IBInspectable open var selectedColor: UIColor? {
didSet {
tagViews.forEach { $0.selectedColor = self.selectedColor }
}
}
/// Text color for tag view in normal (selected) state.
@IBInspectable open var selectedTextColor: UIColor? {
didSet {
tagViews.forEach { $0.selectedTextColor = self.selectedTextColor }
}
}
@IBInspectable open var delimiter: String = "" {
didSet {
tagViews.forEach { $0.displayDelimiter = self.isDelimiterVisible ? self.delimiter : "" }
}
}
@IBInspectable open var isDelimiterVisible: Bool = false {
didSet {
tagViews.forEach { $0.displayDelimiter = self.isDelimiterVisible ? self.delimiter : "" }
}
}
/// Whether the text field should tokenize strings automatically when the keyboard is dismissed.
@IBInspectable open var shouldTokenizeAfterResigningFirstResponder: Bool = false
@IBInspectable open var maxHeight: CGFloat = CGFloat.infinity {
didSet {
tagViews.forEach { $0.displayDelimiter = self.isDelimiterVisible ? self.delimiter : "" }
}
}
/// Max number of lines of tags can display in WSTagsField before its contents become scrollable. Default value is 0, which means WSTagsField always resize to fit all tags.
@IBInspectable open var numberOfLines: Int = 0 {
didSet {
repositionViews()
}
}
/// Whether or not the WSTagsField should become scrollable
@IBInspectable open var enableScrolling: Bool = true
@IBInspectable open var cornerRadius: CGFloat = 3.0 {
didSet {
tagViews.forEach { $0.cornerRadius = self.cornerRadius }
}
}
@IBInspectable open var borderWidth: CGFloat = 0.0 {
didSet {
tagViews.forEach { $0.borderWidth = self.borderWidth }
}
}
@IBInspectable open var borderColor: UIColor? {
didSet {
if let borderColor = borderColor { tagViews.forEach { $0.borderColor = borderColor } }
}
}
open override var layoutMargins: UIEdgeInsets {
didSet {
tagViews.forEach { $0.layoutMargins = self.layoutMargins }
}
}
@available(*, deprecated, message: "use 'textField.textColor' directly.")
open var fieldTextColor: UIColor? {
didSet {
textField.textColor = fieldTextColor
}
}
@available(iOS 10.0, *)
@available(*, deprecated, message: "use 'textField.fieldTextContentType' directly.")
open var fieldTextContentType: UITextContentType! {
set {
textField.textContentType = newValue
}
get {
return textField.textContentType
}
}
@IBInspectable open var placeholder: String = "Tags" {
didSet {
updatePlaceholderTextVisibility()
}
}
@IBInspectable open var placeholderColor: UIColor? {
didSet {
updatePlaceholderTextVisibility()
}
}
@IBInspectable open var placeholderFont: UIFont? {
didSet {
updatePlaceholderTextVisibility()
}
}
@IBInspectable open var placeholderAlwaysVisible: Bool = false {
didSet {
updatePlaceholderTextVisibility()
}
}
open var font: UIFont? {
didSet {
textField.font = font
tagViews.forEach { $0.font = self.font }
}
}
open var keyboardAppearance: UIKeyboardAppearance = .default {
didSet {
textField.keyboardAppearance = self.keyboardAppearance
tagViews.forEach {
$0.keyboardAppearance = self.keyboardAppearance
}
}
}
@IBInspectable open var readOnly: Bool = false {
didSet {
unselectAllTagViewsAnimated()
textField.isEnabled = !readOnly
repositionViews()
}
}
/// By default, the return key is used to create a tag in the field. You can change it, i.e., to use comma or space key instead.
open var acceptTagOption: WSTagAcceptOption = .return
open override var contentInset: UIEdgeInsets {
didSet {
repositionViews()
}
}
@IBInspectable open var spaceBetweenTags: CGFloat = 2.0 {
didSet {
repositionViews()
}
}
@IBInspectable open var spaceBetweenLines: CGFloat = 2.0 {
didSet {
repositionViews()
}
}
open override var isFirstResponder: Bool {
guard super.isFirstResponder == false, textField.isFirstResponder == false else {
return true
}
for i in 0..<tagViews.count where tagViews[i].isFirstResponder {
return true
}
return false
}
open fileprivate(set) var tags = [WSTag]()
open var tagViews = [WSTagView]()
// MARK: - Events
/// Called when the text field should return.
open var onShouldAcceptTag: ((WSTagsField) -> Bool)?
/// Called when the text field text has changed. You should update your autocompleting UI based on the text supplied.
open var onDidChangeText: ((WSTagsField, _ text: String?) -> Void)?
/// Called when a tag has been added. You should use this opportunity to update your local list of selected items.
open var onDidAddTag: ((WSTagsField, _ tag: WSTag) -> Void)?
/// Called when a tag has been removed. You should use this opportunity to update your local list of selected items.
open var onDidRemoveTag: ((WSTagsField, _ tag: WSTag) -> Void)?
/// Called when a tag has been selected.
open var onDidSelectTagView: ((WSTagsField, _ tag: WSTagView) -> Void)?
/// Called when a tag has been unselected.
open var onDidUnselectTagView: ((WSTagsField, _ tag: WSTagView) -> Void)?
/// Called before a tag is added to the tag list. Here you return false to discard tags you do not want to allow.
open var onValidateTag: ((WSTag, [WSTag]) -> Bool)?
/**
* Called when the user attempts to press the Return key with text partially typed.
* @return A Tag for a match (typically the first item in the matching results),
* or nil if the text shouldn't be accepted.
*/
open var onVerifyTag: ((WSTagsField, _ text: String) -> Bool)?
/**
* Called when the view has updated its own height. If you are
* not using Autolayout, you should use this method to update the
* frames to make sure the tag view still fits.
*/
open var onDidChangeHeightTo: ((WSTagsField, _ height: CGFloat) -> Void)?
// MARK: - Properties
fileprivate var oldIntrinsicContentHeight: CGFloat = 0
fileprivate var estimatedInitialMaxLayoutWidth: CGFloat {
// Workaround: https://stackoverflow.com/questions/42342402/how-can-i-create-a-view-has-intrinsiccontentsize-just-like-uilabel
// "So how the system knows the label's width so that it can calculate the height before layoutSubviews"
// Re: "It calculates it. It asks “around” first by checking the last constraint (if there is one) for width. It asks it subviews (your custom class) for its constrains and then makes the calculations."
// This is necessary because, while using the WSTagsField in a `UITableViewCell` with a dynamic height, the `intrinsicContentSize` is called first than the `layoutSubviews`, which leads to an unknown view width when AutoLayout is being used.
if let superview = superview {
var layoutWidth = superview.frame.width
for constraint in superview.constraints where constraint.firstItem === self && constraint.secondItem === superview {
if constraint.firstAttribute == .leading && constraint.secondAttribute == .leading {
layoutWidth -= constraint.constant
}
if constraint.firstAttribute == .trailing && constraint.secondAttribute == .trailing {
layoutWidth += constraint.constant
}
}
return layoutWidth
}
else {
for constraint in constraints where constraint.firstAttribute == .width {
return constraint.constant
}
}
return 200 //default estimation
}
open var preferredMaxLayoutWidth: CGFloat {
return bounds.width == 0 ? estimatedInitialMaxLayoutWidth : bounds.width
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: self.frame.size.width,
height: min(maxHeight, maxHeightBasedOnNumberOfLines, calculateContentHeight(layoutWidth: preferredMaxLayoutWidth) + contentInset.top + contentInset.bottom))
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return .init(width: size.width, height: calculateContentHeight(layoutWidth: size.width) + contentInset.top + contentInset.bottom)
}
// MARK: -
public override init(frame: CGRect) {
super.init(frame: frame)
internalInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
internalInit()
}
deinit {
if #available(iOS 13, *) {
// Observers should be cleared when NSKeyValueObservation is deallocated.
// Let's just keep the code for older iOS versions unmodified to make
// sure we don't break anything.
layerBoundsObserver = nil
}
else {
if let observer = layerBoundsObserver {
removeObserver(observer, forKeyPath: "layer.bounds")
observer.invalidate()
self.layerBoundsObserver = nil
}
}
}
open override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
tagViews.forEach { $0.setNeedsLayout() }
repositionViews()
}
open override func layoutSubviews() {
super.layoutSubviews()
repositionViews()
}
/// Set corner radius of tag views
open func setCornerRadius(to cornerRadius: CGFloat) {
tagViews.forEach { $0.cornerRadius = cornerRadius }
}
/// Take the text inside of the field and make it a Tag.
open func acceptCurrentTextAsTag() {
if let currentText = tokenizeTextFieldText(), !isTextFieldEmpty {
self.addTag(currentText)
}
}
open var isEditing: Bool {
return self.textField.isEditing
}
open func beginEditing() {
self.textField.becomeFirstResponder()
self.unselectAllTagViewsAnimated(false)
}
open func endEditing() {
// NOTE: We used to check if .isFirstResponder and then resign first responder, but sometimes we noticed
// that it would be the first responder, but still return isFirstResponder=NO.
// So always attempt to resign without checking.
self.textField.resignFirstResponder()
}
open override func reloadInputViews() {
self.textField.reloadInputViews()
}
// MARK: - Adding / Removing Tags
open func addTags(_ tags: [String]) {
tags.forEach { addTag($0) }
}
open func addTags(_ tags: [WSTag]) {
tags.forEach { addTag($0) }
}
open func addTag(_ tag: String) {
addTag(WSTag(tag))
}
open func addTag(_ tag: WSTag) {
if let onValidateTag = onValidateTag, !onValidateTag(tag, self.tags) {
return
}
// else if self.tags.contains(tag) {
// return
// }
self.tags.append(tag)
let tagView = WSTagView(tag: tag)
tagView.font = self.font
tagView.tintColor = self.tintColor
tagView.textColor = self.textColor
tagView.selectedColor = self.selectedColor
tagView.selectedTextColor = self.selectedTextColor
tagView.displayDelimiter = self.isDelimiterVisible ? self.delimiter : ""
tagView.cornerRadius = self.cornerRadius
tagView.borderWidth = self.borderWidth
tagView.borderColor = self.borderColor
tagView.keyboardAppearance = self.keyboardAppearance
tagView.layoutMargins = self.layoutMargins
tagView.onDidRequestSelection = { [weak self] tagView in
self?.selectTagView(tagView, animated: true)
}
tagView.onDidRequestDelete = { [weak self] tagView, replacementText in
// First, refocus the text field
self?.textField.becomeFirstResponder()
if (replacementText?.isEmpty ?? false) == false {
self?.textField.text = replacementText
}
// Then remove the view from our data
if let index = self?.tagViews.firstIndex(of: tagView) {
self?.removeTagAtIndex(index)
}
}
tagView.onDidInputText = { [weak self] tagView, text in
if text == "\n" {
self?.selectNextTag()
} else {
self?.textField.becomeFirstResponder()
self?.textField.text = text
}
}
self.tagViews.append(tagView)
addSubview(tagView)
self.textField.text = ""
onDidAddTag?(self, tag)
// Clearing text programmatically doesn't call this automatically
onTextFieldDidChange(self.textField)
updatePlaceholderTextVisibility()
repositionViews()
}
open func removeTag(_ tag: String) {
removeTag(WSTag(tag))
}
open func removeTag(_ tag: WSTag) {
if let index = self.tags.firstIndex(of: tag) {
removeTagAtIndex(index)
}
}
open func removeTagAtIndex(_ index: Int) {
if index < 0 || index >= self.tags.count { return }
let tagView = self.tagViews[index]
tagView.removeFromSuperview()
self.tagViews.remove(at: index)
let removedTag = self.tags[index]
self.tags.remove(at: index)
onDidRemoveTag?(self, removedTag)
updatePlaceholderTextVisibility()
repositionViews()
}
open func removeTags() {
self.tags.enumerated().reversed().forEach { index, _ in removeTagAtIndex(index) }
}
@discardableResult
open func tokenizeTextFieldText() -> WSTag? {
let text = self.textField.text?.trimmingCharacters(in: CharacterSet.whitespaces) ?? ""
if text.isEmpty == false && (onVerifyTag?(self, text) ?? true) {
let tag = WSTag(text)
addTag(tag)
self.textField.text = ""
onTextFieldDidChange(self.textField)
return tag
}
return nil
}
// MARK: - Actions
@objc open func onTextFieldDidChange(_ sender: AnyObject) {
onDidChangeText?(self, textField.text)
}
// MARK: - Tag selection
open func selectNextTag() {
guard let selectedIndex = tagViews.firstIndex(where: { $0.selected }) else {
return
}
let nextIndex = tagViews.index(after: selectedIndex)
if nextIndex < tagViews.count {
tagViews[selectedIndex].selected = false
tagViews[nextIndex].selected = true
}
else {
textField.becomeFirstResponder()
}
}
open func selectPrevTag() {
guard let selectedIndex = tagViews.firstIndex(where: { $0.selected }) else {
return
}
let prevIndex = tagViews.index(before: selectedIndex)
if prevIndex >= 0 {
tagViews[selectedIndex].selected = false
tagViews[prevIndex].selected = true
}
}
open func selectTagView(_ tagView: WSTagView, animated: Bool = false) {
if self.readOnly {
return
}
if tagView.selected {
tagView.onDidRequestDelete?(tagView, nil)
return
}
tagView.selected = true
tagViews.filter { $0 != tagView }.forEach {
$0.selected = false
onDidUnselectTagView?(self, $0)
}
onDidSelectTagView?(self, tagView)
}
open func unselectAllTagViewsAnimated(_ animated: Bool = false) {
tagViews.forEach {
$0.selected = false
onDidUnselectTagView?(self, $0)
}
}
// MARK: internal & private properties or methods
// Reposition tag views when bounds changes.
fileprivate var layerBoundsObserver: NSKeyValueObservation?
}
// MARK: TextField Properties
extension WSTagsField {
@available(*, deprecated, message: "use 'textField.keyboardType' directly.")
public var keyboardType: UIKeyboardType {
get { return textField.keyboardType }
set { textField.keyboardType = newValue }
}
@available(*, deprecated, message: "use 'textField.returnKeyType' directly.")
public var returnKeyType: UIReturnKeyType {
get { return textField.returnKeyType }
set { textField.returnKeyType = newValue }
}
@available(*, deprecated, message: "use 'textField.spellCheckingType' directly.")
public var spellCheckingType: UITextSpellCheckingType {
get { return textField.spellCheckingType }
set { textField.spellCheckingType = newValue }
}
@available(*, deprecated, message: "use 'textField.autocapitalizationType' directly.")
public var autocapitalizationType: UITextAutocapitalizationType {
get { return textField.autocapitalizationType }
set { textField.autocapitalizationType = newValue }
}
@available(*, deprecated, message: "use 'textField.autocorrectionType' directly.")
public var autocorrectionType: UITextAutocorrectionType {
get { return textField.autocorrectionType }
set { textField.autocorrectionType = newValue }
}
@available(*, deprecated, message: "use 'textField.enablesReturnKeyAutomatically' directly.")
public var enablesReturnKeyAutomatically: Bool {
get { return textField.enablesReturnKeyAutomatically }
set { textField.enablesReturnKeyAutomatically = newValue }
}
public var text: String? {
get { return textField.text }
set { textField.text = newValue }
}
@available(*, deprecated, message: "Use 'inputFieldAccessoryView' instead")
override open var inputAccessoryView: UIView? {
return super.inputAccessoryView
}
open var inputFieldAccessoryView: UIView? {
get { return textField.inputAccessoryView }
set { textField.inputAccessoryView = newValue }
}
var isTextFieldEmpty: Bool {
return textField.text?.isEmpty ?? true
}
}
// MARK: Private functions
extension WSTagsField {
fileprivate func internalInit() {
self.isScrollEnabled = false
self.showsHorizontalScrollIndicator = false
textColor = .white
selectedColor = .gray
selectedTextColor = .black
clipsToBounds = true
textField.backgroundColor = .clear
textField.autocorrectionType = UITextAutocorrectionType.no
textField.autocapitalizationType = UITextAutocapitalizationType.none
textField.spellCheckingType = .no
textField.delegate = self
textField.font = font
addSubview(textField)
layerBoundsObserver = self.observe(\.layer.bounds, options: [.old, .new]) { [weak self] sender, change in
guard change.oldValue?.size.width != change.newValue?.size.width else {
return
}
self?.repositionViews()
}
textField.onDeleteBackwards = { [weak self] in
if self?.readOnly ?? true {
return
}
if self?.isTextFieldEmpty ?? true, let tagView = self?.tagViews.last {
self?.selectTagView(tagView, animated: true)
self?.textField.resignFirstResponder()
}
}
textField.addTarget(self, action: #selector(onTextFieldDidChange(_:)), for: UIControl.Event.editingChanged)
repositionViews()
}
fileprivate func calculateContentHeight(layoutWidth: CGFloat) -> CGFloat {
var totalRect: CGRect = .null
enumerateItemRects(layoutWidth: layoutWidth) { (_, tagRect: CGRect?, textFieldRect: CGRect?) in
if let tagRect = tagRect {
totalRect = tagRect.union(totalRect)
}
else if let textFieldRect = textFieldRect {
totalRect = textFieldRect.union(totalRect)
}
}
return totalRect.height
}
fileprivate func enumerateItemRects(layoutWidth: CGFloat, using closure: (_ tagView: WSTagView?, _ tagRect: CGRect?, _ textFieldRect: CGRect?) -> Void) {
if layoutWidth == 0 {
return
}
let maxWidth: CGFloat = layoutWidth - contentInset.left - contentInset.right
var curX: CGFloat = 0.0
var curY: CGFloat = 0.0
var totalHeight: CGFloat = Constants.STANDARD_ROW_HEIGHT
// Tag views Rects
var tagRect = CGRect.null
for tagView in tagViews {
tagRect = CGRect(origin: CGPoint.zero, size: tagView.sizeToFit(.init(width: maxWidth, height: 0)))
if curX + tagRect.width > maxWidth {
// Need a new line
curX = 0
curY += Constants.STANDARD_ROW_HEIGHT + spaceBetweenLines
totalHeight += Constants.STANDARD_ROW_HEIGHT
}
tagRect.origin.x = curX
// Center our tagView vertically within STANDARD_ROW_HEIGHT
tagRect.origin.y = curY + ((Constants.STANDARD_ROW_HEIGHT - tagRect.height)/2.0)
closure(tagView, tagRect, nil)
curX = tagRect.maxX + self.spaceBetweenTags
}
// Always indent TextField by a little bit
curX += max(0, Constants.TEXT_FIELD_HSPACE - self.spaceBetweenTags)
var availableWidthForTextField: CGFloat = maxWidth - curX
if textField.isEnabled {
var textFieldRect = CGRect.zero
textFieldRect.size.height = Constants.STANDARD_ROW_HEIGHT
if availableWidthForTextField < Constants.MINIMUM_TEXTFIELD_WIDTH {
// If in the future we add more UI elements below the tags,
// isOnFirstLine will be useful, and this calculation is important.
// So leaving it set here, and marking the warning to ignore it
curX = 0 + Constants.TEXT_FIELD_HSPACE
curY += Constants.STANDARD_ROW_HEIGHT + spaceBetweenLines
totalHeight += Constants.STANDARD_ROW_HEIGHT
// Adjust the width
availableWidthForTextField = maxWidth - curX
}
textFieldRect.origin.y = curY
textFieldRect.origin.x = curX
textFieldRect.size.width = availableWidthForTextField
closure(nil, nil, textFieldRect)
}
}
fileprivate func repositionViews() {
if self.bounds.width == 0 {
return
}
var contentRect: CGRect = .null
enumerateItemRects(layoutWidth: self.bounds.width) { (tagView: WSTagView?, tagRect: CGRect?, textFieldRect: CGRect?) in
if let tagRect = tagRect, let tagView = tagView {
tagView.frame = tagRect
tagView.setNeedsLayout()
contentRect = tagRect.union(contentRect)
}
else if let textFieldRect = textFieldRect {
textField.frame = textFieldRect
contentRect = textFieldRect.union(contentRect)
}
}
textField.isHidden = !textField.isEnabled
invalidateIntrinsicContentSize()
let newIntrinsicContentHeight = intrinsicContentSize.height
if constraints.isEmpty {
frame.size.height = newIntrinsicContentHeight.rounded()
}
if oldIntrinsicContentHeight != newIntrinsicContentHeight {
if let didChangeHeightToEvent = self.onDidChangeHeightTo {
didChangeHeightToEvent(self, newIntrinsicContentHeight)
}
oldIntrinsicContentHeight = newIntrinsicContentHeight
}
if self.enableScrolling {
self.isScrollEnabled = contentRect.height + contentInset.top + contentInset.bottom > newIntrinsicContentHeight
}
self.contentSize.width = self.bounds.width - contentInset.left - contentInset.right
self.contentSize.height = contentRect.height
if self.isScrollEnabled {
// FIXME: this isn't working. Need to think in a workaround.
//self.scrollRectToVisible(textField.frame, animated: false)
}
}
fileprivate func updatePlaceholderTextVisibility() {
textField.attributedPlaceholder = (placeholderAlwaysVisible || tags.count == 0) ? attributedPlaceholder() : nil
}
private func attributedPlaceholder() -> NSAttributedString {
var attributes: [NSAttributedString.Key: Any]?
if let placeholderColor = placeholderColor {
attributes = [NSAttributedString.Key.foregroundColor: placeholderColor]
}
if let placeholderFont = placeholderFont {
attributes = [NSAttributedString.Key.font: placeholderFont]
}
return NSAttributedString(string: placeholder, attributes: attributes)
}
private var maxHeightBasedOnNumberOfLines: CGFloat {
guard self.numberOfLines > 0 else {
return CGFloat.infinity
}
return contentInset.top + contentInset.bottom + Constants.STANDARD_ROW_HEIGHT * CGFloat(numberOfLines) + spaceBetweenLines * CGFloat(numberOfLines - 1)
}
}
extension WSTagsField: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
textDelegate?.textFieldDidBeginEditing?(textField)
unselectAllTagViewsAnimated(true)
}
public func textFieldDidEndEditing(_ textField: UITextField) {
if !isTextFieldEmpty, shouldTokenizeAfterResigningFirstResponder {
tokenizeTextFieldText()
}
textDelegate?.textFieldDidEndEditing?(textField)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let onShouldAcceptTag = onShouldAcceptTag, !onShouldAcceptTag(self) {
return false
}
if !isTextFieldEmpty, acceptTagOption.contains(.return) {
tokenizeTextFieldText()
return true
}
return textDelegate?.textFieldShouldReturn?(textField) ?? false
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if acceptTagOption.contains(.comma) && string == "," && onShouldAcceptTag?(self) ?? true {
tokenizeTextFieldText()
return false
}
if acceptTagOption.contains(.space) && string == " " && onShouldAcceptTag?(self) ?? true {
tokenizeTextFieldText()
return false
}
return true
}
}
extension WSTagsField {
public static func == (lhs: UITextField, rhs: WSTagsField) -> Bool {
return lhs == rhs.textField
}
}
| 33.759479 | 249 | 0.628751 |
e4698cf4d21a674744fd2bb8a95c43ffd6848450 | 3,088 | import Foundation
public class WebSocketMessage: Codable {
public let MessageType: String
public var ID: Int?
public var Success: Bool?
public var Payload: [String: Any]?
public var Result: [String: Any]?
public var Message: String?
public var HAVersion: String?
private enum CodingKeys: String, CodingKey {
case MessageType = "type"
case ID = "id"
case Success = "success"
case Payload = "payload"
case Result = "result"
case Message = "message"
case HAVersion = "ha_version"
}
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
MessageType = try values.decode(String.self, forKey: .MessageType)
ID = try? values.decode(Int.self, forKey: .ID)
Success = try? values.decode(Bool.self, forKey: .Success)
Payload = try? values.decode([String: Any].self, forKey: .Payload)
Result = try? values.decode([String: Any].self, forKey: .Result)
Message = try? values.decode(String.self, forKey: .Message)
HAVersion = try? values.decode(String.self, forKey: .HAVersion)
}
public init?(_ dictionary: [String: Any]) {
guard let mType = dictionary["type"] as? String else {
return nil
}
self.MessageType = mType
self.ID = dictionary["id"] as? Int
self.Payload = dictionary["payload"] as? [String: Any]
self.Result = dictionary["result"] as? [String: Any]
self.Success = dictionary["success"] as? Bool
}
public init(_ incomingMessage: WebSocketMessage, _ result: [String: Any]) {
self.ID = incomingMessage.ID
self.MessageType = "result"
self.Result = result
self.Success = true
}
public init(id: Int, type: String, result: [String: Any], success: Bool = true) {
self.ID = id
self.MessageType = type
self.Result = result
self.Success = success
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(MessageType, forKey: .MessageType)
if let ID = ID {
try container.encode(ID, forKey: .ID)
}
if let Success = Success {
try container.encode(Success, forKey: .Success)
}
if let Message = Message {
try container.encode(Message, forKey: .Message)
}
if let Result = Result {
try container.encode(Result, forKey: .Result)
}
}
init(_ messageType: String) {
self.MessageType = messageType
}
}
extension WebSocketMessage: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
"WebSocketMessage(type: \(MessageType), id: \(String(describing: ID)), payload: \(String(describing: Payload)), result: \(String(describing: Result)), success: \(String(describing: Success)))"
}
public var debugDescription: String {
description
}
}
| 34.696629 | 200 | 0.620466 |
e41f759582ff08cfb0b5ed91c7d182b414bffba8 | 5,211 | //
// InterfaceController.swift
// PokGoWatch Extension
//
// Created by Jose Luis on 16/8/16.
// Copyright © 2016 crass45. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
class InterfaceController: WKInterfaceController, WCSessionDelegate {
var session:WCSession!
@IBOutlet var lbTitle: WKInterfaceLabel!
@IBOutlet var grupoBolas: WKInterfaceGroup!
@IBOutlet var grupoSplash: WKInterfaceGroup!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
if applicationData.count > 0 {
grupoSplash.setHidden(true)
grupoBolas.setHidden(false)
}else{
grupoSplash.setHidden(false)
grupoBolas.setHidden(true)
}
if (WCSession.isSupported()) {
session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// se llama cuando se pulsa una acción en la notificación
func handleActionWithIdentifier(identifier: String?, forLocalNotification localNotification: UILocalNotification, withResponseInfo responseInfo: [NSObject : AnyObject]) {
}
func testCatchHandler( message: [String : AnyObject]) {
if message.count > 0 {
if let status = message["status"] as? String {
if status == "CATCH_ESCAPE"{
let h0 = { print("ok")}
let h1 = {
applicationData = [String: AnyObject]()
self.willActivate()
}
let action1 = WKAlertAction(title: "Reintentar", style: .Default, handler:h0)
let action2 = WKAlertAction(title: "Abandonar", style: .Default, handler:h1)
presentAlertControllerWithTitle("Resultado", message: status, preferredStyle: .ActionSheet, actions: [action1,action2])
}
else {
let h1 = {
applicationData = [String: AnyObject]()
self.willActivate()
}
let action = WKAlertAction(title: "OK", style: .Default, handler:h1)
presentAlertControllerWithTitle("Resultado", message: status, preferredStyle: .ActionSheet, actions: [action])
}
}
}else {
let h0 = { print("ok")}
let action1 = WKAlertAction(title: "OK", style: .Default, handler:h0)
presentAlertControllerWithTitle("Error", message: "Ha ocurrido un error al capturar el Pokemon", preferredStyle: .ActionSheet, actions: [action1])
}
}
@IBAction func lanzaPokeball() {
var datosPokeball = applicationData
datosPokeball["accion"] = "LanzaPokeball"
self.lbTitle.setText("WAITING HANDLER")
session.sendMessage(datosPokeball, replyHandler: {(respuesta)->Void in
print(respuesta)
// handle reply from iPhone app here
self.lbTitle.setText("HANDLER")
if respuesta.count > 0 {
if let status = respuesta["status"] as? String {
self.lbTitle.setText(status)
}else {
self.lbTitle.setText("No hay status")
}
}
else{
self.lbTitle.setText("Respuesta count 0")
}
self.testCatchHandler(respuesta)
}, errorHandler: {(error )->Void in
// catch any errors here
print(error.localizedDescription)
})
}
@IBAction func lanzaSuperBall() {
var datosPokeball = applicationData
datosPokeball["accion"] = "LanzaSuperBall"
session.sendMessage(datosPokeball, replyHandler: {(respuesta)->Void in
print(respuesta)
// handle reply from iPhone app here
}, errorHandler: {(error )->Void in
// catch any errors here
print(error.localizedDescription)
})
}
@IBAction func lanzaUltraBall() {
var datosPokeball = applicationData
datosPokeball["accion"] = "LanzaUltraBall"
session.sendMessage(datosPokeball, replyHandler: {(respuesta)->Void in
print(respuesta)
// handle reply from iPhone app here
}, errorHandler: {(error )->Void in
// catch any errors here
print(error.localizedDescription)
})
}
}
| 34.058824 | 174 | 0.545769 |
fb2343515b0bba92a3eea2cbdab826116b5a275f | 3,562 | //
// The MIT License
//
// Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.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.
//
//
// AAValetMode.swift
// AutoAPI
//
// Generated by AutoAPIGenerator for Swift.
// Copyright © 2021 High-Mobility GmbH. All rights reserved.
//
import Foundation
import HMUtilities
public final class AAValetMode: AACapability, AAPropertyIdentifying {
/// Information about the introduction and last update of this capability.
public enum API: AAAPICurrent {
/// Level (version) of *AutoAPI* when `AAValetMode` was introduced to the spec.
public static let intro: UInt8 = 3
/// Level (version) of *AutoAPI* when `AAValetMode` was last updated.
public static let updated: UInt8 = 11
}
// MARK: Identifiers
public class override var identifier: UInt16 { 0x0028 }
/// Property identifiers for `AAValetMode`.
public enum PropertyIdentifier: UInt8, CaseIterable {
case status = 0x01
}
// MARK: Properties
/// Status value.
public var status: AAProperty<AAActiveState>?
// MARK: Getters
/// Get `AAValetMode` state (all properties).
///
/// - returns: The request as `[UInt8]` to send to the vehicle.
public static func getValetMode() -> [UInt8] {
AAAutoAPI.protocolVersion.bytes + Self.identifier.bytes + AACommandType.get.rawValue.bytes
}
/// Get `AAValetMode` state properties availability.
///
/// - returns: The request as `[UInt8]` to send to the vehicle.
public static func getValetModeAvailability() -> [UInt8] {
AAAutoAPI.protocolVersion.bytes + Self.identifier.bytes + AACommandType.availability.rawValue.bytes
}
// MARK: Setters
/// Activate or deactivate valet mode.
///
/// - parameters:
/// - status: Status value.
///
/// - returns: Command as `[UInt8]` to send to the vehicle.
public static func activateDeactivateValetMode(status: AAActiveState) -> [UInt8] {
var properties: [AAOpaqueProperty?] = []
properties.append(AAProperty(id: PropertyIdentifier.status, value: status))
let propertiesBytes = properties.compactMap { $0 }.sorted { $0.id < $1.id }.flatMap { $0.bytes }
return setterHeader + propertiesBytes
}
// MARK: AACapability
public required init?(bytes: [UInt8]) {
super.init(bytes: bytes)
status = extract(property: .status)
}
}
| 32.678899 | 107 | 0.676305 |
6728ae16e91c4ab1ef21828fa0c11ceeaedb1b09 | 3,566 | //
// ModalTransitionDelegate.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-25.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
enum ModalType {
case regular
case transactionDetail
}
class ModalTransitionDelegate: NSObject, Subscriber {
// MARK: - Public
init(type: ModalType) {
self.type = type
super.init()
}
func reset() {
isInteractive = false
presentedViewController = nil
if let panGr = panGestureRecognizer {
UIApplication.shared.keyWindow?.removeGestureRecognizer(panGr)
}
Store.trigger(name: .showStatusBar)
}
var shouldDismissInteractively = true
// MARK: - Private
fileprivate let type: ModalType
fileprivate var isInteractive: Bool = false
fileprivate let interactiveTransition = UIPercentDrivenInteractiveTransition()
fileprivate var presentedViewController: UIViewController?
fileprivate var panGestureRecognizer: UIPanGestureRecognizer?
private var yVelocity: CGFloat = 0.0
private var progress: CGFloat = 0.0
private let velocityThreshold: CGFloat = 50.0
private let progressThreshold: CGFloat = 0.5
@objc fileprivate func didUpdate(gr: UIPanGestureRecognizer) {
guard shouldDismissInteractively else { return }
switch gr.state {
case .began:
isInteractive = true
presentedViewController?.dismiss(animated: true, completion: nil)
case .changed:
guard let vc = presentedViewController else { break }
let yOffset = gr.translation(in: vc.view).y
let progress = yOffset/vc.view.bounds.height
yVelocity = gr.velocity(in: vc.view).y
self.progress = progress
interactiveTransition.update(progress)
case .cancelled:
reset()
interactiveTransition.cancel()
case .ended:
if transitionShouldFinish {
reset()
interactiveTransition.finish()
} else {
isInteractive = false
interactiveTransition.cancel()
}
case .failed:
break
case .possible:
break
@unknown default:
assertionFailure("unknown gesture")
}
}
private var transitionShouldFinish: Bool {
if progress > progressThreshold || yVelocity > velocityThreshold {
return true
} else {
return false
}
}
}
extension ModalTransitionDelegate: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
presentedViewController = presented
return PresentModalAnimator(shouldCoverBottomGap: type == .regular, completion: {
let panGr = UIPanGestureRecognizer(target: self, action: #selector(ModalTransitionDelegate.didUpdate(gr:)))
UIApplication.shared.keyWindow?.addGestureRecognizer(panGr)
self.panGestureRecognizer = panGr
})
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissModalAnimator()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return isInteractive ? interactiveTransition : nil
}
}
| 33.641509 | 170 | 0.663769 |
18f669c7f47e731fde4e502c7031ce97977221b4 | 179 | import Cocoa
class SidebarTableRowView: NSTableRowView {
override var isEmphasized: Bool {
set {}
get {
return false;
}
}
}
| 13.769231 | 43 | 0.519553 |
907b5b94b0e3ba7a0baeaef3592186b6f0b61ba0 | 1,442 | // --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// 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
/// a schema types that are primitive language values
typealias PrimitiveSchema = ValueSchema
| 46.516129 | 79 | 0.680999 |
fe275652d182da63a1eaa25029f2ecdf0544aa10 | 1,292 | //
// AttentionListRequest.swift
// Hollow
//
// Created on 2021/1/18.
//
import Foundation
import Alamofire
/// Fetch the posts in the user's attention list.
public struct AttentionListRequest: DefaultRequest {
public typealias Configuration = PostListRequest.Configuration
typealias Result = PostListRequest.Result
public typealias ResultData = [PostWrapper]
public typealias Error = DefaultRequestError
var configuration: Configuration
public init(configuration: Configuration) {
self.configuration = configuration
}
public func performRequest(completion: @escaping (ResultType<ResultData, Error>) -> Void) {
let urlPath = "v3/contents/post/attentions" + Constants.urlSuffix
let headers: HTTPHeaders = [
"TOKEN": self.configuration.token,
"Accept": "application/json"
]
let parameters: [String : Encodable] = [
"page" : configuration.page
]
performRequest(
urlRoot: self.configuration.apiRoot,
urlPath: urlPath,
parameters: parameters,
headers: headers,
method: .get,
transformer: { $0.toPostWrappers() },
completion: completion
)
}
}
| 28.086957 | 95 | 0.627709 |
ac32c98d9876706137400622c0f94709ce9dc77d | 3,754 | //
// ViewController.swift
// AANotifier
//
// Created by Engr. Ahsan Ali on 02/11/2017.
// Copyright © 2017 AA-Creations. All rights reserved.
//
import UIKit
import AANotifier
class ViewController: UIViewController {
lazy var toastViewNotifier: AANotifier = {
let notifierView = UIView.fromNib(nibName: "ToastView")!
let options: [AANotifierOptions] = [
.deadline(2.0),
.transitionA(.fromBottom, 0.4),
.transitionB(.toBottom, 5.0),
.position(.bottom),
.preferedHeight(50),
.margins(H: 60, V: 40)
]
let notifier = AANotifier(notifierView, withOptions: options)
return notifier
}()
lazy var statusViewNotifier: AANotifier = {
let notifierView = UIView.fromNib(nibName: "StatusView")!
let options: [AANotifierOptions] = [
.deadline(2.0),
.preferedHeight(50),
.margins(H: 0, V: 30),
.position(.top),
.transitionA(.fromTop, 0.8),
.transitionB(.toTop, 0.8)
]
let notifier = AANotifier(notifierView, withOptions: options)
return notifier
}()
lazy var popupViewNotifier: AANotifier = {
let notifierView = UIView.fromNib(nibName: "PopupView")!
let options: [AANotifierOptions] = [
.deadline(2.0),
.position(.middle),
.preferedHeight(250),
.margins(H: 20, V: nil),
.transitionA(.fromTop, 0.8),
.transitionB(.toBottom, 0.8)
]
let button = notifierView.viewWithTag(100) as! UIButton
button.addTarget(self, action: #selector(hidePopupView), for: .touchUpInside)
let notifier = AANotifier(notifierView, withOptions: options)
return notifier
}()
lazy var infoViewNotifier: AANotifier = {
let notifierView = UIView.fromNib(nibName: "InfoView")!
let options: [AANotifierOptions] = [
.deadline(2.0),
.position(.top),
.preferedHeight(80),
.transitionA(.fromTop, 0.8),
.transitionB(.toTop, 0.8)
]
let notifier = AANotifier(notifierView, withOptions: options)
return notifier
}()
lazy var snackBarViewNotifier: AANotifier = {
let notifierView = LikeView()
let options: [AANotifierOptions] = [
.deadline(2.0),
.position(.bottom),
.preferedHeight(60),
.hideOnTap,
.transitionA(.fromBottom, 0.8),
.transitionB(.toLeft, 0.8)
]
let notifier = AANotifier(notifierView, withOptions: options)
notifierView.notifer = notifier
return notifier
}()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func hidePopupView() {
popupViewNotifier.hide()
}
}
extension ViewController {
@IBAction func snackBarViewAction(_ sender: Any) {
snackBarViewNotifier.show()
}
@IBAction func bannerViewAction(_ sender: Any) {
infoViewNotifier.show()
}
@IBAction func toastViewAction(_ sender: Any) {
let notifier = toastViewNotifier
notifier.didTapped = {
notifier.hide()
}
notifier.show()
}
@IBAction func statusViewAction(_ sender: Any) {
statusViewNotifier.show()
}
@IBAction func popupViewAction(_ sender: Any) {
popupViewNotifier.show()
}
}
| 25.889655 | 85 | 0.566596 |
332fb1a4ce9a78f9e1b191d089f8feb8393e7d63 | 603 | //
// FavoriteButton.swift
// LandmarksSwiftUI
//
// Created by Adem Deliaslan on 28.03.2022.
//
import SwiftUI
struct FavoriteButton: View {
@Binding var isSet: Bool
var body: some View {
Button {
isSet.toggle()
} label: {
Label("Toggle Favorite", systemImage: isSet ? "star.fill" : "star")
.labelStyle(.iconOnly)
.foregroundColor(isSet ? .yellow : .gray)
}
}
}
struct FavoriteButton_Previews: PreviewProvider {
static var previews: some View {
FavoriteButton(isSet: .constant(true))
}
}
| 21.535714 | 79 | 0.588723 |
564320201630ce63ee15b7776f244c3259a3cb96 | 7,868 | // Copyright 2022 Pera Wallet, LDA
// 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.
//
// TransactionsListLayout.swift
import UIKit
import MacaroonUIKit
final class TransactionsListLayout: NSObject {
private lazy var theme = Theme()
lazy var handlers = Handlers()
private var sizeCache: [String: CGSize] = [:]
private let draft: TransactionListing
private weak var transactionsDataSource: TransactionsDataSource?
init(draft: TransactionListing, transactionsDataSource: TransactionsDataSource?) {
self.draft = draft
self.transactionsDataSource = transactionsDataSource
super.init()
}
}
extension TransactionsListLayout: UICollectionViewDelegateFlowLayout {
func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
guard let itemIdentifier = transactionsDataSource?.itemIdentifier(for: indexPath) else {
return CGSize((collectionView.bounds.width, 0))
}
switch itemIdentifier {
case .algosInfo(let item):
return listView(
collectionView,
layout: collectionViewLayout,
sizeForAlgosDetailInfo: item
)
case .assetInfo(let item):
return listView(
collectionView,
layout: collectionViewLayout,
sizeForAssetDetailInfo: item
)
case .filter:
return CGSize(theme.transactionHistoryFilterCellSize)
case .transaction, .pending, .reward:
return CGSize(theme.transactionHistoryCellSize)
case .title:
return CGSize(theme.transactionHistoryTitleCellSize)
case .empty(let emptyState):
switch emptyState {
case .algoTransactionHistoryLoading:
var theme = AlgoTransactionHistoryLoadingViewCommonTheme()
theme.buyAlgoVisible = !draft.accountHandle.value.isWatchAccount()
let cellHeight = AlgoTransactionHistoryLoadingCell.height(
for: theme
)
return CGSize(width: collectionView.bounds.width - 48, height: cellHeight)
case .assetTransactionHistoryLoading:
let cellHeight = AssetTransactionHistoryLoadingCell.height(
for: AssetTransactionHistoryLoadingViewCommonTheme()
)
return CGSize(width: collectionView.bounds.width - 48, height: cellHeight)
case .transactionHistoryLoading:
return CGSize(width: collectionView.bounds.width - 48, height: 500)
default:
let width = collectionView.bounds.width
var height = collectionView.bounds.height -
collectionView.adjustedContentInset.bottom -
collectionView.contentInset.top -
theme.transactionHistoryTitleCellSize.h
if draft.type != .all {
let sizeCacheIdentifier = draft.type == .algos ?
AlgosDetailInfoViewCell.reuseIdentifier : AssetDetailInfoViewCell.reuseIdentifier
let cachedInfoSize = sizeCache[sizeCacheIdentifier]
if let cachedInfoSize = cachedInfoSize {
height -= cachedInfoSize.height
}
}
return CGSize((width, height))
}
case .nextList:
return CGSize((collectionView.bounds.width, 100))
}
}
func collectionView(
_ collectionView: UICollectionView,
willDisplay cell: UICollectionViewCell,
forItemAt indexPath: IndexPath
) {
handlers.willDisplay?(cell, indexPath)
}
func collectionView(
_ collectionView: UICollectionView,
didEndDisplaying cell: UICollectionViewCell,
forItemAt indexPath: IndexPath
) {
guard let itemIdentifier = transactionsDataSource?.itemIdentifier(for: indexPath) else {
return
}
switch itemIdentifier {
case .nextList:
let loadingCell = cell as! LoadingCell
loadingCell.stopAnimating()
case .empty(let emptyState):
switch emptyState {
case .loading:
let loadingCell = cell as! LoadingCell
loadingCell.stopAnimating()
case .algoTransactionHistoryLoading:
let loadingCell = cell as! AlgoTransactionHistoryLoadingCell
loadingCell.stopAnimating()
case .assetTransactionHistoryLoading:
let loadingCell = cell as! AssetTransactionHistoryLoadingCell
loadingCell.stopAnimating()
case .transactionHistoryLoading:
let loadingCell = cell as? TransactionHistoryLoadingCell
loadingCell?.stopAnimating()
default:
break
}
case .pending:
guard let pendingTransactionCell = cell as? PendingTransactionCell else {
return
}
pendingTransactionCell.stopAnimating()
default:
break
}
}
func collectionView(
_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath
) {
handlers.didSelect?(indexPath)
}
}
extension TransactionsListLayout {
private func listView(
_ listView: UICollectionView,
layout listViewLayout: UICollectionViewLayout,
sizeForAssetDetailInfo item: AssetDetailInfoViewModel
) -> CGSize {
let sizeCacheIdentifier = AssetDetailInfoViewCell.reuseIdentifier
if let cachedSize = sizeCache[sizeCacheIdentifier] {
return cachedSize
}
let width = calculateContentWidth(for: listView)
let size = AssetDetailInfoViewCell.calculatePreferredSize(
item,
for: AssetDetailInfoViewCell.theme,
fittingIn: CGSize((width, .greatestFiniteMagnitude))
)
sizeCache[sizeCacheIdentifier] = size
return size
}
private func listView(
_ listView: UICollectionView,
layout listViewLayout: UICollectionViewLayout,
sizeForAlgosDetailInfo item: AlgosDetailInfoViewModel
) -> CGSize {
let sizeCacheIdentifier = AlgosDetailInfoViewCell.reuseIdentifier
if let cachedSize = sizeCache[sizeCacheIdentifier] {
return cachedSize
}
let width = calculateContentWidth(for: listView)
let size = AlgosDetailInfoViewCell.calculatePreferredSize(
item,
for: AlgosDetailInfoViewCell.theme,
fittingIn: CGSize((width, .greatestFiniteMagnitude))
)
sizeCache[sizeCacheIdentifier] = size
return size
}
}
extension TransactionsListLayout {
private func calculateContentWidth(
for listView: UICollectionView
) -> LayoutMetric {
return listView.bounds.width - listView.contentInset.horizontal
}
}
extension TransactionsListLayout {
struct Handlers {
var willDisplay: ((UICollectionViewCell, IndexPath) -> Void)?
var didSelect: ((IndexPath) -> Void)?
}
}
| 34.968889 | 101 | 0.633071 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.