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
f5a05162270fdccb281d2feb93841e7bd903c475
7,951
// // CLIExtractorTests.swift // ApolloCodegenTests // // Created by Ellen Shapiro on 10/7/19. // Copyright © 2019 Apollo GraphQL. All rights reserved. // import XCTest @testable import ApolloCodegenLib // Only available on macOS #if os(macOS) class CLIExtractorTests: XCTestCase { override func setUp() { super.setUp() CodegenTestHelper.downloadCLIIfNeeded() CodegenTestHelper.deleteExistingApolloFolder() } private func checkSHASUMFileContentsDirectly(at url: URL, match expected: String, file: StaticString = #file, line: UInt = #line) { guard let contents = try? String(contentsOf: url, encoding: .utf8) else { XCTFail("Could not load file at \(url.path)", file: file, line: line) return } XCTAssertEqual(contents, expected, "Direct check of SHASUM failed. Got \(contents), expected \(expected)", file: #file, line: #line) } private func validateSHASUMFile(shouldBeValid: Bool, apolloFolderURL: URL, match expected: String, file: StaticString = #file, line: UInt = #line) { do { let isValid = try CLIExtractor.validateSHASUMInExtractedFile(apolloFolderURL: apolloFolderURL, expected: expected) XCTAssertEqual(isValid, shouldBeValid, file: file, line: line) } catch { XCTFail("Error validating shasum in extracted file: \(error)", file: file, line: line) } } func validateCLIIsExtractedWithRealSHASUM(file: StaticString = #file, line: UInt = #line) { let binaryFolderURL = CodegenTestHelper.binaryFolderURL() XCTAssertTrue(FileManager.default.apollo_folderExists(at: binaryFolderURL), "Binary folder doesn't exist at \(binaryFolderURL)", file: file, line: line) let binaryURL = ApolloFilePathHelper.binaryURL(fromBinaryFolder: binaryFolderURL) XCTAssertTrue(FileManager.default.apollo_fileExists(at: binaryURL), "Binary doesn't exist at \(binaryURL)", file: file, line: line) let shasumFileURL = CodegenTestHelper.shasumFileURL() self.checkSHASUMFileContentsDirectly(at: shasumFileURL, match: CLIExtractor.expectedSHASUM, file: file, line: line) } func testValidatingSHASUMWithMatchingWorks() throws { let cliFolderURL = CodegenTestHelper.cliFolderURL() let zipFileURL = ApolloFilePathHelper.zipFileURL(fromCLIFolder: cliFolderURL) try CLIExtractor.validateZipFileSHASUM(at: zipFileURL, expected: CLIExtractor.expectedSHASUM) } func testValidatingSHASUMFailsWithoutMatch() throws { let cliFolderURL = CodegenTestHelper.cliFolderURL() let zipFileURL = ApolloFilePathHelper.zipFileURL(fromCLIFolder: cliFolderURL) let bogusSHASUM = CLIExtractor.expectedSHASUM + "NOPE" do { try CLIExtractor.validateZipFileSHASUM(at: zipFileURL, expected: bogusSHASUM) XCTFail("This should not have validated!") } catch { switch error { case CLIExtractor.CLIExtractorError.zipFileHasInvalidSHASUM(let expectedSHASUM, let gotSHASUM): XCTAssertEqual(expectedSHASUM, bogusSHASUM) XCTAssertEqual(gotSHASUM, CLIExtractor.expectedSHASUM) default: XCTFail("Unexpected error: \(error)") } } } func testExtractingZip() throws { // Check that the binary hasn't already been extracted // (it should be getting deleted in `setUp`) let binaryFolderURL = CodegenTestHelper.binaryFolderURL() XCTAssertFalse(FileManager.default.apollo_folderExists(at: binaryFolderURL)) // Actually extract the CLI let cliFolderURL = CodegenTestHelper.cliFolderURL() let extractedURL = try CLIExtractor.extractCLIIfNeeded(from: cliFolderURL) // Make sure we're getting the binary folder path back and that something's now there. XCTAssertEqual(extractedURL.path, binaryFolderURL.path) self.validateCLIIsExtractedWithRealSHASUM() // Make sure the validator is working let apolloFolderURL = CodegenTestHelper.apolloFolderURL() self.validateSHASUMFile(shouldBeValid: true, apolloFolderURL: apolloFolderURL, match: CLIExtractor.expectedSHASUM) self.validateSHASUMFile(shouldBeValid: false, apolloFolderURL: apolloFolderURL, match: "NOPE") } func testReExtractingZipWithDifferentSHA() throws { // Extract the existing CLI let cliFolderURL = CodegenTestHelper.cliFolderURL() _ = try CLIExtractor.extractCLIIfNeeded(from: cliFolderURL) // Validate that it extracted and has the correct shasum self.validateCLIIsExtractedWithRealSHASUM() // Replace the SHASUM file URL with a fake that doesn't match let shasumFileURL = CodegenTestHelper.shasumFileURL() let fakeSHASUM = "Old Shasum" try fakeSHASUM.write(to: shasumFileURL, atomically: true, encoding: .utf8) // Validation should now fail since the SHASUMs don't match let apolloFolderURL = CodegenTestHelper.apolloFolderURL() XCTAssertFalse(try CLIExtractor.validateSHASUMInExtractedFile(apolloFolderURL: apolloFolderURL)) // Now try extracting again, and check SHASUM is now real again _ = try CLIExtractor.extractCLIIfNeeded(from: cliFolderURL) self.validateCLIIsExtractedWithRealSHASUM() } func testFolderExistsButMissingSHASUMFileReExtractionWorks() throws { // Make sure there is an apollo folder but no `.shasum` file let apolloFolder = CodegenTestHelper.apolloFolderURL() try FileManager.default.apollo_createFolderIfNeeded(at: apolloFolder) let cliFolderURL = CodegenTestHelper.cliFolderURL() // Now try extracting again, and check SHASUM is now real again _ = try CLIExtractor.extractCLIIfNeeded(from: cliFolderURL) self.validateCLIIsExtractedWithRealSHASUM() } func testCorrectSHASUMButMissingBinaryReExtractionWorks() throws { // Write just the SHASUM file, but nothing else try CodegenTestHelper.writeSHASUMOnly(CLIExtractor.expectedSHASUM) // Make sure the binary folder's not there let binaryFolderURL = CodegenTestHelper.binaryFolderURL() XCTAssertFalse(FileManager.default.apollo_folderExists(at: binaryFolderURL)) // Re-extract and now everything should be there let cliFolderURL = CodegenTestHelper.cliFolderURL() _ = try CLIExtractor.extractCLIIfNeeded(from: cliFolderURL) self.validateCLIIsExtractedWithRealSHASUM() } func testMissingSHASUMFileButCorrectZipFileCreatesSHASUMFile() throws { let shasumFileURL = CodegenTestHelper.shasumFileURL() try FileManager.default.apollo_deleteFile(at: shasumFileURL) XCTAssertFalse(FileManager.default.apollo_fileExists(at: shasumFileURL)) let cliFolderURL = CodegenTestHelper.cliFolderURL() let zipFileURL = ApolloFilePathHelper.zipFileURL(fromCLIFolder: cliFolderURL) XCTAssertTrue(FileManager.default.apollo_fileExists(at: zipFileURL)) let binaryURL = try CLIExtractor.extractCLIIfNeeded(from: cliFolderURL) /// Was the binary extracted? XCTAssertTrue(FileManager.default.apollo_folderExists(at: binaryURL)) /// Did the SHASUM file get created? XCTAssertTrue(FileManager.default.apollo_fileExists(at: shasumFileURL)) self.validateCLIIsExtractedWithRealSHASUM() } } #endif
40.360406
120
0.6735
3302ed0e176942427be9c269d2969a13c4cf3255
118
import XCTest import SwiftMVCTests var tests = [XCTestCaseEntry]() tests += SwiftMVCTests.allTests() XCTMain(tests)
14.75
33
0.779661
e84e830857c780d68404ce8f3bae802aa2ed21d2
5,041
// // TreeTrunk.swift // // Created by Zack Brown on 01/07/2021. // import Euclid import GameKit import SwiftUI import Meadow class TreeTrunk: Codable, Hashable, ObservableObject { static let `default`: TreeTrunk = TreeTrunk(stump: .default, trunk: .default) enum CodingKeys: CodingKey { case stump case trunk } @Published var stump: Stump @Published var trunk: Trunk init(stump: Stump, trunk: Trunk) { self.stump = stump self.trunk = trunk } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) stump = try container.decode(Stump.self, forKey: .stump) trunk = try container.decode(Trunk.self, forKey: .trunk) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(stump, forKey: .stump) try container.encode(trunk, forKey: .trunk) } func hash(into hasher: inout Hasher) { hasher.combine(stump) hasher.combine(trunk) } static func == (lhs: TreeTrunk, rhs: TreeTrunk) -> Bool { return lhs.stump == rhs.stump && lhs.trunk == rhs.trunk } } extension TreeTrunk: Prop { typealias Builder = (polygons: [Euclid.Polygon], position: Vector, plane: Euclid.Plane) func build(position: Vector) -> [Euclid.Polygon] { guard let plane = Plane(normal: .up, pointOnPlane: .zero) else { return [] } return build(position: position, plane: plane).polygons } func build(position: Vector, plane: Euclid.Plane) -> Builder { let legUVs = UVs(start: Vector(x: 0, y: 0.5, z: 0), end: Vector(x: 1, y: 0.75, z: 0)) let trunkUVs = UVs(start: Vector(x: 0, y: 0.75, z: 0), end: Vector(x: 1, y: 1, z: 0)) let sample = Double.random(in: 0..<1, using: &rng) let curveStep = 1.0 / Double(trunk.slices) let yStep = trunk.height / Double(trunk.slices) let offset = Vector(sample * trunk.spread, trunk.height, sample * trunk.spread) let control = Vector(0, trunk.height, 0) let normal = curve(start: position, end: offset, control: control, interpolator: curveStep) var mesh = Euclid.Mesh([]) // /// Create trunk segments // var slices: [[Vector]] = [] var rotation = Euclid.Angle(radians: Math.pi2 / Double(trunk.segments)) for slice in 0...trunk.slices { let interpolator = curveStep * Double(slice) var layer: [Vector] = [] let length = (1.0 - Math.ease(curve: .out, value: interpolator)) * (trunk.baseRadius - trunk.peakRadius) let radius = slice == 0 ? trunk.baseRadius : (trunk.peakRadius + length) for segment in 0..<trunk.segments { let angle = (rotation * Double(segment)) + (rotation / 2.0) let distance = Double(slice) * yStep var point = plot(radians: angle.radians, radius: radius).project(onto: plane) + (plane.normal * (distance)) if slice == 0 { point.y += TrunkLeg.Constants.floor } layer.append(point) } slices.append(layer) if slices.count > 1 { let lower = slices.removeFirst() guard let upper = slices.first else { continue } let trunkSlice = TrunkSlice(upper: upper, lower: lower, cap: (slice == 1 ? .throne : slice == trunk.slices ? .apex : nil), textureCoordinates: trunkUVs) mesh = mesh.union(Mesh(trunkSlice.build(position: position))) } } // /// Create stump legs // guard let plane = Plane(normal: normal, pointOnPlane: .zero) else { return ([], position, plane) } rotation = Euclid.Angle(radians: Math.pi2 / Double(stump.legs)) for leg in 0..<stump.legs { let angle = (rotation.radians * Double(leg)) let trunkLeg = TrunkLeg(plane: plane, angle: angle, spread: stump.spread, innerRadius: stump.innerRadius, outerRadius: stump.outerRadius, peak: stump.peak, base: stump.base, segments: stump.segments, textureCoordinates: legUVs) mesh = mesh.union(Mesh(trunkLeg.build(position: position))) } return (mesh.polygons, slices.last?.average() ?? position, plane) } }
32.314103
239
0.525094
67cdea747ceba3e38683a85616ee0ef74d0b1ea6
4,977
@testable import SwiftLintFramework import XCTest struct RuleWithLevelsMock: ConfigurationProviderRule { var configuration = SeverityLevelsConfiguration(warning: 2, error: 3) static let description = RuleDescription(identifier: "severity_level_mock", name: "", description: "", kind: .style, deprecatedAliases: ["mock"]) init() {} init(configuration: Any) throws { self.init() try self.configuration.apply(configuration: configuration) } func validate(file: SwiftLintFile) -> [StyleViolation] { return [] } } class RuleTests: XCTestCase { fileprivate struct RuleMock1: Rule { var configurationDescription: String { return "N/A" } static let description = RuleDescription(identifier: "RuleMock1", name: "", description: "", kind: .style) init() {} init(configuration: Any) throws { self.init() } func validate(file: SwiftLintFile) -> [StyleViolation] { return [] } } fileprivate struct RuleMock2: Rule { var configurationDescription: String { return "N/A" } static let description = RuleDescription(identifier: "RuleMock2", name: "", description: "", kind: .style) init() {} init(configuration: Any) throws { self.init() } func validate(file: SwiftLintFile) -> [StyleViolation] { return [] } } fileprivate struct RuleWithLevelsMock2: ConfigurationProviderRule { var configuration = SeverityLevelsConfiguration(warning: 2, error: 3) static let description = RuleDescription(identifier: "violation_level_mock2", name: "", description: "", kind: .style) init() {} init(configuration: Any) throws { self.init() try self.configuration.apply(configuration: configuration) } func validate(file: SwiftLintFile) -> [StyleViolation] { return [] } } func testRuleIsEqualTo() { XCTAssertTrue(RuleMock1().isEqualTo(RuleMock1())) } func testRuleIsNotEqualTo() { XCTAssertFalse(RuleMock1().isEqualTo(RuleMock2())) } func testRuleArraysWithDifferentCountsNotEqual() { XCTAssertFalse([RuleMock1(), RuleMock2()] == [RuleMock1()]) } func testSeverityLevelRuleInitsWithConfigDictionary() { let config = ["warning": 17, "error": 7] let rule = try? RuleWithLevelsMock(configuration: config) var comp = RuleWithLevelsMock() comp.configuration.warning = 17 comp.configuration.error = 7 XCTAssertEqual(rule?.isEqualTo(comp), true) } func testSeverityLevelRuleInitsWithWarningOnlyConfigDictionary() { let config = ["warning": 17] let rule = try? RuleWithLevelsMock(configuration: config) var comp = RuleWithLevelsMock() comp.configuration.warning = 17 comp.configuration.error = nil XCTAssertEqual(rule?.isEqualTo(comp), true) } func testSeverityLevelRuleInitsWithErrorOnlyConfigDictionary() { let config = ["error": 17] let rule = try? RuleWithLevelsMock(configuration: config) var comp = RuleWithLevelsMock() comp.configuration.error = 17 XCTAssertEqual(rule?.isEqualTo(comp), true) } func testSeverityLevelRuleInitsWithConfigArray() { let config = [17, 7] as Any let rule = try? RuleWithLevelsMock(configuration: config) var comp = RuleWithLevelsMock() comp.configuration.warning = 17 comp.configuration.error = 7 XCTAssertEqual(rule?.isEqualTo(comp), true) } func testSeverityLevelRuleInitsWithSingleValueConfigArray() { let config = [17] as Any let rule = try? RuleWithLevelsMock(configuration: config) var comp = RuleWithLevelsMock() comp.configuration.warning = 17 comp.configuration.error = nil XCTAssertEqual(rule?.isEqualTo(comp), true) } func testSeverityLevelRuleInitsWithLiteral() { let config = 17 as Any let rule = try? RuleWithLevelsMock(configuration: config) var comp = RuleWithLevelsMock() comp.configuration.warning = 17 comp.configuration.error = nil XCTAssertEqual(rule?.isEqualTo(comp), true) } func testSeverityLevelRuleNotEqual() { let config = 17 as Any let rule = try? RuleWithLevelsMock(configuration: config) XCTAssertEqual(rule?.isEqualTo(RuleWithLevelsMock()), false) } func testDifferentSeverityLevelRulesNotEqual() { XCTAssertFalse(RuleWithLevelsMock().isEqualTo(RuleWithLevelsMock2())) } }
35.805755
85
0.610006
39e83716c91ad6dfb1912c44a52cde8b3bad264f
6,950
/* See LICENSE folder for this sample’s licensing information. Abstract: Combines video frames and JET depth frames. */ import CoreMedia import CoreVideo import Metal import MetalKit class VideoMixer { var description: String = "Video Mixer" var isPrepared = false private(set) var inputFormatDescription: CMFormatDescription? private(set) var outputFormatDescription: CMFormatDescription? private var outputPixelBufferPool: CVPixelBufferPool? private let metalDevice = MTLCreateSystemDefaultDevice()! private var renderPipelineState: MTLRenderPipelineState? private var sampler: MTLSamplerState? private var textureCache: CVMetalTextureCache! private lazy var commandQueue: MTLCommandQueue? = { return self.metalDevice.makeCommandQueue() }() private var fullRangeVertexBuffer: MTLBuffer? var mixFactor: Float = 1.0 init() { let vertexData: [Float] = [ -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0 ] fullRangeVertexBuffer = metalDevice.makeBuffer(bytes: vertexData, length: vertexData.count * MemoryLayout<Float>.size, options: []) let defaultLibrary = metalDevice.makeDefaultLibrary()! let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.vertexFunction = defaultLibrary.makeFunction(name: "vertexMixer") pipelineDescriptor.fragmentFunction = defaultLibrary.makeFunction(name: "fragmentMixer") do { renderPipelineState = try metalDevice.makeRenderPipelineState(descriptor: pipelineDescriptor) } catch { fatalError("Unable to create video mixer pipeline state. (\(error))") } // To determine how our textures are sampled, we create a sampler descriptor, which // is used to ask for a sampler state object from our device. let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.minFilter = .linear samplerDescriptor.magFilter = .linear sampler = metalDevice.makeSamplerState(descriptor: samplerDescriptor) } func prepare(with videoFormatDescription: CMFormatDescription, outputRetainedBufferCountHint: Int) { reset() (outputPixelBufferPool, _, outputFormatDescription) = allocateOutputBufferPool(with: videoFormatDescription, outputRetainedBufferCountHint: outputRetainedBufferCountHint) if outputPixelBufferPool == nil { return } inputFormatDescription = videoFormatDescription var metalTextureCache: CVMetalTextureCache? if CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, metalDevice, nil, &metalTextureCache) != kCVReturnSuccess { assertionFailure("Unable to allocate video mixer texture cache") } else { textureCache = metalTextureCache } isPrepared = true } func reset() { outputPixelBufferPool = nil outputFormatDescription = nil inputFormatDescription = nil textureCache = nil isPrepared = false } struct MixerParameters { var mixFactor: Float } func mix(videoPixelBuffer: CVPixelBuffer, depthPixelBuffer: CVPixelBuffer) -> CVPixelBuffer? { if !isPrepared { assertionFailure("Invalid state: Not prepared") return nil } var newPixelBuffer: CVPixelBuffer? CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, outputPixelBufferPool!, &newPixelBuffer) guard let outputPixelBuffer = newPixelBuffer else { print("Allocation failure: Could not get pixel buffer from pool (\(self.description))") return nil } guard let outputTexture = makeTextureFromCVPixelBuffer(pixelBuffer: outputPixelBuffer), let inputTexture0 = makeTextureFromCVPixelBuffer(pixelBuffer: videoPixelBuffer), let inputTexture1 = makeTextureFromCVPixelBuffer(pixelBuffer: depthPixelBuffer) else { return nil } var parameters = MixerParameters(mixFactor: mixFactor) let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = outputTexture guard let fullRangeVertexBuffer = fullRangeVertexBuffer else { print("Failed to create Metal vertex buffer") CVMetalTextureCacheFlush(textureCache!, 0) return nil } guard let sampler = sampler else { print("Failed to create Metal sampler") CVMetalTextureCacheFlush(textureCache!, 0) return nil } // Set up command queue, buffer, and encoder guard let commandQueue = commandQueue, let commandBuffer = commandQueue.makeCommandBuffer(), let commandEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { print("Failed to create Metal command queue") CVMetalTextureCacheFlush(textureCache!, 0) return nil } commandEncoder.label = "Video Mixer" commandEncoder.setRenderPipelineState(renderPipelineState!) commandEncoder.setVertexBuffer(fullRangeVertexBuffer, offset: 0, index: 0) commandEncoder.setFragmentTexture(inputTexture0, index: 0) commandEncoder.setFragmentTexture(inputTexture1, index: 1) commandEncoder.setFragmentSamplerState(sampler, index: 0) commandEncoder.setFragmentBytes( UnsafeMutableRawPointer(&parameters), length: MemoryLayout<MixerParameters>.size, index: 0) commandEncoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) commandEncoder.endEncoding() commandBuffer.commit() return outputPixelBuffer } func makeTextureFromCVPixelBuffer(pixelBuffer: CVPixelBuffer) -> MTLTexture? { let width = CVPixelBufferGetWidth(pixelBuffer) let height = CVPixelBufferGetHeight(pixelBuffer) // Create a Metal texture from the image buffer var cvTextureOut: CVMetalTexture? CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, textureCache, pixelBuffer, nil, .bgra8Unorm, width, height, 0, &cvTextureOut) guard let cvTexture = cvTextureOut, let texture = CVMetalTextureGetTexture(cvTexture) else { print("Video mixer failed to create preview texture") CVMetalTextureCacheFlush(textureCache, 0) return nil } return texture } }
38.611111
148
0.659137
67e519dfa3b19390876b6640e45dced40b9cb04f
129
// // Created by Mike on 7/31/21. // import Foundation internal struct LayoutPass: Hashable { internal let uuid = UUID() }
12.9
38
0.674419
674aea4db1bfc5a92229843dee842f60fbaebb1b
447
// // SequenceType.swift // KPCTabsControl // // Created by Christian Tietze on 04/08/16. // Licensed under the MIT License (see LICENSE file) // import Foundation extension Sequence { internal func findFirst(_ predicate: (Self.Iterator.Element) -> Bool) -> Self.Iterator.Element? { for element in self { if predicate(element) { return element } } return nil } }
19.434783
101
0.592841
48d81b43de1dcfd1fcf1ace1712283bdb5c90302
3,609
// // Copyright (c) 2018 cauli.works // // 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 /// The NoCacheFloret modifies the desigantedRequest and the response of a record /// to prevent returning cached data or writing data to the cache. /// /// On the designatedRequest it will: /// * change the **cachePolicy** to **.reloadIgnoringLocalCacheData** /// * **remove** the value for the **If-Modified-Since** key on allHTTPHeaderFields /// * **remove** the value for the **If-None-Match** key on allHTTPHeaderFields /// * change **Cache-Control** to **no-cache** /// /// On the response it will: /// * **remove** the value for the **Last-Modified** key on allHTTPHeaderFields /// * **remove** the value for the **ETag** key on allHTTPHeaderFields /// * change **Expires** to **0** /// * change **Cache-Control** to **no-cache** public class NoCacheFloret: FindReplaceFloret { /// Public initalizer to create an instance of the `NoCacheFloret`. public required init() { let willRequestReplaceDefinition = RecordModifier(keyPath: \Record.designatedRequest) { designatedRequest -> (URLRequest) in var request = designatedRequest request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData request.setValue(nil, forHTTPHeaderField: "If-Modified-Since") request.setValue(nil, forHTTPHeaderField: "If-None-Match") request.setValue("no-cache", forHTTPHeaderField: "Cache-Control") return request } let didRespondReplaceDefinition = RecordModifier(keyPath: \Record.result) { result in guard case .result(let response)? = result, let httpURLResponse = response.urlResponse as? HTTPURLResponse, let url = httpURLResponse.url else { return result } var allHTTPHeaderFields = httpURLResponse.allHeaderFields as? [String: String] ?? [:] allHTTPHeaderFields.removeValue(forKey: "Last-Modified") allHTTPHeaderFields.removeValue(forKey: "ETag") allHTTPHeaderFields["Expires"] = "0" allHTTPHeaderFields["Cache-Control"] = "no-cache" guard let newHTTPURLRespones = HTTPURLResponse(url: url, statusCode: httpURLResponse.statusCode, httpVersion: nil, headerFields: allHTTPHeaderFields) else { return result } return Result.result(Response(newHTTPURLRespones, data: response.data)) } super.init(willRequestModifiers: [willRequestReplaceDefinition], didRespondModifiers: [didRespondReplaceDefinition], name: "NoCacheFloret") } }
50.830986
184
0.714879
083ffbfb1046fb37d0fc1b7dca1393d6861ff9c9
910
// // RWPickFlavorTests.swift // RWPickFlavorTests // // Created by josafa on 6/22/15. // Copyright (c) 2015 josafafilho. All rights reserved. // import UIKit import XCTest class RWPickFlavorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.594595
111
0.61978
d62aa6cc3b34c39eeacf41cc44d89b03be14c9a4
964
// // CatalogBaseCell.swift // TelenavDemo // // Created by ezaderiy on 30.10.2020. // import UIKit import TelenavEntitySDK class CatalogBaseCell: UITableViewCell { @IBOutlet weak var mainImageView: UIImageView! @IBOutlet weak var mainLabel: UILabel! @IBOutlet weak var mainImageLeadingConstraint: NSLayoutConstraint! override func awakeFromNib() { super.awakeFromNib() } func fillCategory(_ category: TelenavCategoryDisplayModel) { mainLabel.text = category.category.name if let img = UIImage(named: category.imgName) { mainImageView.image = img } else if let img = UIImage(systemName: category.imgName) { mainImageView.image = img } if category.catLevel > 0 { mainImageLeadingConstraint.constant = CGFloat(15 * category.catLevel) } else { mainImageLeadingConstraint.constant = 10 } } }
24.717949
81
0.643154
fbe3e751f594f2387694afab0411b2bf785eaa1c
2,832
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation /// Motor error. @objc(GSMotorError) public enum MotorError: Int { /// No error. case noError /// Motor is stalled. case stalled /// Motor has been put in security mode. case securityMode /// Motor has been stopped due to emergency. case emergencyStop /// Battery voltage out of bounds. case batteryVoltage /// Incorrect number of LIPO cells. case lipocells /// Too hot or too cold Cypress temperature. case temperature /// Defective MOSFET or broken motor phases. case mosfet /// Other error. case other /// Debug description. public var description: String { switch self { case .noError: return "noError" case .stalled: return "stalled" case .securityMode: return "securityMode" case .emergencyStop: return "emergencyStop" case .batteryVoltage: return "batteryVoltage" case .lipocells: return "lipocells" case .temperature: return "temperature" case .mosfet: return "mosfet" case .other: return "other" } } }
32.551724
76
0.665254
efd4aea1d68ca49e89f58724086934cfdf5117f2
10,977
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import SystemConfiguration import Foundation //swiftlint: disable public enum ReachabilityError: Error { case failedToCreateWithAddress(sockaddr_in) case failedToCreateWithHostname(String) case unableToSetCallback case unableToSetDispatchQueue } @available(*, unavailable, renamed: "Notification.Name.reachabilityChanged") public let reachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") extension Notification.Name { public static let reachabilityChanged = Notification.Name("reachabilityChanged") } func callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() reachability.reachabilityChanged() } public class Reachability { public typealias NetworkReachable = (Reachability) -> Void public typealias NetworkUnreachable = (Reachability) -> Void @available(*, unavailable, renamed: "Conection") public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public enum Connection: CustomStringConvertible { case none, wifi, cellular public var description: String { switch self { case .cellular: return "Cellular" case .wifi: return "WiFi" case .none: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? @available(*, deprecated, renamed: "allowsCellularConnection") public let reachableOnWWAN: Bool = true /// Set to `false` to force Reachability.connection to .none when on cellular connection (default value `true`) public var allowsCellularConnection: Bool // The notification center on which "reachability changed" events are being posted public var notificationCenter: NotificationCenter = NotificationCenter.default @available(*, deprecated, renamed: "connection.description") public var currentReachabilityString: String { return "\(connection)" } @available(*, unavailable, renamed: "connection") public var currentReachabilityStatus: Connection { return connection } public var connection: Connection { guard isReachableFlagSet else { return .none } // If we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return .wifi } var connection = Connection.none if !isConnectionRequiredFlagSet { connection = .wifi } if isConnectionOnTrafficOrDemandFlagSet { if !isInterventionRequiredFlagSet { connection = .wifi } } if isOnWWANFlagSet { if !allowsCellularConnection { connection = .none } else { connection = .cellular } } return connection } fileprivate var previousFlags: SCNetworkReachabilityFlags? fileprivate var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate let reachabilityRef: SCNetworkReachability fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") required public init(reachabilityRef: SCNetworkReachability) { allowsCellularConnection = true self.reachabilityRef = reachabilityRef } public convenience init?(hostname: String) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref) } public convenience init?() { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref = SCNetworkReachabilityCreateWithAddress(nil, &zeroAddress) else { return nil } self.init(reachabilityRef: ref) } deinit { stopNotifier() } } public extension Reachability { // MARK: - *** Notifier methods *** func startNotifier() throws { guard !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.unableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.unableToSetDispatchQueue } // Perform an initial check reachabilitySerialQueue.async { self.reachabilityChanged() } notifierRunning = true } func stopNotifier() { defer { notifierRunning = false } SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** @available(*, deprecated, message: "Please use `connection != .none`") var isReachable: Bool { guard isReachableFlagSet else { return false } if isConnectionRequiredAndTransientFlagSet { return false } if isRunningOnDevice { if isOnWWANFlagSet && !reachableOnWWAN { // We don't want to connect when on cellular connection return false } } return true } @available(*, deprecated, message: "Please use `connection == .cellular`") var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet } @available(*, deprecated, message: "Please use `connection == .wifi`") var isReachableViaWiFi: Bool { // Check we're reachable guard isReachableFlagSet else { return false } // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return true } // Check we're NOT on WWAN return !isOnWWANFlagSet } var description: String { let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func reachabilityChanged() { guard previousFlags != flags else { return } let block = connection != .none ? whenReachable : whenUnreachable DispatchQueue.main.async { block?(self) self.notificationCenter.post(name: .reachabilityChanged, object: self) } previousFlags = flags } var isOnWWANFlagSet: Bool { #if os(iOS) return flags.contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return flags.contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return flags.contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return flags.contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return flags.contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return flags.contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !flags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return flags.contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return flags.contains(.isLocalAddress) } var isDirectFlagSet: Bool { return flags.contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { let value = flags.intersection([.connectionRequired, .transientConnection]) return value == [.connectionRequired, .transientConnection] } var flags: SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(reachabilityRef, &flags) { return flags } else { return SCNetworkReachabilityFlags() } } }
32.865269
115
0.65947
e8e00b28f727eff91004eb8383c1093a2b97781b
7,027
// // MainScreenViewController.swift // Crypticc // // Created by Squiretoss on 1.04.2020. // Copyright © 2020 Oguz Demirhan. All rights reserved. // import UIKit class MainScreenTableViewController: UITableViewController { var baseURL = "https://api.coinranking.com/v1/public/coins" var nameArray = [String]() var iconArray = [String]() var colorArray = [String]() var valueArray = [String]() var descriptionArray = [String]() var highestPriceArray = [String]() var symbolArray = [String]() let delayTime = 1.0 let coinMg = CoinManager() override func viewDidLoad() { super.viewDidLoad() coinMg.getRequest(url: baseURL) { (CyrptoCurrencyItem) in for i in 0...(CyrptoCurrencyItem.data.coins.count-1) { self.nameArray.append(CyrptoCurrencyItem.data.coins[i].name) self.iconArray.append(CyrptoCurrencyItem.data.coins[i].iconURL) self.colorArray.append(CyrptoCurrencyItem.data.coins[i].color ?? "#ffffffff") self.valueArray.append(String(format:"%.2f",Float(CyrptoCurrencyItem.data.coins[i].price)!)) self.descriptionArray.append(CyrptoCurrencyItem.data.coins[i].coinDescription ?? "lorem ipsum") self.highestPriceArray.append(CyrptoCurrencyItem.data.coins[i].allTimeHigh.price) self.symbolArray.append(CyrptoCurrencyItem.data.coins[i].symbol) } self.baseURL = CyrptoCurrencyItem.data.coins[0].name DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + self.delayTime) { self.tableView.reloadData() self.tableView.delegate = self self.tableView.dataSource = self } print(self.iconArray) } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "descriptionSegue" { let VC = segue.destination as! DescriptionViewController let customIndex = tableView.indexPathForSelectedRow?.row let color = UIColor(hex: "\(colorArray[customIndex!])ff") VC.descriptionText = descriptionArray[(customIndex ?? 0)] //VC.descriptionTextView.backgroundColor = .clear VC.title = nameArray[customIndex!] VC.price = valueArray[customIndex!] VC.highestPrice = String(format:"%.2f",Float(highestPriceArray[customIndex!])!) VC.view.backgroundColor = color } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(indexPath.row) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return nameArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CryptoCurrencyReusableCell", for: indexPath) as! CoinTableViewCell //cell.iconView = UIView(SVGURL: URL(string: iconArray[indexPath.row])!) // let svgString = iconArray[indexPath.row] // cell.wkWebView.loadHTMLString(svgString, baseURL:URL(string: svgString)!) let color = UIColor(hex: "\(colorArray[indexPath.row])ff") cell.coinNameLabel.text = "\(nameArray[indexPath.row]) (\(symbolArray[indexPath.row]))" cell.CoinValueLabel.text = valueArray[indexPath.row] cell.coinNameLabel.textColor = color cell.CoinValueLabel.textColor = color // Configure the cell... return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension UIColor { public convenience init?(hex: String) { let r, g, b, a: CGFloat if hex.hasPrefix("#") { let start = hex.index(hex.startIndex, offsetBy: 1) let hexColor = String(hex[start...]) if hexColor.count == 8 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } } return nil } }
35.135
137
0.612068
b95337725df5b00ed9262b1535d70217584f4df7
2,198
// // ViewController.swift // NFC Reader // // Created by Thomas Prosser on 07.11.17. // Copyright © 2017 thomIT. All rights reserved. // import UIKit import CoreNFC import TICoreNFCExtensions class ViewController: UIViewController, NFCNDEFReaderSessionDelegate { var isScanning = false @IBOutlet weak var payloadLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBAction func scanButtonPressed(_ sender: UIButton) { let readerSession: NFCNDEFReaderSession = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false) if isScanning { readerSession.invalidate() } else { readerSession.begin() } isScanning = !isScanning } func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) { NSLog("Reader Session Ready: \(session.isReady), error: \(error.localizedDescription)") self.isScanning = false } func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]){ var type: String = "Unknown" var text: String = "No Text" for message:NFCNDEFMessage in messages { message.records.forEach({ (record) in NSLog("Record Type: \(record.parsedPayload)") text = record.parsedPayload.encodedPayload! type = record.typeString }) DispatchQueue.main.async { self.typeLabel.text = String(type) self.payloadLabel.text = text } } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func parsePayload(_ payload: Data) -> String { let code = payload.first if(code == 0x01){ return "Well known" } return "something else" } }
25.858824
131
0.577798
e8ae18a8b02c97bc5eb446f5ccee9659f7e4ced3
1,125
// // PXCause.swift // MercadoPagoSDK // // Created by Eden Torres on 10/20/17. // Copyright © 2017 MercadoPago. All rights reserved. // import Foundation /// :nodoc: open class PXCause: NSObject, Codable { open var code: String? open var _description: String? public init(code: String?, description: String?) { self.code = code self._description = description } public enum PXCauseKeys: String, CodingKey { case code case description = "description" } required public convenience init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PXCauseKeys.self) var code = "" do { let codeInt = try container.decodeIfPresent(Int.self, forKey: .code) code = (codeInt?.stringValue)! } catch { let stringId = try container.decodeIfPresent(String.self, forKey: .code) code = stringId! } let description: String? = try container.decodeIfPresent(String.self, forKey: .description) self.init(code: code, description: description) } }
28.125
99
0.632889
21fb3bc5e9aa9cf24d8d157533f16393af12cd67
1,665
// // CommonLabel.swift // Timi // // Created by 田子瑶 on 16/8/30. // Copyright © 2016年 田子瑶. All rights reserved. // import UIKit var xlLabel:UILabel? class CommonLabel: UIView { fileprivate var upLabel:UILabel! fileprivate var downLabel:UILabel! override init(frame: CGRect) { super.init(frame: frame) setupViews() } convenience init(){ self.init(frame: CGRect(x: 0,y: 0,width: 60, height: 60)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUpLabel(_ text:String) { upLabel.text = text upLabel.sizeToFit() } func setDownLabel(_ text:String) { downLabel.text = text downLabel.sizeToFit() } fileprivate func setupViews() { let downLabel = UILabel() downLabel.textAlignment = .center downLabel.sizeToFit() self.downLabel = downLabel self.addSubview(downLabel) downLabel.snp_makeConstraints {[weak self] (make) in if let weakSelf = self{ make.centerX.equalTo(weakSelf.snp_centerX) make.bottom.equalTo(weakSelf.snp_bottom) } } let upperLabel = UILabel() upperLabel.textAlignment = .center upperLabel.sizeToFit() self.upLabel = upperLabel self.addSubview(upperLabel) upperLabel.snp_makeConstraints {[weak self] (make) in if let weakSelf = self{ make.centerX.equalTo(weakSelf.snp_centerX) make.top.equalTo(weakSelf.snp_top) } } } }
25.615385
65
0.589189
f77bc967d3d3364c9e52ecd138625accfc08ff39
2,125
//: ## Expander //: ## import AudioKit let file = try AVAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AudioPlayer(file: file) player.looping = true var expander = Expander(player) engine.output = expander try engine.start() player.play() class LiveView: View { override func viewDidLoad() { addTitle("Expander") addView(Button(title: "Stop Expander") { button in let node = expander node.isStarted ? node.stop() : node.play() button.title = node.isStarted ? "Stop Expander" : "Start Expander" }) addView(Slider(property: "Ratio", value: expander.expansionRatio, range: 1 ... 50, format: "%0.2f" ) { sliderValue in expander.expansionRatio = sliderValue }) addView(Slider(property: "Threshold", value: expander.expansionThreshold, range: 1 ... 50, format: "%0.2f" ) { sliderValue in expander.expansionThreshold = sliderValue }) addView(Slider(property: "Attack Duration", value: expander.attackDuration, range: 0.001 ... 0.2, format: "%0.4f s" ) { sliderValue in expander.attackDuration = sliderValue }) addView(Slider(property: "Release Duration", value: expander.releaseDuration, range: 0.01 ... 3, format: "%0.3f s" ) { sliderValue in expander.releaseDuration = sliderValue }) addView(Slider(property: "Master Gain", value: expander.masterGain, range: -40 ... 40, format: "%0.2f dB" ) { sliderValue in expander.masterGain = sliderValue }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
29.513889
78
0.521412
717a23f3b089345b79adc339457b29298673a25b
5,692
// // SecondViewController.swift // myFirstApp // // Created by Damián Krajňák on 18/05/2020. // Copyright © 2020 Damián Krajňák. All rights reserved. // import UIKit class SecondViewController: UIViewController { @IBOutlet weak var textField: UITextField! var XCoordinateArray: [Int] = [0]; var YCoordinateArray: [Int] = [0]; // premenná reprezentuje orientáciu v miestnosti var currentDirection: String = "up"; // počet vrcholov mnohouholníka var numberOfPoints: Int = 1; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func textFieldDidBeginEditing(textField: UITextField) { textField.text = "" } @IBOutlet weak var result: UILabel! // človek sa otočí v rohu miestnosti doľava // takisto kliká na šípku vľavu v aplikácii @IBAction func left(_ sender: Any) { // user stláča tlačidlo šípky -> je v rohu // miestnosto -> vrcholy++ numberOfPoints += 1 // načítanie dĺžky steny zadaej userom let input: String = textField.text! textField.text = "" if let num = Int(input) { // jednoduchý postup na pridanie novej // súradnice rohu miestnosti switch currentDirection { case "up": YCoordinateArray.append(YCoordinateArray.last! + num) XCoordinateArray.append(XCoordinateArray.last!) currentDirection = "left" case "down": YCoordinateArray.append(YCoordinateArray.last! - num) XCoordinateArray.append(XCoordinateArray.last!) currentDirection = "right" case "right": XCoordinateArray.append(XCoordinateArray.last! + num) YCoordinateArray.append(YCoordinateArray.last!) currentDirection = "up" case "left": XCoordinateArray.append(XCoordinateArray.last! - num) YCoordinateArray.append(YCoordinateArray.last!) currentDirection = "down" default: () } } } // človek sa otočí v rohu miestnosti doprava // takisto kliká na šípku vľavu v aplikácii @IBAction func right(_ sender: Any) { // user stláča tlačidlo šípky -> je v rohu // miestnosto -> vrcholy++ numberOfPoints += 1 // načítanie dĺžky steny zadaej userom let input: String = textField.text! textField.text = "" if let num = Int(input) { // jednoduchý postup na pridanie novej // súradnice rohu miestnosti switch currentDirection { case "up": YCoordinateArray.append(YCoordinateArray.last! + num) XCoordinateArray.append(XCoordinateArray.last!) currentDirection = "right" case "down": YCoordinateArray.append(YCoordinateArray.last! - num) XCoordinateArray.append(XCoordinateArray.last!) currentDirection = "left" case "right": XCoordinateArray.append(XCoordinateArray.last! + num) YCoordinateArray.append(YCoordinateArray.last!) currentDirection = "down" case "left": XCoordinateArray.append(XCoordinateArray.last! - num) YCoordinateArray.append(YCoordinateArray.last!) currentDirection = "up" default: () } } } @IBAction func end(_ sender: Any) { // Ak je medzi X súradnicami nejaká záporná // jej negatívna hodnota bude prirátaná // ku každému elementu poľa. Tým zaručíme, že // Pole bude obsahovať len kladné súradnice a // algoritmus bude fungovať správne if(XCoordinateArray.min()! < 0) { let temp: Int = XCoordinateArray.min()! * -1 let help = XCoordinateArray.count - 1 for index in 0...help { XCoordinateArray[index] += temp } } // Ak je medzi Y súradnicami nejaká záporná // jej negatívna hodnota bude prirátaná // ku každému elementu poľa. Tým zaručíme, že // Pole bude obsahovať len kladné súradnice a // algoritmus bude fungovať správne if(YCoordinateArray.min()! < 0) { let temp: Int = YCoordinateArray.min()! * -1 let help = YCoordinateArray.count - 1 for index in 0...help { YCoordinateArray[index] += temp } } // Algoritmus pre zistenie obsahu polygónu var area: Int = 0 var j: Int = numberOfPoints - 1 for index in 0...j { area += (XCoordinateArray[j] + XCoordinateArray[index]) * (YCoordinateArray[j] - YCoordinateArray[index]) j = index } area = area / 2 // Vypísanie výsledku result.text = "Area: \(area) cm2" // Vynulovanie premenných textField.text = "" area = 0 numberOfPoints = 1 XCoordinateArray = [0] YCoordinateArray = [0] currentDirection = "up" } /* // 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.destination. // Pass the selected object to the new view controller. } */ }
34.49697
117
0.570625
fbf528caa8a3aa9e5f433701fd88e4c25a339b7d
254
// // InteractiveModelType.swift // Domain // // Created by Behrad Kazemi on 8/14/18. // Copyright © 2018 Behrad Kazemi. All rights reserved. // import Foundation protocol InteractiveModelType { associatedtype Request associatedtype Response }
16.933333
56
0.740157
7184d3b3b6edfb62f123c95f8c67c4303d9b4ba3
1,365
// // iOS.swift // Memorize // // Created by Takeshi on 10/9/21. // import SwiftUI extension UIImage { var imamgeData: Data? { jpegData(compressionQuality: 1.0) } } extension View { func paletteControlButtonStyle() -> some View { self } func popoverPadding() -> some View { self } @ViewBuilder func wrappedInNavigationViewToMakeDismissable(_ dismiss: (() -> Void)?) -> some View { if UIDevice.current.userInterfaceIdiom != .pad, let dismiss = dismiss { NavigationView { self.navigationBarTitleDisplayMode(.inline) .dismissable(dismiss) } .navigationViewStyle(StackNavigationViewStyle()) } else { self } } @ViewBuilder func dismissable(_ dismiss:(() -> Void)?) -> some View { if UIDevice.current.userInterfaceIdiom != .pad, let dismiss = dismiss { self.toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } } } else { self } } } struct Pasteboard { static var imageData:Data? { UIPasteboard.general.image?.imamgeData } static var imageURL: URL? { UIPasteboard.general.url?.imageURL } }
22.016129
90
0.547253
edd8a2b0caf7ca7a6e83a093cee7c68e6cbbb5c4
2,416
import Cocoa protocol SessionObserver: class { func sessionDidAdd(label: String) func sessionDidRemove(label: String) func sessionDidAdd(annotation: AnnotationModel) func sessionDidRemove(annotation: AnnotationModel) } protocol ImageAnnotatingSessionProtocol { var annotationList: [AnnotationModel] {get} var labelList: Array<String> {get} func add(label: String) func remove(label: String) func add(observer: SessionObserver) func remove(observer: SessionObserver!) func clearAnnotations() func isLabelListEmpty() -> Bool func removeAnnotation(imageURL: URL) func add(annotation: AnnotationModel) } class ImageAnnotatingSession: ImageAnnotatingSessionProtocol { private class WeakSessionObserver { weak private(set) var object: SessionObserver? init(_ observer: SessionObserver) { object = observer } } private var observerList = [WeakSessionObserver]() public var labelList = [String]() public var annotationList = [AnnotationModel]() func add(label: String) { labelList.append(label) observerList.forEach { $0.object?.sessionDidAdd(label: label) } } func remove(label: String) { guard labelList.contains(label) else { return } labelList.removeAll { $0 == label } observerList.forEach { $0.object?.sessionDidRemove(label: label) } } //MARK: - Work with observers public func add(observer: SessionObserver) { observerList.append(WeakSessionObserver(observer)) } public func remove(observer: SessionObserver!) { observerList.removeAll { $0.object === observer } } func clearAnnotations() { annotationList.removeAll() } func isLabelListEmpty() -> Bool { return labelList.isEmpty } func removeAnnotation(imageURL: URL) { if let index = (annotationList.firstIndex { $0.imageURL == imageURL }) { let annotation = annotationList[index] annotationList.remove(at: index) observerList.forEach{ $0.object?.sessionDidRemove(annotation: annotation) } } } func add(annotation: AnnotationModel) { annotationList.append(annotation) observerList.forEach{ $0.object?.sessionDidAdd(annotation: annotation) } } }
27.454545
87
0.651904
9142a22fd72c01c61b6a17b7aa56eae467f746ad
1,113
// // ReorderCollectionViewCell.swift // Gifted // // Created by Nick Nguyen on 4/28/20. // Copyright © 2020 Nick Nguyen. All rights reserved. // import UIKit class ReorderCollectionViewCell: UICollectionViewCell { var imageView: UIImageView = { let m = UIImageView() m.translatesAutoresizingMaskIntoConstraints = false m.contentMode = .scaleAspectFit return m }() override init(frame: CGRect) { super.init(frame: frame) layoutContrainsts() layer.borderColor = UIColor.black.cgColor layer.borderWidth = 2 } required init?(coder: NSCoder) { super.init(coder: coder) layoutContrainsts() layer.borderColor = UIColor.black.cgColor layer.borderWidth = 2 } private func layoutContrainsts() { addSubview(imageView) NSLayoutConstraint.activate([ imageView.leadingAnchor.constraint(equalTo: leadingAnchor), imageView.trailingAnchor.constraint(equalTo: trailingAnchor), imageView.topAnchor.constraint(equalTo: topAnchor), imageView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) } }
23.680851
67
0.698113
90ac7290d58f0152f8274dae56ddc230e23e811c
761
import UIKit import XCTest import DMUtilities 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.366667
111
0.605782
23eaa36e92455735146db7ea0aadbe7a98dc090c
534
// // NatsMessageTests.swift // SwiftyNatsTests // // Created by Ray Krow on 4/4/18. // import XCTest @testable import SwiftyNats class NatsMessageTests: XCTestCase { static var allTests = [ ("testMessageParser", testMessageParser) ] func testMessageParser() { let str = "MSG swift.test 643CE192 6\r\ntest-1\r\n" let message = NatsMessage.parse(str) XCTAssert(message?.payload == "test-1") XCTAssert(message?.subject.id == "643CE192") } }
19.071429
59
0.604869
235cedfad26bc0aeb9cfe72c11b70203b72f1a16
2,813
// // MapController.swift // Maps // // Created by Rudson Lima on 7/16/16. // Copyright © 2016 Rudson Lima. All rights reserved. // import UIKit import MapKit import CoreLocation class MapController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet var mapView: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() configureLocationManager(); } func configureLocationManager() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest // Seu não tiver permissão, fazer o pedido de acesso a localização ao usuário if CLLocationManager.authorizationStatus() != .AuthorizedWhenInUse { locationManager.requestWhenInUseAuthorization() } mapView.showsUserLocation = true locationManager.startUpdatingLocation() } func configureMapView(coordinate: CLLocationCoordinate2D, region: MKCoordinateRegion){ // Setando informação ao marcador do mapa let annotation = MKPointAnnotation() annotation.title = "Fortaleza/CE" annotation.subtitle = "Brasil" annotation.coordinate = coordinate mapView.addAnnotation(annotation) mapView.setRegion(region, animated: true) locationManager.stopUpdatingLocation() } // MKMapViewDelegate - Custom map pin func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?{ let annotationReuseId = "Place" var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationReuseId) if anView == nil { anView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationReuseId) } else { anView!.annotation = annotation } anView!.image = UIImage(named: "MapPin") anView!.backgroundColor = UIColor.clearColor() anView!.canShowCallout = true return anView } // CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){ let location = locations.last let center = CLLocationCoordinate2DMake(location!.coordinate.latitude, location!.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)) configureMapView(location!.coordinate, region: region) } func locationManager(manager: CLLocationManager, didFailWithError error: NSError){ print("Errors: " + error.localizedDescription) } }
32.333333
122
0.666193
2111974cf646ca20ecf36aeccfd46c83cb53820a
2,805
import UIKit protocol {{ name }}Assembler { {% if use_window %} func resolve(window: UIWindow, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewController func resolve(window: UIWindow, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewModel func resolve(window: UIWindow, {{ model_variable }}: {{ model_name }}) -> {{ name }}NavigatorType {% else %} func resolve(navigationController: UINavigationController, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewController func resolve(navigationController: UINavigationController, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewModel func resolve(navigationController: UINavigationController) -> {{ name }}NavigatorType {% endif %} func resolve() -> {{ name }}UseCaseType } extension {{ name }}Assembler { {% if use_window %} func resolve(window: UIWindow, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewController { let vc = {{ name }}ViewController.instantiate() let vm: {{ name }}ViewModel = resolve(window: window, {{ model_variable }}: {{ model_variable }}) vc.bindViewModel(to: vm) return vc } func resolve(window: UIWindow, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewModel { return {{ name }}ViewModel( navigator: resolve(window: window, {{ model_variable }}: {{ model_variable }}), useCase: resolve(), {{ model_variable }}: {{ model_variable }} ) } {% else %} func resolve(navigationController: UINavigationController, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewController { let vc = {{ name }}ViewController.instantiate() let vm: {{ name }}ViewModel = resolve(navigationController: navigationController, {{ model_variable }}: {{ model_variable }}) vc.bindViewModel(to: vm) return vc } func resolve(navigationController: UINavigationController, {{ model_variable }}: {{ model_name }}) -> {{ name }}ViewModel { return {{ name }}ViewModel( navigator: resolve(navigationController: navigationController), useCase: resolve(), {{ model_variable }}: {{ model_variable }} ) } {% endif %} } extension {{ name }}Assembler where Self: DefaultAssembler { {% if use_window %} func resolve(window: UIWindow) -> {{ name }}NavigatorType { return {{ name }}Navigator(assembler: self, window: window) } {% else %} func resolve(navigationController: UINavigationController) -> {{ name }}NavigatorType { return {{ name }}Navigator(assembler: self, navigationController: navigationController) } {% endif %} func resolve() -> {{ name }}UseCaseType { return {{ name }}UseCase() } }
43.153846
133
0.619964
72a3f3432de3a65f1fcb9933221ad12c4c258cf8
281
import Swift extension String { /// Returns a copy of the receiver with its character uppercased. /// Source: https://stackoverflow.com/a/26306372/870560 public func uppercasingFirstLetter() -> String { return prefix(1).uppercased() + self.dropFirst() } }
28.1
69
0.686833
22b8795418df418e395d1528dc214a5e0e5aaa57
540
// // FakeTemperatureFetcher.swift // UniWeatherTests // // Created by Frederick Rudolf Janse van Rensburg on 2018/01/15. // Copyright © 2018 SakuraDev. All rights reserved. // import Foundation @testable import UniWeather class FakeTemperatureFetcher: TemperatureFetcher { var temperatureToReturn: Double? var errorToReturn: Error? func getTemperatureFromServer(latitude: String, longitude: String, completion: @escaping (Double?, Error?) -> ()) { completion(temperatureToReturn, errorToReturn) } }
25.714286
119
0.727778
485c361c49ab95517f879b7ac89e1173b50576c3
3,582
// // AppUpdater+UI.swift // // // Created by Tatsuya Tanaka on 2022/04/23. // import SwiftUI import VCamEntity import VCamLocalization @available(macOS 12, *) struct AppUpdateInformationView: View { let release: AppUpdater.LatestRelease let window: NSWindow @AppStorage(key: .skipThisVersion) var skipThisVersion var body: some View { VStack(alignment: .leading) { Text(L10n.existsNewAppVersion(release.version.description).key, bundle: .localize) .font(.title) .fontWeight(.bold) Text(L10n.currentVersion(Version.current.description).key, bundle: .localize) Text(L10n.releaseNotes.key, bundle: .localize) .fontWeight(.bold) .padding(.top) ScrollView { Text((try? AttributedString(markdown: release.body, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? .init(release.body)) .lineLimit(nil) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) .padding() } .background(.thinMaterial) HStack { Button { skipThisVersion = release.version.description window.close() } label: { Text(L10n.skipThisVersion.key, bundle: .localize) } .keyboardShortcut(.cancelAction) Spacer() Button { switch LocalizationEnvironment.language { case .japanese: NSWorkspace.shared.open(URL(string: "https://tattn.fanbox.cc/posts/3541433")!) case .english: NSWorkspace.shared.open(URL(string: "https://www.patreon.com/posts/64958634")!) } } label: { Text(L10n.downloadSupporterVersion.key, bundle: .localize) } Button { NSWorkspace.shared.open(release.downloadURL) } label: { Text(L10n.download.key, bundle: .localize) } .keyboardShortcut(.defaultAction) } } .padding() } } @available(macOS 12, *) extension AppUpdater { @MainActor public func presentUpdateAlert() async { guard let release = try? await check() else { let alert = NSAlert() alert.messageText = L10n.upToDate.text alert.informativeText = L10n.upToDateMessage(Version.current.description).text alert.alertStyle = NSAlert.Style.warning alert.addButton(withTitle: "OK") alert.runModal() return } presentWindow(title: L10n.update.text, id: nil, size: .init(width: 600, height: 400)) { window in AppUpdateInformationView(release: release, window: window) .background(.thinMaterial) } } @MainActor public func presentUpdateAlertIfAvailable() async { guard let release = try? await check(), UserDefaults.standard.value(for: .skipThisVersion) < release.version else { return // already latest or error } presentWindow(title: L10n.update.text, id: nil, size: .init(width: 600, height: 400)) { window in AppUpdateInformationView(release: release, window: window) .background(.thinMaterial) } } }
36.181818
160
0.556951
189284d791f2db7602b75377c157e9fe2b7dcb30
8,720
// // NotificationManager.swift // Memories // // Created by Michael Brown on 07/09/2015. // Copyright © 2015 Michael Brown. All rights reserved. // import Foundation import UIKit import Photos import PHAssetHelper import UserNotifications import ReactiveSwift struct NotificationsController { struct Key { static let hasPromptedForUserNotifications = "HasPromptedForUserNotifications" static let notificationTime = "NotificationTime" static let notificationsEnabled = "NotificationsEnabled" static let notificationLaunchDate = "NotificationLaunchDate" } let notificationCenter = UNUserNotificationCenter.current() func registerSettings() { notificationCenter.requestAuthorization(options: [.alert, .sound]) { granted, error in Current.userDefaults.set(true, forKey: Key.hasPromptedForUserNotifications) } } /// returns whether Notifications are allowed for this app at the System level func notificationsAllowed() -> SignalProducer<Bool, Never> { return SignalProducer { [notificationCenter] observer, _ in notificationCenter.getNotificationSettings() { settings in switch settings.alertSetting { case .enabled: observer.send(value: true) default: observer.send(value: false) } observer.sendCompleted() } } } func launchDate() -> Date? { if let date = Current.userDefaults.object(forKey: Key.notificationLaunchDate) as? Date { // clear the date as soon as it's read setLaunchDate(nil) return date } return nil } func setLaunchDate(_ launchDate: Date?) { if let date = launchDate { Current.userDefaults.set(date, forKey: Key.notificationLaunchDate) } else { Current.userDefaults.removeObject(forKey: Key.notificationLaunchDate) } } /// returns whether the user has been prompted with the system "Allow Notifications" prompt func hasPromptedForUserNotification() -> Bool { return Current.userDefaults.bool(forKey: Key.hasPromptedForUserNotifications) } /// returns whether the user has requested notifications to be enabled func notificationsEnabled() -> Bool { return Current.userDefaults.bool(forKey: Key.notificationsEnabled) } /// returns the current notification time from the user defaults func notificationTime() -> (hour: Int, minute: Int) { let notificationTime = Current.userDefaults.integer(forKey: Key.notificationTime) let notificationHour = notificationTime / 100 let notificationMinute = notificationTime - notificationHour * 100 return (notificationHour, notificationMinute) } /// sets the current notification time in the user defaults func setNotificationTime(_ hour: Int, _ minute: Int) { Current.userDefaults.set(hour * 100 + minute, forKey: Key.notificationTime) } /// attempts to enable notifications, prompting the user for authorization if required func enableNotifications() { Current.userDefaults.set(true, forKey: Key.notificationsEnabled) // if the user has never been prompted for allowing notifications // register for notifications to force the prompt if !hasPromptedForUserNotification() { registerSettings() return } // if the user has disabled notifications in Settings // give them the opportunity to go to settings notificationsAllowed() .observe(on: UIScheduler()) .filter((!)) .startWithValues { _ in let alert = UIAlertController(title: NSLocalizedString("Notifications Disabled", comment: ""), message: NSLocalizedString("You have disabled notifications for Memories. If you want to receive notifications you need to enable this access in Settings. Would you like to do this now?", comment: ""), preferredStyle: .alert) let settings = UIAlertAction(title: NSLocalizedString("Settings", comment: ""), style: .default, handler: { (action) -> Void in let url = URL(string: UIApplication.openSettingsURLString)! UIApplication.shared.open(url) }) let nothanks = UIAlertAction(title: NSLocalizedString("No thanks", comment: ""), style: .cancel, handler: { (action) -> Void in }) alert.addAction(nothanks) alert.addAction(settings) UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil) } } /// disables all notifications func disableNotifications() { notificationCenter.removeAllPendingNotificationRequests() Current.userDefaults.set(false, forKey: Key.notificationsEnabled) } /// schedules notifications, runs on a background thread func scheduleNotifications() { guard notificationsEnabled() else { return } notificationsAllowed() .filter { $0 } .startWithValues { _ in let operation = BlockOperation { () -> Void in self.scheduleNotifications(with: PHAssetHelper().datesMap()) } let queue = OperationQueue() queue.addOperation(operation) } } private func scheduleNotifications(with datesMap: [Date:Int]) { let bodyFormatString = NSLocalizedString("You have %lu photo memories for today", comment: "") let titleFormatString = NSLocalizedString("%lu Photo Memories", comment: "") let gregorian = Date.gregorianCalendar let todayComps = gregorian.dateComponents([.year, .month, .day], from: Date()) let todayKey = todayComps.month! * 100 + todayComps.day! let currentYear = todayComps.year! let time = notificationTime() let notifications : [UNNotificationRequest] = datesMap.map { (date: Date, count: Int) -> (date: Date, count: Int) in // adjust dates so that any date earlier than today has the // following year as its notification date let comps = gregorian.dateComponents([.month, .day], from: date) let key = comps.month! * 100 + comps.day! let notificationYear = key >= todayKey ? currentYear : currentYear + 1 let notificationDate = gregorian.date(from: DateComponents(era: 1, year: notificationYear, month: comps.month!, day: comps.day!, hour: time.hour, minute: time.minute, second: 0, nanosecond: 0))! return (date: notificationDate, count: count) }.sorted { $0.date.compare($1.date) == .orderedAscending }.prefix(64).map { (date, count) in let content = UNMutableNotificationContent() content.sound = UNNotificationSound(named: UNNotificationSoundName("notification.mp3")) content.title = String(format: titleFormatString, count) content.body = String(format: bodyFormatString, count) let trigger = UNCalendarNotificationTrigger( dateMatching: gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date), repeats: false ) return UNNotificationRequest(identifier: "\(date)", content: content, trigger: trigger) } guard notifications.count > 0 else { return } #if targetEnvironment(simulator) guard let testNote = notifications.first else { return } let now = Date() let noteTime = now.addingTimeInterval(20) let trigger = UNCalendarNotificationTrigger( dateMatching: gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: noteTime), repeats: false ) notificationCenter.add( UNNotificationRequest(identifier: "\(noteTime)", content: testNote.content, trigger: trigger) ) #else notifications.forEach { notificationCenter.add($0) } #endif } } class NotificationCenterDelegate: NSObject, UNUserNotificationCenterDelegate { func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { Current.notificationsController.setLaunchDate(response.notification.date) completionHandler() } }
40.747664
336
0.642202
20d3a2db788f62c8e7ebe420f603a3f00f913532
715
// // Constants.swift // VinylScrobble // // Created by Haaris Muneer on 6/29/17. // Copyright © 2017 Haaris. All rights reserved. // import UIKit struct Constants { static let discogsRequestTokenURL = "https://api.discogs.com/oauth/request_token" static let discogsAuthorizeURL = "https://www.discogs.com/oauth/authorize" static let discogsAccessTokenURL = "https://api.discogs.com/oauth/access_token" static let discogsBaseURL = "https://api.discogs.com" static let albumTableViewIdentifier = "albumTableViewCell" static let albumCollectionViewIdentifier = "albumCollectionViewCell" static let statusBarHeight = UIApplication.shared.statusBarFrame.height }
27.5
85
0.734266
0e3ba9a84922e61945a2beeae48a1b3f9400574b
2,306
// // YYRefresh+UIScrollView.swift // SwiftProject // // Created by yangyuan on 2018/9/25. // Copyright © 2018 huan. All rights reserved. // import UIKit public extension UIScrollView { @discardableResult func addYYRefresh(position: YYRefresh.Position, config: YYRefresh.Config? = nil, refreshView: YYRefreshView? = nil, action: ((YYRefresh) -> Void)?) -> YYRefresh { let refresh = YYRefresh(position: position, config: config, refreshView: refreshView, action: action) switch position { case .top: yy_topRefresh = refresh case .left: yy_leftRefresh = refresh case .bottom: yy_bottomRefresh = refresh case .right: yy_rightRefresh = refresh } addSubview(refresh) return refresh } var yy_topRefresh: YYRefresh? { get { objc_getAssociatedObject(self, &Keys.topRefreash) as? YYRefresh } set { objc_setAssociatedObject(self, &Keys.topRefreash, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var yy_leftRefresh: YYRefresh? { get { objc_getAssociatedObject(self, &Keys.leftRefreash) as? YYRefresh } set { objc_setAssociatedObject(self, &Keys.leftRefreash, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var yy_bottomRefresh: YYRefresh? { get { objc_getAssociatedObject(self, &Keys.bottomRefreash) as? YYRefresh } set { objc_setAssociatedObject(self, &Keys.bottomRefreash, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var yy_rightRefresh: YYRefresh? { get { objc_getAssociatedObject(self, &Keys.rightRefreash) as? YYRefresh } set { objc_setAssociatedObject(self, &Keys.rightRefreash, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private struct Keys { static var topRefreash: UInt8 = 0 static var leftRefreash: UInt8 = 0 static var bottomRefreash: UInt8 = 0 static var rightRefreash: UInt8 = 0 } }
29.564103
110
0.580659
38355343880a04a598d0c3e2261304ccb53fbc04
2,788
// // UITableView+Yep.swift // Yep // // Created by nixzhu on 15/12/11. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit extension UITableView { enum WayToUpdate { case none case reloadData case reloadIndexPaths([IndexPath]) case insert([IndexPath]) var needsLabor: Bool { switch self { case .none: return false case .reloadData: return true case .reloadIndexPaths: return true case .insert: return true } } func performWithTableView(_ tableView: UITableView) { switch self { case .none: println("tableView WayToUpdate: None") break case .reloadData: println("tableView WayToUpdate: ReloadData") SafeDispatch.async { tableView.reloadData() } case .reloadIndexPaths(let indexPaths): println("tableView WayToUpdate: ReloadIndexPaths") SafeDispatch.async { tableView.reloadRows(at: indexPaths, with: .none) } case .insert(let indexPaths): println("tableView WayToUpdate: Insert") SafeDispatch.async { tableView.insertRows(at: indexPaths, with: .none) } } } } } extension UITableView { func registerClassOf<T: UITableViewCell>(_: T.Type) where T: Reusable { register(T.self, forCellReuseIdentifier: T.yep_reuseIdentifier) } func registerNibOf<T: UITableViewCell>(_: T.Type) where T: Reusable, T: NibLoadable { let nib = UINib(nibName: T.yep_nibName, bundle: nil) register(nib, forCellReuseIdentifier: T.yep_reuseIdentifier) } func registerHeaderFooterClassOf<T: UITableViewHeaderFooterView>(_: T.Type) where T: Reusable { register(T.self, forHeaderFooterViewReuseIdentifier: T.yep_reuseIdentifier) } func dequeueReusableCell<T: UITableViewCell>() -> T where T: Reusable { guard let cell = self.dequeueReusableCell(withIdentifier: T.yep_reuseIdentifier) as? T else { fatalError("Could not dequeue cell with identifier: \(T.yep_reuseIdentifier)") } return cell } func dequeueReusableHeaderFooter<T: UITableViewHeaderFooterView>() -> T where T: Reusable { guard let view = dequeueReusableHeaderFooterView(withIdentifier: T.yep_reuseIdentifier) as? T else { fatalError("Could not dequeue HeaderFooter with identifier: \(T.yep_reuseIdentifier)") } return view } }
27.333333
108
0.587159
87ac7495ead40a49e4b0069cacd16d73f9cf05d3
499
// // IntSlider.swift // Nimble // // Created by UnsafePointers on 11/7/21. // License: Apache 2.0 import SwiftUI struct IntSlider: View { @ObservedObject var viewModel: ReaderViewModel var bridge: Binding<Double> { Binding<Double>.init(get: { Double(viewModel.wpm) }, set: { viewModel.wpm = Int($0) }) } var body: some View { VStack { Text("\(viewModel.wpm) words / min.") Slider(value: bridge, in: 60...500, step: 5) { _ in } } } }
17.206897
59
0.589178
e64cb4f1365ea168817a84fb0a31167b27787e6b
1,214
// // CustomerlyDemoUITests.swift // CustomerlyDemoUITests // // Created by Paolo Musolino on 19/11/16. // // import XCTest class CustomerlyDemoUITests: 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. } }
32.810811
182
0.663921
892e404f22fbcf8ec4793ea8746e091a6db8c22e
1,054
import Foundation import azureSwiftRuntime // DeleteAsyncNoRetrySucceeded long running delete request, service returns a 202 to the initial request. Poll the // endpoint indicated in the azureAsyncOperation header for operation status This method may poll for completion. // Polling can be canceled by passing the cancel channel argument. The channel will be used to cancel polling and any // outstanding HTTP requests. class LROsDeleteAsyncNoRetrySucceededCommand : BaseCommand { override init() { super.init() self.method = "Delete" self.isLongRunningOperation = true self.path = "/lro/deleteasync/noretry/succeeded" } override func preCall() { } public func execute(client: RuntimeClient) throws -> Decodable? { return try client.execute(command: self) } public func executeAsync(client: RuntimeClient, completionHandler: @escaping (Error?) -> Void) { client.executeAsyncLRO (command: self) { error in completionHandler(error) } } }
34
117
0.705882
e6f38dc199ea31cfac5d4db2a945860431b4efcb
2,130
// // CanvasSwiftUIView.swift // StrokeExtensions // // Copyright © 2022 Chris Davis, https://www.nthState.com // // See https://github.com/nthState/StrokeExtensions/blob/main/LICENSE for license information. // import SwiftUI struct CanvasSwiftUIView { @State var isAnimating = false @State var numberOfOrnaments: Int = 3 @State var offset: CGFloat = 0 @State var spacing: CGFloat = 0.1 @State var distribution: Distribution = .continuous @State var direction: Direction = .forward @State var useXNormal: Bool = true @State var useYNormal: Bool = true var intProxy: Binding<Double>{ Binding<Double>(get: { return Double(numberOfOrnaments) }, set: { numberOfOrnaments = Int($0) }) } } extension CanvasSwiftUIView: View { var body: some View { VStack { Text("Canvas Example") curve ControllerView(isAnimating: $isAnimating, numberOfOrnaments: intProxy, offset: $offset, spacing: $spacing, distribution: $distribution, direction: $direction, useXNormal: $useXNormal, useYNormal: $useYNormal) } } var curve: some View { ZStack { Curve() .stroke(Color.red, lineWidth: 1) .frame(width: 100, height: 100) Curve() .strokeWithCanvas(itemCount: numberOfOrnaments, from: offset, spacing: spacing, distribution: distribution, direction: direction, size: CGSize(width: 100, height: 100)) { item, _ in if item % 2 == 0 { Circle() .fill(Color.blue) .frame(width: 10, height: 10) } else { Circle() .fill(Color.red) .frame(width: 20, height: 20) } } .frame(width: 100, height: 100) } .background(Color.yellow) } } struct CanvasSwiftUIView_Previews: PreviewProvider { static var previews: some View { CanvasSwiftUIView() } }
24.767442
189
0.561033
d5a918b654fcaa43926ffed25f7d5bb245d9a8d9
1,007
// // InvitePopup.swift // TodoList // // Created by Usama Jamil on 26/09/2019. // Copyright © 2019 Usama Jamil. All rights reserved. // import UIKit class InvitePopup: UIView { @IBOutlet weak var lblEmail: UITextField! // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code self.setRounded(cornerRadius: 5) } @IBAction func actSend(_ sender: Any) { if let email = lblEmail.text, !email.isEmpty, email.isValidEmail() { if email == Persistence.shared.currentUserEmail { Utility.showSnackBar(msg: App.Validations.listShared, icon: nil) } else { MembersListVM.shared.invite(email: email) } } else { Utility.showSnackBar(msg: App.Validations.emailValidationStr, icon: nil) } } }
25.175
84
0.601787
f9c8a15c21ed58f536fded38bce93b2be1f9d1a9
1,918
// // Operator.swift // Troll // // Copyright (c) 2021 BlueDino Software (https://bluedino.net) // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. public enum BinaryOperandSchema { case collectionCollection case collectionSingleton case deferOperand case singletonCollection case singletonSingleton case stringString } public enum UnaryOperandSchema { case collection case deferOperand case double case pair case singleton }
45.666667
92
0.769552
01e0ae9ebd118e05d397b621191330a4f19cfbc1
3,917
// // KeyboardAction.swift // KeyboardKit // // Created by Daniel Saidi on 2018-02-02. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit /** This action enum specifies all currently supported keyboard actions and their standard behavior. Most keyboard actions have standard actions that has effect on either the input view controller or text document proxy. `KeyboardActionHandler`s can choose to use these actions or ignore them. These properties just specify standard actions that are commonly used with each respective keyboard action. Many actions require manual handling. For instance, `image` has no standard action, since it depends on what a keyboard does with an image. Actions like these are a way for you to express your intent, but you must handle them yourself in a custom keyboard action handler. */ public enum KeyboardAction: Equatable { case none, backspace, capsLock, character(String), command, custom(name: String), dismissKeyboard, escape, function, image(description: String, keyboardImageName: String, imageName: String), moveCursorBackward, moveCursorForward, newLine, option, shift, shiftDown, space, switchKeyboard, switchToKeyboard(KeyboardType), tab, empty, backImage } // MARK: - Public Properties public extension KeyboardAction { /** Whether or not the action is a delete action. */ var isDeleteAction: Bool { switch self { case .backspace, .backImage: return true default: return false } } /** Whether or not the action is a content input action. */ var isInputAction: Bool { switch self { case .character: return true case .image: return true case .space: return true default: return false } } /** Whether or not the action is something that handles the system instead of content. */ var isSystemAction: Bool { switch self { case .backspace, .backImage: return true case .capsLock: return true case .command: return true case .dismissKeyboard: return true case .escape: return true case .function: return true case .moveCursorBackward: return true case .moveCursorForward: return true case .newLine: return true case .option: return true case .shift: return true case .shiftDown: return true case .switchKeyboard: return true case .switchToKeyboard: return true case .tab: return true default: return false } } /** The standard action, if any, that should be executed on the input view controller when the action is triggered. */ var standardInputViewControllerAction: ((UIInputViewController?) -> Void)? { switch self { case .dismissKeyboard: return { controller in controller?.dismissKeyboard() } default: return nil } } /** The standard action, if any, that should be executed on the text document proxy when the action is triggered. */ var standardTextDocumentProxyAction: ((UITextDocumentProxy?) -> Void)? { switch self { case .backspace, .backImage: return { proxy in proxy?.deleteBackward() } case .character(let char): return { proxy in proxy?.insertText(char) } case .moveCursorBackward: return { proxy in proxy?.adjustTextPosition(byCharacterOffset: -1) } case .moveCursorForward: return { proxy in proxy?.adjustTextPosition(byCharacterOffset: 1) } case .newLine: return { proxy in proxy?.insertText("\n") } case .space: return { proxy in proxy?.insertText(" ") } case .tab: return { proxy in proxy?.insertText("\t") } default: return nil } } }
29.231343
102
0.65254
f5a1b724df646afa2f1b341f4e5f6ddbd9cdff53
5,635
// // ViewController.swift // KBScrollMagic // // Created by liuxingqipan on 04/02/2017. // Copyright (c) 2017 liuxingqipan. All rights reserved. // import UIKit import SnapKit import VTMagic import KBScrollMagic import MJRefresh class ViewController: UIViewController { fileprivate let magicVC = VTMagicController() fileprivate let listArr = ["推荐", "热点", "视频", "图片", "段子", "社会", "娱乐", "社会"] let size = UIScreen.main.bounds.size var lastPoint: CGPoint? var isTableViewBounces = true fileprivate let scrollView: UIScrollView = { let scrollView = UIScrollView() return scrollView }() fileprivate let headerIV = UIImageView() fileprivate let scrollBackView: UIView = { let view = UIView() return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white scrollView.contentSize = CGSize(width: size.width, height: size.height + 200) view.addSubview(scrollView) scrollView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headerRefreshHandle)) scrollView.addSubview(scrollBackView) headerIV.image = UIImage(named: "image_0") scrollBackView.addSubview(headerIV) createMenu() self.addChildViewController(self.magicVC) scrollView.addSubview(self.magicVC.view) self.view.setNeedsUpdateConstraints() self.magicVC.magicView.reloadData() scrollView.snp.makeConstraints { (make) in make.edges.equalToSuperview(); } scrollBackView.snp.makeConstraints { (make) in make.edges.equalToSuperview() make.width.equalToSuperview() make.bottom.equalTo(self.magicVC.view.snp.bottom) } headerIV.snp.makeConstraints { (make) in make.top.left.right.equalToSuperview() make.height.equalTo(200) } let settingItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(settingItemHandle)) navigationItem.rightBarButtonItem = settingItem } func createMenu() { magicVC.magicView.backgroundColor = UIColor.white magicVC.view.translatesAutoresizingMaskIntoConstraints = false; magicVC.magicView.navigationColor = .white //mRGB(35, 38, 45); magicVC.magicView.sliderColor = .black //mRGB(35, 38, 45); magicVC.magicView.switchStyle = .default; self.magicVC.magicView.navigationHeight = 44.0; self.magicVC.magicView.sliderExtension = 0.0; self.magicVC.magicView.sliderHeight = 2.0; self.magicVC.magicView.dataSource = self; self.magicVC.magicView.delegate = self; } override func updateViewConstraints() { self.magicVC.view.snp.updateConstraints { (make) in make.top.equalToSuperview().offset(200); make.left.right.equalToSuperview(); make.height.equalTo(size.height) } super.updateViewConstraints() } func settingItemHandle() { isTableViewBounces = !isTableViewBounces magicVC.magicView.reloadData() let alert = UIAlertController(title: "Changed", message: "tableView.bounces = \(isTableViewBounces ? "true" : "false")", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } func headerRefreshHandle() { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in self?.scrollView.mj_header.endRefreshing() } } } extension ViewController: KBScrollMagicDelegate { func scrollMagicDidEndDrag(when superScrollView: UIScrollView, offSetY: CGFloat) { if offSetY < -44 { superScrollView.mj_header.beginRefreshing() } } } extension ViewController: VTMagicViewDelegate { func magicView(_ magicView: VTMagicView, viewDidAppear viewController: UIViewController, atPage pageIndex: UInt) { } } extension ViewController: VTMagicViewDataSource { func menuTitles(for magicView: VTMagicView) -> [String] { return listArr } func magicView(_ magicView: VTMagicView, menuItemAt itemIndex: UInt) -> UIButton { let itemIdentifier = "itemIdentifier" var menuItem = magicView.dequeueReusableItem(withIdentifier: itemIdentifier) if menuItem == nil { menuItem = UIButton(type:.custom) menuItem?.setTitleColor(.black, for: .normal) menuItem?.setTitleColor(.black, for: .selected) menuItem?.titleLabel?.textAlignment = .center } return menuItem! } func magicView(_ magicView: VTMagicView, viewControllerAtPage pageIndex: UInt) -> UIViewController { let itemIdentifier1 = "itemIdentifier.0" var ovc = magicView.dequeueReusablePage(withIdentifier: itemIdentifier1) as? SubViewController if ovc == nil { ovc = SubViewController() ovc?.tableView.kbs.set(superScrollView: scrollView, insetY: 200, delegate: self) /* OR ovc?.tableView.kbs.setDelegate(self) ovc?.tableView.kbs.setinsetY(200) ovc?.tableView.kbs.setSuperScrollView(scrollView) */ } ovc?.tableView.bounces = isTableViewBounces return ovc! } }
32.953216
152
0.638332
f45dae1538a4801ddedb7e16fd7bfc1a9e64bb93
1,261
// // TestTableViewCell.swift // MacroCHallengeApp // // Created by Felipe Semissatto on 06/10/20. // import UIKit class TestTableViewCell: UITableViewCell { // MARK: -IBOutlets @IBOutlet weak var cardView: UIView! @IBOutlet weak var testLabel: UILabel! @IBOutlet weak var circularProgressLabel: UILabel! @IBOutlet weak var circularProgressView: UIView! // MARK: - Lifecyle override func awakeFromNib() { super.awakeFromNib() settingShadowAndCornerRadiusOnView(view: cardView) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } // MARK: - Private Methods /** Método responsável por acrescentar sombra e corner radius em uma view. - parameters view: view no qual será acrescentado sombra e corner radius. */ private func settingShadowAndCornerRadiusOnView(view: UIView) { view.layer.cornerRadius = 6 view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.25 view.layer.shadowOffset = CGSize(width: 0, height: 4) view.layer.shadowRadius = 1 view.layer.masksToBounds = false } }
26.270833
78
0.658208
1dac407c66f20f52f4387e987660bab94c6d08ea
469
// // CurrentlyPlaying.swift // SEDaily-IOS // // Created by Dawid Cedrych on 5/6/19. // Copyright © 2019 Altalogy. All rights reserved. // import Foundation // This is a workaround to keep global playing state class CurrentlyPlaying { static let shared = CurrentlyPlaying() private var currentlyPlayingId: String = "" func setCurrentlyPlaying(id: String) { currentlyPlayingId = id } func getCurrentlyPlayingId()-> String { return currentlyPlayingId } }
22.333333
52
0.735608
90cdc85c4a08a59236f536263282f2ae8b0687cc
451
// // InstancePropertyViewController.swift // HardDependencies // // Created by Ben Chatelain on 4/11/20. // Copyright © 2020 Ben Chatelain. All rights reserved. // import UIKit class InstancePropertyViewController: UIViewController { lazy var analytics = Analytics.shared override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) analytics.track(event: "viewDidAppear - \(type(of: self))") } }
22.55
67
0.709534
bf54003cb4e9be970e78822e6fb773cb33a6d488
988
import Foundation class QueueFactory { private static let queueKey = DispatchSpecificKey<String>() static let queue: DispatchQueue = { //定义了一个队列 let q = DispatchQueue(label: "Zenon.ProcessingQueue") //在队列里面加入一个Specific的标识,通常用于之后判断是不是在这个队列里面,取不出来就不在这个队列 q.setSpecific(key: QueueFactory.queueKey, value: "Zenon.ProcessingQueue") return q }() static func getQueue() -> DispatchQueue { //获取队列 return QueueFactory.queue } static func onQueue() -> Bool { //根据 Specific的标识判断,是否存在 return DispatchQueue.getSpecific(key: QueueFactory.queueKey) == "Zenon.ProcessingQueue" } static func executeOnQueueSynchronizedly<T>(block: () throws -> T ) rethrows -> T { if onQueue() {//存在,直接回调 block return try block() } else {//不存在,调取 getQueue 的 sync 方法,再回调 block return try getQueue().sync { return try block() } } } }
28.228571
95
0.61336
1a6f8ab455034621d0f3fc3d9758dc397afebfbb
5,090
// // StyleDictionarySize.swift // // Do not edit directly // Generated on Fri, 27 Aug 2021 08:25:22 GMT import UIKit public enum StyleDictionarySize { public static let effectFluffyElevation1OffsetX = 0 public static let effectFluffyElevation1OffsetY = 5 public static let effectFluffyElevation1Radius = 15 public static let effectFluffyElevation1Spread = 0 public static let effectFluffyElevation2OffsetX = 0 public static let effectFluffyElevation2OffsetY = 6.25 public static let effectFluffyElevation2Radius = 20 public static let effectFluffyElevation2Spread = 0 public static let effectFluffyElevation3OffsetX = 0 public static let effectFluffyElevation3OffsetY = 10 public static let effectFluffyElevation3Radius = 30 public static let effectFluffyElevation3Spread = 0 public static let effectFluffyElevation4OffsetX = 0 public static let effectFluffyElevation4OffsetY = 10 public static let effectFluffyElevation4Radius = 35 public static let effectFluffyElevation4Spread = 0 public static let effectFluffyElevation5OffsetX = 0 public static let effectFluffyElevation5OffsetY = 15 public static let effectFluffyElevation5Radius = 60 public static let effectFluffyElevation5Spread = 0 public static let effectFluffyElevation6OffsetX = 0 public static let effectFluffyElevation6OffsetY = 17.5 public static let effectFluffyElevation6Radius = 70 public static let effectFluffyElevation6Spread = 0 public static let effectFluffyElevation7OffsetX = 0 public static let effectFluffyElevation7OffsetY = 35 public static let effectFluffyElevation7Radius = 90 public static let effectFluffyElevation7Spread = 0 public static let effectTightElevation1OffsetX = 0 public static let effectTightElevation1OffsetY = 1 public static let effectTightElevation1Radius = 3 public static let effectTightElevation1Spread = 0 public static let effectTightElevation2OffsetX = 0 public static let effectTightElevation2OffsetY = 1.25 public static let effectTightElevation2Radius = 4 public static let effectTightElevation2Spread = 0 public static let effectTightElevation3OffsetX = 0 public static let effectTightElevation3OffsetY = 2 public static let effectTightElevation3Radius = 6 public static let effectTightElevation3Spread = 0 public static let effectTightElevation4OffsetX = 0 public static let effectTightElevation4OffsetY = 2 public static let effectTightElevation4Radius = 7 public static let effectTightElevation4Spread = 0 public static let effectTightElevation5OffsetX = 0 public static let effectTightElevation5OffsetY = 3 public static let effectTightElevation5Radius = 12 public static let effectTightElevation5Spread = 0 public static let effectTightElevation6OffsetX = 0 public static let effectTightElevation6OffsetY = 3.5 public static let effectTightElevation6Radius = 14 public static let effectTightElevation6Spread = 0 public static let effectTightElevation7OffsetX = 0 public static let effectTightElevation7OffsetY = 7 public static let effectTightElevation7Radius = 18 public static let effectTightElevation7Spread = 0 public static let effectTightElevation8OffsetX = 0 public static let effectTightElevation8OffsetY = 12 public static let effectTightElevation8Radius = 28 public static let effectTightElevation8Spread = 0 public static let effectTightElevation9OffsetX = 0 public static let effectTightElevation9OffsetY = 13 public static let effectTightElevation9Radius = 36 public static let effectTightElevation9Spread = 0 public static let gridCondensed0MobileCount = 4 public static let gridCondensed0MobileGutterSize = 24 public static let gridCondensed0MobileOffset = 16 public static let gridCondensed1200Desktop0Count = 12 public static let gridCondensed1200Desktop0GutterSize = 24 public static let gridCondensed1200Desktop0SectionSize = 74 public static let gridCondensed1200Desktop1Count = 2 public static let gridCondensed1200Desktop1GutterSize = 1200 public static let gridCondensed1200Desktop1Offset = 0 public static let gridCondensed576TabletCount = 6 public static let gridCondensed576TabletGutterSize = 24 public static let gridCondensed576TabletOffset = 24 public static let gridSpacious0MobileCount = 4 public static let gridSpacious0MobileGutterSize = 24 public static let gridSpacious0MobileOffset = 24 public static let gridSpacious1200Desktop0Count = 12 public static let gridSpacious1200Desktop0GutterSize = 48 public static let gridSpacious1200Desktop0SectionSize = 45 public static let gridSpacious1200Desktop1Count = 2 public static let gridSpacious1200Desktop1GutterSize = 1200 public static let gridSpacious1200Desktop1Offset = 0 public static let gridSpacious576TabletCount = 6 public static let gridSpacious576TabletGutterSize = 32 public static let gridSpacious576TabletOffset = 40 }
49.901961
64
0.8
d75f3d247b200789e7c76d1b5b91ac5b92e12298
1,713
// // IBarChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc public protocol IBarChartDataSet: IBarLineScatterCandleBubbleChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// `true` if this DataSet is stacked (stacksize > 1) or not. var isStacked: Bool { get } /// The maximum number of bars that can be stacked upon another in this DataSet. var stackSize: Int { get } /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value var barShadowColor: NSUIColor { get set } /// the width used for drawing borders around the bars. If borderWidth == 0, no border will be drawn. var barBorderWidth : CGFloat { get set } /// the color drawing borders around the bars. var barBorderColor: NSUIColor { get set } /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) var highlightAlpha: CGFloat { get set } /// array of labels used to describe the different values of the stacked bars var stackLabels: [String] { get set } ///bar corner radius var cornerRadius: CGFloat {get set} /// set corners to round ///if true cornerRadius is ignored var isRoundCorners: Bool {get set} /// Draw values var isDrawValuesAtBottom: Bool {get set} ///bar rounding corners var roundingCorners: UIRectCorner {get set} }
31.145455
148
0.699942
9b3acf8d477ea8a08be1aae3fa970fd063dbcb20
1,191
import UIKit final class RecordSummaryView: UIView { private var stackView: UIStackView! private var identifierInfoView: InfoView! private var descriptionInfoView: InfoView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { let stackView = UIStackView(frame: bounds) stackView.axis = .vertical stackView.spacing = 4 stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) stackView.pinToSuperview() self.identifierInfoView = InfoView(frame: .zero) self.descriptionInfoView = InfoView(frame: .zero) stackView.addArrangedSubview(identifierInfoView) stackView.addArrangedSubview(descriptionInfoView) self.stackView = stackView } func setUp(with record: Record) { self.identifierInfoView.configure(with: ("identifier".uppercased(), record.identifier)) self.descriptionInfoView.configure(with: ("description".uppercased(), record.description)) } }
29.775
98
0.684299
501bd4decf360908fb67b132b0bc221892cff502
1,333
// // CSActionCell.swift // Demo // // Created by huangchusheng on 2018/12/6. // Copyright © 2018 huangchusheng. All rights reserved. // import UIKit class CSActionCell: UITableViewCell { typealias SegmentedControlValueChangedHandler = (CSActionCell, Int) -> Void static let identifier = "CSActionCell" @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! var valueChangedHandler: SegmentedControlValueChangedHandler? var actionModel: CSActionModel? override func awakeFromNib() { super.awakeFromNib() segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged), for: .valueChanged) } @objc func segmentedControlValueChanged() { actionModel?.selectedIndex = segmentedControl.selectedSegmentIndex if let handler = self.valueChangedHandler { handler(self, segmentedControl.selectedSegmentIndex) } } func setValueChangedHandler(handler: @escaping SegmentedControlValueChangedHandler) { self.valueChangedHandler = handler } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
26.137255
109
0.698425
725e944367146037b6ce90eefbe9aa518815864d
489
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct S{struct Q<T where g:P{class B{let d=A}}struct A{class d{struct A{struct Q{enum e:Boolean
48.9
96
0.750511
ab6ec5f676b81e04f4e034f3ab690134c80207e5
1,197
// // UPennAutoLogoutCell.swift // Penn Chart Live // // Created by Rashad Abdul-Salam on 3/18/19. // Copyright © 2019 University of Pennsylvania Health System. All rights reserved. // import Foundation import UIKit class UPennAutoLogoutCell : UPennBasicCell { @IBOutlet weak var timeoutControl: UPennBasicSegmentControl! override func awakeFromNib() { super.awakeFromNib() self.timeoutControl.tintColor = UIColor.upennMediumBlue // Set font attributes to avoid segment label truncation let font = UIFont.helvetica(size: 15.0) let attributes : [AnyHashable : Any] = [NSAttributedString.Key.font:font] self.timeoutControl.setTitleTextAttributes(attributes as? [NSAttributedString.Key : Any], for: .normal) self.timeoutControl.setTitleTextAttributes(attributes as? [NSAttributedString.Key : Any], for: .selected) self.timeoutControl.selectedSegmentIndex = UPennTimerUIApplication.timeoutIndex } @IBAction func pressedTimeoutControl(_ sender: UISegmentedControl) { UPennTimerUIApplication.updateTimeoutInterval(index: self.timeoutControl.selectedSegmentIndex) } }
35.205882
113
0.721805
169cd0f83c2bc1fdbd1beed8d5370745f7e161a7
3,906
import Foundation import SpriteKit public class SettingsScene: FlowableScene { /// NodeSelectors are used to describe a specific node in the scene in /// a more declarative way. enum NodeSelectors: String, NodeSelector { case title case backButton case musicCheckBox case musicLabel case changeThemeButton var isUserInteractable: Bool { switch self { case .backButton, .musicCheckBox, .changeThemeButton: return true default: return false } } } /// The settingsFlowDelegate allows us to alter global game settings weak var settingsFlowDelegate: SettingsFlowDelegate? // MARK: Nodes lazy var titleLabelNode: SKSpriteNode = { let node = SKSpriteNode(imageNamed: GameTheme.current.filePath(for: "Settings/Title")) node.position = CGPoint(x: 250, y: 630) node.addGlow() node.name = NodeSelectors.title.rawValue return node }() lazy var backButton: SKSpriteNode = { let node = SKSpriteNode(imageNamed: GameTheme.current.filePath(for: "Levels/Assets/BackButton")) node.size = CGSize(width: 30, height: 30) node.position = CGPoint(x: 60, y: 630) node.addGlow() node.name = NodeSelectors.backButton.rawValue return node }() lazy var musicCheckBoxNode: CheckBoxNode = { let node = CheckBoxNode(isEnabled: true) node.position = CGPoint(x: 60, y: 530) node.name = NodeSelectors.musicCheckBox.rawValue node.addGlow() return node }() lazy var musicLabelNode: SKSpriteNode = { let node = SKSpriteNode(imageNamed: GameTheme.current.filePath(for: "Settings/EnableMusicLabel")) node.position = CGPoint(x: 250, y: 530) node.name = NodeSelectors.musicLabel.rawValue node.addGlow() return node }() lazy var changeThemeButton: SKSpriteNode = { let node = SKSpriteNode(imageNamed: GameTheme.current.filePath(for: "Settings/ChangeThemeButton")) node.position = CGPoint(x: 250, y: 430) node.size = CGSize(width: 304, height: 77) node.name = NodeSelectors.changeThemeButton.rawValue node.addGlow() return node }() // MARK: LifeCycle required public init(size: CGSize, flowDelegate: GameFlowDelegate) { super.init(size: size, flowDelegate: flowDelegate) configureScene() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureScene() } private func configureScene() { backgroundColor = GameTheme.current.backgroundColor // Add necessary child nodes addChild(titleLabelNode) addChild(backButton) addChild(musicCheckBoxNode) addChild(musicLabelNode) addChild(changeThemeButton) } // MARK: TouchEvents public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard let nodeName = resolveNamedNode(for: touches, with: NodeSelectors.selectableNodes)?.name else { return } switch nodeName { case NodeSelectors.backButton.rawValue: flowDelegate?.changeGameState(to: .menu, with: .push(direction: .down)) case NodeSelectors.musicCheckBox.rawValue: musicCheckBoxNode.animatePop() let isEnabled = !musicCheckBoxNode.isEnabled musicCheckBoxNode.setIsEnabled(isEnabled) settingsFlowDelegate?.toggleMusic(to: isEnabled) case NodeSelectors.changeThemeButton.rawValue: let newTheme: GameTheme = GameTheme.current == .neon ? .bold : .neon settingsFlowDelegate?.changeTheme(to: newTheme) default: return } } }
33.101695
118
0.642089
e2b0b8c99cc2d2f674e66554ec20492f1c63053a
1,106
// // TrackKit // // Created by Jelle Vandebeeck on 30/12/2016. // import Quick import Nimble import TrackKit class LOCCommonSpec: QuickSpec { override func spec() { var file: File! describe("common data") { beforeEach { let content = "<loc src='Groundspeak' version='1.0'>" + "<waypoint></waypoint>" + "</loc>" let data = content.data(using: .utf8) file = try! TrackParser(data: data, type: .loc).parse() } it("should have a source") { expect(file.source) == "Groundspeak" } context("empty file") { beforeEach { let content = "<loc version='1.0'></loc>" let data = content.data(using: .utf8) file = try! TrackParser(data: data, type: .loc).parse() } it("should not have a source") { expect(file.source).to(beNil()) } } } } }
26.333333
75
0.44123
c186fcea94c9306524b4a3042b17d7c6e06b1bdd
13,531
// // Copyright Amazon.com Inc. or its affiliates. // All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import XCTest @testable import Amplify @testable import AmplifyTestCommon @testable import AWSPluginsCore class GraphQLRequestAnyModelWithSyncTests: XCTestCase { override func setUp() { ModelRegistry.register(modelType: Comment.self) ModelRegistry.register(modelType: Post.self) } override func tearDown() { ModelRegistry.reset() } func testQueryGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .get)) documentBuilder.add(decorator: ModelIdDecorator(id: post.id)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ query GetPost($id: ID!) { getPost(id: $id) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult?>.query(modelName: post.modelName, byId: post.id) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult?.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } XCTAssertEqual(variables["id"] as? String, post.id) } func testCreateMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .create)) documentBuilder.add(decorator: ModelDecorator(model: post)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.createMutation(of: post, modelSchema: post.schema) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssert(input["title"] as? String == post.title) XCTAssert(input["content"] as? String == post.content) } func testUpdateMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .update)) documentBuilder.add(decorator: ModelDecorator(model: post)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ mutation UpdatePost($input: UpdatePostInput!) { updatePost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.updateMutation(of: post, modelSchema: post.schema) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssert(input["title"] as? String == post.title) XCTAssert(input["content"] as? String == post.content) } func testDeleteMutationGraphQLRequest() throws { let post = Post(title: "title", content: "content", createdAt: .now()) var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelName: post.modelName, operationType: .mutation) documentBuilder.add(decorator: DirectiveNameDecorator(type: .delete)) documentBuilder.add(decorator: ModelIdDecorator(id: post.id)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ mutation DeletePost($input: DeletePostInput!) { deletePost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.deleteMutation(modelName: post.modelName, id: post.id) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssertEqual(input["id"] as? String, post.id) } func testCreateSubscriptionGraphQLRequest() throws { let modelType = Post.self as Model.Type var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .subscription) documentBuilder.add(decorator: DirectiveNameDecorator(type: .onCreate)) documentBuilder.add(decorator: ConflictResolutionDecorator()) let document = documentBuilder.build() let documentStringValue = """ subscription OnCreatePost { onCreatePost { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<MutationSyncResult>.subscription(to: modelType.schema, subscriptionType: .onCreate) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) XCTAssertNil(request.variables) } func testSyncQueryGraphQLRequest() throws { let modelType = Post.self as Model.Type let nextToken = "nextToken" let limit = 100 let lastSync = 123 var documentBuilder = ModelBasedGraphQLDocumentBuilder(modelSchema: modelType.schema, operationType: .query) documentBuilder.add(decorator: DirectiveNameDecorator(type: .sync)) documentBuilder.add(decorator: PaginationDecorator(limit: limit, nextToken: nextToken)) documentBuilder.add(decorator: ConflictResolutionDecorator(lastSync: lastSync)) let document = documentBuilder.build() let documentStringValue = """ query SyncPosts($lastSync: AWSTimestamp, $limit: Int, $nextToken: String) { syncPosts(lastSync: $lastSync, limit: $limit, nextToken: $nextToken) { items { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } nextToken startedAt } } """ let request = GraphQLRequest<SyncQueryResult>.syncQuery(modelSchema: modelType.schema, limit: limit, nextToken: nextToken, lastSync: lastSync) XCTAssertEqual(document.stringValue, request.document) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == SyncQueryResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } XCTAssertNotNil(variables["limit"]) XCTAssertEqual(variables["limit"] as? Int, limit) XCTAssertNotNil(variables["nextToken"]) XCTAssertEqual(variables["nextToken"] as? String, nextToken) XCTAssertNotNil(variables["lastSync"]) XCTAssertEqual(variables["lastSync"] as? Int, lastSync) } func testUpdateMutationWithEmptyFilter() { let post = Post(title: "title", content: "content", createdAt: .now()) let documentStringValue = """ mutation UpdatePost($input: UpdatePostInput!) { updatePost(input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let request = GraphQLRequest<Post>.updateMutation(of: post, where: [:]) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssert(input["title"] as? String == post.title) XCTAssert(input["content"] as? String == post.content) } func testUpdateMutationWithFilter() { let post = Post(title: "myTitle", content: "content", createdAt: .now()) let documentStringValue = """ mutation UpdatePost($condition: ModelPostConditionInput, $input: UpdatePostInput!) { updatePost(condition: $condition, input: $input) { id content createdAt draft rating status title updatedAt __typename _version _deleted _lastChangedAt } } """ let filter: [String: Any] = ["title": ["eq": "myTitle"]] let request = GraphQLRequest<Post>.updateMutation(of: post, where: filter) XCTAssertEqual(documentStringValue, request.document) XCTAssert(request.responseType == MutationSyncResult.self) guard let variables = request.variables else { XCTFail("The request doesn't contain variables") return } guard let input = variables["input"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid input") return } XCTAssert(input["title"] as? String == post.title) XCTAssert(input["content"] as? String == post.content) guard let condition = variables["condition"] as? [String: Any] else { XCTFail("The document variables property doesn't contain a valid condition") return } guard let conditionValue = condition["title"] as? [String: String] else { XCTFail("Failed to get 'title' from the condition") return } XCTAssertEqual(conditionValue["eq"], "myTitle") } }
37.378453
116
0.587835
fb137e7c4fc5cf170ca90c14fe442e5a1be16ed0
16,688
/// An SQL function or aggregate. public final class DatabaseFunction: Hashable { // SQLite identifies functions by (name + argument count) private struct Identity: Hashable { let name: String let nArg: Int32 // -1 for variadic functions } /// The name of the SQL function public var name: String { identity.name } private let identity: Identity let pure: Bool private let kind: Kind private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } /// Creates an SQL function. /// /// For example: /// /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { /// return nil /// } /// return int + 1 /// } /// db.add(function: fn) /// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2 /// /// - parameters: /// - name: The function name. /// - argumentCount: The number of arguments of the function. If /// omitted, or nil, the function accepts any number of arguments. /// - pure: Whether the function is "pure", which means that its results /// only depends on its inputs. When a function is pure, SQLite has /// the opportunity to perform additional optimizations. Default value /// is false. /// - function: A function that takes an array of DatabaseValue /// arguments, and returns an optional DatabaseValueConvertible such /// as Int, String, NSDate, etc. The array is guaranteed to have /// exactly *argumentCount* elements, provided *argumentCount* is /// not nil. public init( _ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .function{ (argc, argv) in let arguments = (0..<Int(argc)).map { index in DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!) } return try function(arguments) } } /// Creates an SQL aggregate function. /// /// For example: /// /// struct MySum: DatabaseAggregate { /// var sum: Int = 0 /// /// mutating func step(_ dbValues: [DatabaseValue]) { /// if let int = Int.fromDatabaseValue(dbValues[0]) { /// sum += int /// } /// } /// /// func finalize() -> DatabaseValueConvertible? { /// return sum /// } /// } /// /// let dbQueue = DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// try dbQueue.write { db in /// db.add(function: fn) /// try db.execute(sql: "CREATE TABLE test(i)") /// try db.execute(sql: "INSERT INTO test(i) VALUES (1)") /// try db.execute(sql: "INSERT INTO test(i) VALUES (2)") /// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3 /// } /// /// - parameters: /// - name: The function name. /// - argumentCount: The number of arguments of the aggregate. If /// omitted, or nil, the aggregate accepts any number of arguments. /// - pure: Whether the aggregate is "pure", which means that its /// results only depends on its inputs. When an aggregate is pure, /// SQLite has the opportunity to perform additional optimizations. /// Default value is false. /// - aggregate: A type that implements the DatabaseAggregate protocol. /// For each step of the aggregation, its `step` method is called with /// an array of DatabaseValue arguments. The array is guaranteed to /// have exactly *argumentCount* elements, provided *argumentCount* is /// not nil. public init<Aggregate: DatabaseAggregate>( _ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .aggregate { Aggregate() } } /// Returns an SQL expression that applies the function. /// /// See https://github.com/groue/GRDB.swift/#sql-functions public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { switch kind { case .aggregate: return .function(name, arguments.map(\.sqlExpression)) case .function: return .aggregate(name, arguments.map(\.sqlExpression)) } } /// Calls sqlite3_create_function_v2 /// See https://sqlite.org/c3ref/create_function.html func install(in db: Database) { // Retain the function definition let definition = kind.definition let definitionP = Unmanaged.passRetained(definition).toOpaque() let code = sqlite3_create_function_v2( db.sqliteConnection, identity.name, identity.nArg, eTextRep, definitionP, kind.xFunc, kind.xStep, kind.xFinal, { definitionP in // Release the function definition Unmanaged<AnyObject>.fromOpaque(definitionP!).release() }) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage)) } } /// Calls sqlite3_create_function_v2 /// See https://sqlite.org/c3ref/create_function.html func uninstall(in db: Database) { let code = sqlite3_create_function_v2( db.sqliteConnection, identity.name, identity.nArg, eTextRep, nil, nil, nil, nil, nil) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage)) } } /// The way to compute the result of a function. /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// http://sqlite.org/capi3ref.html#sqlite3_create_function private class FunctionDefinition { let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible? init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) { self.compute = compute } } /// The way to start an aggregate. /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// http://sqlite.org/capi3ref.html#sqlite3_create_function private class AggregateDefinition { let makeAggregate: () -> DatabaseAggregate init(makeAggregate: @escaping () -> DatabaseAggregate) { self.makeAggregate = makeAggregate } } /// The current state of an aggregate, storable in SQLite private class AggregateContext { var aggregate: DatabaseAggregate var hasErrored = false init(aggregate: DatabaseAggregate) { self.aggregate = aggregate } } /// A function kind: an "SQL function" or an "aggregate". /// See http://sqlite.org/capi3ref.html#sqlite3_create_function private enum Kind { /// A regular function: SELECT f(1) case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz case aggregate(() -> DatabaseAggregate) /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// http://sqlite.org/capi3ref.html#sqlite3_create_function var definition: AnyObject { switch self { case .function(let compute): return FunctionDefinition(compute: compute) case .aggregate(let makeAggregate): return AggregateDefinition(makeAggregate: makeAggregate) } } /// Feeds the `xFunc` parameter of sqlite3_create_function_v2 /// http://sqlite.org/capi3ref.html#sqlite3_create_function var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? { guard case .function = self else { return nil } return { (sqliteContext, argc, argv) in let definition = Unmanaged<FunctionDefinition> .fromOpaque(sqlite3_user_data(sqliteContext)) .takeUnretainedValue() do { try DatabaseFunction.report( result: definition.compute(argc, argv), in: sqliteContext) } catch { DatabaseFunction.report(error: error, in: sqliteContext) } } } /// Feeds the `xStep` parameter of sqlite3_create_function_v2 /// http://sqlite.org/capi3ref.html#sqlite3_create_function var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? { guard case .aggregate = self else { return nil } return { (sqliteContext, argc, argv) in let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext) let aggregateContext = aggregateContextU.takeUnretainedValue() assert(!aggregateContext.hasErrored) // assert SQLite behavior do { let arguments = (0..<Int(argc)).map { index in DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!) } try aggregateContext.aggregate.step(arguments) } catch { aggregateContext.hasErrored = true DatabaseFunction.report(error: error, in: sqliteContext) } } } /// Feeds the `xFinal` parameter of sqlite3_create_function_v2 /// http://sqlite.org/capi3ref.html#sqlite3_create_function var xFinal: (@convention(c) (OpaquePointer?) -> Void)? { guard case .aggregate = self else { return nil } return { (sqliteContext) in let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext) let aggregateContext = aggregateContextU.takeUnretainedValue() aggregateContextU.release() guard !aggregateContext.hasErrored else { return } do { try DatabaseFunction.report( result: aggregateContext.aggregate.finalize(), in: sqliteContext) } catch { DatabaseFunction.report(error: error, in: sqliteContext) } } } } /// Helper function that extracts the current state of an aggregate from an /// sqlite function execution context. /// /// The result must be released when the aggregate concludes. /// /// See https://sqlite.org/c3ref/context.html /// See https://sqlite.org/c3ref/aggregate_context.html private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> { // > The first time the sqlite3_aggregate_context(C,N) routine is called // > for a particular aggregate function, SQLite allocates N of memory, // > zeroes out that memory, and returns a pointer to the new memory. // > On second and subsequent calls to sqlite3_aggregate_context() for // > the same aggregate function instance, the same buffer is returned. let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride let aggregateContextBufferP = UnsafeMutableRawBufferPointer( start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride) if aggregateContextBufferP.contains(where: { $0 != 0 }) { // Buffer contains non-zero byte: load aggregate context let aggregateContextP = aggregateContextBufferP .baseAddress! .assumingMemoryBound(to: Unmanaged<AggregateContext>.self) return aggregateContextP.pointee } else { // Buffer contains null pointer: create aggregate context. let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)) .takeUnretainedValue() .makeAggregate() let aggregateContext = AggregateContext(aggregate: aggregate) // retain and store in SQLite's buffer let aggregateContextU = Unmanaged.passRetained(aggregateContext) let aggregateContextP = aggregateContextU.toOpaque() withUnsafeBytes(of: aggregateContextP) { aggregateContextBufferP.copyMemory(from: $0) } return aggregateContextU } } private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) { switch result?.databaseValue.storage ?? .null { case .null: sqlite3_result_null(sqliteContext) case .int64(let int64): sqlite3_result_int64(sqliteContext, int64) case .double(let double): sqlite3_result_double(sqliteContext, double) case .string(let string): sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT) case .blob(let data): data.withUnsafeBytes { sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT) } } } private static func report(error: Error, in sqliteContext: OpaquePointer?) { if let error = error as? DatabaseError { if let message = error.message { sqlite3_result_error(sqliteContext, message, -1) } sqlite3_result_error_code(sqliteContext, error.extendedResultCode.rawValue) } else { sqlite3_result_error(sqliteContext, "\(error)", -1) } } } extension DatabaseFunction { /// :nodoc: public func hash(into hasher: inout Hasher) { hasher.combine(identity) } /// Two functions are equal if they share the same name and arity. /// :nodoc: public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { lhs.identity == rhs.identity } } /// The protocol for custom SQLite aggregates. /// /// For example: /// /// struct MySum : DatabaseAggregate { /// var sum: Int = 0 /// /// mutating func step(_ dbValues: [DatabaseValue]) { /// if let int = Int.fromDatabaseValue(dbValues[0]) { /// sum += int /// } /// } /// /// func finalize() -> DatabaseValueConvertible? { /// return sum /// } /// } /// /// let dbQueue = DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// try dbQueue.write { db in /// db.add(function: fn) /// try db.execute(sql: "CREATE TABLE test(i)") /// try db.execute(sql: "INSERT INTO test(i) VALUES (1)") /// try db.execute(sql: "INSERT INTO test(i) VALUES (2)") /// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3 /// } public protocol DatabaseAggregate { /// Creates an aggregate. init() /// This method is called at each step of the aggregation. /// /// The dbValues argument contains as many values as given to the SQL /// aggregate function. /// /// -- One value /// SELECT maxLength(name) FROM player /// /// -- Two values /// SELECT maxFullNameLength(firstName, lastName) FROM player /// /// This method is never called after the finalize() method has been called. mutating func step(_ dbValues: [DatabaseValue]) throws /// Returns the final result func finalize() throws -> DatabaseValueConvertible? }
41.002457
117
0.588447
4b4ccdc97166bd0f7106bb3b268758a82d3cf06a
3,187
// // FTPCSegmentCell.swift // FTPageController // // Created by liufengting on 2018/8/8. // import UIKit public class FTPCSegmentCell: UICollectionViewCell { static let identifier = "\(FTPCSegmentCell.classForCoder())" public lazy var titleLabel: UILabel = { let label = UILabel() label.textAlignment = NSTextAlignment.center return label }() public var titleModel: FTPCTitleModel! public var indexPath: IndexPath! public override init(frame: CGRect) { super.init(frame: frame) self.contentView.addSubview(self.titleLabel) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.contentView.addSubview(self.titleLabel) } open override func layoutSubviews() { super.layoutSubviews() self.titleLabel.frame = self.bounds } public func setupWith(titleModel: FTPCTitleModel, indexPath: IndexPath, selected: Bool) { self.titleModel = titleModel self.backgroundColor = titleModel.backgroundColor self.titleLabel.text = titleModel.title self.titleLabel.font = titleModel.defaultFont; self.indexPath = indexPath self.setSelected(selected: selected) } func setSelected(selected: Bool) { self.isSelected = selected let backgroundColor = selected ? self.titleModel.selectedBackgroundColor : self.titleModel.backgroundColor let textColor = selected ? self.titleModel.selectedTitleColor : self.titleModel.defaultTitleColor let font = selected ? self.titleModel.selectedFont : self.titleModel.defaultFont self.backgroundColor = backgroundColor self.titleLabel.textColor = textColor self.titleLabel.font = font self.titleLabel.transform = CGAffineTransform.identity } func handleTransition(percent: CGFloat) { // backgroundColor if self.titleModel.backgroundColor.isEqual(color: self.titleModel.selectedBackgroundColor) == false { let bgColor = UIColor.transit(fromColor: self.titleModel.selectedBackgroundColor, toColor: self.titleModel.backgroundColor, percent: percent) self.backgroundColor = bgColor } // titleLabel.textColor if self.titleModel.selectedTitleColor.isEqual(color: self.titleModel.defaultTitleColor) == false { let textColor = UIColor.transit(fromColor: self.titleModel.selectedTitleColor, toColor: self.titleModel.defaultTitleColor, percent: percent) self.titleLabel.textColor = textColor } // titleLabel.transform if self.titleModel.selectedFont.pointSize != self.titleModel.defaultFont.pointSize { if self.titleLabel.font != self.titleModel.defaultFont { self.titleLabel.font = self.titleModel.defaultFont } let scale = self.titleModel.selectedFont.pointSize/self.titleModel.defaultFont.pointSize - ((self.titleModel.selectedFont.pointSize/self.titleModel.defaultFont.pointSize - 1)*percent) self.titleLabel.transform = CGAffineTransform(scaleX: scale, y: scale); } } }
39.8375
195
0.690304
e0a9ef9786c63e94ffd110caa972b3bbd0559f69
3,173
// // AnotherTest.swift // Business_Search // // Created by admin on 5/1/19. // Copyright © 2019 admin. All rights reserved. // import UIKit import CoreData class OpeningController: UIViewController, UISearchControllerDelegate, UISearchBarDelegate, UnBlurViewProtocol { lazy var tableDataSource = OpeningTableDataSource(dataController: dataController, latitude: latitude, longitude: longitude, model: model) lazy var tableDelegate = OpeningTableDelegate(delegate: self, dataSourceDelegate: tableDataSource) let model = OpeningModel() var getDataController : DataController {return dataController} var getLatitude : Double {return latitude} var getLongitude : Double {return longitude} var getModel : OpeningTableDataSource {return tableDataSource} var latitude : Double! //MARK: Injected var longitude : Double! //MARK: Injected var moc : NSManagedObjectContext! //Parent-Context var privateMoc : NSManagedObjectContext! //Child-Context for CoreData Concurrency var dataController : DataController!{ //MARK: Injected didSet { moc = dataController.viewContext privateMoc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) privateMoc.parent = moc } } var currentLocationID: NSManagedObjectID? //Connects downloaded Business to Location var doesLocationEntityExist = false //true after create/find location var urlsQueue = [CreateYelpURLDuringLoopingStruct]() //enumeration loop for semaphores lazy var searchController: UISearchController = { let searchController = UISearchController(searchResultsController: nil) searchController.searchBar.scopeButtonTitles = ["Business", "Category"] searchController.obscuresBackgroundDuringPresentation = false //searchController.searchBar.barStyle = .black searchController.searchBar.tintColor = UIColor.white searchController.searchBar.barTintColor = UIColor.white searchController.searchBar.placeholder = "Enter search term ..." searchController.searchBar.delegate = self searchController.searchResultsUpdater = self //Setting background for search controller if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField { if let backgroundview = textfield.subviews.first { backgroundview.backgroundColor = UIColor.white backgroundview.layer.cornerRadius = 10 backgroundview.clipsToBounds = true } } return searchController }() }
48.815385
118
0.602269
de77161fc5764c79af2f0c284cc3250b66039882
1,020
// // ViewController.swift // Toast // // Created by toshi0383 on 2016/10/23. // // import AppKit import Foundation final class HudViewController: NSViewController { var text = "" var closeAfter: Double = 3.0 override func viewDidAppear() { super.viewDidAppear() view.makeToast(text, closeAfter) } } final class HudWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() super.window?.backgroundColor = NSColor(calibratedRed: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) } func setCloseDelay(closeAfter: Double) { let c = super.window?.contentViewController as! HudViewController c.closeAfter = closeAfter } func setText(text: String) { let c = super.window?.contentViewController as! HudViewController c.text = text } func changeText(text: String) { let c = super.window?.contentViewController as! HudViewController c.view.changeToastText(text) } }
23.72093
102
0.662745
e0f97afe9887372aceb3e7522719d57729b1d24e
8,152
// // UIViewController+bitmex.swift // Coin // // Created by gm on 2018/12/14. // Copyright © 2018年 COIN. All rights reserved. // //struct BitMexSubscribeType: OptionSet { // let rawValue: Int // static let instrument = BitMexSubscribeType(rawValue: 0x0001 << 0) // static let OrderBook10 = BitMexSubscribeType(rawValue: 0x0001 << 1) // static let trade = BitMexSubscribeType(rawValue: 0x0001 << 2) // static let tradeBin1m = BitMexSubscribeType(rawValue: 0x0001 << 3) //} enum BitMexSubscribeType: String { case instrument = "instrument" //行情 case OrderBook10 = "orderBook10" //委托数据 深度 case trade = "trade" //交易 case tradeBin1m = "tradeBin1m" //k线 } enum BitMexSubscribeCancelState: Int { case could //可取消 case couldNot //不可取消 } extension UIViewController { /// 开启bitMex通知 注意 需要实现监听方法 /// /// - Parameter subscribeTypeArray: 需要监听的通知类型 final func addBitMex(subscribeTypeArray: [BitMexSubscribeType]){ _ = (BitMexWebSocketFactory().getWebSocket() as! BitMexWebSocket) if subscribeTypeArray.contains(.instrument){ addInstrumentNoti() } if subscribeTypeArray.contains(.OrderBook10){ addOrderBook10Noti() } if subscribeTypeArray.contains(.trade){ addTradeNoti() } if subscribeTypeArray.contains(.tradeBin1m){ addTradeBin1mNoti() } } final func getBitMexWebSocket() -> BitMexWebSocket { return BitMexWebSocketFactory().getWebSocket() as! BitMexWebSocket } final func addInstrumentNoti(){ NotificationCenter.default.addObserver(self, selector: #selector(receiveInstrumentNoti(noti:)), name: COINNotificationKeys.instrument, object: nil) } final func addOrderBook10Noti(){ NotificationCenter.default.addObserver(self, selector: #selector(receiveOderBook10Noti(noti:)), name: COINNotificationKeys.orderBook10, object: nil) } final func addTradeNoti(){ NotificationCenter.default.addObserver(self, selector: #selector(receiveTradeNoti(noti:)), name: COINNotificationKeys.trade, object: nil) } final func addTradeBin1mNoti(){ NotificationCenter.default.addObserver(self, selector: #selector(receiveTradeBin1mNoti(noti:)), name: COINNotificationKeys.tradeBin1m, object: nil) } //MARK: ------------- 发送命令 ----------------- /// 添加symbol的多种监听类型 /// /// - Parameters: /// - symbol: 合约名称 /// - subscribeTypeArray: 多种监听类型 /// - cancelState: 是否可以取消 默认是可取消 .could final func startSubscribeArray_bitMex(symbol: String, subscribeTypeArray: [BitMexSubscribeType], cancelState: BitMexSubscribeCancelState = .could){ for subscribeType in subscribeTypeArray { startSubscribe_bitMex(symbol: symbol, subscribeType: subscribeType, cancelState: cancelState) } } /// 取消symbol的多种监听类型 /// /// - Parameters: /// - symbol: 合约名称 /// - subscribeTypeArray: 多种监听类型 final func startCancelArray_bitMex(symbol: String, subscribeTypeArray: [BitMexSubscribeType]){ for subscribeType in subscribeTypeArray { startCancel_bitMex(symbol: symbol, subscribeType: subscribeType) } } /// 添加symbol的单个监听类型 /// /// - Parameters: /// - symbol: 合约名称 /// - subscribeType: 单个监听类型 /// - cancelState: 是否可以取消 默认是可取消 .could final func startSubscribe_bitMex(symbol: String, subscribeType: BitMexSubscribeType, cancelState: BitMexSubscribeCancelState = .could){ let dict = [ "op": "subscribe", "args":"\(subscribeType.rawValue):\(symbol)" ] as [String : Any] if cancelState == .could { getBitMexWebSocket().sendStrMessage(string: dict.tojsonStr()!) }else{ getBitMexWebSocket().sendStrMessageCannotCancel(string: dict.tojsonStr()!) } } /// 取消symbol的单个监听类型 /// /// - Parameters: /// - symbol: 合约名称 /// - subscribeType: 单个监听类型 final func startCancel_bitMex(symbol: String, subscribeType: BitMexSubscribeType){ let dict = [ "op": "unsubscribe", "args":"\(subscribeType.rawValue):\(symbol)" ] as [String : Any] getBitMexWebSocket().sendStrMessage(string: dict.tojsonStr()!) } //MARK: ------------- 需要覆盖的方法 ----------------- ///Book10 的回调方法 需要重新实现 /// /// - Parameter noti: Book10 的通知数据 @objc func receiveOderBook10Noti(noti: Notification){} /// Instrument 的回调方法 需要重新实现 /// /// - Parameter noti: Instrument 的通知数据 @objc func receiveInstrumentNoti(noti: Notification){} /// trade 的回调方法 需要重新实现 /// /// - Parameter noti: trade 的通知数据 @objc func receiveTradeNoti(noti: Notification){} /// tradeBin1m 的回调方法 需要重新实现 /// /// - Parameter noti: tradeBin1m 的通知数据 @objc func receiveTradeBin1mNoti(noti: Notification){} // func startSubscribeInstrument(_ symbol: String, cannotCancel: Bool = false){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"subscribe\", \"args\": [\"instrument:\(symbol)\"]}" // // if cannotCancel { // getBitMexWebSocket().sendStrMessageCannotCancel(string: subscribeStr) // }else{ // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } // } // // // func startSubscribe(_ symbol:String,subscribeType: [BitMexSubscribeType] = [.instrument]){ // if subscribeType.contains(.instrument) { // startSubscribeInstrument(symbol) // } // if subscribeType.contains(.OrderBook10) { // startSubscribeOrderBook10(symbol) // } // } // func startCancelSubscribe(_ symbol:String,subscribeType: [BitMexSubscribeType] = [.instrument]){ // // if subscribeType.contains(.instrument) { // startCancelInstrument(symbol) // } // if subscribeType.contains(.OrderBook10) { // startCancelSubscribeOrderBook10(symbol) // } // } // // func startCancelInstrument(_ symbol: String){ // //debugPrint("startCancel",symbol) // let unsubscribeStr = "{\"op\": \"unsubscribe\", \"args\": [\"instrument:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: unsubscribeStr) // } // // func startSubscribeOrderBook10(_ symbol: String){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"subscribe\", \"args\": [\"orderBook10:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } // // func startCancelSubscribeOrderBook10(_ symbol: String){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"unsubscribe\", \"args\": [\"orderBook10:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } // // func startTradeSubscribe(_ symbol: String){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"subscribe\", \"args\": [\"trade:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } // func startTradeBin1mSubscribe(_ symbol: String){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"subscribe\", \"args\": [\"tradeBin1m:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } // func startCancelTradeBin1mSubscribe(_ symbol: String){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"unsubscribe\", \"args\": [\"trade:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } // func startCancelTradeSubscribe(_ symbol: String){ // //debugPrint("startSubscribe",symbol) // let subscribeStr = "{\"op\": \"unsubscribe\", \"args\": [\"instrument:\(symbol)\"]}" // getBitMexWebSocket().sendStrMessage(string: subscribeStr) // } }
35.290043
156
0.618376
fe150193575b82f6dc884e0351db583895ccdf6e
594
// // File.swift // // // Created by Nickolay Truhin on 02.12.2020. // import Foundation public extension JSONDecoder { static var snakeCased: JSONDecoder = { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.dateDecodingStrategy = .iso8601 return decoder }() } public extension JSONEncoder { static var snakeCased: JSONEncoder = { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase encoder.dateEncodingStrategy = .iso8601 return encoder }() }
22
59
0.666667
67500d97aa1bfb1d56f5f507b5b5ed1d2de2dd5e
882
// // UserTests.swift // UserTests // // Created by Adriano Dias on 27/09/20. // import XCTest @testable import User class UserTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.941176
111
0.657596
338f8120b9ec8ad3c3753539649ef915c113a6bd
1,343
// // AppDelegate.swift // Example-iOS // // Created by lau on 2021/5/29. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.297297
179
0.744602
725f9a84b4dd45cb20ec43a0c98ea5a70c098526
958
// // AnimationImageProvider.swift // Lottie_iOS // // Created by Alexandr Goncharov on 07/06/2019. // import Foundation /** Text provider is a protocol that is used to supply text to `AnimationView`. */ public protocol AnimationTextProvider: AnyObject { func textFor(keypathName: String, sourceText: String) -> String } /// Text provider that simply map values from dictionary public final class DictionaryTextProvider: AnimationTextProvider { public init(_ values: [String: String]) { self.values = values } let values: [String: String] public func textFor(keypathName: String, sourceText: String) -> String { return values[keypathName] ?? sourceText } } /// Default text provider. Uses text in the animation file public final class DefaultTextProvider: AnimationTextProvider { public func textFor(keypathName: String, sourceText: String) -> String { return sourceText } public init() {} }
26.611111
76
0.715031
908cca59da4b88d2bc901b8152a4d46fa314720f
75
@objc public protocol ListIDRepresentable { var listID: ListID { get } }
15
43
0.733333
8fd32a2a7a7eef821db23447b48f21df0df11d6e
1,346
// // BannerView.swift // ComicsInfo // // Created by Aleksandar Dinic on 30/08/2021. // import SwiftUI struct BannerView: View { @State private var isLoading = true @Binding var showBanner: Bool let adUnitID: String var body: some View { HStack { Spacer() ZStack(alignment: .topTrailing) { GoogleBannerViewController( didReceiveAd: { withAnimation { isLoading = false } } ) .frame(width: 320, alignment: .center) // Image(systemName: "xmark.square.fill") // .opacity(isLoading ? 0 : 1) // .foregroundColor(.red) // .background(Color.white) // .onTapGesture { // withAnimation { // showBanner.toggle() // } // } } Spacer() } .frame(height: isLoading ? 0 : 50) } } struct BannerView_Previews: PreviewProvider { @State static var showBanner = true static var previews: some View { BannerView(showBanner: $showBanner, adUnitID: Environment.adUnitID) } }
24.925926
75
0.455423
562ad033e6f7814781e9d7fc33f9408f2bab07ee
535
// // ArcTableViewCell.swift // BFWControls Demo // // Created by Tom Brodhurst-Hill on 9/8/18. // Copyright © 2018 BareFeetWare. All rights reserved. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit import BFWControls @IBDesignable class ArcTableViewCell: NibTableViewCell { @IBOutlet weak var arcView: ArcView! @IBInspectable var arcEnd: Double { get { return arcView.end } set { arcView.end = newValue } } }
19.814815
71
0.631776
385c7cc1d15893efc5eb2b35cf7bb2c745ca3f96
487
// // ViewController.swift // DY // // Created by imac on 2018/3/14. // Copyright © 2018年 imac. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
18.730769
80
0.659138
21625c9ca9f83c5b572339333afa39cda5c11e56
15,410
// // HashMap.swift // Algorithm // // Created by 孙虎林 on 2020/11/27. // import Foundation // 2的倍数 let MapDefaultCapacity = 1 << 3 let MapNotFound = -1 class HashMap { typealias Node = KVNode<String, Int> typealias K = String typealias V = Int private var tables: Array<Node> private var defaultCapacity = MapDefaultCapacity private(set) var size = 0 init(capacity: Swift.Int) { defaultCapacity = capacity tables = Array<Node>(repeating: Node(k: "", v: -1), count: defaultCapacity) tableSetup() } convenience init () { self.init(capacity: MapDefaultCapacity) } public func isEmpty() -> Bool { return size == 0 } public func clear() { for node in tables { if isNullNode(node: node) { continue } else { makeNullNode(node: node) } } size = 0 } public func put(key: K, value: V) -> V { let idx = index(key: key) let idxNode = tables[idx] let newNode = Node(k: key, v: value) // 位置是空的.插入 if isNullNode(node: idxNode) { // 根节点 newNode.parent = nil tables[idx] = newNode } else { // hash 冲突 // 找到父节点。插进去 var node:Node? = idxNode var parent: Node! var compareValue = 0 while node != nil { if let nd = node { parent = nd compareValue = compare(key1: key, key2: nd.key) if compareValue < 0 { node = node?.left } else if compareValue > 0 { node = node?.right } else { // 相等 nd.value = value break } } } // 添加: 这个时候 parent有值了 compareValue 代表添加在左右 newNode.parent = parent if compareValue > 0 { parent.right = newNode } else if compareValue < 0 { parent.left = newNode } else { // do nothing } } size+=1 afterAddNode(node: newNode) return newNode.value } public func get(key: K) -> V? { if let nd = getNode(key: key){ return nd.value } return MapNotFound } public func remove(key: K) { guard let nd = getNode(key: key) else { return } remove(node: nd) } public func containKey(_ key: K) -> Bool { guard let _ = getNode(key: key) else { return false } return true } private func index(key: K) -> Int { if key.count == 0 { return 0 } // key.hash % index return key.hash & (defaultCapacity - 1) } private func isNullNode(node: Node) -> Bool { return node.key == "" && node.value == -1 } private func compare(key1: K, key2: K) -> Int { if key1 > key2 { return 1 } else if key1 < key2 { return -1 } else { return 0 } } private func afterAddNode(node: Node) { // 添加的是根节点 if !node.hasParent() { _ = black(node: node) return } // 父节点是黑色,添加红色不需要处理 : 4中情况 if isBlack(node: node.parent) { return } // 父节点是红色,双红,需要处理下 let parent = node.parent! let uncle = parent.sibling() let grand = parent.parent! // 如果uncle 是红色,那么是 原来的节点(B树节点)为红黑红。 会发生上溢 -> 红黑红 4种情况 if isRed(node: uncle) { _ = black(node: parent) if let uc = uncle { _ = black(node: uc) } // 将grand染成红色,当做新节点添加 _ = red(node: grand) afterAddNode(node: grand) return } // 能来到这里 uncle节点 不是红色 .则旋转 红黑 , 黑红 4种情况 if parent.isLeftChild() { // L if node.isLeftChild() { // LL // 将父节点染成黑色, _ = black(node: parent) _ = red(node: grand) rotateRight(node: grand) } else { // LR _ = black(node: node) _ = red(node: grand) rotateLeft(node: parent) rotateRight(node: grand) } } else { //R if node.isLeftChild() { // RL _ = black(node: node) _ = red(node: grand) rotateRight(node: parent) rotateLeft(node: grand) } else { // RR _ = black(node: parent) _ = red(node: grand) rotateLeft(node: grand) } } } /// 右旋转 LL /// - Parameter node: grand节点 private func rotateRight(node: Node) { let grand = node let parent = grand.left let child = parent?.right parent?.right = grand grand.left = child afterRotate(grand: grand, parent: parent!, child: child) } /// 左旋转 RR /// - Parameter node: grand private func rotateLeft(node: Node) { let grand = node let parent = grand.right let child = parent?.left parent?.left = grand grand.right = child afterRotate(grand: grand, parent: parent!, child: child) } /// 旋转之后的操作 /// - Parameters: /// - grand: grand /// - parent: p /// - child: p的子节点 private func afterRotate(grand: Node, parent: Node, child: Node?) { // 让p成为root if grand.isLeftChild() { grand.parent?.left = parent } else if grand.isRightChild() { grand.parent?.right = parent } else { // 获取key let idx = index(key: parent.key) tables[idx] = parent } parent.parent = grand.parent grand.parent = parent child?.parent = grand } /// 染色 private func makeMolor(node: Node, color: NodeColor) -> Node { node.color = color return node } private func red(node: Node) -> Node { makeMolor(node: node, color: .Red) } private func black(node: Node) -> Node { makeMolor(node: node, color: .Black) } private func isBlack(node: Node?) -> Bool { /// 虚拟节点默认为黑色 guard let nd = node else { return true } return nd.color == .Black } private func isRed(node: Node?) -> Bool { guard let nd = node else { return false } return nd.color == .Red } /// 三种情况:删除叶子节点 ,删除节点度为1的,删除节点度为2的 /// 删除节点 /// - Parameter node: 删除节点 private func remove(node: Node) { size-=1 var toDelete = node var replace: Node? // 度为2 if toDelete.hasTwoChild() { // 找到他的前驱节点 let predessor = predecessor(node: node) guard let prede = predessor else { return } // 替换值 node.key = prede.key node.value = prede.value ///////////////// 度为2的节点,他的前驱或者后继节点只能为0 或者1 /////////////////////////////////// toDelete = prede // 标记这个要删除的节点, } // 下面分别处理 删除 0 1的情况 /// 删除的是叶子节点 if toDelete.isLeaf() { /// 有父节点 if toDelete.hasParent() { if toDelete.isLeftChild() { toDelete.parent!.left = nil } if toDelete.isRightChild() { toDelete.parent!.right = nil } } else { // 叶子节点,且没有父节点。那么只能是根节点。删除的是根节点 let idx = index(key: node.key) let idxNode = tables[idx] makeNullNode(node: idxNode) tables[idx] = idxNode } replace = nil } /// 删除的度为1的节点 if toDelete.hasSingleChild() { let replaceNode = toDelete.hasLeft() ? toDelete.left! : toDelete.right! if toDelete.hasParent() { replace = replaceNode if toDelete.isLeftChild() { toDelete.parent?.left = replaceNode } else { toDelete.parent?.right = replaceNode } replaceNode.parent = toDelete.parent } else { // 删除的是根节点 let idx = index(key: node.key) tables[idx] = replaceNode // 根节点无父节点 replaceNode.parent = nil replace = nil } } // toDelete parent 这根线不能断 afterRemoveNode(node: toDelete,replacement: replace) } /// 删除节点 /// - Parameters: /// - node: 删除的节点 /// - replacement: 用以替代删除节点的节点,单叶子节点 private func afterRemoveNode(node: Node, replacement: Node?) { // 如果删除的是红色,啥也不用干 if isRed(node: node) { return } // 删除的是黑色根节点 if node.parent == nil { return } // 处理删除黑色的情况 // 用以替代的节点时红色,是叶子节点,那么将它染黑就好。 if let rp = replacement, isRed(node: rp) { _ = black(node: rp) return } // 能来到这里,删除的是叶子节点。单个黑 // 获取parent let parent = node.parent! // 获取兄弟节点 // 这个节点也就被删除了。那么通过node.sibling拿不到兄弟节点,只能判断当初删除的是那边获取兄弟节点 // 删除的是左边 let left = parent.left == nil || node.isLeftChild() // 兄弟节点一定有值,因为4阶B树的节点个数为1-3个 var sibling = left ? parent.right! : parent.left! // 判断方向,涉及到旋转 // 删除的叶子节点时左节点 if left { if isBlack(node: sibling) { if isBlack(node: sibling.left) && isBlack(node: sibling.right) { if isRed(node: parent) { _ = red(node: sibling) _ = black(node: parent) } else { _ = red(node: sibling) afterRemoveNode(node: parent, replacement: nil) } } else { if sibling.hasRight() { rotateLeft(node: parent) _ = makeMolor(node: sibling, color: parent.color) _ = black(node: parent) _ = black(node: sibling.right!) } else { rotateRight(node: sibling) rotateLeft(node: parent) _ = makeMolor(node: sibling.left!, color: parent.color) _ = black(node: parent) } } } else { rotateLeft(node: parent) _ = black(node: parent) _ = red(node: sibling) afterRemoveNode(node: node, replacement: nil) } } else { // 判断是不是黑兄弟 if isBlack(node: sibling) { // 黑兄弟没有节点借给我 if isBlack(node: sibling.left) && isBlack(node: sibling.right) { // 黑兄弟借不了。那么只能父节点下移合并 if isRed(node: parent) { _ = red(node: sibling) _ = black(node: parent) } else { // 父节点也是黑色。下移合并也会发生下溢 _ = red(node: sibling) // 把parent当做删除的节点 afterRemoveNode(node: parent, replacement: nil) } } else { // 黑兄弟,并且有一个或者两个红色节点借给我 if sibling.hasLeft() { // LL rotateRight(node: parent) // 中心节点继承parent颜色 _ = makeMolor(node: sibling, color: parent.color) _ = black(node: parent) _ = black(node: sibling.left!) } else { // LR rotateLeft(node: sibling) rotateRight(node: parent) _ = makeMolor(node: sibling.right!, color: parent.color) _ = black(node: parent) } } } else { // 兄弟节点为红色,兄弟没得借,这个时候应该问兄弟的儿子借,因为兄弟不在一个层级上 // 让跟兄弟的儿子做兄弟 -> 旋转 LL _ = black(node: sibling) _ = red(node: parent) rotateRight(node: parent) sibling = parent.left! // 兄弟要变一下 afterRemoveNode(node: node, replacement: nil) } } } public func predecessor(node: Node?) -> Node? { guard let nd = node else { return nil } // 前驱节点一定左子树中。 if nd.hasLeft() { var predecessor = nd.left! while predecessor.right != nil { predecessor = predecessor.right! } return predecessor } // 没有左节点。 if !nd.hasLeft() && nd.hasParent() { var current = nd while current.parent != nil && !current.isRightChild() { current = current.parent! } return current.hasParent() ? current.parent! : nil } if !nd.hasParent() && !nd.hasLeft(){ return nil } return nil } /// 中序遍历 // private func travse(node: Node, _ visitor: (Node)-> Bool) { // if node.hasLeft() { // travse(node: node.left!, visitor) // } // if visitor(node) { // return // } // if node.hasRight() { // travse(node: node.right!, visitor) // } // } /// 通过key获取node /// - Parameter key: key /// - Returns: node private func getNode(key: K) -> Node? { if isEmpty() { return nil } let idx = index(key: key) let idxNode = tables[idx] if idxNode.key == key { return idxNode } // 能来到这里,就是有hash冲突的情况 // 遍历红黑树,获取key的node var node: Node? = idxNode while node != nil { if let nd = node { let compareValue = compare(key1: key, key2: nd.key) if compareValue == 0 { return nd } else if compareValue < 0 { node = node?.left } else { node = node?.right } } } return nil } private func makeNullNode(node: Node) { if isNullNode(node: node) { return } node.key = "" node.value = -1 node.left = nil node.right = nil } private func tableSetup() { for node in tables { node.parent = nil _ = black(node: node) } } } extension HashMap { public class func hashMapTest() { let map = HashMap() _ = map.put(key: "1", value: 1) _ = map.put(key: "1", value: 3) _ = map.put(key: "2", value: 14) _ = map.put(key: "3", value: 13) _ = map.put(key: "4", value: 12) _ = map.put(key: "5", value: 11) print("--") } }
29.521073
91
0.445555
b9e29ffb52e83544679e41a8ee72caf1064d0d73
2,109
// // AppDelegate.swift // SlotMachine // // Created by Kenneth Wilcox on 12/30/14. // Copyright (c) 2014 Kenneth Wilcox. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
45.847826
281
0.770507
e0b1ab34c0157cf90024ed8cde5f8bd129d6e562
442
// // Model.swift // TestApplication // // Created by nastia on 23.11.16. // Copyright © 2016 Anastasiia Soboleva. All rights reserved. // import Foundation struct Person { let firstName: String let secondName: String /* failable initialiser */ init?(firstName fn: String?, secondName sn: String?) { guard let fn = fn, let sn = sn, !fn.isEmpty, !sn.isEmpty else { return nil } firstName = fn secondName = sn } }
15.785714
65
0.660633
1cf35782291765c197f75dc987eb20301a8da077
152
// // Titleable.swift // // // Created by Ben Gottlieb on 9/13/20. // import Foundation public protocol Titleable { var title: String { get } }
10.857143
39
0.638158
f7d4373e76a28c3ba8f10ffc3a5e016792c5cc1d
2,093
// // TemplateCollectionViewController.swift // collects.art // // Created by Nozlee Samadzadeh on 4/24/17. // Copyright © 2017 Nozlee Samadzadeh and Bunny Rogers. All rights reserved. // import UIKit protocol TemplateDelegate { func saveTemplate(index: Int) } class TemplateCollectionViewCell: UICollectionViewCell { @IBOutlet var templateView: UIImageView! } class TemplateCollectionViewController: UICollectionViewController { var templateIndex: Int! var timestamp: String! var templates: NSArray = UserDefaults.standard.object(forKey: "templates") as! NSArray var delegate: TemplateDelegate! override func viewWillAppear(_ animated: Bool) { self.view?.superview?.layer.cornerRadius = 0 super.viewWillAppear(animated) } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return templates.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TemplateCollectionViewCell", for: indexPath) as! TemplateCollectionViewCell let template = templates.object(at: indexPath.row) as! NSDictionary let url = template.value(forKey: "url") as! String cell.templateView.af_setImage(withURL: URL(string: url)!) cell.layer.borderWidth = 1.0 cell.layer.cornerRadius = 0 if templateIndex == template.value(forKey: "index") as! Int { cell.layer.borderColor = UIColor.gray.cgColor } else { cell.layer.borderColor = UIColor.clear.cgColor } return cell } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { templateIndex = (templates.object(at: indexPath.row) as! NSDictionary).value(forKey: "index") as! Int delegate.saveTemplate(index: templateIndex) } }
29.478873
147
0.752031
14f53f5f31d670ee87de1632b4fffaac1d6cc9fc
2,395
/*: # Iterator for Combination https://leetcode.com/explore/challenge/card/august-leetcoding-challenge/550/week-2-august-8th-august-14th/3422/ --- ### Problem Statement: Design an Iterator class, which has: + A constructor that takes a string `characters` of sorted distinct lowercase English letters and a number `combinationLength` as arguments. + A function next() that returns the next combination of length `combinationLength` in lexicographical order. + A function `hasNext()` that returns `True` if and only if there exists a next combination. ### Example: ``` CombinationIterator iterator = new CombinationIterator("abc", 2); // creates the iterator. iterator.next(); // returns "ab" iterator.hasNext(); // returns true iterator.next(); // returns "ac" iterator.hasNext(); // returns true iterator.next(); // returns "bc" iterator.hasNext(); // returns false ``` ### Constraints: + 1 <= combinationLength <= characters.length <= 15 + There will be at most 10^4 function calls per test. + It's guaranteed that all calls of the function next are valid. ### Hint: + Generate all combinations as a preprocessing. + Use bit masking to generate all the combinations. */ import UIKit // 16 / 16 test cases passed. // Status: Accepted // Runtime: 68 ms // Memory Usage: 21.8 MB class CombinationIterator { private var queue = [String]() init(_ characters: String, _ combinationLength: Int) { generateCombinations(Array(characters), combinationLength, 0, "") } func next() -> String { return queue.removeFirst() } func hasNext() -> Bool { return !queue.isEmpty } private func generateCombinations(_ characters: [Character], _ len: Int, _ index: Int, _ temp: String) { if temp.count == len { queue.append(temp) return } for i in index..<characters.count { generateCombinations(characters, len, i + 1, temp + String(characters[i])) } } } // Your CombinationIterator object will be instantiated and called as such: let obj = CombinationIterator("abc", 2) let ret_1: String = obj.next() // ab let ret_2: Bool = obj.hasNext() // true let ret_3: String = obj.next() // ac let ret_4: Bool = obj.hasNext() // true let ret_5: String = obj.next() // bc let ret_6: Bool = obj.hasNext() // false
27.528736
141
0.66263
208cbf1e6a008e4ce81b281199a594f6ee262621
15,586
// // FundsRequestDetailsViewController.swift // MyMonero // // Created by Paul Shapiro on 7/12/17. // Copyright (c) 2014-2019, MyMonero.com // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // import UIKit import PKHUD class FundsRequestDetailsViewController: UICommonComponents.Details.ViewController { // // Constants/Types let fieldLabels_variant = UICommonComponents.Details.FieldLabel.Variant.middling // // Properties var fundsRequest: FundsRequest // let sectionView_instanceCell = UICommonComponents.Details.SectionView(sectionHeaderTitle: nil) let sectionView_codeAndLink = UICommonComponents.Details.SectionView(sectionHeaderTitle: nil) let sectionView_message = UICommonComponents.Details.SectionView(sectionHeaderTitle: nil) var deleteButton: UICommonComponents.LinkButtonView! // // // Imperatives - Init init(fundsRequest: FundsRequest) { self.fundsRequest = fundsRequest super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // // Overrides override func setup_views() { super.setup_views() do { let sectionView = self.sectionView_instanceCell do { let view = UICommonComponents.Details.FundsRequestCellFieldView( fundsRequest: self.fundsRequest, displayMode: .noQRCode ) sectionView.add(fieldView: view) } self.scrollView.addSubview(sectionView) } do { let sectionView = self.sectionView_codeAndLink do { let view = QRImageButtonDisplayingFieldView( labelVariant: self.fieldLabels_variant, title: NSLocalizedString("QR Code", comment: ""), tapped_fn: { [unowned self] in self.qrImageFieldView_tapped() } ) let image = QRCodeImages.new_qrCode_UIImage( // generating a new image here - is this performant enough? fromCGImage: self.fundsRequest.qrCode_cgImage, withQRSize: .medium ) view.set(image: image) sectionView.add(fieldView: view) } do { let view = UICommonComponents.Details.SharableLongStringFieldView( labelVariant: self.fieldLabels_variant, title: NSLocalizedString("Request Link", comment: ""), valueToDisplayIfZero: nil ) view.contentLabel.lineBreakMode = .byCharWrapping // flows better w/o awkward break let url = self.fundsRequest.new_URI(inMode: .addressAsAuthority) // clickable view.set(text: url.absoluteString, url: url) sectionView.add(fieldView: view) } self.scrollView.addSubview(sectionView) } do { let sectionView = self.sectionView_message do { let view = UICommonComponents.Details.SharableLongStringFieldView( labelVariant: self.fieldLabels_variant, title: NSLocalizedString("Message for Requestee", comment: ""), valueToDisplayIfZero: nil ) view.set( text: self.new_requesteeMessagePlaintextString, ifNonNil_overridingTextAndZeroValue_attributedDisplayText: self.new_requesteeMessageNSAttributedString ) sectionView.add(fieldView: view) } self.scrollView.addSubview(sectionView) } do { let view = UICommonComponents.LinkButtonView(mode: .mono_destructive, size: .larger, title: "DELETE REQUEST") view.addTarget(self, action: #selector(deleteButton_tapped), for: .touchUpInside) self.deleteButton = view self.scrollView.addSubview(view) } // self.view.borderSubviews() self.view.setNeedsLayout() } override func setup_navigation() { super.setup_navigation() self.set_navigationTitle() // also to be called on contact info updated } // override func startObserving() { super.startObserving() NotificationCenter.default.addObserver(self, selector: #selector(wasDeleted), name: PersistableObject.NotificationNames.wasDeleted.notificationName, object: self.fundsRequest) } override func stopObserving() { super.stopObserving() NotificationCenter.default.removeObserver(self, name: PersistableObject.NotificationNames.wasDeleted.notificationName, object: self.fundsRequest) } // // Accessors - Overrides override var overridable_wantsBackButton: Bool { return true } override func new_contentInset() -> UIEdgeInsets { var inset = super.new_contentInset() inset.bottom += 14 return inset } // // Accessors - Factories var new_requesteeMessagePlaintextString: String { let hasAmount = self.fundsRequest.amount != nil && self.fundsRequest.amount != "" // // var value = "" // must use \r\n instead of \n for Windows if hasAmount == false { value += String( format: NSLocalizedString( "Someone has requested a %@ payment.", comment: "Someone has requested a {Monero} payment." ), MoneroConstants.currency_name ) } else { value += String( format: NSLocalizedString( "Someone has requested a %@ payment of %@ %@.", comment: "Someone has requested a {Monero} payment of {amount} {currency symbol}." ), MoneroConstants.currency_name, self.fundsRequest.amount!, (self.fundsRequest.amountCurrency ?? MoneroConstants.currency_symbol) ) } var numberOfLinesAddedInSection = 0 do { if let message = self.fundsRequest.message, message != "" { value += "\r\n" // spacer value += "\r\n" // linebreak value += String( format: NSLocalizedString( "Memo: \"%@\"", comment: "Memo: \"{Monero request message memo}\"" ), message ) numberOfLinesAddedInSection += 1 } if let description = self.fundsRequest.description, description != "" { value += "\r\n" // spacer value += "\r\n" // linebreak value += String( format: NSLocalizedString( "Description: \"%@\"", comment: "Description: \"{Monero request message description}\"" ), description ) numberOfLinesAddedInSection += 1 } } value += "\r\n" // spacer value += "\r\n" // linebreak value += "------------" value += "\r\n" // linebreak value += NSLocalizedString("If you have MyMonero installed, use this link to send the funds: ", comment: "") value += self.fundsRequest.new_URI(inMode: .addressAsAuthority).absoluteString // addr as authority b/c we want it to be clickable value += "\r\n" // spacer value += "\r\n" // linebreak value += String(format: NSLocalizedString( "If you don't have MyMonero installed, download it from %@", comment: "" ), Homepage.appDownloadLink_fullURL ) // return value } var new_requesteeMessageNSAttributedString: NSAttributedString { let value = self.new_requesteeMessagePlaintextString let value_NSString = value as NSString let attributes: [NSAttributedString.Key : Any] = [:] let attributedString = NSMutableAttributedString(string: value, attributes: attributes) let linkColor = UIColor.white attributedString.addAttributes( [ NSAttributedString.Key.foregroundColor: linkColor ], range: value_NSString.range(of: self.fundsRequest.new_URI(inMode: .addressAsAuthority).absoluteString) // clickable addr ) attributedString.addAttributes( [ NSAttributedString.Key.foregroundColor: linkColor ], range: value_NSString.range(of: Homepage.appDownloadLink_fullURL) ) // return attributedString } // // Imperatives func set_navigationTitle() { self.navigationItem.title = NSLocalizedString("Monero Request", comment: "") } // // Overrides - Layout override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // let subviewLayoutInsets = self.new_subviewLayoutInsets let label_x = CGFloat.form_label_margin_x + subviewLayoutInsets.left // let section_x = subviewLayoutInsets.left let section_w = self.scrollView/*not view*/.bounds.size.width - subviewLayoutInsets.left - subviewLayoutInsets.right self.sectionView_instanceCell.layOut( withContainingWidth: section_w, // since width may have been updated… withXOffset: section_x, andYOffset: self.yOffsetForViewsBelowValidationMessageView ) self.sectionView_codeAndLink.layOut( withContainingWidth: section_w, // since width may have been updated… withXOffset: section_x, andYOffset: self.sectionView_instanceCell.frame.origin.y + self.sectionView_instanceCell.frame.size.height + UICommonComponents.Details.SectionView.interSectionSpacing ) self.sectionView_message.layOut( withContainingWidth: section_w, // since width may have been updated… withXOffset: section_x, andYOffset: self.sectionView_codeAndLink.frame.origin.y + self.sectionView_codeAndLink.frame.size.height + UICommonComponents.Details.SectionView.interSectionSpacing ) // self.deleteButton.frame = CGRect( x: label_x, y: self.sectionView_message.frame.origin.y + self.sectionView_message.frame.size.height + UICommonComponents.Details.SectionView.interSectionSpacing, width: self.deleteButton.frame.size.width, height: self.deleteButton.frame.size.height ) // self.scrollableContentSizeDidChange( withBottomView: self.deleteButton, bottomPadding: 12 ) // btm padding in .contentInset } // // Delegation @objc func deleteButton_tapped() { let generator = UINotificationFeedbackGenerator() generator.prepare() generator.notificationOccurred(.warning) // let alertController = UIAlertController( title: NSLocalizedString("Delete this request?", comment: ""), message: NSLocalizedString( "Delete this request? This cannot be undone.", comment: "" ), preferredStyle: .alert ) alertController.addAction( UIAlertAction( title: NSLocalizedString("Cancel", comment: ""), style: .default ) { (result: UIAlertAction) -> Void in } ) alertController.addAction( UIAlertAction( title: NSLocalizedString("Delete", comment: ""), style: .destructive ) { (result: UIAlertAction) -> Void in let err_str = FundsRequestsListController.shared.givenBooted_delete(listedObject: self.fundsRequest) if err_str != nil { self.setValidationMessage(err_str!) return } // wait for wasDeleted() } ) self.navigationController!.present(alertController, animated: true, completion: nil) } // // Delegation - Notifications - Object @objc func wasDeleted() { // was instead of willBe b/c willBe is premature and won't let us see a returned deletion error // but we must perform this method's operations on next tick so as not to prevent delete()'s err_str from being returned before we can perform them DispatchQueue.main.async { if self.navigationController!.topViewController! != self { assert(false) return } self.navigationController!.popViewController(animated: true) } } // // Delegation - Interactions func qrImageFieldView_tapped() { let controller = FundsRequestQRDisplayViewController(fundsRequest: self.fundsRequest) let navigationController = UICommonComponents.NavigationControllers.SwipeableNavigationController(rootViewController: controller) self.navigationController!.present(navigationController, animated: true, completion: nil) } } // // extension UICommonComponents.Details { class FundsRequestCellFieldView: UICommonComponents.Details.FieldView { // // Constants - Overrides override var contentInsets: UIEdgeInsets { return UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0) } // // Constants static let cellHeight: CGFloat = 80 // // Properties var cellContentView: FundsRequestsCellContentView! // // Init init( fundsRequest: FundsRequest, displayMode: FundsRequestsCellContentView.DisplayMode? = .withQRCode ) { do { let view = FundsRequestsCellContentView(displayMode: displayMode ?? .withQRCode) self.cellContentView = view view.willBeDisplayedWithRightSideAccessoryChevron = false // so we get proper right margin view.configure(withObject: fundsRequest) } super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setup() { super.setup() self.addSubview(self.cellContentView) } // // Imperatives - Layout - Overrides override func layOut( withContainerWidth containerWidth: CGFloat, withXOffset xOffset: CGFloat, andYOffset yOffset: CGFloat ) { let contentInsets = self.contentInsets let content_x: CGFloat = contentInsets.left let content_rightMargin: CGFloat = contentInsets.right let content_w = containerWidth - content_x - content_rightMargin // self.cellContentView.frame = CGRect( x: content_x, y: contentInsets.top, width: content_w, height: FundsRequestCellFieldView.cellHeight ) // self.frame = CGRect( x: xOffset, y: yOffset, width: containerWidth, height: FundsRequestCellFieldView.cellHeight ) } } } class QRImageButtonDisplayingFieldView: UICommonComponents.Details.ImageButtonDisplayingFieldView { // // Properties var qrCodeMatteView: UIImageView! // // Properties - Overrides override var _bottomMostView: UIView { return self.qrCodeMatteView // to support proper bottom inset } // override func setup() { super.setup() do { let view = UIImageView( image: FundsRequestCellQRCodeMatteCells.stretchableImage ) self.qrCodeMatteView = view self.insertSubview(view, at: 0) // underneath image } } // override func layOut_contentView(content_x: CGFloat, content_w: CGFloat) { // not going to call on super let qrCodeImageSide = QRCodeImages.QRSize.medium.side let qrCodeInsetFromMatteView: CGFloat = 3 let offsetFromImage = CGFloat(FundsRequestCellQRCodeMatteCells.imagePaddingInset) + qrCodeInsetFromMatteView let qrCodeMatteViewSide: CGFloat = qrCodeImageSide + 2*offsetFromImage self.qrCodeMatteView!.frame = CGRect( x: content_x + 1 - CGFloat(FundsRequestCellQRCodeMatteCells.imagePaddingInset), // +1 for visual, y: self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 12 - CGFloat(FundsRequestCellQRCodeMatteCells.imagePaddingInset), width: qrCodeMatteViewSide, height: qrCodeMatteViewSide ).integral self.contentImageButton.frame = self.qrCodeMatteView!.frame.insetBy( dx: offsetFromImage, dy: offsetFromImage ).integral } }
33.091295
177
0.7338
d9bc375ca4188e28db045ab300a38ef48becb271
2,509
// Router.swift // // Copyright (c) 2016 Auth0 (http://auth0.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. import Foundation import UIKit import Auth0 protocol Router: Navigable { var observerStore: ObserverStore { get } var controller: LockViewController? { get } var root: Presentable? { get } } extension Router { func present(_ controller: UIViewController) { self.controller?.present(controller, animated: true, completion: nil) } func resetScroll(_ animated: Bool) { self.controller?.scrollView.setContentOffset(CGPoint.zero, animated: animated) } func scroll(toPosition: CGPoint, animated: Bool) { self.controller?.scrollView.setContentOffset(toPosition, animated: animated) } func exit(withError error: Error) { let controller = self.controller?.presentingViewController let observerStore = self.observerStore Queue.main.async { controller?.dismiss(animated: true, completion: { observerStore.onFailure(error) }) } } func reload(with connections: Connections) { self.controller?.reload(connections: connections) } func unrecoverableError(for error: UnrecoverableError) -> Presentable? { guard let options = self.controller?.lock.options else { return nil } let presenter = UnrecoverableErrorPresenter(error: error, navigator: self, options: options) return presenter } }
38.015152
100
0.716222
edd84aa876c1a3d7788d2afc4bdeb3fb49f17d90
292
// // Hours.swift // Yelp // // Created by Alexander Kerendian on 3/2/19. // Copyright © 2019 Alexander Kerendian. All rights reserved. // import Foundation public struct Hours: Decodable { public let open: [Day]? public let hoursType: String? public let isOpenNow: Bool? }
18.25
62
0.681507
f58f90807365c86a7c27fd8d9a5401a5f79f3f8f
1,489
// // MenuComponent.swift // Composite Pattern // // Based on "Head First Design Patterns," Freeman & Robson, O'Reilly. // // Created by Brian Arnold on 2/6/18. // Copyright © 2018 Brian Arnold. All rights reserved. // enum MenuError: Error { case unsupportedOperation } // IN SWIFT: I'd like to use var: property { get } but the example wants to throw. I cut down on the amount of throwing by making name, description and print required. public protocol MenuComponent { func add(_ menuComponent: MenuComponent) throws func remove(_ menuComponent: MenuComponent) throws func child(at index: Int) throws -> MenuComponent var name: String { get } var description: String { get } func price() throws -> Double func isVegetarian() throws -> Bool func print() func makeIterator() -> AnyIterator<MenuComponent> } extension MenuComponent { public func add(_ menuComponent: MenuComponent) throws { throw MenuError.unsupportedOperation } public func remove(_ menuComponent: MenuComponent) throws { throw MenuError.unsupportedOperation } public func child(at index: Int) throws -> MenuComponent { throw MenuError.unsupportedOperation } public func price() throws -> Double { throw MenuError.unsupportedOperation } public func isVegetarian() throws -> Bool { throw MenuError.unsupportedOperation } }
24.409836
167
0.665547
e8d83110424c2f2bffb59d4bdb7c59aa0e4b38f7
801
// // AppDelegate.swift // LaunchAtLoginHelperApp // // Created by Remco on 02/01/2017. // Copyright © 2017 KeyTalk. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(_ aNotification: Notification) { var url = Bundle.main.bundleURL url = url.deletingLastPathComponent() url = url.deletingLastPathComponent() url = url.deletingLastPathComponent() url = url.appendingPathComponent("MacOS", isDirectory: true) url = url.appendingPathComponent("KeyTalk Client", isDirectory: false) NSWorkspace.shared().launchApplication(url.path) NSApp.terminate(nil) } func applicationWillTerminate(_ aNotification: Notification) { } }
25.03125
74
0.742821
0a40ab748f754707791ed90872d800033f07658b
640
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "GLibObject", products: [ .library(name: "GLibObject", targets: ["GLibObject"]), ], dependencies: [ .package(name: "gir2swift", url: "https://github.com/rhx/gir2swift.git", .branch("main")), .package(name: "GLib", url: "https://github.com/rhx/SwiftGLib.git", .branch("main")) ], targets: [ .target(name: "GLibObject", dependencies: ["GObjectCHelpers", "GLib"]), .target(name: "GObjectCHelpers", dependencies: ["GLib"]), .testTarget(name: "GLibObjectTests", dependencies: ["GLibObject"]), ] )
35.555556
98
0.626563
9cae498dbd4093f0fda33ea74bbc788c2b88e84d
1,405
// // RootSceneOperation.swift // Navigator // // Created by liuxc on 2019/7/2. // Copyright © 2019 liuxc. All rights reserved. // import Foundation class RootSceneOperation { private let scene: Scene private let manager: SceneOperationManager init(scene: Scene, manager: SceneOperationManager) { self.scene = scene self.manager = manager } } // MARK: SceneOperation methods extension RootSceneOperation: InterceptableSceneOperation { func execute(with completion: CompletionBlock?) { logTrace("[RootSceneOperation] Executing operation") guard let viewControllerContainer = scene.view() as? ViewControllerContainer else { logError("[RootSceneOperation] View builded from \(scene) is not a ViewControllerContainer") completion?() return } if !manager.canReused(container: viewControllerContainer) { logDebug("[RootSceneOperation] Current ViewControllerContainer can't be reused for scene \(scene)") manager.set(container: viewControllerContainer) } else { logDebug("[RootSceneOperation] Current ViewControllerContainer will be reused for scene \(scene)") } completion?() } func context(from: [SceneState]) -> SceneOperationContext { return SceneOperationContext(currentState: from, targetState: [scene]) } }
29.270833
111
0.680427
76c468be222d1ffb547ff12536d43e6637e2ef38
4,992
// // EmptyDataSet+Rx.swift // RxExtensions // // Created by my on 2022/2/8. // import UIKit import RxSwift import RxCocoa import EmptyDataSet_Swift fileprivate class _TableViewDelegate: NSObject, UITableViewDelegate, Disposable { let configSectionHeader: ((Int) -> UIView?)? let configSectionFooter: ((Int) -> UIView?)? var retainSelf: _TableViewDelegate? init(configSectionHeader: ((Int) -> UIView?)?, configSectionFooter: ((Int) -> UIView?)?) { self.configSectionHeader = configSectionHeader self.configSectionFooter = configSectionFooter } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return configSectionHeader?(section) } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return configSectionFooter?(section) } func dispose() { retainSelf = nil } } internal final class TableViewEmptyDataSource: NSObject, EmptyDataSetSource { var title: NSAttributedString? var image: UIImage? var verticalOffset: CGFloat = 0 func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { return title } func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? { return image } func verticalOffset(forEmptyDataSet scrollView: UIScrollView) -> CGFloat { return verticalOffset } } internal class TableViewEmptyDelegate: NSObject, EmptyDataSetDelegate { var allowScroll: Bool = true var didTapView: ((UIView) -> Void)? func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool { return allowScroll } func emptyDataSet(_ scrollView: UIScrollView, didTap view: UIView) { didTapView?(view) } } fileprivate final class _TableViewEmptyDelegateObserver: TableViewEmptyDelegate, Disposable { var retainSelf: _TableViewEmptyDelegateObserver? init(didTapView: @escaping (UIView) -> Void) { super.init() self.didTapView = didTapView self.retainSelf = self } func dispose() { retainSelf = nil } } internal final class TableViewEmptyDelegateObservable: ObservableType { typealias Element = UIView weak var target: UITableView? init(target: UITableView) { self.target = target } func subscribe<O>(_ observer: O) -> Disposable where O : ObserverType, Element == O.Element { let _observer = _TableViewEmptyDelegateObserver { observer.onNext($0) } target?.emptyDataSetDelegate = _observer return Disposables.create(with: _observer.dispose) } } fileprivate var emptySetDataSourceAssociatedKey = "com.xgxw.table.view.empty.set.datasource" fileprivate var emptySetDelegateAssociatedKey = "com.xgxw.table.view.empty.set.delegate" extension UITableView { private var emptySetDelgate: TableViewEmptyDelegate? { var _delegate = objc_getAssociatedObject(self, &emptySetDelegateAssociatedKey) as? TableViewEmptyDelegate if _delegate == nil { _delegate = TableViewEmptyDelegate() objc_setAssociatedObject(self, &emptySetDelegateAssociatedKey, _delegate, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } emptyDataSetDelegate = _delegate return _delegate } private var emptySetDataSource: TableViewEmptyDataSource? { var _dataSource = objc_getAssociatedObject(self, &emptySetDataSourceAssociatedKey) as? TableViewEmptyDataSource if _dataSource == nil { _dataSource = TableViewEmptyDataSource() emptyDataSetSource = _dataSource objc_setAssociatedObject(self, &emptySetDataSourceAssociatedKey, _dataSource, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return _dataSource } public var titleForEmpty: NSAttributedString? { get { emptySetDataSource?.title } set { emptySetDataSource?.title = newValue } } public var imageForEmpty: UIImage? { get { emptySetDataSource?.image } set { emptySetDataSource?.image = newValue } } public var verticleOffsetForEmpty: CGFloat? { get { emptySetDataSource?.verticalOffset } set { emptySetDataSource?.verticalOffset = newValue ?? 0 } } } extension Reactive where Base: UITableView { public func setSection(_ header: ((Int) -> UIView?)?, _ footer: ((Int) -> UIView?)? = nil) -> Disposable { let _delegate = _TableViewDelegate(configSectionHeader: header, configSectionFooter: footer) let dispose = base.rx.setDelegate(_delegate) return Disposables.create(dispose, _delegate) } public var emptyDataSetDidTapView: Observable<UIView> { return TableViewEmptyDelegateObservable(target: base).asObservable() } }
30.254545
125
0.674679
3a64dfee028a67687837c2e69ede67a274827f90
6,735
import Foundation import Capacitor public class CapacitorUrlRequest: NSObject, URLSessionTaskDelegate { private var request: URLRequest; private var headers: [String:String]; enum CapacitorUrlRequestError: Error { case serializationError(String?) } init(_ url: URL, method: String) { request = URLRequest(url: url) request.httpMethod = method headers = [:] if let lang = Locale.autoupdatingCurrent.languageCode { if let country = Locale.autoupdatingCurrent.regionCode { headers["Accept-Language"] = "\(lang)-\(country),\(lang);q=0.5" } else { headers["Accept-Language"] = "\(lang);q=0.5" } request.addValue(headers["Accept-Language"]!, forHTTPHeaderField: "Accept-Language") } } private func getRequestDataAsJson(_ data: JSValue) throws -> Data? { // We need to check if the JSON is valid before attempting to serialize, as JSONSerialization.data will not throw an exception that can be caught, and will cause the application to crash if it fails. if JSONSerialization.isValidJSONObject(data) { return try JSONSerialization.data(withJSONObject: data) } else { throw CapacitorUrlRequest.CapacitorUrlRequestError.serializationError("[ data ] argument for request of content-type [ application/json ] must be serializable to JSON") } } private func getRequestDataAsFormUrlEncoded(_ data: JSValue) throws -> Data? { guard var components = URLComponents(url: request.url!, resolvingAgainstBaseURL: false) else { return nil } components.queryItems = [] guard let obj = data as? JSObject else { // Throw, other data types explicitly not supported throw CapacitorUrlRequestError.serializationError("[ data ] argument for request with content-type [ multipart/form-data ] may only be a plain javascript object") } obj.keys.forEach { (key: String) in components.queryItems?.append(URLQueryItem(name: key, value: "\(obj[key] ?? "")")) } if components.query != nil { return Data(components.query!.utf8) } return nil } private func getRequestDataAsMultipartFormData(_ data: JSValue) throws -> Data { guard let obj = data as? JSObject else { // Throw, other data types explicitly not supported. throw CapacitorUrlRequestError.serializationError("[ data ] argument for request with content-type [ application/x-www-form-urlencoded ] may only be a plain javascript object") } let strings: [String: String] = obj.compactMapValues { any in any as? String } var data = Data() let boundary = UUID().uuidString let contentType = "multipart/form-data; boundary=\(boundary)" request.setValue(contentType, forHTTPHeaderField: "Content-Type") headers["Content-Type"] = contentType strings.forEach { key, value in data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!) data.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!) data.append(value.data(using: .utf8)!) } data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) return data } private func getRequestDataAsString(_ data: JSValue) throws -> Data { guard let stringData = data as? String else { throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed as string") } return Data(stringData.utf8) } private func getRequestDataAsRaw(_ data: JSValue) throws -> Data? { guard let obj = data as? JSObject else { throw CapacitorUrlRequestError.serializationError("[ data ] argument could not be parsed as raw data") } let strings: [String: Int] = obj.compactMapValues { any in any as? Int } var raw = [UInt8](repeating: 0, count: strings.keys.count) strings.forEach { key, value in raw[Int(key) ?? 0] = UInt8(value) } return Data(raw) } func getRequestHeader(_ index: String) -> Any? { var normalized = [:] as [String:Any] self.headers.keys.forEach { (key: String) in normalized[key.lowercased()] = self.headers[key] } return normalized[index.lowercased()] } func getRequestData(_ body: JSValue, _ contentType: String) throws -> Data? { // If data can be parsed directly as a string, return that without processing. if let strVal = try? getRequestDataAsString(body) { return strVal } else if contentType.contains("application/json") { return try getRequestDataAsJson(body) } else if contentType.contains("application/x-www-form-urlencoded") { return try getRequestDataAsFormUrlEncoded(body) } else if contentType.contains("multipart/form-data") { return try getRequestDataAsMultipartFormData(body) } return try getRequestDataAsRaw(body); } public func setRequestHeaders(_ headers: [String: String]) { headers.keys.forEach { (key: String) in let value = headers[key] request.addValue(value!, forHTTPHeaderField: key) self.headers[key] = value } } public func setRequestBody(_ body: JSValue) throws { let contentType = self.getRequestHeader("Content-Type") as? String if contentType != nil { request.httpBody = try getRequestData(body, contentType!) } } public func setContentType(_ data: String?) { request.setValue(data, forHTTPHeaderField: "Content-Type") } public func setTimeout(_ timeout: TimeInterval) { request.timeoutInterval = timeout; } public func getUrlRequest() -> URLRequest { return request; } public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } public func getUrlSession(_ call: CAPPluginCall) -> URLSession { let disableRedirects = call.getBool("disableRedirects") ?? false if (!disableRedirects) { return URLSession.shared } return URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) } }
40.089286
211
0.627617
fef2b984b3d4464befd7de401dcd4fb1355222ec
1,221
// // AccessibilityCLButton.swift // edX // // Created by Ehmad Zubair Chughtai on 28/07/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class AccessibilityCLButton: CustomPlayerButton { private var selectedAccessibilityLabel : String? private var normalAccessibilityLabel : String? override public var isSelected: Bool { didSet { if isSelected { if let selectedLabel = selectedAccessibilityLabel { self.accessibilityLabel = selectedLabel } } else { if let normalLabel = normalAccessibilityLabel { self.accessibilityLabel = normalLabel } } } } public func setAccessibilityLabelsForStateNormal(normalStateLabel normalLabel: String?, selectedStateLabel selectedLabel: String?) { self.selectedAccessibilityLabel = selectedLabel self.normalAccessibilityLabel = normalLabel } public override func draw(_ rect: CGRect) { let r = UIBezierPath(ovalIn: rect) UIColor.black.withAlphaComponent(0.65).setFill() r.fill() super.draw(rect) } }
28.395349
136
0.620803
2350ad31078121f1b83dc9098a3c83d43831a556
2,468
// // SFRoundImageViewController.swift // iOSTips // // Created by brian on 2018/3/13. // Copyright © 2018年 brian. All rights reserved. // import UIKit class SFRoundImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { roundImageWithBorder() // roundImage() } // 不带边框的圆角图片 func roundImage() { guard let image = UIImage(named: "girl") else { return } // 1. 开启一个位图上下文 UIGraphicsBeginImageContext(CGSize(width: image.size.width, height: image.size.width)) // 2. 获取一个圆形路径(用来设置圆形裁剪区域) let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.width)) // 3. 设置路径为上下文的裁剪区域,超过裁剪区域以外的内容会被裁剪(对之后绘制的内容有效,对已绘制到上下文的内容无效) path.addClip() // 4. 把图片绘制到上下文中 image.draw(at: CGPoint.zero) // 5. 从上下文中生成一张图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 6. 手动开启的位图上下文需要手动关闭 UIGraphicsEndImageContext() imageView.image = newImage } var borderWidth: CGFloat = 30 // 带有边框的圆角图片 func roundImageWithBorder() { guard let image = UIImage(named: "girl") else { return } // 1. 开启一个位图上下文,因为左右边框,所以需要加两倍的边框宽度 UIGraphicsBeginImageContext(CGSize(width: image.size.width + borderWidth * 2, height: image.size.width + borderWidth * 2)) // 2. 获取一个圆形路径,用来实现圆形边框的效果 let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: image.size.width + borderWidth * 2, height: image.size.width + borderWidth * 2)) // 3. 设置填充颜色和填充到上下文中 UIColor.red.set() path.fill() // 4.获取小圆圆形区域(用来设置圆形裁剪区域) let clipPath = UIBezierPath(ovalIn: CGRect(x: borderWidth, y: borderWidth, width: image.size.width, height: image.size.width)) // 5. 设置路径为上下文的裁剪区域,超过裁剪区域以外的内容会被裁剪(对之后绘制的内容有效,对已绘制到上下文的内容无效) clipPath.addClip() // 7. 把图片绘制到上下文中 image.draw(at: CGPoint(x: borderWidth, y: borderWidth)) // 8. 从上下文中生成一张图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 9. 关闭上下文 UIGraphicsEndImageContext() imageView.image = newImage } }
29.380952
146
0.594003
612f3bcb737d3219f90cb090b2749a31b9caed86
468
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse protocol A{{{ }}struct B{ struct A{ func a{{init{ let a{ var d{ class case,
27.529412
78
0.735043
034226550cb1161d79dde276112ce5ebd7aa2b3f
884
// swift-tools-version:5.0 // // MLChat.swift // MLChat // // Created by Michel Anderson Lutz Teixeira on 01/04/19. // Copyright © 2019 micheltlutz. All rights reserved. // import PackageDescription let package = Package( name: "MLChat", platforms: [ .iOS(.v8), .tvOS(.v9) ], products: [ .library( name: "MLChat", targets: ["MLChat"] ) ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ .target( name: "MLChat", dependencies: [], path: "Sources" ), .testTarget( name: "MLChatTests", dependencies: ["MLChat"], path: "Tests" ) ], swiftLanguageVersions: [.v5] )
21.047619
76
0.503394
4b1d6ceffcecd78c01cdadd3a864c67760d66b18
2,097
// // settings.swift // WoosmapGeofencing // // import Foundation // Tracking public var trackingEnable = true // Woosmap SearchAPI Key public var WoosmapAPIKey = "" public var searchWoosmapAPI = "https://api.woosmap.com/stores/search/?private_key=\(WoosmapAPIKey)&lat=%@&lng=%@&stores_by_page=1" // Woosmap DistanceAPI public enum DistanceMode: String { case driving case cycling case walking } public var distanceMode = DistanceMode.driving // cycling,walking public var distanceWoosmapAPI = "https://api.woosmap.com/distance/distancematrix/json?mode=\(distanceMode)&units=metric&origins=%@,%@&destinations=%@&private_key=\(WoosmapAPIKey)&elements=duration_distance" // Location filters public var currentLocationDistanceFilter = 0.0 public var currentLocationTimeFilter = 0 // Search API filters public var searchAPIRequestEnable = true public var searchAPIDistanceFilter = 0.0 public var searchAPITimeFilter = 0 public var searchAPICreationRegionEnable = true public var firstSearchAPIRegionRadius = 100.0 public var secondSearchAPIRegionRadius = 200.0 public var thirdSearchAPIRegionRadius = 300.0 // Distance API filters public var distanceAPIRequestEnable = true // Active visit public var visitEnable = true public var accuracyVisitFilter = 50.0 // Active creation of ZOI public var creationOfZOIEnable = false // Active Classification public var classificationEnable = false public var radiusDetectionClassifiedZOI = 100.0 // Delay of Duration data public var dataDurationDelay = 30// number of day // delay for obsolote notification public var outOfTimeDelay = 300 // Google Map Static Key public var GoogleStaticMapKey = "" // Google Map static API public let GoogleMapStaticAPIBaseURL = "http://maps.google.com/maps/api/staticmap" public let GoogleMapStaticAPIOneMark = GoogleMapStaticAPIBaseURL + "?markers=color:blue|%@,%@&zoom=15&size=400x400&sensor=true&key=\(GoogleStaticMapKey)" public let GoogleMapStaticAPITwoMark = GoogleMapStaticAPIBaseURL + "?markers=color:red|%@,%@&markers=color:blue|%@,%@&zoom=14&size=400x400&sensor=true&key=\(GoogleStaticMapKey)"
32.261538
206
0.7897
d9df240edf40b976b6955fc6340a765083f548ff
1,621
// // StopPointRouteSection.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class StopPointRouteSection: JSONEncodable { public var naptanId: String? public var lineId: String? public var mode: String? public var validFrom: Date? public var validTo: Date? public var direction: String? public var routeSectionName: String? public var lineString: String? public var isActive: Bool? public var serviceType: String? public var vehicleDestinationText: String? public var destinationName: String? public init() {} // MARK: JSONEncodable open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["naptanId"] = self.naptanId nillableDictionary["lineId"] = self.lineId nillableDictionary["mode"] = self.mode nillableDictionary["validFrom"] = self.validFrom?.encodeToJSON() nillableDictionary["validTo"] = self.validTo?.encodeToJSON() nillableDictionary["direction"] = self.direction nillableDictionary["routeSectionName"] = self.routeSectionName nillableDictionary["lineString"] = self.lineString nillableDictionary["isActive"] = self.isActive nillableDictionary["serviceType"] = self.serviceType nillableDictionary["vehicleDestinationText"] = self.vehicleDestinationText nillableDictionary["destinationName"] = self.destinationName let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } }
33.770833
85
0.702653
3aedf9a2334b6a9ed2b069ac1263f74317c5ad7c
1,448
// // Types.swift // Pods // // Created by Jesse Curry on 10/26/15. // // /** Count of Calories. */ public typealias C2CalorieCount = Int /** Integer date value. */ public typealias C2Date = Int /** Distance in meters. */ public typealias C2Distance = Double /** . */ public typealias C2DragFactor = Int /** Drive length in meters. */ public typealias C2DriveLength = Double /** . */ public typealias C2DriveForce = Double /** Time of drive in seconds. */ public typealias C2DriveTime = NSTimeInterval /** Heart rate in beats per minute. */ public typealias C2HeartRate = Int /** Heart rate belt type (1 byte). */ public typealias C2HeartRateBeltType = UInt8 /** Heart rate belt ID (4 bytes). */ public typealias C2HeartRateBeltID = UInt32 /** Heart rate belt manufacturer ID (1 byte). */ public typealias C2HeartRateBeltManufacturerID = UInt8 /** Count of intervals. */ public typealias C2IntervalCount = Int /** The size of the current interval group. */ public typealias C2IntervalSize = Int /** . */ public typealias C2Pace = Double /** . */ public typealias C2Power = Int /** . */ public typealias C2Speed = Double /** Count of strokes. */ public typealias C2StrokeCount = Int /** Stroke rate in strokes per minute. */ public typealias C2StrokeRate = Int /** . */ public typealias C2Time = Int /** Amount of time in seconds. */ public typealias C2TimeInterval = NSTimeInterval /** . */ public typealias C2Work = Double
20.394366
54
0.702348
e07fa28ff4ce782d9f12074d8d18860250f1d15e
4,402
// // ComboboxRcloneParameters.swift // rcloneosx // // Created by Thomas Evensen on 27/10/2019. // Copyright © 2019 Thomas Evensen. All rights reserved. // import Foundation struct ComboboxRcloneParameters { // Array storing combobox values private var comboBoxValues: [String]? private var config: Configuration? // Function for getting for rsync arguments to use in ComboBoxes in ViewControllerRsyncParameters // - parameter none: none // - return : array of String func getComboBoxValues() -> [String] { return self.comboBoxValues ?? [""] } // Returns Int value of argument private func indexofrcloneparameter(argument: String) -> Int { var index: Int = -1 loop: for i in 0 ..< SuffixstringsRcloneParameters().rcloneArguments.count where argument == SuffixstringsRcloneParameters().rcloneArguments[i].0 { index = i break loop } return index } // Split an rclone argument into argument and value private func split(str: String) -> [String] { let argument: String? let value: String? var split = str.components(separatedBy: "=") argument = String(split[0]) if split.count > 1 { if split.count > 2 { split.remove(at: 0) value = split.joined(separator: "=") } else { value = String(split[1]) } } else { value = argument } return [argument!, value!] } func indexandvaluercloneparameter(parameter: String?) -> (Int, String) { guard parameter != nil else { return (0, "") } let splitstr: [String] = self.split(str: parameter!) guard splitstr.count > 1 else { return (0, "") } let argument = splitstr[0] let value = splitstr[1] var returnvalue: String? var returnindex: Int? if argument != value, self.indexofrcloneparameter(argument: argument) >= 0 { returnvalue = value returnindex = self.indexofrcloneparameter(argument: argument) } else { if self.indexofrcloneparameter(argument: splitstr[0]) >= 0 { returnvalue = "\"" + argument + "\" " + "no arguments" } else { if argument == value { returnvalue = value } else { returnvalue = argument + "=" + value } } if argument != value, self.indexofrcloneparameter(argument: argument) >= 0 { returnindex = self.indexofrcloneparameter(argument: argument) } else { if self.indexofrcloneparameter(argument: splitstr[0]) >= 0 { returnindex = self.indexofrcloneparameter(argument: argument) } else { returnindex = 0 } } } return (returnindex!, returnvalue!) } func getParameter(rcloneparameternumber: Int) -> (Int, String) { var indexandvalue: (Int, String)? guard self.config != nil else { return (0, "") } switch rcloneparameternumber { case 8: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter8) case 9: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter9) case 10: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter10) case 11: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter11) case 12: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter12) case 13: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter13) case 14: indexandvalue = self.indexandvaluercloneparameter(parameter: self.config!.parameter14) default: return (0, "") } return indexandvalue! } init(config: Configuration?) { self.config = config self.comboBoxValues = [String]() for i in 0 ..< SuffixstringsRcloneParameters().rcloneArguments.count { self.comboBoxValues!.append(SuffixstringsRcloneParameters().rcloneArguments[i].0) } } }
36.991597
101
0.588823
75e90899cfcc9be8db76fce5e403744b26c33f21
959
import Foundation import UIKit @_functionBuilder public struct ContentBuilder { public static func buildBlock(_ content: Content) -> Content { return Container(contents: [content] ) } public static func buildBlock(_ contents: Content?...) -> Content { return Container(contents: contents.compactMap { $0 } ) } public static func buildIf(_ content: Content?) -> Content? { return content } public static func buildEither(first: Content) -> Content { return first } public static func buildEither(second: Content) -> Content { return second } } public struct Container: Content { public var contents: [Content]? public init(contents: [Content] = []) { self.contents = contents } } extension Container { public init(@ContentBuilder _ builder: () -> Content) { self.init(contents: builder().contents ?? []) } }
19.979167
71
0.622523
01b5ebca79d2592a6b36399030b0c09ab238d1f3
3,312
// // LLRBTreeTests.swift // LLRBTreeTests // // Created by Valeriano Della Longa on 2021/01/30. // Copyright © 2021 Valeriano Della Longa // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import LLRBTree final class LLRBTreeTests: BaseLLRBTreeTestCase { func testInit() { sut = LLRBTree() XCTAssertNotNil(sut) XCTAssertNil(sut.root) } func testRoot() { sut = LLRBTree() XCTAssertNil(sut.root) whenRootContainsAllGivenElements() XCTAssertNotNil(sut.root) let newRoot = LLRBTree.Node(key: givenKeys.randomElement()!, value: givenRandomValue(), color: .black) sut.root = newRoot XCTAssertTrue(sut.root === newRoot, "has not set root") } func testInitRoot() { sut = LLRBTree(nil) XCTAssertNil(sut.root) let newRoot = LLRBTree.Node(key: givenKeys.randomElement()!, value: givenRandomValue(), color: .black) sut = LLRBTree(newRoot) XCTAssertTrue(sut.root === newRoot) } func testInitOther() { var other = LLRBTree<String, Int>() sut = LLRBTree(other) XCTAssertNil(sut.root) let newRoot = LLRBTree.Node(key: givenKeys.randomElement()!, value: givenRandomValue(), color: .black) other = LLRBTree(newRoot) sut = LLRBTree(other) XCTAssertTrue(sut.root === newRoot, "has set different root") } func testMakeUnique_whenRootIsNil_thenNothingHappens() { sut = LLRBTree() sut.makeUnique() XCTAssertNil(sut.root) } func testMakeUnique_whenRootIsNotNilAndHasNotOtherStrongReferences_thenNothingHappens() { whenRootContainsHalfGivenElements() weak var prevRoot = sut.root sut.makeUnique() XCTAssertTrue(sut.root === prevRoot, "root changed to different reference") } func testMakeUnique_whenRootIsNotNilAndHasAnotherStrongReference_thenRootIsCloned() { whenRootContainsHalfGivenElements() let prevRoot = sut.root sut.makeUnique() XCTAssertFalse(sut.root === prevRoot, "root is still same reference") XCTAssertEqual(sut.root, prevRoot) } }
34.863158
110
0.673913
fb381c841397778fdf0533e0b9bb3317c4ae3307
8,378
// // Data.swift // furychainsaw // // Created by Alex Gajewski on 11/16/17. // Copyright © 2017 Ashwin Aggarwal. All rights reserved. // import Foundation import ToneAnalyzerV3 import Alamofire import FacebookCore let connection = GraphRequestConnection() let username = "ea1084fe-510b-4010-bbd0-7ef2a085e119" let password = "WzYSjsR18jgZ" let version = "2017-5-16" // use today's date for the most recent version let toneAnalyzer = ToneAnalyzer(username: username, password: password, version: version) let failure = { (error: Error) in print("Failed") print(error) } let twilioAccount = "AC93621d61ba0285d60b27d00febfc1b77" let twilioToken = "2e988b61145768c30b7da1b6edadea2b" let twilioPhone = "+12243343599" let mockPhone = "+13126364192" let mockBody = "Test Text" let twilioUrl = "https://api.twilio.com/2010-04-01/Accounts/\(twilioAccount)/Messages.json" let fbUrl = "http://52.37.127.238/api/postfb/" let hrvUrl = "http://52.37.127.238/api/posthrv/" let tempUrl = "http://52.37.127.238/api/posttemp/" let mockUrl = "http://52.37.127.238/api/mockday" let mockHrv: [Double] = [72, 75, 69, 75, 77, 82, 90, 76, 66, 70, 80, 70, 63, 65, 79, 86, 80, 73, 78, 65, 83, 71, 71, 94, 91, 76, 67, 77, 72, 70, 54, 65, 78, 71, 72, 65, 76, 64, 99, 61, 69, 79, 79, 78, 72, 93, 83, 76, 87, 73, 69, 74, 82, 72, 60, 84, 86, 66, 66, 59, 37, 44, 53, 57, 54, 52, 36, 40, 38, 33] let mockTemp = [ 98.22284143, 98.79929454, 98.45961613, 98.41712772, 97.96367459, 98.14818749, 98.55388506, 98.71323798, 98.37979458, 98.25825408, 98.28622595, 98.4782776 , 98.3862218 , 97.93057665, 99.03002896, 98.47166459, 98.31998228, 98.39205376, 98.43791651, 98.34441214, 98.12380799, 98.03576089, 97.99188554, 98.47178435, 98.26118668, 98.24537048, 98.60231422, 98.80872836, 98.53692568, 98.50718894, 98.96055143, 98.29038829, 98.44371808, 98.04005067, 98.934649 , 98.64402952, 97.89363178, 98.49392864, 98.64444936, 98.6918899 , 98.20145914, 98.45226952, 98.47456369, 98.51374756, 98.14188479, 98.74960947, 97.96353578, 98.5842481 , 98.26937078, 98.2595298 , 98.18083426, 98.86450125, 98.24658326, 98.10864777, 98.48711854, 98.56967772, 98.04253586, 97.9886871 , 98.19585956, 98.13214437] + [ 99.09009849, 98.98328831, 99.32094841, 98.93543486, 99.20567045, 99.37735157, 98.82549875, 99.57753664, 98.84043425, 99.08131765] var firstDay = 59 var secondDay = 69 var sentFirstHeart = false var sentSecondHeart = false class Data: NSObject { var lowVariability = false var newestDate: Date? = nil var targetCount = 0 var allPosts: [(Date, Double)] = [] func requestScore(text: String, cb: @escaping (Double) -> Void) { toneAnalyzer.getTone(ofText: text, failure: failure) { tones in var sadness: Double = 0 let emotions = tones.documentTone.filter{(category: ToneCategory) in category.categoryID == "emotion_tone"} if emotions.count > 0 { let sadness_tones = emotions[0].tones.filter{(tone: ToneScore) in tone.id == "sadness"} if sadness_tones.count > 0 { sadness = sadness_tones[0].score } else { print("No sadness") } } else { print("No emotions") } cb(sadness) } } func sendText(to: String, body: String) { Alamofire.request(twilioUrl, method: .post, parameters: ["To": to, "From": twilioPhone, "Body": body]) .authenticate(user: twilioAccount, password: twilioToken) .responseString{response in print(response) } } func updatePosts() { if AccessToken.current != nil { struct MyProfileRequest: GraphRequestProtocol { struct Response: GraphResponseProtocol { var messages: [(Date, String)] = [] init(rawResponse: Any?) { let dict = rawResponse as! NSDictionary let posts = dict["posts"] as! NSDictionary let listOfPosts = posts["data"] as! NSArray for post in listOfPosts { let p = post as! NSDictionary if let message = p["message"] { let created_time = p["created_time"] as! String let m = message as! String let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let date = dateFormatter.date(from: created_time)! messages.append((date, m)) } } } } var graphPath = "/me" var parameters: [String : Any]? = ["fields": "id, name, posts.limit(500)"] var accessToken = AccessToken.current var httpMethod: GraphRequestHTTPMethod = .GET var apiVersion: GraphAPIVersion = .defaultVersion } let connection = GraphRequestConnection() let oldCount = targetCount print(oldCount) connection.add(MyProfileRequest()) { http, result in switch result { case .success(let response): var newMessages = response.messages.filter{m in self.newestDate == nil || m.0 > self.newestDate!} newMessages.sort(by: {(a, b) in a.0 < b.0}) if newMessages.count > 0 { self.newestDate = newMessages[newMessages.count - 1].0 } self.targetCount += newMessages.count for (idx, post) in newMessages.enumerated() { self.requestScore(text: post.1, cb: {score in // self.allPosts.append((post.0, score)) print(self.targetCount) print("Getting to \(fbUrl + "\(score)/\(idx + oldCount)")") Alamofire.request(fbUrl + "\(score)/\(idx + oldCount)" , method: .get) }) } case .failed(let error): print(error) } } connection.start() } } func mockSadDay() { if !sentSecondHeart { /* for (idx, hrv) in mockHrv[firstDay + 1...secondDay].enumerated() { Alamofire.request(hrvUrl + "\(hrv)/\(firstDay + 1 + idx)" , method: .get) } for (idx, temp) in mockTemp[firstDay + 1...secondDay].enumerated() { Alamofire.request(tempUrl + "\(temp)/\(firstDay + 1 + idx)" , method: .get) }*/ Alamofire.request(mockUrl , method: .get) sendText(to: mockPhone, body: "X is depressed") sentSecondHeart = true } } func fetchData() { print("Setting up data fetching") /* for (idx, hrv) in mockHrv[0...firstDay].enumerated() { Alamofire.request(hrvUrl + "\(hrv)/\(idx)" , method: .get) } for (idx, temp) in mockTemp[0...firstDay].enumerated() { Alamofire.request(tempUrl + "\(temp)/\(idx)" , method: .get) } */ Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: {timer in print("fetching now") // let baseline = mockHrv[0...currentDay].reduce(0, +) / mockHeartvar.count // print(baseline) // self.updatePosts() if sentSecondHeart { Alamofire.request(mockUrl , method: .get) } }) } } let data = Data()
42.527919
304
0.517546
678a64bf56b5404ab75f8816bfaa4c01532a3a9c
5,189
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Buttons_Buttons import third_party_objective_c_material_components_ios_components_Typography_Typography /// A button subclass for the record button to change accessibility labels when selected or not. class RecordButton: MDCFlatButton { override var isSelected: Bool { didSet { accessibilityLabel = isSelected ? String.btnStopDescription : String.btnRecordDescription } } } /// The record button view is a bar containing a record button. It has a snapshot button on the left /// and has a timer label on the right. class RecordButtonView: UIView { // MARK: - Properties /// The record button. let recordButton = RecordButton(type: .custom) /// The snapshot button. let snapshotButton = MDCFlatButton(type: .custom) /// The timer label. let timerLabel = UILabel() /// The elapsed time formatter. let timeFormatter = ElapsedTimeFormatter() // MARK: - Public override init(frame: CGRect) { super.init(frame: .zero) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: ViewConstants.toolbarHeight) } /// Updates `timerLabel.text` with a formatted version of `duration`. /// /// - Parameter duration: The duration to format and display. func updateTimerLabel(with duration: Int64) { let oneHour: Int64 = 1000 * 60 * 60 timeFormatter.shouldDisplayTenths = duration < oneHour timerLabel.text = timeFormatter.string(fromTimestamp: duration) } // MARK: - Private private func configureView() { // The snapshot button. let snapshotWrapper = UIView() snapshotWrapper.translatesAutoresizingMaskIntoConstraints = false snapshotWrapper.addSubview(snapshotButton) snapshotButton.setImage(UIImage(named: "ic_snapshot_action"), for: .normal) snapshotButton.tintColor = .white snapshotButton.translatesAutoresizingMaskIntoConstraints = false snapshotButton.inkStyle = .unbounded snapshotButton.inkMaxRippleRadius = 40.0 snapshotButton.hitAreaInsets = UIEdgeInsets(top: -10, left: -20, bottom: -10, right: -20) snapshotButton.pinToEdgesOfView(snapshotWrapper, withInsets: UIEdgeInsets(top: 0, left: 20, bottom: 0, right: -20)) snapshotButton.accessibilityLabel = String.snapshotButtonText snapshotButton.accessibilityHint = String.snapshotButtonContentDetails // The record button. recordButton.setImage(UIImage(named: "record_button"), for: .normal) recordButton.setImage(UIImage(named: "stop_button"), for: .selected) recordButton.inkColor = .clear recordButton.autoresizesSubviews = false recordButton.contentEdgeInsets = .zero recordButton.imageEdgeInsets = .zero recordButton.translatesAutoresizingMaskIntoConstraints = false recordButton.hitAreaInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10) recordButton.setContentHuggingPriority(.required, for: .horizontal) recordButton.setContentHuggingPriority(.required, for: .vertical) recordButton.isSelected = false // Calls the didSet on isSelected to update a11y label. // The timer label. let timerWrapper = UIView() timerWrapper.translatesAutoresizingMaskIntoConstraints = false timerWrapper.addSubview(timerLabel) timerLabel.font = MDCTypography.headlineFont() timerLabel.textAlignment = .left timerLabel.textColor = .white timerLabel.translatesAutoresizingMaskIntoConstraints = false timerLabel.setContentHuggingPriority(.defaultHigh, for: .horizontal) timerLabel.leadingAnchor.constraint(equalTo: timerWrapper.leadingAnchor, constant: 16.0).isActive = true timerLabel.centerYAnchor.constraint(equalTo: timerWrapper.centerYAnchor).isActive = true timerLabel.isAccessibilityElement = true timerLabel.accessibilityTraits = .updatesFrequently let stackView = UIStackView(arrangedSubviews: [snapshotWrapper, recordButton, timerWrapper]) addSubview(stackView) stackView.distribution = .fillEqually stackView.alignment = .center stackView.translatesAutoresizingMaskIntoConstraints = false stackView.pinToEdgesOfView(self) } }
38.723881
100
0.71825
3ab23f9fedce3e1ebc999c89787e43aa0754d154
3,964
// // UIImageView+Extension.swift // CarForIos // // Created by chilunyc on 2018/7/19. // Copyright © 2018 chilunyc. All rights reserved. // import UIKit import Kingfisher extension UIImageView { func setImage(with url: Resource?) { setImage(with: url, placeHolder: Image(named: "DefaultNoData")) } func setImage(with url: Resource?, completionHandler: CompletionHandler? = nil) { setImage(with: url, placeHolder: nil, completionHandler: completionHandler) } func setImage(with url: Resource?, placeHolder: Image?=nil) { kf.setImage(with: url, placeholder: placeHolder, options: [.transition(.fade(1))], progressBlock: nil, completionHandler: nil) } func setImage(with url: Resource? , placeHolder: Image?=nil, completionHandler: CompletionHandler? = nil) { kf.setImage(with: url, placeholder: placeHolder, options: [.transition(.fade(1))], progressBlock: nil, completionHandler: completionHandler) } } extension UIImage { //将图片缩放成指定尺寸(多余部分自动删除) func scaled(to newSize: CGSize) -> UIImage { //计算比例 let aspectWidth = newSize.width/size.width let aspectHeight = newSize.height/size.height let aspectRatio = max(aspectWidth, aspectHeight) //图片绘制区域 var scaledImageRect = CGRect.zero scaledImageRect.size.width = size.width * aspectRatio scaledImageRect.size.height = size.height * aspectRatio scaledImageRect.origin.x = (newSize.width - size.width * aspectRatio) / 2.0 scaledImageRect.origin.y = (newSize.height - size.height * aspectRatio) / 2.0 //绘制并获取最终图片 UIGraphicsBeginImageContext(newSize) draw(in: scaledImageRect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } } // //extension UIImage{ // /** // 设置是否是圆角(默认:3.0,图片大小) // */ // func isRoundCorner() -> UIImage{ // return self.isRoundCorner(radius: 3.0, size: self.size) // } // /** // 设置是否是圆角 // - parameter radius: 圆角大小 // - parameter size: size // - returns: 圆角图片 // */ // func isRoundCorner(radius:CGFloat,size:CGSize) -> UIImage { // let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) // //开始图形上下文 // UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) // //绘制路线 // UIGraphicsGetCurrentContext()!.addPath(UIBezierPath(roundedRect: rect, // byRoundingCorners: UIRectCorner.allCorners, // cornerRadii: CGSize(width: radius, height: radius)).cgPath) // //裁剪 // UIGraphicsGetCurrentContext()?.clip() // //将原图片画到图形上下文 // self.draw(in: rect) // CGContext.drawPath(UIGraphicsGetCurrentContext()!) // CGContextDrawPath(UIGraphicsGetCurrentContext()!, .fillStroke) // let output = UIGraphicsGetImageFromCurrentImageContext(); // //关闭上下文 // UIGraphicsEndImageContext(); // return output! // } // /** // 设置圆形图片 // - returns: 圆形图片 // */ // func isCircleImage() -> UIImage { // //开始图形上下文 // UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale) // //获取图形上下文 // let contentRef:CGContext = UIGraphicsGetCurrentContext()! // //设置圆形 // let rect = CGRect(x:0, y:0, width:self.size.width, height:self.size.height) // //根据 rect 创建一个椭圆 // CGContextAddEllipseInRect(contentRef, rect) // //裁剪 // CGContextClip(contentRef) // //将原图片画到图形上下文 // self.drawInRect(rect) // //从上下文获取裁剪后的图片 // let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() // //关闭上下文 // UIGraphicsEndImageContext() // return newImage // } //}
34.77193
148
0.611504
384c8e772e187bc02648925d95a1867275823689
6,053
/** * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import WatchKit import Foundation @IBDesignable class PageInterfaceController: WKInterfaceController { var stock: Stock! var graphHeightRatio: CGFloat = 0.875 // default also set in interface builder var detailsHeightRatio: CGFloat = 0.125 // default also set in interface builder var screenSize: CGSize { return self.contentFrame.size // for convenience } @IBOutlet var graphImage: WKInterfaceImage! @IBOutlet var detailsGroup: WKInterfaceGroup! @IBOutlet var changeLabel: WKInterfaceLabel! @IBOutlet var tickerSymbolLabel: WKInterfaceLabel! override func awake(withContext context: Any?) { super.awake(withContext: context) if let context = context as? Stock { self.stock = context } } override func willActivate() { super.willActivate() updateForAccessibility() changeLabel.setText("\(stock.changeCharacter) \(stock.changePercentAsString)") changeLabel.setTextColor(stock.changeColor) tickerSymbolLabel.setText(stock.tickerSymbol) generateImage() } func generateImage() { DispatchQueue.global(qos: .default).async { let graphGenerator = GraphGenerator(settings: WatchGraphGeneratorSettings()) let height = self.graphHeightRatio * self.screenSize.height let graphRect = CGRect(x: 0, y: 0, width: self.screenSize.width, height: height) let image = graphGenerator.image(graphRect, with: self.stock.last5days) DispatchQueue.main.async { self.graphImage.setImage(image) } } } func updateForAccessibility() { if WKAccessibilityIsVoiceOverRunning() { makeLayoutAccessible() makeGraphAccessible() makeGroupAccessible() } } func makeLayoutAccessible() { graphHeightRatio = 0.6 detailsHeightRatio = 0.4 graphImage.setHeight(graphHeightRatio * screenSize.height) detailsGroup.setHeight(detailsHeightRatio * screenSize.height) } func makeGraphAccessible() { // 1 var imageRegions: [WKAccessibilityImageRegion] = [] // 2 for index in 1..<stock.last5days.count { // skip the first day // 3 let imageRegion = WKAccessibilityImageRegion() // 4 imageRegion.frame = imageRegionFrameForTrailingIndex(index) // 5 imageRegion.label = summaryForTrailingIndex(index) // 6 imageRegions.append(imageRegion) } // 7 graphImage.setAccessibilityImageRegions(imageRegions) } func makeGroupAccessible(){ // 1 detailsGroup.setIsAccessibilityElement(true) // 2 let percentage = percentageChangeForVoiceOver( from: stock.last5days.first!, to: stock.last5days.last!) // 3 let label = "\(stock.companyName), past five days, \(percentage)" // 4 detailsGroup.setAccessibilityLabel(label) // 5 detailsGroup.setAccessibilityTraits( UIAccessibilityTraitSummaryElement) } func imageRegionFrameForTrailingIndex(_ trailingIndex: Int) -> CGRect { let height = screenSize.height * graphHeightRatio let width = screenSize.width / CGFloat(stock.last5days.count - 1) let x = width * (CGFloat(trailingIndex) - 1) return CGRect(x: x, y: 0, width: width, height: height) } func summaryForTrailingIndex(_ trailingIndex: Int) -> String { let percentageDescription = percentageChangeForVoiceOver(from: stock.last5days[trailingIndex - 1], to: stock.last5days[trailingIndex]) // 2 var timeDescription = String() switch trailingIndex { case 1: timeDescription = "3 days ago" case 2: timeDescription = "day before yesterday" case 3: timeDescription = "yesterday" case 4: timeDescription = "today" default: break } // 3 return "\(percentageDescription) \(timeDescription)" } func percentageChangeForVoiceOver(from previous: Double, to current: Double) -> String { // 1 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .percent numberFormatter.minimumFractionDigits = 2 numberFormatter.maximumFractionDigits = 2 // 2 let change = (current - previous) / previous // 3 let direction = change > 0 ? "up" : "down" // 4 let percent = numberFormatter.string(from: NSNumber(value: abs(change)))! // 5 return "\(direction) \(percent)" } }
32.196809
90
0.70081
de650f60d1e762c71cd63ae69f79d64aa4de1e03
242
import Foundation /// Типы символов для повторения предыдущих токенов. /// - oneOrMore: Один или более раз. /// - zeroOrMore: 0 либо более раз. public enum RepeaterSymbolType: Character { case oneOrMore = "+" case zeroOrMore = "*" }
24.2
52
0.698347
db502fa431d1e4aaeeff5429ac5726b6e88793b1
9,264
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation import GroundSdk /// Leds supported capabilities @objc(GSLedsSupportedCapabilities) public enum LedsSupportedCapabilities: Int, CustomStringConvertible { /// Leds switch is off @objc(GSLedsSupportedCapabilitiesOnOff) case onOff /// Debug description. public var description: String { switch self { case .onOff: return "onOff" } } /// Comparator public static func < (lhs: LedsSupportedCapabilities, rhs: LedsSupportedCapabilities) -> Bool { return lhs.rawValue < rhs.rawValue } /// Set containing all possible values public static let allCases: Set<LedsSupportedCapabilities> = [ .onOff] } /// Base controller for leds peripheral class LedsController: DeviceComponentController, LedsBackend { /// Leds component private var leds: LedsCore! /// component settings key private static let settingKey = "LedsController" /// Preset store for this leds interface private var presetStore: SettingsStore? /// All settings that can be stored enum SettingKey: String, StoreKey { case stateKey = "state" } /// Stored settings enum Setting: Hashable { case state(Bool) /// Setting storage key var key: SettingKey { switch self { case .state: return .stateKey } } /// All values to allow enumerating settings static let allCases: Set<Setting> = [.state(false)] func hash(into hasher: inout Hasher) { hasher.combine(key) } static func == (lhs: Setting, rhs: Setting) -> Bool { return lhs.key == rhs.key } } /// Setting values as received from the drone private var droneSettings = Set<Setting>() /// Constructor /// /// - Parameter deviceController: device controller owning this component controller (weak) override init(deviceController: DeviceController) { if GroundSdkConfig.sharedInstance.offlineSettings == .off { presetStore = nil } else { presetStore = deviceController.presetStore.getSettingsStore(key: LedsController.settingKey) } super.init(deviceController: deviceController) leds = LedsCore(store: deviceController.device.peripheralStore, backend: self) // load settings if let presetStore = presetStore, !presetStore.new { loadPresets() leds.publish() } } func set(state: Bool) -> Bool { presetStore?.write(key: SettingKey.stateKey, value: state).commit() if connected { return sendStateCommand(state) } else { leds.update(state: state).notifyUpdated() return false } } /// Switch Activation or deactivation command /// /// - Parameter state: requested state. /// - Returns: true if the command has been sent func sendStateCommand(_ state: Bool) -> Bool { var commandSent = false if state { sendCommand(ArsdkFeatureLeds.activateEncoder()) commandSent = true } else { sendCommand(ArsdkFeatureLeds.deactivateEncoder()) commandSent = true } return commandSent } /// Load saved settings private func loadPresets() { if let presetStore = presetStore { Setting.allCases.forEach { switch $0 { case .state: if let state: Bool = presetStore.read(key: $0.key) { leds.update(state: state) } leds.notifyUpdated() } } } } /// Drone is connected override func didConnect() { applyPresets() if leds.supportedSwitch { leds.publish() } else { leds.unpublish() } } /// Drone is disconnected override func didDisconnect() { leds.cancelSettingsRollback() // unpublish if offline settings are disabled if GroundSdkConfig.sharedInstance.offlineSettings == .off { leds.unpublish() } leds.notifyUpdated() } /// Drone is about to be forgotten override func willForget() { leds.unpublish() super.willForget() } /// Preset has been changed override func presetDidChange() { super.presetDidChange() // reload preset store presetStore = deviceController.presetStore.getSettingsStore(key: LedsController.settingKey) loadPresets() if connected { applyPresets() } } /// Apply a preset /// /// Iterate settings received during connection private func applyPresets() { // iterate settings received during the connection for setting in droneSettings { switch setting { case .state(let state): if let preset: Bool = presetStore?.read(key: setting.key) { if preset != state { _ = sendStateCommand(preset) } leds.update(state: preset).notifyUpdated() } else { leds.update(state: state).notifyUpdated() } } } } /// Called when a command that notify a setting change has been received /// - Parameter setting: setting that changed func settingDidChange(_ setting: Setting) { droneSettings.insert(setting) switch setting { case .state(let state): if connected { leds.update(state: state).notifyUpdated() } } leds.notifyUpdated() } /// A command has been received /// /// - Parameter command: received command override func didReceiveCommand(_ command: OpaquePointer) { if ArsdkCommand.getFeatureId(command) == kArsdkFeatureLedsUid { ArsdkFeatureLeds.decode(command, callback: self) } } } /// Leds decode callback implementation extension LedsController: ArsdkFeatureLedsCallback { func onSwitchState(switchState: ArsdkFeatureLedsSwitchState) { switch switchState { case .off: settingDidChange(.state(false)) case .on: settingDidChange(.state(true)) case .sdkCoreUnknown: fallthrough @unknown default: // don't change anything if value is unknown ULog.w(.tag, "Unknown LedsSwitchState, skipping this event.") } } func onCapabilities(supportedCapabilitiesBitField: UInt) { leds.update(supportedSwitch: LedsSupportedCapabilities.createSetFrom( bitField: supportedCapabilitiesBitField).contains(.onOff)) } } extension LedsSupportedCapabilities: ArsdkMappableEnum { /// Create set of led capabilites from all value set in a bitfield /// /// - Parameter bitField: arsdk bitfield /// - Returns: set containing all led capabilites set in bitField static func createSetFrom(bitField: UInt) -> Set<LedsSupportedCapabilities> { var result = Set<LedsSupportedCapabilities>() ArsdkFeatureLedsSupportedCapabilitiesBitField.forAllSet(in: UInt(bitField)) { arsdkValue in if let state = LedsSupportedCapabilities(fromArsdk: arsdkValue) { result.insert(state) } } return result } static var arsdkMapper = Mapper<LedsSupportedCapabilities, ArsdkFeatureLedsSupportedCapabilities>([ .onOff: .onOff]) }
32.851064
103
0.624028
500a6e921d888eb27c6a247db18efd3a5db14939
2,264
// // SendFundConfirmationViewController.swift // ConcordiumWallet // // Created by Concordium on 29/05/2020. // Copyright © 2020 concordium. All rights reserved. // import UIKit class SendFundConfirmationFactory { class func create(with presenter: SendFundConfirmationPresenter) -> SendFundConfirmationViewController { SendFundConfirmationViewController.instantiate(fromStoryboard: "SendFund") { coder in return SendFundConfirmationViewController(coder: coder, presenter: presenter) } } } class SendFundConfirmationViewController: BaseViewController, SendFundConfirmationViewProtocol, Storyboarded { var presenter: SendFundConfirmationPresenterProtocol @IBOutlet weak var line1: UILabel! @IBOutlet weak var line2: UILabel! @IBOutlet weak var line3: UILabel! @IBOutlet weak var line4: UILabel! @IBOutlet weak var line5: UILabel! @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var shieldedWaterMark: UIImageView! var line1Text: String? { didSet { line1.text = line1Text } } var line2Text: String? { didSet { line2.text = line2Text } } var line3Text: String? { didSet { line3.text = line3Text } } var line4Text: String? { didSet { line4.text = line4Text } } var line5Text: String? { didSet { line5.text = line5Text } } var buttonText: String? { didSet { sendButton.setTitle(buttonText, for: .normal) } } var visibleWaterMark: Bool = false { didSet { shieldedWaterMark.isHidden = !visibleWaterMark } } init?(coder: NSCoder, presenter: SendFundConfirmationPresenterProtocol) { self.presenter = presenter super.init(coder: coder) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() presenter.view = self presenter.viewDidLoad() } @IBAction func confirmButtonTapped(_ sender: Any) { presenter.userTappedConfirm() } }
24.344086
110
0.626325
d91c719bc5d9a917b02ffff3858ce22d2edb2830
4,048
// Copyright (c) 2019 Razeware LLC // For full license & permission details, see LICENSE.markdown. public struct AVLTree<Element: Comparable> { public private(set) var root: AVLNode<Element>? public init() {} } extension AVLTree: CustomStringConvertible { public var description: String { guard let root = root else { return "empty tree" } return String(describing: root) } } extension AVLTree { public mutating func insert(_ value: Element) { root = insert(from: root, value: value) } private func insert(from node: AVLNode<Element>?, value: Element) -> AVLNode<Element> { guard let node = node else { return AVLNode(value: value) } if value < node.value { node.leftChild = insert(from: node.leftChild, value: value) } else { node.rightChild = insert(from: node.rightChild, value: value) } let balancedNode = balanced(node) balancedNode.height = max(balancedNode.leftHeight, balancedNode.rightHeight) + 1 return balancedNode } private func leftRotate(_ node: AVLNode<Element>) -> AVLNode<Element> { let pivot = node.rightChild! node.rightChild = pivot.leftChild pivot.leftChild = node node.height = max(node.leftHeight, node.rightHeight) + 1 pivot.height = max(pivot.leftHeight, pivot.rightHeight) + 1 return pivot } private func rightRotate(_ node: AVLNode<Element>) -> AVLNode<Element> { let pivot = node.leftChild! node.leftChild = pivot.rightChild pivot.rightChild = node node.height = max(node.leftHeight, node.rightHeight) + 1 pivot.height = max(pivot.leftHeight, pivot.rightHeight) + 1 return pivot } private func rightLeftRotate(_ node: AVLNode<Element>) -> AVLNode<Element> { guard let rightChild = node.rightChild else { return node } node.rightChild = rightRotate(rightChild) return leftRotate(node) } private func leftRightRotate(_ node: AVLNode<Element>) -> AVLNode<Element> { guard let leftChild = node.leftChild else { return node } node.leftChild = leftRotate(leftChild) return rightRotate(node) } private func balanced(_ node: AVLNode<Element>) -> AVLNode<Element> { switch node.balanceFactor { case 2: if let leftChild = node.leftChild, leftChild.balanceFactor == -1 { return leftRightRotate(node) } else { return rightRotate(node) } case -2: if let rightChild = node.rightChild, rightChild.balanceFactor == 1 { return rightLeftRotate(node) } else { return leftRotate(node) } default: return node } } } extension AVLTree { public func contains(_ value: Element) -> Bool { var current = root while let node = current { if node.value == value { return true } if value < node.value { current = node.leftChild } else { current = node.rightChild } } return false } } private extension AVLNode { var min: AVLNode { leftChild?.min ?? self } } extension AVLTree { public mutating func remove(_ value: Element) { root = remove(node: root, value: value) } private func remove(node: AVLNode<Element>?, value: Element) -> AVLNode<Element>? { guard let node = node else { return nil } if value == node.value { if node.leftChild == nil && node.rightChild == nil { return nil } if node.leftChild == nil { return node.rightChild } if node.rightChild == nil { return node.leftChild } node.value = node.rightChild!.min.value node.rightChild = remove(node: node.rightChild, value: node.value) } else if value < node.value { node.leftChild = remove(node: node.leftChild, value: value) } else { node.rightChild = remove(node: node.rightChild, value: value) } let balancedNode = balanced(node) balancedNode.height = max(balancedNode.leftHeight, balancedNode.rightHeight) + 1 return balancedNode } }
26.986667
89
0.646492