repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
ngageoint/mage-ios
Mage/Navigation/NavigationOverlay.swift
1
807
// // NavigationOverlay.swift // // Created by Tyler Burgett on 8/21/20. // Copyright © 2020 NGA. All rights reserved. // import Foundation import MapKit class NavigationOverlay: MKPolyline, OverlayRenderable { var color: UIColor = UIColor.systemRed var lineWidth: CGFloat = 1.0 var renderer: MKOverlayRenderer { get { let renderer = MKPolylineRenderer(overlay: self); renderer.strokeColor = self.color; renderer.lineWidth = self.lineWidth; return renderer; } } public convenience init(points: UnsafePointer<MKMapPoint>, count: Int, color: UIColor = .systemRed, lineWidth: CGFloat = 8.0) { self.init(points: points, count: count); self.color = color; self.lineWidth = lineWidth; } }
apache-2.0
carabina/ColorDebugView
ColorDebugViewExample/ViewController.swift
2
1176
// // ViewController.swift // ColorDebugViewExample // // Created by Jonathan Hull on 7/30/15. // Copyright © 2015 Jonathan Hull. 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. } @IBOutlet weak var debugView: ColorDebugView! @IBAction func animateHit(sender: UIButton) { UIView.animateWithDuration(2.0, animations: { self.debugView.transform = CGAffineTransformMakeScale(1.5, 1.5) }, completion: { flag in UIView.animateWithDuration(2.0, animations: { self.debugView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) }, completion: { flag in UIView.animateWithDuration(2.0, animations: { self.debugView.transform = CGAffineTransformIdentity }) }) }) } }
mit
swift-lang/swift-k
tests/language-behaviour/mappers/071-singlefilemapper-input.swift
2
243
type messagefile; app (messagefile o) write(messagefile i) { echo @filename(i) stdout=@filename(o); } messagefile infile <"071-singlefilemapper-input.in">; messagefile outfile <"071-singlefilemapper-input.out">; outfile = write(infile);
apache-2.0
brightdigit/tubeswift
TubeSwift/SubscriptionClient.swift
1
3258
// // SubscriptionClient.swift // TubeSwift // // Created by Leo G Dion on 4/29/15. // Copyright (c) 2015 Leo G Dion. All rights reserved. // public struct SubscriptionSubscriberSnippet { public let title:String public let description:String public let channelId:String public let thumbnails:[String:Thumbnail] public init?(result:[String:AnyObject]?) { if let dictionary = result, let title = dictionary["title"] as? String, let description = dictionary["description"] as? String, let channelId = dictionary["channelId"] as? String, let thumbnails = Thumbnail.Set((dictionary["thumbnails"] as? [String:[String:AnyObject]])) { self.title = title self.description = description self.channelId = channelId self.thumbnails = thumbnails } else { return nil } } } public struct SubscriptionSnippet { public let publishedAt:NSDate public let channelId: String? public let title: String public let description: String public let thumbnails:[String:Thumbnail] public let channelTitle:String? public let tags:[String] public init?(result: [String:AnyObject]?) { if let publishAtStr = result?["publishedAt"] as? String, let publishedAt = _dateFormatter.dateFromString(publishAtStr), let title = result?["title"] as? String, let description = result?["description"] as? String, let thumbnails = Thumbnail.Set((result?["thumbnails"] as? [String:[String:AnyObject]])) { self.publishedAt = publishedAt self.channelId = result?["channelId"] as? String self.title = title self.description = description self.thumbnails = thumbnails self.channelTitle = result?["channelTitle"] as? String self.tags = result?["tags"] as? [String] ?? [String]() } else { return nil } } } public struct Subscription { public let etag:String public let id:String //public let contentDetails:ContentDetails public let kind:YouTubeKind = YouTubeKind.Subscription public let subscriberSnippet:SubscriptionSubscriberSnippet? public let snippet:SubscriptionSnippet? public init?(result: [String:AnyObject]) { if let etag = result["etag"] as? String, let id = result["id"] as? String { self.etag = etag self.id = id self.subscriberSnippet = SubscriptionSubscriberSnippet(result: result["subscriberSnippet"] as? [String:AnyObject]) self.snippet = SubscriptionSnippet(result: result["snippet"] as? [String:AnyObject]) } else { return nil } } } public class SubscriptionClient: NSObject { public let client: TubeSwiftClient public init (client: TubeSwiftClient) { self.client = client } public func list (query: ResourceQuery, completion: (NSURLRequest, NSURLResponse?, Response<Subscription>?, NSError?) -> Void) { request(.GET, "https://www.googleapis.com/youtube/v3/subscriptions", parameters: query.parameters).responseJSON(options: .allZeros) { (request, response, result, error) -> Void in if let aError = error { completion(request, response, nil, aError) } else if let clRes = Response<Subscription>(kind: YouTubeKind.SubscriptionListResponse,result: result, itemFactory: {Subscription(result: $0)}) { completion(request, response, clRes, nil) } else { completion(request, response, nil, NSError()) } } } }
mit
justindarc/focus
Blockzilla/DictionaryExtensions.swift
4
377
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation extension Dictionary { public mutating func merge(with dictionary: Dictionary) { dictionary.forEach { updateValue($1, forKey: $0) } } }
mpl-2.0
ShiWeiCN/Goku
Goku/Source/Maker/AlertMakerFinalizable.swift
1
1629
// AlertMakerFinalizable.swift // Goku (https://github.com/ShiWeiCN/Goku) // // // Copyright (c) 2017 shiwei (http://shiweicn.github.io/) // // 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. #if os(iOS) import UIKit #endif public class AlertMakerFinalizable { internal let description: AlertDescription internal init(_ description: AlertDescription) { self.description = description } @discardableResult public func labeled(_ label: String) -> AlertMakerFinalizable { self.description.label = label return self } }
mit
lukaszwas/mcommerce-api
Sources/App/Controllers/UserController.swift
1
1719
import Vapor import HTTP // /users final class UserController: ResourceRepresentable { // GET / // Get all users func getAllUsers(req: Request) throws -> ResponseRepresentable { return try User.all().makeJSON() } // GET /:id // Get user with id func getUserWithId(req: Request, user: User) throws -> ResponseRepresentable { return user } // POST / // Create user func createUser(req: Request) throws -> ResponseRepresentable { let user = try req.user() try user.save() return user } // DELETE /:id // Delete user with id func deleteUser(req: Request, user: User) throws -> ResponseRepresentable { try user.delete() return Response(status: .ok) } // DELETE / // Delete all users func deleteAllUsers(req: Request) throws -> ResponseRepresentable { try User.makeQuery().delete() return Response(status: .ok) } // PATCH /:id // Update user func updateUser(req: Request, user: User) throws -> ResponseRepresentable { try user.update(for: req) try user.save() return user } // Resource func makeResource() -> Resource<User> { return Resource( index: getAllUsers, store: createUser, show: getUserWithId, update: updateUser, destroy: deleteUser, clear: deleteAllUsers ) } } // Deserialize JSON extension Request { func user() throws -> User { guard let json = json else { throw Abort.badRequest } return try User(json: json) } } extension UserController: EmptyInitializable { }
mit
kperson/FSwift
FSwift/Dictionary/Dictionary.swift
1
329
// // Dictionary.swift // FSwift // // Created by Maxime Ollivier on 1/27/15. // Copyright (c) 2015 Kelton. All rights reserved. // import Foundation extension Dictionary { mutating func addOptional(_ optional:Value?, forKey:Key) { if let object = optional { self[forKey] = object } } }
mit
mathcamp/hldb
Example/Todotastic/Carthage/Checkouts/hldb/Carthage/Checkouts/BrightFutures/Carthage/Checkouts/Result/Tests/Result/ResultTests.swift
8
7300
// Copyright (c) 2015 Rob Rix. All rights reserved. final class ResultTests: XCTestCase { func testMapTransformsSuccesses() { XCTAssertEqual(success.map { $0.characters.count } ?? 0, 7) } func testMapRewrapsFailures() { XCTAssertEqual(failure.map { $0.characters.count } ?? 0, 0) } func testInitOptionalSuccess() { XCTAssert(Result("success" as String?, failWith: error) == success) } func testInitOptionalFailure() { XCTAssert(Result(nil, failWith: error) == failure) } // MARK: Errors func testErrorsIncludeTheSourceFile() { let file = #file XCTAssert(Result<(), NSError>.error().file == file) } func testErrorsIncludeTheSourceLine() { let (line, error) = (#line, Result<(), NSError>.error()) XCTAssertEqual(error.line ?? -1, line) } func testErrorsIncludeTheCallingFunction() { let function = #function XCTAssert(Result<(), NSError>.error().function == function) } // MARK: Try - Catch func testTryCatchProducesSuccesses() { let result: Result<String, NSError> = Result(try tryIsSuccess("success")) XCTAssert(result == success) } func testTryCatchProducesFailures() { #if os(Linux) /// FIXME: skipped on Linux because of crash with swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a. print("Test Case `\(#function)` skipped on Linux because of crash with swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a.") #else let result: Result<String, NSError> = Result(try tryIsSuccess(nil)) XCTAssert(result.error == error) #endif } func testTryCatchWithFunctionProducesSuccesses() { let function = { try tryIsSuccess("success") } let result: Result<String, NSError> = Result(attempt: function) XCTAssert(result == success) } func testTryCatchWithFunctionCatchProducesFailures() { #if os(Linux) /// FIXME: skipped on Linux because of crash with swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a. print("Test Case `\(#function)` skipped on Linux because of crash with swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a.") #else let function = { try tryIsSuccess(nil) } let result: Result<String, NSError> = Result(attempt: function) XCTAssert(result.error == error) #endif } func testMaterializeProducesSuccesses() { let result1 = materialize(try tryIsSuccess("success")) XCTAssert(result1 == success) let result2: Result<String, NSError> = materialize { try tryIsSuccess("success") } XCTAssert(result2 == success) } func testMaterializeProducesFailures() { #if os(Linux) /// FIXME: skipped on Linux because of crash with swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a. print("Test Case `\(#function)` skipped on Linux because of crash with swift-DEVELOPMENT-SNAPSHOT-2016-03-01-a.") #else let result1 = materialize(try tryIsSuccess(nil)) XCTAssert(result1.error == error) let result2: Result<String, NSError> = materialize { try tryIsSuccess(nil) } XCTAssert(result2.error == error) #endif } // MARK: Cocoa API idioms #if !os(Linux) func testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference() { let result = `try` { attempt(true, succeed: false, error: $0) } XCTAssertFalse(result ?? false) XCTAssertNotNil(result.error) } func testTryProducesFailuresForOptionalWithErrorReturnedByReference() { let result = `try` { attempt(1, succeed: false, error: $0) } XCTAssertEqual(result ?? 0, 0) XCTAssertNotNil(result.error) } func testTryProducesSuccessesForBooleanAPI() { let result = `try` { attempt(true, succeed: true, error: $0) } XCTAssertTrue(result ?? false) XCTAssertNil(result.error) } func testTryProducesSuccessesForOptionalAPI() { let result = `try` { attempt(1, succeed: true, error: $0) } XCTAssertEqual(result ?? 0, 1) XCTAssertNil(result.error) } func testTryMapProducesSuccess() { let result = success.tryMap(tryIsSuccess) XCTAssert(result == success) } func testTryMapProducesFailure() { let result = Result<String, NSError>.Success("fail").tryMap(tryIsSuccess) XCTAssert(result == failure) } #endif // MARK: Operators func testConjunctionOperator() { let resultSuccess = success &&& success if let (x, y) = resultSuccess.value { XCTAssertTrue(x == "success" && y == "success") } else { XCTFail() } let resultFailureBoth = failure &&& failure2 XCTAssert(resultFailureBoth.error == error) let resultFailureLeft = failure &&& success XCTAssert(resultFailureLeft.error == error) let resultFailureRight = success &&& failure2 XCTAssert(resultFailureRight.error == error2) } } // MARK: - Fixtures let success = Result<String, NSError>.Success("success") let error = NSError(domain: "com.antitypical.Result", code: 1, userInfo: nil) let error2 = NSError(domain: "com.antitypical.Result", code: 2, userInfo: nil) let failure = Result<String, NSError>.Failure(error) let failure2 = Result<String, NSError>.Failure(error2) // MARK: - Helpers #if !os(Linux) func attempt<T>(value: T, succeed: Bool, error: NSErrorPointer) -> T? { if succeed { return value } else { #if swift(>=3.0) error.pointee = Result<(), NSError>.error() #else error.memory = Result<(), NSError>.error() #endif return nil } } #endif func tryIsSuccess(text: String?) throws -> String { guard let text = text where text == "success" else { throw error } return text } extension NSError { var function: String? { return userInfo[Result<(), NSError>.functionKey] as? String } var file: String? { return userInfo[Result<(), NSError>.fileKey] as? String } var line: Int? { return userInfo[Result<(), NSError>.lineKey] as? Int } } #if os(Linux) extension ResultTests { static var allTests: [(String, ResultTests -> () throws -> Void)] { return [ ("testMapTransformsSuccesses", testMapTransformsSuccesses), ("testMapRewrapsFailures", testMapRewrapsFailures), ("testInitOptionalSuccess", testInitOptionalSuccess), ("testInitOptionalFailure", testInitOptionalFailure), ("testErrorsIncludeTheSourceFile", testErrorsIncludeTheSourceFile), ("testErrorsIncludeTheSourceLine", testErrorsIncludeTheSourceLine), ("testErrorsIncludeTheCallingFunction", testErrorsIncludeTheCallingFunction), ("testTryCatchProducesSuccesses", testTryCatchProducesSuccesses), ("testTryCatchProducesFailures", testTryCatchProducesFailures), ("testTryCatchWithFunctionProducesSuccesses", testTryCatchWithFunctionProducesSuccesses), ("testTryCatchWithFunctionCatchProducesFailures", testTryCatchWithFunctionCatchProducesFailures), ("testMaterializeProducesSuccesses", testMaterializeProducesSuccesses), ("testMaterializeProducesFailures", testMaterializeProducesFailures), // ("testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference", testTryProducesFailuresForBooleanAPIWithErrorReturnedByReference), // ("testTryProducesFailuresForOptionalWithErrorReturnedByReference", testTryProducesFailuresForOptionalWithErrorReturnedByReference), // ("testTryProducesSuccessesForBooleanAPI", testTryProducesSuccessesForBooleanAPI), // ("testTryProducesSuccessesForOptionalAPI", testTryProducesSuccessesForOptionalAPI), // ("testTryMapProducesSuccess", testTryMapProducesSuccess), // ("testTryMapProducesFailure", testTryMapProducesFailure), ("testConjunctionOperator", testConjunctionOperator), ] } } #endif import Foundation import Result import XCTest
mit
Ryce/flickrpickr
Carthage/Checkouts/judokit/Example-Swift/JudoKitSwiftExample/ExampleAppCredentials.swift
2
1313
// // ExampleAppCredentials.swift // JudoKitSwiftExample // // Copyright (c) 2016 Alternative Payments Ltd // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation let judoId = "<#YOUR JUDOID#>" let token = "<#YOUR TOKEN#>" let secret = "<#YOUR SECRET#>"
mit
kishanravindra/load-facebook-profile-ios-swift
LoadFacebookProfileKitTests/FakeLoginWithFacebookTests.swift
3
3052
import Foundation import XCTest @testable import LoadFacebookProfileKit class FakeLoginWithFacebookTests: XCTestCase { var dictionary: [String: AnyObject]! override func setUp() { super.setUp() } override func tearDown() { super.tearDown() FacebookUserLoader.simulateLoadAfterDelay = 0.1 FacebookUserLoader.simulateSuccessUser = nil FacebookUserLoader.simulateError = false } func testLoadUser() { FacebookUserLoader.simulateSuccessUser = TegFacebookUser(id: "fake user id", accessToken: "test access tokeb", email: "test@email.com", firstName: "test first name", lastName: "test last name", name: "test name" ) let loader = FacebookUserLoader() var errorReturned = false var userReturned: TegFacebookUser? let expectation = expectationWithDescription("load facebook profile") loader.load(askEmail: true, onError: { errorReturned = true }, onSuccess: { user in expectation.fulfill() userReturned = user } ) waitForExpectationsWithTimeout(1) { error in } XCTAssertFalse(errorReturned) XCTAssertEqual("test@email.com", userReturned!.email!) } func testLoadUser_synchronously() { FacebookUserLoader.simulateSuccessUser = TegFacebookUser(id: "fake user id", accessToken: "test access tokeb", email: "test@email.com", firstName: "test first name", lastName: "test last name", name: "test name" ) FacebookUserLoader.simulateLoadAfterDelay = 0 let loader = FacebookUserLoader() var errorReturned = false var userReturned: TegFacebookUser? loader.load(askEmail: true, onError: { errorReturned = true }, onSuccess: { user in userReturned = user } ) XCTAssertFalse(errorReturned) XCTAssertEqual("test@email.com", userReturned!.email!) } func testLoadUser_returnError() { FacebookUserLoader.simulateError = true let loader = FacebookUserLoader() var errorReturned = false var userReturned: TegFacebookUser? let expectation = expectationWithDescription("load facebook profile") loader.load(askEmail: true, onError: { errorReturned = true expectation.fulfill() }, onSuccess: { user in userReturned = user } ) waitForExpectationsWithTimeout(1) { error in } XCTAssert(errorReturned) XCTAssert(userReturned == nil) } func testLoadUser_returnErrorSynchronously() { FacebookUserLoader.simulateError = true FacebookUserLoader.simulateLoadAfterDelay = 0 let loader = FacebookUserLoader() var errorReturned = false var userReturned: TegFacebookUser? loader.load(askEmail: true, onError: { errorReturned = true }, onSuccess: { user in userReturned = user } ) XCTAssert(errorReturned) XCTAssert(userReturned == nil) } }
mit
ProsoftEngineering/TimeMachineRemoteStatus
TimeMachineRemoteStatus/ProcessExtensions.swift
1
2476
// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // All rights reserved. // // 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 Prosoft 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 PROSOFT ENGINEERING, INC. 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 extension Process { // http://stackoverflow.com/a/25729093/412179 static func run(launchPath: String, args: [String]) -> (status: Int32, output: String, error: String) { let task = Process() task.launchPath = launchPath task.arguments = args let stdoutPipe = Pipe() let stderrPipe = Pipe() task.standardOutput = stdoutPipe task.standardError = stderrPipe task.launch() let stdoutData = stdoutPipe.fileHandleForReading.readDataToEndOfFile() let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile() task.waitUntilExit() let output = String(data: stdoutData, encoding: .utf8) let error = String(data: stderrData, encoding: .utf8) return (task.terminationStatus, output!, error!) } }
bsd-3-clause
asp2insp/yowl
yowl/ResultsStore.swift
1
1171
// // ResultsStore.swift // yowl // // Created by Josiah Gaskin on 5/17/15. // Copyright (c) 2015 Josiah Gaskin. All rights reserved. // import Foundation let RESULTS = Getter(keyPath:["results", "businesses"]) // ID: results class SearchResultsStore : Store { override func getInitialState() -> Immutable.State { return Immutable.toState([]) } override func initialize() { self.on("setResults", handler: { (state, results, action) -> Immutable.State in let offset = Reactor.instance.evaluateToSwift(OFFSET) as! Int if offset == 0 { return Immutable.toState(results as! AnyObject) } else { return state.mutateIn(["businesses"], withMutator: {(s) -> Immutable.State in let newResults = results as! [String:AnyObject] let newBiz = newResults["businesses"] as! [AnyObject] var result = s! for biz in newBiz { result = result.push(Immutable.toState(biz)) } return result }) } }) } }
mit
openbuild-sheffield/jolt
Sources/RouteCMS/validate.BodyTemplatePath.swift
1
287
import OpenbuildExtensionPerfect //TODO / FIXME - change this to a closure and check if the template exists let ValidateBodyTemplatePath = RequestValidationBody( name: "template_path", required: true, type: RequestValidationTypeString( regex: "^(.*){1,255}$" ) )
gpl-2.0
natecook1000/swift
stdlib/public/SDK/Foundation/NSDictionary.swift
1
9274
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims //===----------------------------------------------------------------------===// // Dictionaries //===----------------------------------------------------------------------===// extension NSDictionary : ExpressibleByDictionaryLiteral { public required convenience init( dictionaryLiteral elements: (Any, Any)... ) { // FIXME: Unfortunate that the `NSCopying` check has to be done at runtime. self.init( objects: elements.map { $0.1 as AnyObject }, forKeys: elements.map { $0.0 as AnyObject as! NSCopying }, count: elements.count) } } extension Dictionary { /// Private initializer used for bridging. /// /// The provided `NSDictionary` will be copied to ensure that the copy can /// not be mutated by other code. public init(_cocoaDictionary: _NSDictionary) { assert( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), "Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C") // FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an // objc_msgSend() for instances of CoreFoundation types. We can't do that // today because CFDictionaryCreateCopy() copies dictionary contents // unconditionally, resulting in O(n) copies even for immutable dictionaries. // // <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone: // // The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS // and watchOS. self = Dictionary( _immutableCocoaDictionary: unsafeBitCast(_cocoaDictionary.copy(with: nil) as AnyObject, to: _NSDictionary.self)) } } // Dictionary<Key, Value> is conditionally bridged to NSDictionary extension Dictionary : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSDictionary { return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject, to: NSDictionary.self) } public static func _forceBridgeFromObjectiveC( _ d: NSDictionary, result: inout Dictionary? ) { if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf( d as AnyObject) { result = native return } if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = [Key : Value]( _cocoaDictionary: unsafeBitCast(d as AnyObject, to: _NSDictionary.self)) return } if Key.self == String.self { // String and NSString have different concepts of equality, so // string-keyed NSDictionaries may generate key collisions when bridged // over to Swift. See rdar://problem/35995647 var dict = Dictionary(minimumCapacity: d.count) d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in let key = Swift._forceBridgeFromObjectiveC( anyKey as AnyObject, Key.self) let value = Swift._forceBridgeFromObjectiveC( anyValue as AnyObject, Value.self) // FIXME: Log a warning if `dict` already had a value for `key` dict[key] = value }) result = dict return } // `Dictionary<Key, Value>` where either `Key` or `Value` is a value type // may not be backed by an NSDictionary. var builder = _DictionaryBuilder<Key, Value>(count: d.count) d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in let anyObjectKey = anyKey as AnyObject let anyObjectValue = anyValue as AnyObject builder.add( key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self), value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self)) }) result = builder.take() } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { let anyDict = x as [NSObject : AnyObject] if _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self) { result = Swift._dictionaryDownCastConditional(anyDict) return result != nil } result = anyDict as? Dictionary return result != nil } public static func _unconditionallyBridgeFromObjectiveC( _ d: NSDictionary? ) -> Dictionary { // `nil` has historically been used as a stand-in for an empty // dictionary; map it to an empty dictionary. if _slowPath(d == nil) { return Dictionary() } var result: Dictionary? = nil _forceBridgeFromObjectiveC(d!, result: &result) return result! } } extension NSDictionary : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as! Dictionary<AnyHashable, AnyHashable>) } } extension NSDictionary : Sequence { // FIXME: A class because we can't pass a struct with class fields through an // [objc] interface without prematurely destroying the references. final public class Iterator : IteratorProtocol { var _fastIterator: NSFastEnumerationIterator var _dictionary: NSDictionary { return _fastIterator.enumerable as! NSDictionary } public func next() -> (key: Any, value: Any)? { if let key = _fastIterator.next() { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return (key: key, value: _dictionary.object(forKey: key)!) } return nil } internal init(_ _dict: NSDictionary) { _fastIterator = NSFastEnumerationIterator(_dict) } } // Bridging subscript. @objc public subscript(key: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { // Deliberately avoid the subscript operator in case the dictionary // contains non-copyable keys. This is rare since NSMutableDictionary // requires them, but we don't want to paint ourselves into a corner. return self.object(forKey: key) } } /// Return an *iterator* over the elements of this *sequence*. /// /// - Complexity: O(1). public func makeIterator() -> Iterator { return Iterator(self) } } extension NSMutableDictionary { // Bridging subscript. @objc override public subscript(key: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { return self.object(forKey: key) } @objc(_swift_setObject:forKeyedSubscript:) set { // FIXME: Unfortunate that the `NSCopying` check has to be done at // runtime. let copyingKey = key as AnyObject as! NSCopying if let newValue = newValue { self.setObject(newValue, forKey: copyingKey) } else { self.removeObject(forKey: copyingKey) } } } } extension NSDictionary { /// Initializes a newly allocated dictionary and adds to it objects from /// another given dictionary. /// /// - Returns: An initialized dictionary--which might be different /// than the original receiver--containing the keys and values /// found in `otherDictionary`. @objc(_swiftInitWithDictionary_NSDictionary:) public convenience init(dictionary otherDictionary: NSDictionary) { // FIXME(performance)(compiler limitation): we actually want to do just // `self = otherDictionary.copy()`, but Swift does not have factory // initializers right now. let numElems = otherDictionary.count let stride = MemoryLayout<AnyObject>.stride let alignment = MemoryLayout<AnyObject>.alignment let singleSize = stride * numElems let totalSize = singleSize * 2 assert(stride == MemoryLayout<NSCopying>.stride) assert(alignment == MemoryLayout<NSCopying>.alignment) // Allocate a buffer containing both the keys and values. let buffer = UnsafeMutableRawPointer.allocate( byteCount: totalSize, alignment: alignment) defer { buffer.deallocate() _fixLifetime(otherDictionary) } let valueBuffer = buffer.bindMemory(to: AnyObject.self, capacity: numElems) let buffer2 = buffer + singleSize __NSDictionaryGetObjects(otherDictionary, buffer, buffer2, numElems) let keyBufferCopying = buffer2.assumingMemoryBound(to: NSCopying.self) self.init(objects: valueBuffer, forKeys: keyBufferCopying, count: numElems) } } extension NSDictionary : CustomReflectable { public var customMirror: Mirror { return Mirror(reflecting: self as [NSObject : AnyObject]) } } extension Dictionary: CVarArg {}
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/26917-swift-nominaltype-get.swift
11
423
// 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 enum S<T{func f:a func a<T:T.E
apache-2.0
sync/NearbyTrams
NearbyTramsKit/Source/RouteViewModel.swift
1
1247
// // Copyright (c) 2014 Dblechoc. All rights reserved. // import Foundation public class RouteViewModel: Equatable { public let identifier: String public var routeNo: String public var routeDescription: String public var downDestination: String public var upDestination: String public let color: CGColorRef public init (identifier: String, routeNo: String, routeDescription: String, downDestination: String, upDestination: String, color: CGColorRef = ColorUtility.generateRandomColor()) { self.identifier = identifier self.routeNo = routeNo self.routeDescription = routeDescription self.downDestination = downDestination self.upDestination = upDestination self.color = color } public func updateWithRouteNo(routeNo: String, routeDescription: String, downDestination: String, upDestination: String) { self.routeNo = routeNo self.routeDescription = routeDescription self.downDestination = downDestination self.upDestination = upDestination self.routeDescription = routeDescription } } public func ==(lhs: RouteViewModel, rhs: RouteViewModel) -> Bool { return lhs.identifier == rhs.identifier }
mit
acastano/swift-bootstrap
userinterfacekit/Sources/Classes/Utils/Extensions/UICollectionView+Utils.swift
1
554
import UIKit public extension UICollectionView { public var centerPoint: CGPoint { get { return CGPoint(x:center.x + contentOffset.x, y:center.y + contentOffset.y) } } public var centerCellIndexPath: IndexPath? { var indexPath: IndexPath? if let centerIndexPath = indexPathForItem(at: centerPoint) { indexPath = centerIndexPath } return indexPath } }
apache-2.0
wikimedia/wikipedia-ios
WMF Framework/TimelineView.swift
1
11539
import UIKit public class TimelineView: UIView { public enum Decoration { case doubleDot, singleDot, squiggle } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } open func setup() { } public var decoration: Decoration = .doubleDot { didSet { guard oldValue != decoration else { return } switch decoration { case .squiggle: innerDotShapeLayer.removeFromSuperlayer() outerDotShapeLayer.removeFromSuperlayer() layer.addSublayer(squiggleShapeLayer) updateSquiggleCenterPoint() case .doubleDot: squiggleShapeLayer.removeFromSuperlayer() layer.addSublayer(innerDotShapeLayer) layer.addSublayer(outerDotShapeLayer) case .singleDot: squiggleShapeLayer.removeFromSuperlayer() layer.addSublayer(innerDotShapeLayer) } setNeedsDisplay() } } public var shouldAnimateDots: Bool = false public var minimizeUnanimatedDots: Bool = false public var timelineColor: UIColor? = nil { didSet { refreshColors() } } private var color: CGColor { return timelineColor?.cgColor ?? tintColor.cgColor } public var verticalLineWidth: CGFloat = 1.0 { didSet { squiggleShapeLayer.lineWidth = verticalLineWidth setNeedsDisplay() } } public var pauseDotsAnimation: Bool = true { didSet { displayLink?.isPaused = pauseDotsAnimation } } private var dotRadius: CGFloat { switch decoration { case .singleDot: return 7.0 default: return 9.0 } } private let dotMinRadiusNormal: CGFloat = 0.4 // At a height of less than 30, (due to rounding) the squiggle's curves don't perfectly align with the straight lines. private let squiggleHeight: CGFloat = 30.0 public var dotsY: CGFloat = 0 { didSet { guard shouldAnimateDots == false || decoration == .squiggle else { return } switch decoration { case .doubleDot, .singleDot: updateDotsRadii(to: minimizeUnanimatedDots ? 0.0 : 1.0, at: CGPoint(x: bounds.midX, y: dotsY)) case .squiggle: updateSquiggleCenterPoint() } setNeedsDisplay() } } override public func tintColorDidChange() { super.tintColorDidChange() refreshColors() } override public var backgroundColor: UIColor? { didSet { outerDotShapeLayer.fillColor = backgroundColor?.cgColor squiggleShapeLayer.fillColor = backgroundColor?.cgColor } } private lazy var outerDotShapeLayer: CAShapeLayer = { let shape = CAShapeLayer() shape.fillColor = backgroundColor?.cgColor ?? UIColor.white.cgColor shape.strokeColor = color shape.lineWidth = 1.0 if decoration == .doubleDot { self.layer.addSublayer(shape) } return shape }() private lazy var innerDotShapeLayer: CAShapeLayer = { let shape = CAShapeLayer() shape.fillColor = color shape.strokeColor = color shape.lineWidth = 1.0 if decoration == .doubleDot { self.layer.addSublayer(shape) } return shape }() private lazy var squiggleShapeLayer: CAShapeLayer = { let shape = CAShapeLayer() shape.updateSquiggleLocation(height: squiggleHeight, decorationMidY: dotsY, midX: bounds.midX) shape.strokeColor = color shape.fillColor = backgroundColor?.cgColor ?? UIColor.white.cgColor shape.lineWidth = verticalLineWidth if decoration == .squiggle { self.layer.addSublayer(shape) } return shape }() private lazy var displayLink: CADisplayLink? = { guard decoration == .doubleDot, shouldAnimateDots == true else { return nil } let link = CADisplayLink(target: self, selector: #selector(maybeUpdateDotsRadii)) link.add(to: RunLoop.main, forMode: RunLoop.Mode.common) return link }() override public func removeFromSuperview() { displayLink?.invalidate() displayLink = nil super.removeFromSuperview() } override public func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } drawVerticalLine(in: context, rect: rect) } public var extendTimelineAboveDot: Bool = true { didSet { if oldValue != extendTimelineAboveDot { setNeedsDisplay() } } } private func drawVerticalLine(in context: CGContext, rect: CGRect) { context.setLineWidth(verticalLineWidth) context.setStrokeColor(color) let lineTopY = extendTimelineAboveDot ? rect.minY : dotsY switch decoration { case .doubleDot, .singleDot: context.move(to: CGPoint(x: rect.midX, y: lineTopY)) context.addLine(to: CGPoint(x: rect.midX, y: rect.maxY)) case .squiggle: if extendTimelineAboveDot { context.move(to: CGPoint(x: rect.midX, y: lineTopY)) context.addLine(to: CGPoint(x: rect.midX, y: dotsY-squiggleHeight/2)) } context.move(to: CGPoint(x: rect.midX, y: dotsY+squiggleHeight/2)) context.addLine(to: CGPoint(x: rect.midX, y: rect.maxY)) } context.strokePath() } private func refreshColors() { outerDotShapeLayer.strokeColor = color innerDotShapeLayer.fillColor = color innerDotShapeLayer.strokeColor = color squiggleShapeLayer.strokeColor = color setNeedsDisplay() } // Returns CGFloat in range from 0.0 to 1.0. 0.0 indicates dot should be minimized. // 1.0 indicates dot should be maximized. Approaches 1.0 as timelineView.dotY // approaches vertical center. Approaches 0.0 as timelineView.dotY approaches top // or bottom. private func dotRadiusNormal(with y:CGFloat, in container:UIView) -> CGFloat { let yInContainer = convert(CGPoint(x:0, y:y), to: container).y let halfContainerHeight = container.bounds.size.height * 0.5 return max(0.0, 1.0 - (abs(yInContainer - halfContainerHeight) / halfContainerHeight)) } private var lastDotRadiusNormal: CGFloat = -1.0 // -1.0 so dots with dotAnimationNormal of "0.0" are visible initially @objc private func maybeUpdateDotsRadii() { guard let containerView = window else { return } // Shift the "full-width dot" point up a bit - otherwise it's in the vertical center of screen. let yOffset = containerView.bounds.size.height * 0.15 var radiusNormal = dotRadiusNormal(with: dotsY + yOffset, in: containerView) // Reminder: can reduce precision to 1 (significant digit) to reduce how often dot radii are updated. let precision: CGFloat = 2 let roundingNumber = pow(10, precision) radiusNormal = (radiusNormal * roundingNumber).rounded(.up) / roundingNumber guard radiusNormal != lastDotRadiusNormal else { return } updateDotsRadii(to: radiusNormal, at: CGPoint(x: bounds.midX, y: dotsY)) // Progressively fade the inner dot when it gets tiny. innerDotShapeLayer.opacity = easeInOutQuart(number: Float(radiusNormal)) lastDotRadiusNormal = radiusNormal } private func updateDotsRadii(to radiusNormal: CGFloat, at center: CGPoint) { outerDotShapeLayer.updateDotRadius(dotRadius * max(radiusNormal, dotMinRadiusNormal), center: center) innerDotShapeLayer.updateDotRadius(dotRadius * max((radiusNormal - dotMinRadiusNormal), 0.0), center: center) } private func updateSquiggleCenterPoint() { squiggleShapeLayer.updateSquiggleLocation(height: squiggleHeight, decorationMidY: dotsY, midX: bounds.midX) } private func easeInOutQuart(number:Float) -> Float { return number < 0.5 ? 8.0 * pow(number, 4) : 1.0 - 8.0 * (number - 1.0) * pow(number, 3) } } extension CAShapeLayer { fileprivate func updateDotRadius(_ radius: CGFloat, center: CGPoint) { path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0.0, endAngle:CGFloat.pi * 2.0, clockwise: true).cgPath } fileprivate func updateSquiggleLocation(height: CGFloat, decorationMidY: CGFloat, midX: CGFloat) { let startY = decorationMidY - height/2 // squiggle's middle (not top) should be startY let topPoint = CGPoint(x: midX, y: startY) let quarterOnePoint = CGPoint(x: midX, y: startY + (height*1/4)) let midPoint = CGPoint(x: midX, y: startY + (height*2/4)) let quarterThreePoint = CGPoint(x: midX, y: startY + (height*3/4)) let bottomPoint = CGPoint(x: midX, y: startY + height) /// Math for curves shown/explained on Phab ticket: https://phabricator.wikimedia.org/T258209#6363389 let eighthOfHeight = height/8 let circleDiameter = sqrt(2*(eighthOfHeight*eighthOfHeight)) let radius = circleDiameter/2 /// Without this adjustment, the `arcCenter`s are not the true center of circle and the squiggle has some jagged edges. let centerAdjustedRadius = radius - 1 let arc1Start = CGPoint(x: midX - radius*3, y: topPoint.y + radius*3) let arc1Center = CGPoint(x: arc1Start.x + centerAdjustedRadius, y: arc1Start.y + centerAdjustedRadius) let arc2Start = CGPoint(x: midX + radius*1, y: quarterOnePoint.y - radius*1) let arc2Center = CGPoint(x: arc2Start.x + centerAdjustedRadius, y: arc2Start.y + centerAdjustedRadius) let arc3Start = CGPoint(x: midX - radius*3, y: midPoint.y + radius*3) let arc3Center = CGPoint(x: arc3Start.x + centerAdjustedRadius, y: arc3Start.y + centerAdjustedRadius) let arc4Start = CGPoint(x: midX + radius*1, y: quarterThreePoint.y - radius*1) let arc4Center = CGPoint(x: arc4Start.x + centerAdjustedRadius, y: arc4Start.y + centerAdjustedRadius) let squiggle = UIBezierPath() let fullCircle = 2 * CGFloat.pi // addArc's angles are in radians, let's make it easier squiggle.move(to: topPoint) squiggle.addLine(to: arc1Start) squiggle.addArc(withCenter: arc1Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: false) squiggle.addLine(to: arc2Start) squiggle.addArc(withCenter: arc2Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: true) squiggle.addLine(to: arc3Start) squiggle.addArc(withCenter: arc3Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: false) squiggle.addLine(to: arc4Start) squiggle.addArc(withCenter: arc4Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: true) squiggle.addLine(to: bottomPoint) path = squiggle.cgPath } }
mit
mleiv/MEGameTracker
MEGameTracker/Models/CloudKit/CloudKit Records/CloudKitNotes.swift
1
5777
// // GameNotes.swift // MEGameTracker // // Created by Emily Ivie on 12/31/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import Foundation import CoreData import CloudKit extension Note: CloudDataStorable { /// (CloudDataStorable Protocol) /// Set any additional fields, specific to the object in question, for a cloud kit object. public func setAdditionalCloudFields( record: CKRecord ) { record.setValue(uuid.uuidString as NSString, forKey: "id") record.setValue((gameSequenceUuid?.uuidString ?? "") as NSString, forKey: "gameSequenceUuid") record.setValue(gameVersion.stringValue as NSString, forKey: "gameVersion") record.setValue((shepardUuid?.uuidString ?? "") as NSString, forKey: "shepardUuid") record.setValue(identifyingObject.serializedString, forKey: "identifyingObject") record.setValue(text, forKey: "text") } /// (CloudDataStorable Protocol) /// Alter any CK items before handing to codable to modify/create object public func getAdditionalCloudFields(changeRecord: CloudDataRecordChange) -> [String: Any?] { var changes = changeRecord.changeSet changes["gameSequenceUuid"] = self.gameSequenceUuid //? changes.removeValue(forKey: "identifyingObject") // fallback to element's value // changes.removeValue(forKey: "lastRecordData") return changes } /// (CloudDataStorable Protocol) /// Takes one serialized cloud change and saves it. public static func saveOneFromCloud( changeRecord: CloudDataRecordChange, with manager: CodableCoreDataManageable? ) -> Bool { let recordId = changeRecord.recordId if let (id, gameUuid) = parseIdentifyingName(name: recordId), let noteUuid = UUID(uuidString: id), let shepardUuidString = changeRecord.changeSet["shepardUuid"] as? String, let shepardUuid = UUID(uuidString: shepardUuidString) { // if identifyingObject fails, throw this note away - it can't be recovered :( guard let json = changeRecord.changeSet["identifyingObject"] as? String, let decoder = manager?.decoder, let identifyingObject = try? decoder.decode( IdentifyingObject.self, from: json.data(using: .utf8) ?? Data() ) else { return true } var element = Note.get(uuid: noteUuid) ?? Note( identifyingObject: identifyingObject, uuid: noteUuid, shepardUuid: shepardUuid, gameSequenceUuid: gameUuid ) // apply cloud changes element.rawData = nil let changes = element.getAdditionalCloudFields(changeRecord: changeRecord) element = element.changed(changes) element.isSavedToCloud = true // reapply any local changes if !element.pendingCloudChanges.isEmpty { element = element.changed(element.pendingCloudChanges.dictionary) element.isSavedToCloud = false } // save locally if element.save(with: manager) { print("Saved from cloud \(recordId)") return true } else { print("Save from cloud failed \(recordId)") } } return false } /// (CloudDataStorable Protocol) /// Delete a local object after directed by the cloud to do so. public static func deleteOneFromCloud(recordId: String) -> Bool { guard let (noteUuid, gameUuid) = parseIdentifyingName(name: recordId) else { return false } if let noteUuid = UUID(uuidString: noteUuid) { return delete(uuid: noteUuid, gameSequenceUuid: gameUuid) } else { defaultManager.log("Failed to parse note uuid: \(recordId)") return false } } /// (CloudDataStorable Protocol) /// Create a recordName for any cloud kit object. public static func getIdentifyingName( id: String, gameSequenceUuid: UUID? ) -> String { return "\(gameSequenceUuid?.uuidString ?? "")||\(id)" } /// Convenience version - get the static getIdentifyingName for easy instance reference. public func getIdentifyingName() -> String { return Note.getIdentifyingName(id: uuid.uuidString, gameSequenceUuid: gameSequenceUuid) } /// (CloudDataStorable Protocol) /// Parses a cloud identifier into the parts needed to retrieve it from core data. public static func parseIdentifyingName( name: String ) -> (id: String, gameSequenceUuid: UUID)? { let pieces = name.components(separatedBy: "||") guard pieces.count == 2 else { return nil } if let gameSequenceUuid = UUID(uuidString: pieces[0]) { return (id: pieces[1], gameSequenceUuid: gameSequenceUuid) } else { defaultManager.log("No Game UUID found for: \(name)") return nil } } /// Used for parsing from records public static func getAll( identifiers: [String], with manager: CodableCoreDataManageable? ) -> [Note] { return identifiers.map { (identifier: String) in if let (id, _) = parseIdentifyingName(name: identifier), let uuid = UUID(uuidString: id) { return get(uuid: uuid, with: manager) } return nil }.filter({ $0 != nil }).map({ $0! }) } }
mit
hellogaojun/Swift-coding
03-运算符/03-运算符/main.swift
1
2058
// // main.swift // 03-运算符 // // Created by gaojun on 16/4/2. // Copyright © 2016年 高军. All rights reserved. // import Foundation print("Hello, World!") /* 算术运算符: 除了取模, 其它和OC一样, 包括优先级 + - * / % ++ -- */ var result = 10 + 10 result = 10 * 10 result = 10 - 10 result = 10 / 10 print(result) /* 取模 % OC: 只能对整数取模 NSLog(@"%tu", 10 % 3); Swift: 支持小数取模 */ print(10 % 3.2) /* 注意:Swift是安全严格的编程语言, 会在编译时候检查是否溢出, 但是只会检查字面量而不会检查变量, 所以在Swift中一定要注意隐式溢出 可以检测 var num1:UInt8 = 255 + 1; 无法检测 var num1:UInt8 = 255 var num2:UInt8 = 250 var result = num1 + num2 println(result) 遇到这种问题可以利用溢出运算符解决该问题:http://www.yiibai.com/swift/overflow_operators.html &+ &- &* &/ &% */ //var over1 : UInt8 = 255 //var over2 : UInt8 = 250 //var result1 = over1 + over2 //print(result1) //自增,自减 var number = 10 number++ print(number) number-- print(number) //赋值运算符 var num1 = 10 num1 = 20 num1 += 10 num1 -= 10 num1 *= 10 num1 /= 10 num1 %= 10 print(num1) //关系运算符 var res:Bool = 123 > 12 print(res)//true var res2 = 123 > 12 ? 123:12 print(res2) //逻辑运算符,Swift中的逻辑运算符只能操作Bool类型数据, 而OC可以操作整形(非0即真 //if 5 {//错误写法 // print("5") //} var open = false if !open { print("开房") }else { print("开你个头") } var age = 25 var height = 185 var wage = 30000 if age > 25 && age < 40 && height > 175 || wage > 20000 { print("约炮") }else { print("约你个蛋") } /* 区间 闭区间: 包含区间内所有值 a...b 例如: 1...5 半闭区间: 包含头不包含尾 a..<b 例如: 1..<5 注意: 1.Swift刚出来时的写法是 a..b 2.区间只能用于整数, 写小数会有问题 应用场景: 遍历, 数组等 */ for i in 1...5 { print("闭区间--i:",i) } for i in 1..<5 { print("半闭区间--i:",i) }
apache-2.0
coodly/TalkToCloud
Sources/TalkToCloud/Raw.ZoneID.swift
1
768
/* * Copyright 2020 Coodly LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation extension Raw { internal struct ZoneID: Codable { let zoneName: String let ownerRecordName: String? let zoneType: String? } }
apache-2.0
gusrsilva/Picture-Perfect-iOS
PicturePerfect/ShadowImageView.swift
1
843
// // ShadowImageView.swift // PicturePerfect // // Created by Gus Silva on 4/16/17. // Copyright © 2017 Gus Silva. All rights reserved. // import UIKit class ShadowImageView: UIImageView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ var shadowLayer: CAShapeLayer! override func layoutSubviews() { super.layoutSubviews() layer.masksToBounds = false clipsToBounds = false layer.shadowPath = UIBezierPath(rect: bounds).cgPath layer.shadowColor = UIColor.black.cgColor layer.shadowOffset = CGSize(width: 0, height: 0) layer.shadowOpacity = 0.35 layer.shadowRadius = 5 } }
apache-2.0
amarantine308/OneDayOneDemo_Swift
Day9_video/VideoViewTest/VideoView/AppDelegate.swift
1
2174
// // AppDelegate.swift // VideoView // // Created by 冯毅潇 on 2018/2/26. // Copyright © 2018年 冯毅潇. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-3.0
ustwo/mockingbird
Sources/ResourceKit/Helpers/ResourceHandler.swift
1
1444
// // SwaggerParser.swift // Mockingbird // // Created by Aaron McTavish on 20/12/2016. // Copyright © 2016 ustwo Fampany Ltd. All rights reserved. // import Foundation import LoggerAPI public struct ResourceHandler { // MARK: - Properties private static let sampleName = "sample_swagger" private static let sampleExtension = "json" private static let sampleFullName = ResourceHandler.sampleName + "." + ResourceHandler.sampleExtension public static var swaggerSampleURL: URL { #if os(Linux) // swiftlint:disable:next force_unwrapping return URL(string: "file:///root/Resources/" + ResourceHandler.sampleFullName)! #else // If in Xcode, grab from the resource bundle let frameworkBundle = Bundle(for: DummyClass.self) if let url = frameworkBundle.url(forResource:ResourceHandler.sampleName, withExtension: ResourceHandler.sampleExtension) { return url } // If using the Swift compiler (i.e. `swift build` or `swift test`, use the absolute path. // swiftlint:disable:next force_unwrapping let frameworkURL = Bundle(for: DummyClass.self).resourceURL! return frameworkURL.appendingPathComponent("../../../../../Resources/" + ResourceHandler.sampleFullName) #endif } } private class DummyClass: NSObject { }
mit
gabrielfalcao/MusicKit
MusicKit/ScaleQuality.swift
1
1199
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation public enum ScaleQuality : String { case Chromatic = "Chromatic" case Wholetone = "Wholetone" case Octatonic1 = "Octatonic mode 1" case Octatonic2 = "Octatonic mode 2" case Major = "Major" case Dorian = "Dorian" case Phrygian = "Phrygian" case Lydian = "Lydian" case Mixolydian = "Mixolydian" case Minor = "Minor" case Locrian = "Locrian" public var intervals : [Float] { switch self { case Chromatic: return [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] case Wholetone: return [2, 2, 2, 2, 2, 2] case Octatonic1: return [2, 1, 2, 1, 2, 1, 2] case Octatonic2: return [1, 2, 1, 2, 1, 2, 1] case Major: return [2, 2, 1, 2, 2, 2] case Dorian: return [2, 1, 2, 2, 2, 1] case Phrygian: return [1, 2, 2, 2, 1, 2] case Lydian: return [2, 2, 2, 1, 2, 2] case Mixolydian: return [2, 2, 1, 2, 2, 1] case Minor: return [2, 1, 2, 2, 1, 2] case Locrian: return [1, 2, 2, 1, 2, 2] } } } extension ScaleQuality : Printable { public var description : String { return rawValue } }
mit
casd82/powerup-iOS
Powerup/OOC-Event-Classes/SoundPlayer.swift
1
1532
import UIKit import AVFoundation import AudioToolbox /** Creates a strong reference to AVAudioPlayer and plays a sound file. Convenience class to declutter controller classes. Example Use ``` let soundPlayer : SoundPlayer? = SoundPlayer() guard let player = self.soundPlayer else {return} // player.playSound(fileName: String, volume: Float) player.playSound("sound.mp3", 0.5) ``` - Author: Cadence Holmes 2018 */ class SoundPlayer { var player: AVAudioPlayer? var numberOfLoops: Int = 1 init () { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) } catch let error { print(error.localizedDescription) } } /** Handles checking for AVAudioPlayer and playing a sound. - throws: print(error.localizedDescription) - parameters: - fileName : String - file name as it appears in Sounds.xcassets - volume : Float - volume scaled 0.0 - 1.0 */ func playSound(_ fileName: String, _ volume: Float) { guard let sound = NSDataAsset(name: fileName) else { return } do { player = try AVAudioPlayer(data: sound.data) guard let soundplayer = player else { return } soundplayer.numberOfLoops = numberOfLoops soundplayer.volume = volume soundplayer.play() } catch let error { print(error.localizedDescription) } } }
gpl-2.0
mownier/photostream
Photostream/Module Extensions/FollowListModuleExtension.swift
1
1214
// // FollowListModuleExtension.swift // Photostream // // Created by Mounir Ybanez on 17/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // import UIKit extension FollowListModule { convenience init() { self.init(view: FollowListViewController()) } } extension FollowListDisplayDataItem: UserTableCellItem { } extension FollowListModuleInterface { func presentUserTimeline(for index: Int) { guard let presenter = self as? FollowListPresenter, let item = listItem(at: index) else { return } presenter.wireframe.showUserTimeline( from: presenter.view.controller, userId: item.userId ) } } extension FollowListWireframeInterface { func showUserTimeline(from parent: UIViewController?, userId: String) { let userTimeline = UserTimelineViewController() userTimeline.root = root userTimeline.style = .push userTimeline.userId = userId var property = WireframeEntryProperty() property.parent = parent property.controller = userTimeline userTimeline.enter(with: property) } }
mit
flydream2046/symbolicator
symbolicator/Options.swift
1
730
/* Created by Tomaz Kragelj on 11.06.2014. Copyright (c) 2014 Gentle Bytes. All rights reserved. */ import Foundation class Options: GBOptionsHelper { override init() { super.init() self.applicationVersion = { "1.0" } self.applicationBuild = { "99" } self.printHelpHeader = { "Usage: %APPNAME [OPTIONS] <crash log paths separated by space>\nExample: %APPNAME crashlog1.crash \"~/Downloads/some other crash.txt\"" } self.registerSeparator("OPTIONS") self.registerOption(0, long: settingXcodeArchivesKey, description: "Xcode archives location", flags: GBOptionFlags.RequiredValue) self.registerOption(0, long: settingsPrintHelpKey, description: "Print this help and exit", flags: GBOptionFlags.NoValue) } }
mit
huangxinping/XPKit-swift
Source/Extensions/UIKit/UINavigationBar+XPKit.swift
1
2097
// // UINavigationBar+XPKit.swift // XPKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit /// This extesion adds some useful functions to UINavigationBar public extension UINavigationBar { // MARK: - Instance functions - /** Set the UINavigationBar to transparent or not - parameter transparent: true to set it transparent, false to not - parameter translucent: A Boolean value indicating whether the navigation bar is translucent or not */ public func setTransparent(transparent: Bool, translucent: Bool = true) { if transparent { self.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.shadowImage = UIImage() self.translucent = translucent } else { self.setBackgroundImage(nil, forBarMetrics: .Default) self.shadowImage = nil self.translucent = translucent } } }
mit
lhx931119/DouYuTest
DouYu/DouYu/Classes/Tools/NetWorkTools.swift
1
791
// // NetWorkTools.swift // DouYu // // Created by 李宏鑫 on 17/1/15. // Copyright © 2017年 hongxinli. All rights reserved. // import UIKit import Alamofire enum MethodType { case GET case POST } class NetWorkTools{ class func requestForData(methodType: MethodType, urlString: String, parpams: [String: NSString]? = nil, finishCallBack:(result: AnyObject)->()){ //获取类型 let method = methodType == .GET ? Method.GET : Method.POST Alamofire.request(method, urlString).responseJSON { (response) in guard let result = response.result.value else{ print(response.result.error) return } finishCallBack(result: result) } } }
mit
alessiobrozzi/firefox-ios
Storage/SQL/DeferredDBOperation.swift
2
3685
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import Deferred private let log = Logger.syncLogger private let DeferredQueue = DispatchQueue(label: "BrowserDBQueue", attributes: []) /** This class is written to mimick an NSOperation, but also provide Deferred capabilities as well. Usage: let deferred = DeferredDBOperation({ (db, err) -> Int // ... Do something long running return 1 }, withDb: myDb, onQueue: myQueue).start(onQueue: myQueue) deferred.upon { res in // if cancelled res.isFailure = true }) // ... Some time later deferred.cancel() */ class DeferredDBOperation<T>: Deferred<Maybe<T>>, Cancellable { /// Cancelled is wrapping a ReadWrite lock to make access to it thread-safe. fileprivate var cancelledLock = LockProtected<Bool>(item: false) var cancelled: Bool { get { return self.cancelledLock.withReadLock({ cancelled -> Bool in return cancelled }) } set { let _ = cancelledLock.withWriteLock { cancelled -> T? in cancelled = newValue return nil } } } /// Executing is wrapping a ReadWrite lock to make access to it thread-safe. fileprivate var connectionLock = LockProtected<SQLiteDBConnection?>(item: nil) fileprivate var connection: SQLiteDBConnection? { get { // We want to avoid leaking this connection. If you want access to it, // you should use a read/write lock directly. return nil } set { let _ = connectionLock.withWriteLock { connection -> T? in connection = newValue return nil } } } fileprivate var db: SwiftData fileprivate var block: (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T init(db: SwiftData, block: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) { self.block = block self.db = db super.init() } func start(onQueue queue: DispatchQueue = DeferredQueue) -> DeferredDBOperation<T> { queue.async(execute: self.main) return self } fileprivate func main() { if self.cancelled { let err = NSError(domain: "mozilla", code: 9, userInfo: [NSLocalizedDescriptionKey: "Operation was cancelled before starting"]) fill(Maybe(failure: DatabaseError(err: err))) return } var result: T? = nil let err = db.withConnection(SwiftData.Flags.readWriteCreate) { (db) -> NSError? in self.connection = db if self.cancelled { return NSError(domain: "mozilla", code: 9, userInfo: [NSLocalizedDescriptionKey: "Operation was cancelled before starting"]) } var error: NSError? = nil result = self.block(db, &error) if error == nil { log.verbose("Modified rows: \(db.numberOfRowsModified).") } self.connection = nil return error } if let result = result { fill(Maybe(success: result)) return } fill(Maybe(failure: DatabaseError(err: err))) } func cancel() { self.cancelled = true self.connectionLock.withReadLock({ connection -> Void in connection?.interrupt() return () }) } }
mpl-2.0
rlopezdiez/RLDNavigationSwift
Classes/UINavigationController+RLDNavigationSetup.swift
1
2691
import UIKit extension UINavigationController { func findDestination(navigationSetup navigationSetup:RLDNavigationSetup) -> UIViewController? { for viewController:UIViewController in Array((viewControllers ).reverse()) { if viewController.isDestinationOf(navigationSetup) { return viewController } } return nil } } private extension UIViewController { func isDestinationOf(navigationSetup:RLDNavigationSetup) -> Bool { if self.isKindOfClass(NSClassFromString(navigationSetup.destination)!) == false { return false } if let properties = navigationSetup.properties { for (key, value) in properties { if has(property:key) && valueForKey(key)!.isEqual(value) == false { return false } } } return true } } extension NSObject { func has(property property:String) -> Bool { let expectedProperty = objcProperty(name:property) return expectedProperty != nil } func canSet(property property:String) -> Bool { var canSet = false let expectedProperty = objcProperty(name:property) if expectedProperty != nil { let isReadonly = property_copyAttributeValue(expectedProperty, "R") canSet = isReadonly == nil } return canSet } func set(properties properties:[String:AnyObject]?) { if let properties = properties { for (key, value) in properties { if canSet(property:key) { self.setValue(value, forKey:key) } } } } private func objcProperty(name name:String) -> objc_property_t { if name.characters.count == 0 { return nil } var propertyCount:UInt32 = 0 var sourceClass:AnyClass? = self.dynamicType repeat { let objcProperties:UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(sourceClass, &propertyCount) for index in 0..<Int(propertyCount) { let property:objc_property_t = objcProperties[index] let propertyName = NSString(UTF8String:property_getName(property))! if propertyName == name { return property } } free(objcProperties) sourceClass = sourceClass!.superclass() } while sourceClass != nil return nil } }
apache-2.0
wireapp/wire-ios
Wire-iOS Tests/ProfileTitleViewSnapshotTests.swift
1
1494
// Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire import SnapshotTesting final class ProfileTitleViewSnapshotTests: XCTestCase { var sut: ProfileTitleView! var mockUser: MockUserType! override func setUp() { super.setUp() sut = ProfileTitleView(frame: .init(origin: .zero, size: CGSize(width: 320, height: 44))) mockUser = .createUser(name: "Bill Chan") } override func tearDown() { sut = nil mockUser = nil super.tearDown() } func testForDarkScheme() { sut.overrideUserInterfaceStyle = .dark sut.configure(with: mockUser) verify(matching: sut) } func testForLightScheme() { sut.overrideUserInterfaceStyle = .light sut.configure(with: mockUser) verify(matching: sut) } }
gpl-3.0
tamanyan/SwiftPageMenu
Package.swift
1
1114
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SwiftPageMenu", platforms: [ .iOS(.v12), ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "SwiftPageMenu", targets: ["SwiftPageMenu"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "SwiftPageMenu", dependencies: [], path: "Sources"), .testTarget( name: "SwiftPageMenuTests", dependencies: ["SwiftPageMenu"]), ] )
mit
danielsaidi/KeyboardKit
Sources/KeyboardKit/Extensions/View+Frame.swift
1
368
// // View+Frame.swift // KeyboardKit // // Created by Daniel Saidi on 2021-01-08. // Copyright © 2021 Daniel Saidi. All rights reserved. // import SwiftUI public extension View { /** Apply the size of a `CGSize` to the view. */ func frame(_ size: CGSize) -> some View { self.frame(width: size.width, height: size.height) } }
mit
exponent/exponent
packages/expo-dev-menu-interface/ios/DevMenuExtensionProtocol.swift
2
1451
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation @objc public protocol DevMenuExtensionSettingsProtocol { func wasRunOnDevelopmentBridge() -> Bool } /** A protocol for React Native bridge modules that want to provide their own dev menu actions. */ @objc public protocol DevMenuExtensionProtocol { /** Returns a name of the module and the extension. Required by `RCTBridgeModule`. This function is optional because otherwise we end up with linker warning: `method '+moduleName' in category from /.../expo-dev-menu/libexpo-dev-menu.a(DevMenuExtensions-....o) overrides method from class in /.../expo-dev-menu/libexpo-dev-menu.a(DevMenuExtensions-....o` So we assume that this method will be implemented by `RCTBridgeModule`. In theory we can remove it. However, we leave it to get easy access to the module name. */ @objc optional static func moduleName() -> String! /** Returns an array of the dev menu items to show. It's called only once for the extension instance — results are being cached on first dev menu launch. */ @objc optional func devMenuItems(_ settings: DevMenuExtensionSettingsProtocol) -> DevMenuItemsContainerProtocol? @objc optional func devMenuScreens(_ settings: DevMenuExtensionSettingsProtocol) -> [DevMenuScreen]? @objc optional func devMenuDataSources(_ settings: DevMenuExtensionSettingsProtocol) -> [DevMenuDataSourceProtocol]? }
bsd-3-clause
esttorhe/SlackTeamExplorer
SlackTeamExplorer/Pods/Nimble/Nimble/Wrappers/MatcherFunc.swift
74
3742
/// A convenience API to build matchers that allow full control over /// to() and toNot() match cases. /// /// The final bool argument in the closure is if the match is for negation. /// /// You may use this when implementing your own custom matchers. /// /// Use the Matcher protocol instead of this type to accept custom matchers as /// input parameters. /// @see allPass for an example that uses accepts other matchers as input. public struct FullMatcherFunc<T>: Matcher { public let matcher: (Expression<T>, FailureMessage, Bool) -> Bool public init(_ matcher: (Expression<T>, FailureMessage, Bool) -> Bool) { self.matcher = matcher } public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { return matcher(actualExpression, failureMessage, false) } public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { return matcher(actualExpression, failureMessage, true) } } /// A convenience API to build matchers that don't need special negation /// behavior. The toNot() behavior is the negation of to(). /// /// @see NonNilMatcherFunc if you prefer to have this matcher fail when nil /// values are recieved in an expectation. /// /// You may use this when implementing your own custom matchers. /// /// Use the Matcher protocol instead of this type to accept custom matchers as /// input parameters. /// @see allPass for an example that uses accepts other matchers as input. public struct MatcherFunc<T>: Matcher { public let matcher: (Expression<T>, FailureMessage) -> Bool public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) { self.matcher = matcher } public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { return matcher(actualExpression, failureMessage) } public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { return !matcher(actualExpression, failureMessage) } } /// A convenience API to build matchers that don't need special negation /// behavior. The toNot() behavior is the negation of to(). /// /// Unlike MatcherFunc, this will always fail if an expectation contains nil. /// This applies regardless of using to() or toNot(). /// /// You may use this when implementing your own custom matchers. /// /// Use the Matcher protocol instead of this type to accept custom matchers as /// input parameters. /// @see allPass for an example that uses accepts other matchers as input. public struct NonNilMatcherFunc<T>: Matcher { public let matcher: (Expression<T>, FailureMessage) -> Bool public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) { self.matcher = matcher } public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let pass = matcher(actualExpression, failureMessage) if attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) { return false } return pass } public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { let pass = !matcher(actualExpression, failureMessage) if attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) { return false } return pass } internal func attachNilErrorIfNeeded(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool { if actualExpression.evaluate() == nil { failureMessage.postfixActual = " (use beNil() to match nils)" return true } return false } }
mit
BareFeetWare/BFWControls
BFWControls/Modules/Transition/View/UIViewController+Segue.swift
1
683
// // UIViewController+Segue.swift // BFWControls // // Created by Tom Brodhurst-Hill on 21/04/2016. // Copyright © 2016 BareFeetWare. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit public extension UIViewController { func canPerformSegue(identifier: String) -> Bool { var can = false if let templates = self.value(forKey: "storyboardSegueTemplates") as? NSArray { let predicate = NSPredicate(format: "identifier=%@", identifier) let filteredtemplates = templates.filtered(using: predicate) can = !filteredtemplates.isEmpty } return can } }
mit
ksco/swift-algorithm-club-cn
Breadth-First Search/BreadthFirstSearch.playground/Pages/Simple example.xcplaygroundpage/Contents.swift
1
1187
func breadthFirstSearch(graph: Graph, source: Node) -> [String] { var queue = Queue<Node>() queue.enqueue(source) var nodesExplored = [source.label] source.visited = true while let node = queue.dequeue() { for edge in node.neighbors { let neighborNode = edge.neighbor if !neighborNode.visited { queue.enqueue(neighborNode) neighborNode.visited = true nodesExplored.append(neighborNode.label) } } } return nodesExplored } let graph = Graph() let nodeA = graph.addNode("a") let nodeB = graph.addNode("b") let nodeC = graph.addNode("c") let nodeD = graph.addNode("d") let nodeE = graph.addNode("e") let nodeF = graph.addNode("f") let nodeG = graph.addNode("g") let nodeH = graph.addNode("h") graph.addEdge(nodeA, neighbor: nodeB) graph.addEdge(nodeA, neighbor: nodeC) graph.addEdge(nodeB, neighbor: nodeD) graph.addEdge(nodeB, neighbor: nodeE) graph.addEdge(nodeC, neighbor: nodeF) graph.addEdge(nodeC, neighbor: nodeG) graph.addEdge(nodeE, neighbor: nodeH) graph.addEdge(nodeE, neighbor: nodeF) graph.addEdge(nodeF, neighbor: nodeG) let nodesExplored = breadthFirstSearch(graph, source: nodeA) print(nodesExplored)
mit
ibhupi/cksapp
ios-app/cksapp/Classes/ViewControllers/Views/ContainerCollectionViewCell.swift
1
1173
// // ContainerCollectionViewCell.swift // cksapp // // Created by Bhupendra Singh on 7/2/16. // Copyright © 2016 Bhupendra Singh. All rights reserved. // import UIKit class ContainerCollectionViewCell: BaseCollectionViewCell { @IBOutlet weak var collectionView: BaseCollectionView! @IBOutlet weak var titleLabel: UILabel! /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = nil } override class func cellID() -> String { return "ContainerCollectionViewCell" } func configureFor(sectionManager: BaseSectionManager) -> Void { self.titleLabel.text = sectionManager.title self.collectionView.sectionManager = sectionManager self.collectionView.reloadData() } // override func layoutSubviews() { // super.layoutSubviews() // self.collectionView.reloadData() // } }
apache-2.0
thefuntasty/Sonar
Sources/Sonar/SonarItemView.swift
1
163
import UIKit public struct SonarPosition { let waveIndex: Int let itemIndex: Int } open class SonarItemView: UIView { var position: SonarPosition! }
mit
ifels/swiftDemo
SnapKitDrawer/SnapKitDrawer/src/home/HomeController.swift
1
1699
// // ViewController.swift // SnapKitDrawer // // Created by 聂鑫鑫 on 16/11/10. // Copyright © 2016年 ifels. All rights reserved. // import UIKit class HomeController: DPDrawerViewController { var drawerView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationController?.setNavigationBarHidden(true, animated: true) initDrawer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func initDrawer(){ // 1. get the drawer // embed in storyboard let drawer: DPDrawerViewController = self // not embed in storyboard? add it manually // let drawer: DPDrawerViewController? = self.storyboard?.instantiateViewController(withIdentifier: "DPDrawerViewController") as? DPDrawerViewController // self.addChildViewController(drawer!) // self.view.addSubview(drawer!.view) // 2. create the first view controller let homeViewController: ContentController? = ContentController(); // 4. create leftMenuViewController with DPSlideMenuModel array, then reset the drawer //let leftMenuViewController: DPLeftMenuViewController = DPLeftMenuViewController(slideMenuModels: slideMenuModels, storyboard: self.storyboard) let menuController: MenuController = MenuController() drawer.reset(leftViewController: menuController, centerViewController: homeViewController) } }
apache-2.0
robvs/MVVMSample
MVVMSample/MVVMSampleTests/HomeViewModelTests.swift
1
4590
// // HomeViewModelTests.swift // MVVMSample // // Created by Rob Vander Sloot on 3/17/17. // Copyright © 2017 Random Visual. All rights reserved. // import XCTest //@testable import MVVMSample class HomeViewModelTests: XCTestCase { // MARK: Setup/Teardown 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() } // MARK: Tests func testEmptyGenreList() { // setup let genres: [MovieGenre] = [] // execute let homeVM = HomeViewModel(genres: genres) // validate XCTAssertEqual(homeVM.genreCount, 0) XCTAssertNil(homeVM.genreDescription(forIndex: 0)) XCTAssertNil(homeVM.genreName(forIndex: 0)) // since TitleListViewModel depends upon a service that can't be injected // via homeVM.titleListViewModel(forIndex:delegate:), we'll check only the // properties that do not rely on data being fetched. let titleListVM = homeVM.titleListViewModel(forIndex: 0, delegate: MockTitleListDelegate()) XCTAssertEqual(titleListVM.headingTitle, "Movie Titles") } func testOneGenre() { // setup let genre0 = MovieGenre(id: .action, name: "Action", description: "Action genre") let genres: [MovieGenre] = [genre0] // execute let homeVM = HomeViewModel(genres: genres) // validate XCTAssertEqual(homeVM.genreCount, genres.count) guard let actualDescription0 = homeVM.genreDescription(forIndex: 0) else { XCTFail("genre should not be nil") return } XCTAssertEqual(actualDescription0, genre0.description) guard let actualName0 = homeVM.genreName(forIndex: 0) else { XCTFail("genre should not be nil") return } XCTAssertEqual(actualName0, genre0.name) // since TitleListViewModel depends upon a service that can't be injected // via homeVM.titleListViewModel(forIndex:delegate:), we'll check only the // properties that do not rely on data being fetched. let titleListVM0 = homeVM.titleListViewModel(forIndex: 0, delegate: MockTitleListDelegate()) XCTAssertEqual(titleListVM0.headingTitle, genre0.name + " Movie Titles") } func testMultipleGenres() { // setup let genre0 = MovieGenre(id: .action, name: "Action", description: "Action genre") let genre1 = MovieGenre(id: .comedy, name: "Comedy", description: "Comedy genre") let genres: [MovieGenre] = [genre0, genre1] // execute let homeVM = HomeViewModel(genres: genres) // validate XCTAssertEqual(homeVM.genreCount, genres.count) guard let actualDescription0 = homeVM.genreDescription(forIndex: 0), let actualDescription1 = homeVM.genreDescription(forIndex: 1) else { XCTFail("description should not be nil") return } XCTAssertEqual(actualDescription0, genre0.description) XCTAssertEqual(actualDescription1, genre1.description) guard let actualName0 = homeVM.genreName(forIndex: 0), let actualName1 = homeVM.genreName(forIndex: 1) else { XCTFail("genre should not be nil") return } XCTAssertEqual(actualName0, genre0.name) XCTAssertEqual(actualName1, genre1.name) // since TitleListViewModel depends upon a service that can't be injected // via homeVM.titleListViewModel(forIndex:delegate:), we'll check only the // properties that do not rely on data being fetched. let titleListVM0 = homeVM.titleListViewModel(forIndex: 0, delegate: MockTitleListDelegate()) let titleListVM1 = homeVM.titleListViewModel(forIndex: 1, delegate: MockTitleListDelegate()) XCTAssertEqual(titleListVM0.headingTitle, genre0.name + " Movie Titles") XCTAssertEqual(titleListVM1.headingTitle, genre1.name + " Movie Titles") } } // MARK: - Mock TitleListViewModelDelegate fileprivate final class MockTitleListDelegate: TitleListViewModelDelegate { func refreshDidStart() { } func relreshDidComplete() { } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/00511-swift-constraints-constraintlocator-profile.swift
1
265
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var f = 1 var e: Int let : Int = { c, b in } (f, e) struct d<f where g = f { { } struct B<T : A
mit
kean/Nuke
Tests/NukeExtensionsTests/ImageViewIntegrationTests.swift
1
4000
// The MIT License (MIT) // // Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean). import XCTest @testable import Nuke @testable import NukeExtensions #if os(iOS) || os(tvOS) || os(macOS) @MainActor class ImageViewIntegrationTests: XCTestCase { var imageView: _ImageView! var pipeline: ImagePipeline! @MainActor override func setUp() { super.setUp() pipeline = ImagePipeline { $0.dataLoader = DataLoader() $0.imageCache = MockImageCache() } // Nuke.loadImage(...) methods use shared pipeline by default. ImagePipeline.pushShared(pipeline) imageView = _ImageView() } override func tearDown() { super.tearDown() ImagePipeline.popShared() } var url: URL { Test.url(forResource: "fixture", extension: "jpeg") } var request: ImageRequest { ImageRequest(url: url) } // MARK: - Loading func testImageLoaded() { // When expectToLoadImage(with: request, into: imageView) wait() // Then XCTAssertNotNil(imageView.image) } func testImageLoadedWithURL() { // When let expectation = self.expectation(description: "Image loaded") NukeExtensions.loadImage(with: url, into: imageView) { _ in expectation.fulfill() } wait() // Then XCTAssertNotNil(imageView.image) } // MARK: - Loading with Invalid URL func testLoadImageWithInvalidURLString() { // WHEN let expectation = self.expectation(description: "Image loaded") NukeExtensions.loadImage(with: URL(string: "http://example.com/invalid url"), into: imageView) { result in XCTAssertEqual(result.error, .imageRequestMissing) expectation.fulfill() } wait() // THEN XCTAssertNil(imageView.image) } func testLoadingWithNilURL() { // GIVEN var urlRequest = URLRequest(url: Test.url) urlRequest.url = nil // Not sure why this is even possible // WHEN let expectation = self.expectation(description: "Image loaded") NukeExtensions.loadImage(with: urlRequest, into: imageView) { result in // THEN XCTAssertNotNil(result.error?.dataLoadingError) expectation.fulfill() } wait() // THEN XCTAssertNil(imageView.image) } func testLoadingWithRequestWithNilURL() { // GIVEN let input = ImageRequest(url: nil) // WHEN/THEN let expectation = self.expectation(description: "ImageLoaded") pipeline.loadImage(with: input) { XCTAssertTrue($0.isFailure) XCTAssertNoThrow($0.error?.dataLoadingError) expectation.fulfill() } wait() } // MARK: - Data Passed #if os(iOS) private final class MockView: UIView, Nuke_ImageDisplaying { func nuke_display(image: PlatformImage?, data: Data?) { recordedData.append(data) } var recordedData = [Data?]() } func _testThatAttachedDataIsPassed() throws { // GIVEN pipeline = pipeline.reconfigured { $0.makeImageDecoder = { _ in ImageDecoders.Empty() } } let imageView = MockView() var options = ImageLoadingOptions() options.pipeline = pipeline options.isPrepareForReuseEnabled = false // WHEN let expectation = self.expectation(description: "Image loaded") NukeExtensions.loadImage(with: Test.url, options: options, into: imageView) { result in XCTAssertNotNil(result.value) XCTAssertNotNil(result.value?.container.data) expectation.fulfill() } wait() // THEN let data = try XCTUnwrap(imageView.recordedData.first) XCTAssertNotNil(data) } #endif } #endif
mit
AbhishekThorat/TAGKeyboard
Example/TAGKeyboard/AppDelegate.swift
1
2156
// // AppDelegate.swift // TAGKeyboard // // Created by AbhishekThorat on 05/27/2016. // Copyright (c) 2016 AbhishekThorat. 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:. } }
mit
BrisyIOS/zhangxuWeiBo
zhangxuWeiBo/zhangxuWeiBo/classes/Discover/Controller/DiscoverController.swift
1
873
// // DiscoverController.swift // zhangxuWeiBo // // Created by zhangxu on 16/6/11. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit class DiscoverController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
ahoppen/swift
validation-test/compiler_crashers_fixed/26242-swift-typechecker-validatedecl.swift
65
464
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck if{class b<T where T:U{class n{class B<U{protocol f:typealias F=f
apache-2.0
dreamsxin/swift
validation-test/compiler_crashers_fixed/00957-void.swift
11
599
// 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 import Foundation return x = [0.Iterator.count](#object1: A? = { protocol c = "foo"ab" func d(b: T) { ())() { } func x: String { func f<U -> Any, let f : a! protocol a { typealias d, end: B<T typealias e: d
apache-2.0
Codility-BMSTU/Codility
Codility/Codility/ServiceCell.swift
1
591
// // ServiceCell.swift // OpenBank // // Created by Aleksander Evtuhov on 16/09/2017. // Copyright © 2017 Aleksander Evtuhov. All rights reserved. // import UIKit class ServiceCell: UITableViewCell { @IBOutlet weak var service: UILabel! @IBOutlet weak var queue: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
okkhoury/SafeNights_iOS
SafeNights/HistoryController.swift
1
16829
// // HistoryController.swift // SafeNights // // Created by Owen Khoury on 5/13/17. // Copyright © 2017 SafeNights. All rights reserved. // import UIKit import Siesta import Charts /** * Controller for getting history of previous nights. * Currently just tests that controller can get previous night * history from database. */ class HistoryController: UIViewController { @IBOutlet weak var moneyChartView: LineChartView! @IBOutlet weak var alcoholChartView: LineChartView! @IBOutlet weak var totalSpendingLabel: UILabel! @IBOutlet weak var monthLabel: UILabel! @IBOutlet weak var monthStepper: UIStepper! @IBOutlet weak var loadingMoneyIndicator: UIActivityIndicatorView! @IBOutlet weak var loadingAlcoholIndicator: UIActivityIndicatorView! let API = MyAPI() let preferences = UserDefaults.standard var allData : [Fields] = [] var monthsDictionary = [String: [Fields]]() var todayKey : String = "" var displayMonth : Int = 1 var displayYear : Int = 2017 var totalSpent : Int = 0 //Used to track the months the stepper will go. Starts on max so user can't go into future var stepperOldVal : Int = 100 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // No need for semicolon // Do any additional setup after loading the view, typically from a nib. // Clear old data because they can persist from last on appear not load (when user toggles between tabs after initial load self.allData.removeAll() self.monthsDictionary.removeAll() self.totalSpent = 0 //Starts loading indicator while API is called loadingMoneyIndicator.isHidden = false loadingAlcoholIndicator.isHidden = false loadingMoneyIndicator.startAnimating() loadingAlcoholIndicator.startAnimating() // Sets up all the styling for the graph styling() // Calls API to get the information. Only needs once, it is parsed so can just update dictionary array in future callGetHistoryAPI() } @IBAction func monthStepperAction(_ sender: Any) { if (Int(monthStepper.value) > stepperOldVal) { stepperOldVal=stepperOldVal+1; //Your Code You Wanted To Perform On Increment let calendar = Calendar.current var dateComponents = DateComponents() dateComponents.year = self.displayYear dateComponents.month = self.displayMonth let thisCalMonth = calendar.date(from: dateComponents) let nextCalMonth = calendar.date(byAdding: .month, value: 1, to: thisCalMonth!) let components = calendar.dateComponents([.year, .month, .day], from: nextCalMonth!) self.displayMonth = components.month! self.displayYear = components.year! monthLabel.text = getMonthFromInt(month: components.month!) // Update Graph Again updateGraph() } else { stepperOldVal=stepperOldVal-1; //Your Code You Wanted To Perform On Decrement let calendar = Calendar.current var dateComponents = DateComponents() dateComponents.year = self.displayYear dateComponents.month = self.displayMonth let thisCalMonth = calendar.date(from: dateComponents) let nextCalMonth = calendar.date(byAdding: .month, value: -1, to: thisCalMonth!) let components = calendar.dateComponents([.year, .month, .day], from: nextCalMonth!) self.displayMonth = components.month! self.displayYear = components.year! monthLabel.text = getMonthFromInt(month: components.month!) // Update Graph Again updateGraph() } } func callGetHistoryAPI() { let resource = API.getHistory // Get the global values for username and password let username = self.preferences.string(forKey: "username")! let password = self.preferences.string(forKey: "password")! let postData = ["username": username, "pwd": password] resource.request(.post, urlEncoded: postData).onSuccess() { data in var response = data.jsonDict let answer = response["alcoholtable"] as! NSArray! let arr = Alcoholtable.modelsFromDictionaryArray(array: answer!) for item in arr { self.allData.append(item.fields!) } // Then we parse months. Should only do this once, so after this we can update graph self.parseDataByMonths() }.onFailure { _ in // Display alert to screen to let user know error let OKAction = UIAlertAction(title: "Ok", style: .default){ (action:UIAlertAction) in //print("Request failed") } let alert = UIAlertController(title: "Warning", message: "Something went wrong :( Make sure you have internet access", preferredStyle: .alert) alert.addAction(OKAction) self.present(alert, animated: true, completion: nil) } } func parseDataByMonths() { let calendar = Calendar.current for night in allData { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" //Your date format let day = dateFormatter.date(from: night.day!) let components = calendar.dateComponents([.year, .month, .day], from: day!) let key = String(components.month!) + String(components.year!) if self.monthsDictionary[key] != nil { // now val is not nil and the Optional has been unwrapped, so use it self.monthsDictionary[key]?.append(night) } else { var newMonth : [Fields] = [] newMonth.append(night) monthsDictionary[key] = newMonth } } // This is done for a check to make this months graph nicer and not look at future months let today = Date() let components = calendar.dateComponents([.year, .month, .day], from: today) self.displayMonth = components.month! self.displayYear = components.year! todayKey = String(components.month!) + String(components.year!) monthLabel.text = getMonthFromInt(month: components.month!) //Stop the loading animation. Update graph takes less that 1 second and so can do this now loadingMoneyIndicator.stopAnimating() loadingAlcoholIndicator.stopAnimating() loadingMoneyIndicator.isHidden = true loadingAlcoholIndicator.isHidden = true // This should only be called once, so we now update the Graph. // Note- update graph will be called again every other time when Month is updated updateGraph() } func calculateDrunkness(field : Fields) -> Double { let total = 100.0*((Double(field.beer!) + Double(field.wine!) + Double(field.hardliquor!) + Double(field.shots!))/40.0) return Double(total) } //Logic for setting up months. Called every time month changed func updateGraph(){ let thisMonthKey = String(displayMonth) + String(displayYear) // Null check so no error thrown. if(monthsDictionary[thisMonthKey] == nil){ // Clears data. No data text is set up in styling() moneyChartView.clear(); alcoholChartView.clear(); //Change Label so it doesn't show last months spending totalSpendingLabel.text = "Total= $0" return } //Booleans are to give start and end to month if there is no data for the 1st and 31st var missing1st = true var missing31st = true totalSpent = 0 //Start Charts logic var money_lineChartEntry = [ChartDataEntry]() //this is the Array that will eventually be displayed on the graph. var alcohol_lineChartEntry = [ChartDataEntry]() //here is the for loop for datapoint in monthsDictionary[thisMonthKey]! { let alcoholY = calculateDrunkness(field: datapoint) // Checking for the 1st and 31st if(getDay(date: datapoint.day!) == 0) { missing1st = false } else if(getDay(date: datapoint.day!) == 31) { missing31st = false } let newMoneyEntry = ChartDataEntry(x: getDay(date: datapoint.day!), y: Double(datapoint.money!)) // here we set the X and Y status in a data chart entry money_lineChartEntry.append(newMoneyEntry) // here we add it to the data set let newAlcoholEntry = ChartDataEntry(x: getDay(date: datapoint.day!), y: alcoholY) // here we set the X and Y status in a data chart entry alcohol_lineChartEntry.append(newAlcoholEntry) // here we add it to the data set totalSpent += datapoint.money! } // Set label for total spending totalSpendingLabel.text = "Total= $" + String(totalSpent) //Add Missing if Needed if(missing1st) { money_lineChartEntry.append(ChartDataEntry(x: 0.0, y: 0.0)) alcohol_lineChartEntry.append(ChartDataEntry(x: 0.0, y: 0.0)) } if(todayKey != thisMonthKey) { if(missing31st) { money_lineChartEntry.append(ChartDataEntry(x: 31.0, y: 0.0)) alcohol_lineChartEntry.append(ChartDataEntry(x: 31.0, y: 0.0)) } } //Needs to be sorted to work :) money_lineChartEntry = money_lineChartEntry.sorted { $0.x < $1.x } alcohol_lineChartEntry = alcohol_lineChartEntry.sorted { $0.x < $1.x } let moneySet = LineChartDataSet(values: money_lineChartEntry, label: "money") //Here we convert lineChartEntry to a LineChartDataSet let alcoholSet = LineChartDataSet(values: alcohol_lineChartEntry, label: "alcohol") //Here we convert lineChartEntry to a LineChartDataSet // Styling #1 - some of styling needs to be done to the set moneySet.lineWidth = 3.0 moneySet.circleRadius = 4.0 moneySet.setColor(UIColor.purple) moneySet.circleColors = [UIColor.purple] moneySet.circleHoleColor = UIColor.purple moneySet.drawValuesEnabled = false alcoholSet.lineWidth = 3.0 alcoholSet.circleRadius = 4.0 alcoholSet.setColor(UIColor.red) alcoholSet.circleColors = [UIColor.red] alcoholSet.circleHoleColor = UIColor.red alcoholSet.drawValuesEnabled = false // Add the set to the chart, then we style the chart let moneyData = LineChartData() //This is the object that will be added to the chart moneyData.addDataSet(moneySet) //Adds the line to the dataSet let alcoholData = LineChartData() //This is the object that will be added to the chart alcoholData.addDataSet(alcoholSet) //Adds the line to the dataSet moneyChartView.data = moneyData //finally - it adds the chart data to the chart and causes an update alcoholChartView.data = alcoholData } func styling() { // WHAT IF THERE IS NO DATA?!?!?! moneyChartView.noDataText = "No Data!" + "\n" + "Please record any activity in Confess" alcoholChartView.noDataText = "No Data!" + "\n" + "Please record any activity in Confess" moneyChartView.noDataTextColor = UIColor.white alcoholChartView.noDataTextColor = UIColor.white // Styling #2 // moneySet.setAxisDependency(YAxis.AxisDependency.LEFT); // moneyChartView.leftAxis.axisDependency = true //FIX TOUCH moneyChartView.isMultipleTouchEnabled = false moneyChartView.xAxis.drawGridLinesEnabled = false moneyChartView.leftAxis.drawGridLinesEnabled = false moneyChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom moneyChartView.rightAxis.enabled = false moneyChartView.legend.enabled = false moneyChartView.chartDescription?.enabled = false moneyChartView.xAxis.axisMinimum = 0.0 moneyChartView.xAxis.axisMaximum = 31.0 moneyChartView.xAxis.labelCount = 3 moneyChartView.leftAxis.labelCount = 5 moneyChartView.xAxis.labelFont.withSize(10.0) moneyChartView.leftAxis.labelFont.withSize(14.0) moneyChartView.leftAxis.labelTextColor = UIColor.white moneyChartView.xAxis.labelTextColor = UIColor.white moneyChartView.leftAxis.axisLineColor = UIColor.white moneyChartView.xAxis.axisLineColor = UIColor.white moneyChartView.backgroundColor = UIColor.black //Axis Dependency and Touch alcoholChartView.isMultipleTouchEnabled = false alcoholChartView.xAxis.drawGridLinesEnabled = false alcoholChartView.leftAxis.drawGridLinesEnabled = false alcoholChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom alcoholChartView.rightAxis.enabled = false alcoholChartView.legend.enabled = false alcoholChartView.chartDescription?.enabled = false alcoholChartView.xAxis.axisMinimum = 0.0 alcoholChartView.xAxis.axisMaximum = 31.0 alcoholChartView.xAxis.labelCount = 3 alcoholChartView.leftAxis.labelCount = 5 alcoholChartView.xAxis.labelFont.withSize(10.0) alcoholChartView.leftAxis.labelFont.withSize(14.0) alcoholChartView.leftAxis.labelTextColor = UIColor.white alcoholChartView.xAxis.labelTextColor = UIColor.white alcoholChartView.leftAxis.axisLineColor = UIColor.white alcoholChartView.xAxis.axisLineColor = UIColor.white alcoholChartView.backgroundColor = UIColor.black //Styling #3 - Axis Scaling and Such //moneyChartView.autoScaleMinMaxEnabled = true moneyChartView.leftAxis.axisMinimum = 0.0 moneyChartView.leftAxis.axisMaximum = 200.0 moneyChartView.leftAxis.valueFormatter = DollarFormatter() alcoholChartView.leftAxis.axisMinimum = 0.0 alcoholChartView.leftAxis.axisMaximum = 100.0 alcoholChartView.leftAxis.valueFormatter = PercentFormatter() } class DollarFormatter: NSObject, IAxisValueFormatter { let numFormatter: NumberFormatter override init() { numFormatter = NumberFormatter() numFormatter.minimumFractionDigits = 0 numFormatter.maximumFractionDigits = 1 // if number is less than 1 add 0 before decimal numFormatter.minimumIntegerDigits = 1 // how many digits do want before decimal numFormatter.paddingPosition = .beforePrefix numFormatter.paddingCharacter = "0" } public func stringForValue(_ value: Double, axis: AxisBase?) -> String { return "$" + numFormatter.string(from: NSNumber(floatLiteral: value))! } } class PercentFormatter: NSObject, IAxisValueFormatter { let numFormatter: NumberFormatter override init() { numFormatter = NumberFormatter() numFormatter.minimumFractionDigits = 0 numFormatter.maximumFractionDigits = 1 // if number is less than 1 add 0 before decimal numFormatter.minimumIntegerDigits = 1 // how many digits do want before decimal numFormatter.paddingPosition = .beforePrefix numFormatter.paddingCharacter = "0" } public func stringForValue(_ value: Double, axis: AxisBase?) -> String { return numFormatter.string(from: NSNumber(floatLiteral: value))! + "%" } } func getDay(date : String) -> Double { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" //Your date format let day = dateFormatter.date(from: date) let calendar = Calendar.current let components = calendar.dateComponents([.year, .month, .day], from: day!) return Double(components.day!) } func getMonthFromInt(month : Int) -> String { let dateFormatter: DateFormatter = DateFormatter() let months = dateFormatter.shortMonthSymbols let monthSymbol = months?[month-1] return monthSymbol! } }
mit
ask-fm/AFMActionSheet
Example/AFMActionSheet/ViewController.swift
1
990
// // ViewController.swift // AFMActionSheet // // Created by Ilya Alesker on 08/26/2015. // Copyright (c) 2015 Ask.fm Europe, Ltd. All rights reserved. // import UIKit import AFMActionSheet class ViewController: UIViewController { @IBOutlet var titleView: UIView! @IBAction func buttonTapped(_ sender: AnyObject) { let actionSheet = AFMActionSheetController(style: .actionSheet, transitioningDelegate: AFMActionSheetTransitioningDelegate()) let action1 = AFMAction(title: "Action 1", enabled: true) { (action: AFMAction) -> Void in print(action.title) } let action2 = AFMAction(title: "Action 2", enabled: false, handler: nil) let action3 = AFMAction(title: "Action 3", handler: nil) actionSheet.add(action1) actionSheet.add(action2) actionSheet.add(cancelling: action3) actionSheet.add(title: self.titleView) self.present(actionSheet, animated: true, completion: nil) } }
mit
albinekcom/BitBay-Ticker-iOS
Codebase/Details/Row/DetailsRowViewModel.swift
1
203
struct DetailsRowViewModel: Identifiable, Equatable { var id: String { title } let title: String let valueString: String let valueStringColorStyle: StringColorStyle }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/00585-getselftypeforcontainer.swift
1
566
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol A { let t: T.h> Void>(b: NSManagedObject { } let h == .init() -> : AnyObject) { } typealias e : B<T> ()" struct e : e : B typealias B<T>(c, U)? func a(t: A"""
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/25777-swift-modulefile-gettype.swift
1
450
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func b([Void}let a{var _=A:{}protocol A{}protocol A
apache-2.0
sdhzwm/BaiSI-Swift-
BaiSi/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift
1
10593
// // UIImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 Wei Wang <onevcat@gmail.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 // MARK: - Set Images /** * Set image to use from web. */ public extension UIImageView { /** Set an image with a URL. It will ask for Kingfisher's manager to get the image for the URL. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this URL and store it for next use. - parameter URL: The URL of image. - returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a placeholder image. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placaholder image and options. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placeholder image, options and completion handler. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. - parameter URL: The URL of image. - parameter placeholderImage: A placeholder image when retrieving the image at URL. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { let showIndicatorWhenLoading = kf_showIndicatorWhenLoading var indicator: UIActivityIndicatorView? = nil if showIndicatorWhenLoading { indicator = kf_indicator indicator?.hidden = false indicator?.startAnimating() } image = placeholderImage kf_setWebURL(URL) let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: {[weak self] (image, error, cacheType, imageURL) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if let sSelf = self where imageURL == sSelf.kf_webURL && image != nil { sSelf.image = image; indicator?.stopAnimating() } completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL) }) }) return task } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var showIndicatorWhenLoadingKey: Void? public extension UIImageView { /// Get the image URL binded to this image view. public var kf_webURL: NSURL? { get { return objc_getAssociatedObject(self, &lastURLKey) as? NSURL } } private func kf_setWebURL(URL: NSURL) { objc_setAssociatedObject(self, &lastURLKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Whether show an animating indicator when the image view is loading an image or not. /// Default is false. public var kf_showIndicatorWhenLoading: Bool { get { if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber { return result.boolValue } else { return false } } set { if kf_showIndicatorWhenLoading == newValue { return } else { if newValue { let indicator = UIActivityIndicatorView(activityIndicatorStyle:.Gray) indicator.center = center indicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin] indicator.hidden = true indicator.hidesWhenStopped = true self.addSubview(indicator) kf_setIndicator(indicator) } else { kf_indicator?.removeFromSuperview() kf_setIndicator(nil) } objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } /// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false. /// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true. public var kf_indicator: UIActivityIndicatorView? { get { return objc_getAssociatedObject(self, &indicatorKey) as? UIActivityIndicatorView } } private func kf_setIndicator(indicator: UIActivityIndicatorView?) { objc_setAssociatedObject(self, &indicatorKey, indicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated public extension UIImageView { @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil) } @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler) } @available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler) } }
apache-2.0
josve05a/wikipedia-ios
Wikipedia/Code/ArticlePlaceView.swift
1
22597
import UIKit import WMF import MapKit protocol ArticlePlaceViewDelegate: NSObjectProtocol { func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView) } class ArticlePlaceView: MapAnnotationView { static let smallDotImage = #imageLiteral(resourceName: "places-dot-small") static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium") static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque") static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium") static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque") static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium") static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque") static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large") static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque") static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ") static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium") static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large") static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium") static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large") public weak var delegate: ArticlePlaceViewDelegate? var imageView: UIView! private var imageImageView: UIImageView! private var imageImagePlaceholderView: UIImageView! private var imageOutlineView: UIView! private var imageBackgroundView: UIView! private var selectedImageView: UIView! private var selectedImageImageView: UIImageView! private var selectedImageImagePlaceholderView: UIImageView! private var selectedImageOutlineView: UIView! private var selectedImageBackgroundView: UIView! private var dotView: UIView! private var groupView: UIView! private var countLabel: UILabel! private var dimension: CGFloat! private var collapsedDimension: CGFloat! var groupDimension: CGFloat! var imageDimension: CGFloat! var selectedImageButton: UIButton! private var alwaysShowImage = false private let selectionAnimationDuration = 0.3 private let springDamping: CGFloat = 0.5 private let crossFadeRelativeHalfDuration: TimeInterval = 0.1 private let alwaysRasterize = true // set this or rasterize on animations, not both private let rasterizeOnAnimations = false override func setup() { selectedImageView = UIView() imageView = UIView() selectedImageImageView = UIImageView() imageImageView = UIImageView() selectedImageImageView.accessibilityIgnoresInvertColors = true imageImageView.accessibilityIgnoresInvertColors = true countLabel = UILabel() dotView = UIView() groupView = UIView() imageOutlineView = UIView() selectedImageOutlineView = UIView() imageBackgroundView = UIView() selectedImageBackgroundView = UIView() selectedImageButton = UIButton() imageImagePlaceholderView = UIImageView() selectedImageImagePlaceholderView = UIImageView() let scale = ArticlePlaceView.mediumDotImage.scale let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage collapsedDimension = ArticlePlaceView.smallDotImage.size.width groupDimension = ArticlePlaceView.mediumDotImage.size.width dimension = largeOpaqueDotOutlineImage.size.width imageDimension = mediumOpaqueDotOutlineImage.size.width let gravity = CALayerContentsGravity.bottomRight isPlaceholderHidden = false frame = CGRect(x: 0, y: 0, width: dimension, height: dimension) dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension) dotView.layer.contentsGravity = gravity dotView.layer.contentsScale = scale dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) addSubview(dotView) groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension) groupView.layer.contentsGravity = gravity groupView.layer.contentsScale = scale groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage addSubview(groupView) imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension) imageView.layer.rasterizationScale = scale addSubview(imageView) imageBackgroundView.frame = imageView.bounds imageBackgroundView.layer.contentsGravity = gravity imageBackgroundView.layer.contentsScale = scale imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage imageView.addSubview(imageBackgroundView) imageImagePlaceholderView.frame = imageView.bounds imageImagePlaceholderView.contentMode = .center imageImagePlaceholderView.image = mediumPlaceholderImage imageView.addSubview(imageImagePlaceholderView) var inset: CGFloat = 3.5 var imageViewFrame = imageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) imageImageView.frame = imageViewFrame imageImageView.contentMode = .scaleAspectFill imageImageView.layer.masksToBounds = true imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5 imageImageView.backgroundColor = UIColor.white imageView.addSubview(imageImageView) imageOutlineView.frame = imageView.bounds imageOutlineView.layer.contentsGravity = gravity imageOutlineView.layer.contentsScale = scale imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage imageView.addSubview(imageOutlineView) selectedImageView.bounds = bounds selectedImageView.layer.rasterizationScale = scale addSubview(selectedImageView) selectedImageBackgroundView.frame = selectedImageView.bounds selectedImageBackgroundView.layer.contentsGravity = gravity selectedImageBackgroundView.layer.contentsScale = scale selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage selectedImageView.addSubview(selectedImageBackgroundView) selectedImageImagePlaceholderView.frame = selectedImageView.bounds selectedImageImagePlaceholderView.contentMode = .center selectedImageImagePlaceholderView.image = largePlaceholderImage selectedImageView.addSubview(selectedImageImagePlaceholderView) inset = imageDimension > 40 ? 3.5 : 5.5 imageViewFrame = selectedImageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) selectedImageImageView.frame = imageViewFrame selectedImageImageView.contentMode = .scaleAspectFill selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5 selectedImageImageView.layer.masksToBounds = true selectedImageImageView.backgroundColor = UIColor.white selectedImageView.addSubview(selectedImageImageView) selectedImageOutlineView.frame = selectedImageView.bounds selectedImageOutlineView.layer.contentsGravity = gravity selectedImageOutlineView.layer.contentsScale = scale selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage selectedImageView.addSubview(selectedImageOutlineView) selectedImageButton.frame = selectedImageView.bounds selectedImageButton.accessibilityTraits = UIAccessibilityTraits.none selectedImageView.addSubview(selectedImageButton) countLabel.frame = groupView.bounds countLabel.textColor = UIColor.white countLabel.textAlignment = .center countLabel.font = UIFont.boldSystemFont(ofSize: 16) groupView.addSubview(countLabel) prepareForReuse() super.setup() updateLayout() update(withArticlePlace: annotation as? ArticlePlace) } func set(alwaysShowImage: Bool, animated: Bool) { self.alwaysShowImage = alwaysShowImage let scale = collapsedDimension/imageDimension let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale) if alwaysShowImage { loadImage() imageView.alpha = 0 imageView.isHidden = false dotView.alpha = 1 dotView.isHidden = false imageView.transform = imageViewScaleDownTransform dotView.transform = CGAffineTransform.identity } else { dotView.transform = dotViewScaleUpTransform imageView.transform = CGAffineTransform.identity imageView.alpha = 1 imageView.isHidden = false dotView.alpha = 0 dotView.isHidden = false } let transforms = { if alwaysShowImage { self.imageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform } else { self.imageView.transform = imageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity } } let fadesIn = { if alwaysShowImage { self.imageView.alpha = 1 } else { self.dotView.alpha = 1 } } let fadesOut = { if alwaysShowImage { self.dotView.alpha = 0 } else { self.imageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = false } guard let articlePlace = self.annotation as? ArticlePlace else { return } self.updateDotAndImageHiddenState(with: articlePlace.articles.count) } if animated { if alwaysShowImage { UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } override func didMoveToSuperview() { super.didMoveToSuperview() guard superview != nil else { selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) return } selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) } @objc func selectedImageViewWasTapped(_ sender: UIButton) { delegate?.articlePlaceViewWasTapped(self) } var zPosition: CGFloat = 1 { didSet { guard !isSelected else { return } layer.zPosition = zPosition } } var isPlaceholderHidden: Bool = true { didSet { selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden imageImagePlaceholderView.isHidden = isPlaceholderHidden imageImageView.isHidden = !isPlaceholderHidden selectedImageImageView.isHidden = !isPlaceholderHidden } } private var shouldRasterize = false { didSet { imageView.layer.shouldRasterize = shouldRasterize selectedImageView.layer.shouldRasterize = shouldRasterize } } private var isImageLoaded = false func loadImage() { guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else { return } if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = true let article = articlePlace.articles[0] if let thumbnailURL = article.thumbnailURL { imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in if self.alwaysRasterize { self.shouldRasterize = true } }, success: { self.selectedImageImageView.image = self.imageImageView.image self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect self.isPlaceholderHidden = true if self.alwaysRasterize { self.shouldRasterize = true } }) } } func update(withArticlePlace articlePlace: ArticlePlace?) { let articleCount = articlePlace?.articles.count ?? 1 switch articleCount { case 0: zPosition = 1 isPlaceholderHidden = false imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more") accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles") case 1: zPosition = 1 isImageLoaded = false if isSelected || alwaysShowImage { loadImage() } accessibilityLabel = articlePlace?.articles.first?.displayTitle default: zPosition = 2 let countString = "\(articleCount)" countLabel.text = countString accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group {{Identical|Article}}"), countString) } updateDotAndImageHiddenState(with: articleCount) } func updateDotAndImageHiddenState(with articleCount: Int) { switch articleCount { case 0: fallthrough case 1: imageView.isHidden = !alwaysShowImage dotView.isHidden = alwaysShowImage groupView.isHidden = true default: imageView.isHidden = true dotView.isHidden = true groupView.isHidden = false } } override var annotation: MKAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } override func prepareForReuse() { super.prepareForReuse() if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = false delegate = nil imageImageView.wmf_reset() selectedImageImageView.wmf_reset() countLabel.text = nil set(alwaysShowImage: false, animated: false) setSelected(false, animated: false) alpha = 1 transform = CGAffineTransform.identity } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) guard let place = annotation as? ArticlePlace, place.articles.count == 1 else { selectedImageView.alpha = 0 return } let dotScale = collapsedDimension/dimension let imageViewScale = imageDimension/dimension let scale = alwaysShowImage ? imageViewScale : dotScale let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale) let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale) layer.zPosition = 3 if selected { loadImage() selectedImageView.transform = selectedImageViewScaleDownTransform dotView.transform = CGAffineTransform.identity imageView.transform = CGAffineTransform.identity selectedImageView.alpha = 0 imageView.alpha = 1 dotView.alpha = 1 } else { selectedImageView.transform = CGAffineTransform.identity dotView.transform = dotViewScaleUpTransform imageView.transform = imageViewScaleUpTransform selectedImageView.alpha = 1 imageView.alpha = 0 dotView.alpha = 0 } let transforms = { if selected { self.selectedImageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform self.imageView.transform = imageViewScaleUpTransform } else { self.selectedImageView.transform = selectedImageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity self.imageView.transform = CGAffineTransform.identity } } let fadesIn = { if selected { self.selectedImageView.alpha = 1 } else { self.imageView.alpha = 1 self.dotView.alpha = 1 } } let fadesOut = { if selected { self.imageView.alpha = 0 self.dotView.alpha = 0 } else { self.selectedImageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.shouldRasterize = false } if !selected { self.layer.zPosition = self.zPosition } } if animated { let duration = 2*selectionAnimationDuration if selected { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } func updateLayout() { let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) selectedImageView.center = center imageView.center = center dotView.center = center groupView.center = center } override var frame: CGRect { didSet { guard isSetup else { return } updateLayout() } } override var bounds: CGRect { didSet { guard isSetup else { return } updateLayout() } } }
mit
mrdepth/Neocom
Legacy/Neocom/Neocom/UIColor+NC.swift
2
1216
// // UIColor+NC.swift // Neocom // // Created by Artem Shimanski on 14.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit extension UIColor { convenience init(security: Float) { if security >= 1.0 { self.init(number: 0x2FEFEFFF) } else if security >= 0.9 { self.init(number: 0x48F0C0FF) } else if security >= 0.8 { self.init(number: 0x00EF47FF) } else if security >= 0.7 { self.init(number: 0x00F000FF) } else if security >= 0.6 { self.init(number: 0x8FEF2FFF) } else if security >= 0.5 { self.init(number: 0xEFEF00FF) } else if security >= 0.4 { self.init(number: 0xD77700FF) } else if security >= 0.3 { self.init(number: 0xF06000FF) } else if security >= 0.2 { self.init(number: 0xF04800FF) } else if security >= 0.1 { self.init(number: 0xD73000FF) } else { self.init(number: 0xF00000FF) } } var css:String { let rgba = UnsafeMutablePointer<CGFloat>.allocate(capacity: 4) defer {rgba.deallocate(capacity: 4)} getRed(&rgba[0], green: &rgba[1], blue: &rgba[2], alpha: &rgba[3]) return String(format: "#%.2x%.2x%.2x", Int(rgba[0] * 255.0), Int(rgba[1] * 255.0), Int(rgba[2] * 255.0)) } }
lgpl-2.1
Decybel07/L10n-swift
Source/Core/Plural/Plural.swift
1
3670
// // Plural.swift // L10n_swift // // Created by Adrian Bobrowski on 09.11.2017. // Copyright © 2017 Adrian Bobrowski (Decybel07), adrian071993@gmail.com. All rights reserved. // import Foundation internal enum Plural: String { case zero case one case two case few case many case other case floating } extension Plural { private static let format = Plural.createFormat() static func variants(for number: NSNumber, with locale: Locale?) -> [Plural] { var variants: [Plural] = [] if Double(number.int64Value) != number.doubleValue { variants.append(.floating) } let format = String(format: self.format, locale: locale, number.int64Value) variants.append(contentsOf: self.variants(base: Plural(rawValue: format), alternative: .other)) if variants.last != .other { variants.append(.other) } return variants } private static func variants(base: Plural?, alternative: Plural) -> [Plural] { let variant = base ?? alternative return variant == alternative ? [alternative] : [variant, alternative] } private static func createFormat() -> String { let table = "Plural" let `extension` = "stringsdict" #if SWIFT_PACKAGE var bundle = Bundle.module #else var bundle = Bundle(for: L10n.self) #endif if bundle.url(forResource: table, withExtension: `extension`) == nil { self.createFileIfNeeded(table: table, extension: `extension`, bundle: &bundle) } return bundle.localizedString(forKey: "integer", value: "other", table: table) } /** This is temporary solution for Swift Package Manager. - SeeAlso: [Issue #21](https://github.com/Decybel07/L10n-swift/issues/21) */ private static func createFileIfNeeded(table: String, `extension`: String, bundle: inout Bundle) { let subdirectory = "spmResources" if bundle.url(forResource: table, withExtension: `extension`, subdirectory: subdirectory) == nil { let baseUrl = bundle.bundleURL.appendingPathComponent(subdirectory) let url = baseUrl.appendingPathComponent(table).appendingPathExtension(`extension`) let fileContent = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>integer</key> <dict> <key>NSStringLocalizedFormatKey</key> <string>%#@value@</string> <key>value</key> <dict> <key>NSStringFormatSpecTypeKey</key> <string>NSStringPluralRuleType</string> <key>NSStringFormatValueTypeKey</key> <string>ld</string> <key>zero</key> <string>zero</string> <key>one</key> <string>one</string> <key>two</key> <string>two</string> <key>few</key> <string>few</string> <key>many</key> <string>many</string> <key>other</key> <string>other</string> </dict> </dict> </dict> </plist> """ do { try FileManager.default.createDirectory(at: baseUrl, withIntermediateDirectories: true) try fileContent.write(to: url, atomically: true, encoding: .utf8) bundle = Bundle(url: baseUrl) ?? bundle } catch { L10n.shared.logger?.log("Can't create \(url): \(error.localizedDescription)") } } } }
mit
kaushaldeo/Olympics
Olympics/Views/KDPhaseView.swift
1
826
// // KDPhaseView.swift // Olympics // // Created by Kaushal Deo on 7/22/16. // Copyright © 2016 Scorpion Inc. All rights reserved. // import UIKit class KDPhaseView: UITableViewHeaderFooterView { @IBOutlet weak var titleLabel: UILabel! override func drawRect(rect: CGRect) { // Drawing code var bezierPath = UIBezierPath(rect: rect) UIColor.cellBackgroundColor().setFill() bezierPath.fill() bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPoint(x: 16, y: CGRectGetHeight(rect))) bezierPath.addLineToPoint(CGPoint(x: CGRectGetWidth(rect), y: CGRectGetHeight(rect))) bezierPath.lineWidth = 0.25 UIColor.sepratorColor().setStroke() bezierPath.strokeWithBlendMode(.Exclusion, alpha: 1.0) } }
apache-2.0
ioan-chera/DoomMakerSwift
DoomMakerSwift/Geom.swift
1
9961
/* DoomMaker Copyright (C) 2017 Ioan Chera This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation /// PI representation let π = Double.pi let πf = Float.pi enum Geom { /// Checks if a line clips a rectangle, using Cohen-Sutherland's algorithm /// https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm static func lineClipsRect(_ pp0: NSPoint, _ pp1: NSPoint, rect: NSRect) -> Bool { let inside = 0 let left = 1 let right = 2 let bottom = 4 let top = 8 func computeOutCode(_ p: NSPoint) -> Int { var code = inside if p.x < rect.minX { code |= left } else if p.x > rect.maxX { code |= right } if p.y < rect.minY { code |= bottom } else if p.y > rect.maxY { code |= top } return code } var p0 = pp0 var p1 = pp1 var outcode0 = computeOutCode(p0) var outcode1 = computeOutCode(p1) while true { if (outcode0 | outcode1) == 0 { return true } if (outcode0 & outcode1) != 0 { return false } let outcodeOut = outcode0 != 0 ? outcode0 : outcode1 let p: NSPoint if (outcodeOut & top) != 0 { p = NSPoint(x: p0.x + (p1.x - p0.x) * (rect.maxY - p0.y) / (p1.y - p0.y), y: rect.maxY) } else if (outcodeOut & bottom) != 0 { p = NSPoint(x: p0.x + (p1.x - p0.x) * (rect.minY - p0.y) / (p1.y - p0.y), y: rect.minY) } else if (outcodeOut & right) != 0 { p = NSPoint(x: rect.maxX, y: p0.y + (p1.y - p0.y) * (rect.maxX - p0.x) / (p1.x - p0.x)) } else if (outcodeOut & left) != 0 { p = NSPoint(x: rect.minX, y: p0.y + (p1.y - p0.y) * (rect.minX - p0.x) / (p1.x - p0.x)) } else { assert(false) // should never happen p = NSPoint() } if outcodeOut == outcode0 { p0 = p outcode0 = computeOutCode(p0) } else { p1 = p outcode1 = computeOutCode(p1) } } } /// /// Finds projection of point /// static func projection(point: NSPoint, linep1: NSPoint, linep2: NSPoint) -> NSPoint { let x = point.x let y = point.y let x1 = linep1.x let y1 = linep1.y let dx = linep2.x - x1 let dy = linep2.y - y1 let dxsq = dx * dx let dysq = dy * dy let deltax = -x * dxsq - x1 * dysq + (y1 - y) * dx * dy let deltay = -y * dysq - y1 * dxsq + (x1 - x) * dy * dx let delta = -dxsq - dysq if delta != 0 { return NSPoint(x: deltax / delta, y: deltay / delta) } return linep1 // if not possible, just return one point } /// /// Find intersection point /// static func intersection(p00: NSPoint, p01: NSPoint, p10: NSPoint, p11: NSPoint) -> NSPoint? { let divisor = (p00.x - p01.x) * (p10.y - p11.y) - (p00.y - p01.y) * (p10.x - p11.x) if divisor == 0 { return nil } let fact1 = p00.x * p01.y - p00.y * p01.x let fact2 = p10.x * p11.y - p10.y * p11.x let d1 = fact1 * (p10.x - p11.x) - (p00.x - p01.x) * fact2 let d2 = fact1 * (p10.y - p11.y) - (p00.y - p01.y) * fact2 return NSPoint(x: d1 / divisor, y: d2 / divisor) } } /// NSPoint addition func + (left: NSPoint, right: NSPoint) -> NSPoint { return NSPoint(x: left.x + right.x, y: left.y + right.y) } /// NSPoint-NSSize addition func + (left: NSPoint, right: NSSize) -> NSPoint { return NSPoint(x: left.x + right.width, y: left.y + right.height) } /// NSPoint subtraction func - (left: NSPoint, right: NSPoint) -> NSPoint { return NSPoint(x: left.x - right.x, y: left.y - right.y) } /// NSPoint-NSSize subtraction func - (left: NSPoint, right: NSSize) -> NSPoint { return NSPoint(x: left.x - right.width, y: left.y - right.height) } /// NSPoint-CGFloat division func / (left: NSPoint, right: CGFloat) -> NSPoint { return NSPoint(x: left.x / right, y: left.y / right) } /// NSPoint-Double division func / (left: NSPoint, right: Double) -> NSPoint { return left / CGFloat(right) } /// NSPoint-CGFloat multiplication func * (left: NSPoint, right: CGFloat) -> NSPoint { return NSPoint(x: left.x * right, y: left.y * right) } /// NSPoint-Double multiplication func * (left: NSPoint, right: Double) -> NSPoint { return left * CGFloat(right) } func * (left: NSPoint, right: NSPoint) -> CGFloat { return left.x * right.x + left.y * right.y } /// floor applied to NSPoint elements func floor(_ point: NSPoint) -> NSPoint { return NSPoint(x: floor(point.x), y: floor(point.y)) } /// ceil applied to NSPoint elements func ceil(_ point: NSPoint) -> NSPoint { return NSPoint(x: ceil(point.x), y: ceil(point.y)) } /// Distance operator infix operator <-> : MultiplicationPrecedence /// Additions to the NSPoint structure extension NSPoint { /// Applies rotation to the 2D NSPoint vector func rotated(_ degrees: Float) -> NSPoint { let rad = degrees / 180 * πf let nx = Float(x) * cos(rad) - Float(y) * sin(rad) let ny = Float(x) * sin(rad) + Float(y) * cos(rad) return NSPoint(x: CGFloat(nx), y: CGFloat(ny)) } init(item: DraggedItem) { self.init(x: Int(item.x), y: Int(item.y)) } init(x: Int16, y: Int16) { self.init(x: Int(x), y: Int(y)) } static func <-> (left: NSPoint, right: NSPoint) -> CGFloat { return sqrt(pow(left.x - right.x, 2) + pow(left.y - right.y, 2)) } func distanceToLine(point1 p1: NSPoint, point2 p2: NSPoint) -> CGFloat { // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Cartesian_coordinates return abs((p2.y - p1.y) * x - (p2.x - p1.x) * y + p2.x * p1.y - p2.y * p1.x) / (p1 <-> p2) } func distanceToSegment(point1 p1: NSPoint, point2 p2: NSPoint) -> CGFloat { if (p1 - self) * (p2 - p1) >= 0 { return self <-> p1 } if (self - p2) * (p2 - p1) >= 0 { return self <-> p2 } return distanceToLine(point1: p1, point2: p2) } func withinRoundedRect(_ rect: NSRect, radius: CGFloat) -> Bool { if x >= rect.minX && x < rect.maxX && y >= rect.minY - radius && y < rect.maxY + radius { return true } if x < rect.minX && x >= rect.minX - radius { if y >= rect.minY && y < rect.maxY { return true } if y >= rect.minY - radius && y < rect.minY { return self <-> NSPoint(x: rect.minX, y: rect.minY) <= radius } if y >= rect.maxY && y < rect.maxY + radius { return self <-> NSPoint(x: rect.minX, y: rect.maxY) <= radius } return false } if x >= rect.maxX && x < rect.maxX + radius { if y >= rect.minY && y < rect.maxY { return true } if y >= rect.minY - radius && y < rect.minY { return self <-> NSPoint(x: rect.maxX, y: rect.minY) <= radius } if y >= rect.maxY && y < rect.maxY + radius { return self <-> NSPoint(x: rect.maxX, y: rect.maxY) <= radius } return false } return false } /// Cross product's Z func drill(_ point: NSPoint) -> CGFloat { return x * point.y - point.x * y } } /// NSRect additions extension NSRect { /// Modifies this NSRect by adding the point to this as to a bounding box mutating func pointAdd(_ point: NSPoint) { if point.x > self.maxX { self.size.width = point.x - self.minX } else if point.x < self.minX { self.size.width = self.maxX - point.x self.origin.x = point.x } if point.y > self.maxY { self.size.height = point.y - self.minY } else if point.y < self.minY { self.size.height = self.maxY - point.y self.origin.y = point.y } } init(point1: NSPoint, point2: NSPoint) { self.init() self.origin = point1 self.size = NSSize() pointAdd(point2) } } infix operator /• : MultiplicationPrecedence func /• (left: CGFloat, right: CGFloat) -> CGFloat { return round(left / right) * right } func /• (left: Float, right: Float) -> Float { return round(left / right) * right } func /• (left: NSPoint, right: CGFloat) -> NSPoint { return NSPoint(x: left.x /• right, y: left.y /• right) } // // For line relative position // enum Side { case front case back init(_ value: Int) { self = value == 0 ? .front : .back } init(_ value: Bool) { self = value ? .back : .front } } prefix func ! (right: Side) -> Side { return right == .front ? .back : .front } func anglemod(_ angle: Double) -> Double { var res = angle while res < -π { res += 2 * π } while res >= π { res -= 2 * π } return res }
gpl-3.0
335g/Bass
Bass/Functions/Undefined.swift
1
153
// Copyright © 2016 Yoshiki Kudo. All rights reserved. public func undefined<T>(message: String = "called undefined()") -> T { fatalError(message) }
mit
victorchee/TableView
TableView/TableView/ViewController.swift
1
2941
// // ViewController.swift // TableView // // Created by qihaijun on 11/10/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Normally, a cell’s height is determined by the table view delegate’s tableView:heightForRowAtIndexPath: method. To enable self-sizing table view cells, you must set the table view’s rowHeight property to UITableViewAutomaticDimension. You must also assign a value to the estimatedRowHeight property. As soon as both of these properties are set, the system uses Auto Layout to calculate the row’s actual height. tableView.estimatedRowHeight = 44.0 // tableView.rowHeight = UITableViewAutomaticDimension let blurEffect = UIBlurEffect(style: .Dark) let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect) let enableVibrancy = true if enableVibrancy { tableView.separatorEffect = vibrancyEffect } else { tableView.separatorEffect = blurEffect } } // MARK: - DataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell cell.label.text = "Cell \(indexPath.row)" cell.label.font = cell.label.font.fontWithSize(CGFloat(indexPath.row+1)*4.0) if indexPath.row % 2 == 0 { cell.contentView.backgroundColor = UIColor.lightGrayColor() } else { cell.contentView.backgroundColor = UIColor.whiteColor() } return cell } // MARK: - Delegate override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let destructiveAction = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "Destruct") { (action, indexPath) -> Void in print("Destruct \(indexPath)") } let defaultAction = UITableViewRowAction(style: .Default, title: "Default") { (action, indexPath) -> Void in print("Default \(indexPath)") } defaultAction.backgroundColor = UIColor.orangeColor() let normalAction = UITableViewRowAction(style: .Normal, title: "Normal") { (action, indexPath) -> Void in print("Normal \(indexPath)") } normalAction.backgroundEffect = UIBlurEffect(style: .Dark) return [destructiveAction, defaultAction, normalAction] } }
mit
mquocdung/nullapp
nullapp/DetailViewController.swift
1
994
// // DetailViewController.swift // nullapp // // Created by mquocdung on 1/17/17. // Copyright © 2017 mquocdung. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailDescriptionLabel: UILabel! var detailItem: AnyObject? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let label = self.detailDescriptionLabel { label.text = detail.description } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
VojtaStavik/ProtocolUI
ProtocolUITests/TransluentTRUEProtocolTest.swift
1
1729
// // TransluentTRUEProtocolTest.swift // ProtocolUI // // Created by STRV on 20/08/15. // Copyright © 2015 Vojta Stavik. All rights reserved. // import XCTest @testable import ProtocolUI class TransluentTRUEProtocolTest: XCTestCase { typealias CurrentTestProtocol = TransluentTRUE typealias CurrentTestValueType = Bool static let testValue : CurrentTestValueType = true func testUINavigationBar() { class TestView : UINavigationBar, CurrentTestProtocol { } let test1 = TestView() test1.applyProtocolUIAppearance() XCTAssertEqual(test1.translucent, self.dynamicType.testValue) let test2 = TestView() test2.prepareForInterfaceBuilder() XCTAssertEqual(test2.translucent, self.dynamicType.testValue) } func testUIToolbar() { class TestView : UIToolbar, CurrentTestProtocol { } let test1 = TestView() test1.applyProtocolUIAppearance() XCTAssertEqual(test1.translucent, self.dynamicType.testValue) let test2 = TestView() test2.prepareForInterfaceBuilder() XCTAssertEqual(test2.translucent, self.dynamicType.testValue) } func testUITabBar() { class TestView : UITabBar, CurrentTestProtocol { } let test1 = TestView() test1.applyProtocolUIAppearance() XCTAssertEqual(test1.translucent, self.dynamicType.testValue) let test2 = TestView() test2.prepareForInterfaceBuilder() XCTAssertEqual(test2.translucent, self.dynamicType.testValue) } }
mit
KoCMoHaBTa/MHAppKit
MHAppKitTests/XCTestExtensions.swift
1
2286
// // XCTestExtensions.swift // https://gist.github.com/KoCMoHaBTa/4ba07984d7c95822bc05 // // Created by Milen Halachev on 3/18/16. // Copyright © 2016 Milen Halachev. All rights reserved. // #if !os(watchOS) import Foundation import XCTest extension XCTestCase { public func performExpectation(description: String = "XCTestCase Default Expectation", timeout: TimeInterval = 2, handler: (_ expectation: XCTestExpectation) -> Void) { let expectation = self.expectation(description: description) handler(expectation) self.waitForExpectations(timeout: timeout, handler: { (error) -> Void in XCTAssertNil(error, "Expectation Error") }) } } extension XCTestExpectation { private struct AssociatedKeys { static var conditionsKey = "XCTestExpectation.AssociatedKeys.conditionsKey" } public private(set) var conditions: [String: Bool] { get { return objc_getAssociatedObject(self, &AssociatedKeys.conditionsKey) as? [String: Bool] ?? [:] } set { objc_setAssociatedObject(self, &AssociatedKeys.conditionsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var areAllConditionsFulfulled: Bool { for state in Array(self.conditions.values) { if state == false { return false } } return true } public func add(conditions: [String]) { conditions.forEach { (condition) -> () in self.conditions[condition] = false } } public func fulfill(condition: String) { XCTAssertNotNil(self.conditions[condition], "Cannot fulfil a non-exiting condition: \"\(condition)\"") guard self.conditions[condition] == false else { XCTFail("Cannot fulfil condition again - \(condition)") return } self.conditions[condition] = true guard self.areAllConditionsFulfulled else { return } self.fulfill() } } #endif
mit
khizkhiz/swift
validation-test/stdlib/StdlibUnittest.swift
1
15447
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test import SwiftPrivate import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. #if _runtime(_ObjC) import ObjectiveC #endif _setOverrideOSVersion(.osx(major: 10, minor: 9, bugFix: 3)) _setTestSuiteFailedCallback() { print("abort()") } // // Test that harness aborts when a test fails // var TestSuitePasses = TestSuite("TestSuitePasses") TestSuitePasses.test("passes") { expectEqual(1, 1) } // CHECK: [ OK ] TestSuitePasses.passes{{$}} // CHECK: TestSuitePasses: All tests passed var TestSuiteUXPasses = TestSuite("TestSuiteUXPasses") TestSuiteUXPasses.test("uxpasses").xfail(.osxAny("")).code { expectEqual(1, 1) } // CHECK: [ UXPASS ] TestSuiteUXPasses.uxpasses{{$}} // CHECK: TestSuiteUXPasses: Some tests failed, aborting // CHECK: UXPASS: ["uxpasses"] // CHECK: FAIL: [] // CHECK: SKIP: [] // CHECK: abort() var TestSuiteFails = TestSuite("TestSuiteFails") TestSuiteFails.test("fails") { expectEqual(1, 2) } // CHECK: [ FAIL ] TestSuiteFails.fails{{$}} // CHECK: TestSuiteFails: Some tests failed, aborting // CHECK: UXPASS: [] // CHECK: FAIL: ["fails"] // CHECK: SKIP: [] // CHECK: abort() var TestSuiteXFails = TestSuite("TestSuiteXFails") TestSuiteXFails.test("xfails").xfail(.osxAny("")).code { expectEqual(1, 2) } // CHECK: [ XFAIL ] TestSuiteXFails.xfails{{$}} // CHECK: TestSuiteXFails: All tests passed // // Test 'xfail:' and 'skip:' annotations // var XFailsAndSkips = TestSuite("XFailsAndSkips") // CHECK: [ OK ] XFailsAndSkips.passes{{$}} XFailsAndSkips.test("passes") { expectEqual(1, 1) } // CHECK: [ FAIL ] XFailsAndSkips.fails{{$}} XFailsAndSkips.test("fails") { expectEqual(1, 2) } // CHECK: [ XFAIL ] XFailsAndSkips.fails-always{{$}} XFailsAndSkips.test("fails-always") .xfail(.always("must always fail")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsAndSkips.fails-never{{$}} XFailsAndSkips.test("fails-never") .xfail(.never).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsAndSkips.xfail 10.9.3 passes{{$}} XFailsAndSkips.test("xfail 10.9.3 passes") .xfail(.osxBugFix(10, 9, 3, reason: "")).code { expectEqual(1, 2) } // CHECK: [ XFAIL ] XFailsAndSkips.xfail 10.9.3 fails{{$}} XFailsAndSkips.test("xfail 10.9.3 fails") .xfail(.osxBugFix(10, 9, 3, reason: "")).code { expectEqual(1, 2) } // CHECK: [ SKIP ] XFailsAndSkips.skipAlways (skip: [Always(reason: skip)]){{$}} XFailsAndSkips.test("skipAlways") .skip(.always("skip")).code { fatalError("should not happen") } // CHECK: [ OK ] XFailsAndSkips.skipNever{{$}} XFailsAndSkips.test("skipNever") .skip(.never).code { expectEqual(1, 1) } // CHECK: [ FAIL ] XFailsAndSkips.skip 10.9.2 passes{{$}} XFailsAndSkips.test("skip 10.9.2 passes") .skip(.osxBugFix(10, 9, 2, reason: "")).code { expectEqual(1, 2) } // CHECK: [ FAIL ] XFailsAndSkips.skip 10.9.2 fails{{$}} XFailsAndSkips.test("skip 10.9.2 fails") .skip(.osxBugFix(10, 9, 2, reason: "")).code { expectEqual(1, 2) } // CHECK: [ SKIP ] XFailsAndSkips.skip 10.9.3 (skip: [osx(10.9.3, reason: )]){{$}} XFailsAndSkips.test("skip 10.9.3") .skip(.osxBugFix(10, 9, 3, reason: "")).code { expectEqual(1, 2) fatalError("should not be executed") } // CHECK: XFailsAndSkips: Some tests failed, aborting // CHECK: abort() // // Test custom XFAIL predicates // var XFailsCustomPredicates = TestSuite("XFailsCustomPredicates") // CHECK: [ XFAIL ] XFailsCustomPredicates.matches{{$}} XFailsCustomPredicates.test("matches") .xfail(.custom({ true }, reason: "")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsCustomPredicates.not matches{{$}} XFailsCustomPredicates.test("not matches") .xfail(.custom({ false }, reason: "")).code { expectEqual(1, 1) } // CHECK: XFailsCustomPredicates: All tests passed // // Test version comparison rules // var XFailsOSX = TestSuite("XFailsOSX") // CHECK: [ UXPASS ] XFailsOSX.xfail OSX passes{{$}} XFailsOSX.test("xfail OSX passes").xfail(.osxAny("")).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsOSX.xfail OSX fails{{$}} XFailsOSX.test("xfail OSX fails").xfail(.osxAny("")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsOSX.xfail 9.*{{$}} XFailsOSX.test("xfail 9.*").xfail(.osxMajor(9, reason: "")).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsOSX.xfail 10.*{{$}} XFailsOSX.test("xfail 10.*").xfail(.osxMajor(10, reason: "")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsOSX.xfail 10.8{{$}} XFailsOSX.test("xfail 10.8").xfail(.osxMinor(10, 8, reason: "")).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsOSX.xfail 10.9{{$}} XFailsOSX.test("xfail 10.9").xfail(.osxMinor(10, 9, reason: "")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsOSX.xfail 10.[7-8]{{$}} XFailsOSX.test("xfail 10.[7-8]") .xfail(.osxMinorRange(10, 7...8, reason: "")).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsOSX.xfail 10.[9-10]{{$}} XFailsOSX.test("xfail 10.[9-10]") .xfail(.osxMinorRange(10, 9...10, reason: "")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsOSX.xfail 10.9.2{{$}} XFailsOSX.test("xfail 10.9.2") .xfail(.osxBugFix(10, 9, 2, reason: "")).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsOSX.xfail 10.9.3{{$}} XFailsOSX.test("xfail 10.9.3") .xfail(.osxBugFix(10, 9, 3, reason: "")).code { expectEqual(1, 2) } // CHECK: [ OK ] XFailsOSX.xfail 10.9.[1-2]{{$}} XFailsOSX.test("xfail 10.9.[1-2]") .xfail(.osxBugFixRange(10, 9, 1...2, reason: "")).code { expectEqual(1, 1) } // CHECK: [ XFAIL ] XFailsOSX.xfail 10.9.[3-4]{{$}} XFailsOSX.test("xfail 10.9.[3-4]") .xfail(.osxBugFixRange(10, 9, 3...4, reason: "")).code { expectEqual(1, 2) } // CHECK: XFailsOSX: Some tests failed, aborting // CHECK: abort() // // Check that we pass through stdout and stderr // var PassThroughStdoutStderr = TestSuite("PassThroughStdoutStderr") PassThroughStdoutStderr.test("hasNewline") { print("stdout first") print("stdout second") print("stdout third") var stderr = _Stderr() print("stderr first", to: &stderr) print("stderr second", to: &stderr) print("stderr third", to: &stderr) } // CHECK: [ RUN ] PassThroughStdoutStderr.hasNewline // CHECK-DAG: out>>> stdout first // CHECK-DAG: out>>> stdout second // CHECK-DAG: out>>> stdout third // CHECK-DAG: err>>> stderr first // CHECK-DAG: err>>> stderr second // CHECK-DAG: err>>> stderr third // CHECK: [ OK ] PassThroughStdoutStderr.hasNewline PassThroughStdoutStderr.test("noNewline") { print("stdout first") print("stdout second") print("stdout third", terminator: "") var stderr = _Stderr() print("stderr first", to: &stderr) print("stderr second", to: &stderr) print("stderr third", terminator: "", to: &stderr) } // CHECK: [ RUN ] PassThroughStdoutStderr.noNewline // CHECK-DAG: out>>> stdout first // CHECK-DAG: out>>> stdout second // CHECK-DAG: out>>> stdout third // CHECK-DAG: err>>> stderr first // CHECK-DAG: err>>> stderr second // CHECK-DAG: err>>> stderr third // CHECK: [ OK ] PassThroughStdoutStderr.noNewline // CHECK: PassThroughStdoutStderr: All tests passed // // Test 'setUp' and 'tearDown' // var TestSuiteWithSetUpPasses = TestSuite("TestSuiteWithSetUpPasses") TestSuiteWithSetUpPasses.test("passes") { print("test body") } TestSuiteWithSetUpPasses.setUp { print("setUp") } // CHECK: [ RUN ] TestSuiteWithSetUpPasses.passes // CHECK: out>>> setUp // CHECK: out>>> test body // CHECK: [ OK ] TestSuiteWithSetUpPasses.passes // CHECK: TestSuiteWithSetUpPasses: All tests passed var TestSuiteWithSetUpFails = TestSuite("TestSuiteWithSetUpFails") TestSuiteWithSetUpFails.test("fails") { print("test body") } TestSuiteWithSetUpFails.setUp { print("setUp") expectEqual(1, 2) } // CHECK: [ RUN ] TestSuiteWithSetUpFails.fails // CHECK: out>>> setUp // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> test body // CHECK: [ FAIL ] TestSuiteWithSetUpFails.fails // CHECK: TestSuiteWithSetUpFails: Some tests failed, aborting var TestSuiteWithTearDownPasses = TestSuite("TestSuiteWithTearDownPasses") TestSuiteWithTearDownPasses.test("passes") { print("test body") } TestSuiteWithTearDownPasses.tearDown { print("tearDown") } // CHECK: [ RUN ] TestSuiteWithTearDownPasses.passes // CHECK: out>>> test body // CHECK: out>>> tearDown // CHECK: [ OK ] TestSuiteWithTearDownPasses.passes var TestSuiteWithTearDownFails = TestSuite("TestSuiteWithTearDownFails") TestSuiteWithTearDownFails.test("fails") { print("test body") } TestSuiteWithTearDownFails.tearDown { print("tearDown") expectEqual(1, 2) } // CHECK: TestSuiteWithTearDownPasses: All tests passed // CHECK: [ RUN ] TestSuiteWithTearDownFails.fails // CHECK: out>>> test body // CHECK: out>>> tearDown // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: [ FAIL ] TestSuiteWithTearDownFails.fails // CHECK: TestSuiteWithTearDownFails: Some tests failed, aborting // // Test assertions // var AssertionsTestSuite = TestSuite("Assertions") AssertionsTestSuite.test("expectFailure/Pass") { expectFailure { expectEqual(1, 2) return () } } // CHECK: [ RUN ] Assertions.expectFailure/Pass // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: 1 (of type Swift.Int) // CHECK: out>>> actual: 2 (of type Swift.Int) // CHECK: [ OK ] Assertions.expectFailure/Pass AssertionsTestSuite.test("expectFailure/UXPass") .xfail(.custom({ true }, reason: "test")) .code { expectFailure { expectEqual(1, 2) return () } } // CHECK: [ RUN ] Assertions.expectFailure/UXPass ({{X}}FAIL: [Custom(reason: test)]) // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: 1 (of type Swift.Int) // CHECK: out>>> actual: 2 (of type Swift.Int) // CHECK: [ UXPASS ] Assertions.expectFailure/UXPass AssertionsTestSuite.test("expectFailure/Fail") { expectFailure { return () } } // CHECK: [ RUN ] Assertions.expectFailure/Fail // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: true // CHECK: out>>> running `body` should produce an expected failure // CHECK: [ FAIL ] Assertions.expectFailure/Fail AssertionsTestSuite.test("expectFailure/XFail") .xfail(.custom({ true }, reason: "test")) .code { expectFailure { return () } } // CHECK: [ RUN ] Assertions.expectFailure/XFail ({{X}}FAIL: [Custom(reason: test)]) // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: true // CHECK: out>>> running `body` should produce an expected failure // CHECK: [ XFAIL ] Assertions.expectFailure/XFail AssertionsTestSuite.test("expectFailure/AfterFailure/Fail") { expectEqual(1, 2) expectFailure { expectEqual(3, 4) return () } } // CHECK: [ RUN ] Assertions.expectFailure/AfterFailure/Fail // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: 1 (of type Swift.Int) // CHECK: out>>> actual: 2 (of type Swift.Int) // CHECK: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: 3 (of type Swift.Int) // CHECK: out>>> actual: 4 (of type Swift.Int) // CHECK: [ FAIL ] Assertions.expectFailure/AfterFailure/Fail AssertionsTestSuite.test("expectFailure/AfterFailure/XFail") .xfail(.custom({ true }, reason: "test")) .code { expectEqual(1, 2) expectFailure { expectEqual(3, 4) return () } } // CHECK: [ RUN ] Assertions.expectFailure/AfterFailure/XFail ({{X}}FAIL: [Custom(reason: test)]) // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: 1 (of type Swift.Int) // CHECK: out>>> actual: 2 (of type Swift.Int) // CHECK: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> expected: 3 (of type Swift.Int) // CHECK: out>>> actual: 4 (of type Swift.Int) // CHECK: [ XFAIL ] Assertions.expectFailure/AfterFailure/XFail AssertionsTestSuite.test("expectUnreachable") { expectUnreachable() } // CHECK: [ RUN ] Assertions.expectUnreachable // CHECK-NEXT: out>>> check failed at {{.*}}/stdlib/StdlibUnittest.swift, line // CHECK: out>>> this code should not be executed // CHECK: [ FAIL ] Assertions.expectUnreachable AssertionsTestSuite.test("expectCrashLater/Pass") { let array: [Int] = _opaqueIdentity([]) expectCrashLater() _blackHole(array[0]) } // CHECK: [ RUN ] Assertions.expectCrashLater/Pass // CHECK: err>>> CRASHED: SIG{{.*}} // CHECK: [ OK ] Assertions.expectCrashLater/Pass AssertionsTestSuite.test("expectCrashLater/UXPass") .xfail(.custom({ true }, reason: "test")) .code { let array: [Int] = _opaqueIdentity([]) expectCrashLater() _blackHole(array[0]) } // CHECK: [ RUN ] Assertions.expectCrashLater/UXPass ({{X}}FAIL: [Custom(reason: test)]) // CHECK: err>>> CRASHED: SIG{{.*}} // CHECK: [ UXPASS ] Assertions.expectCrashLater/UXPass AssertionsTestSuite.test("expectCrashLater/Fail") { expectCrashLater() } // CHECK: [ RUN ] Assertions.expectCrashLater/Fail // CHECK: expecting a crash, but the test did not crash // CHECK: [ FAIL ] Assertions.expectCrashLater/Fail AssertionsTestSuite.test("expectCrashLater/XFail") .xfail(.custom({ true }, reason: "test")) .code { expectCrashLater() } // CHECK: [ RUN ] Assertions.expectCrashLater/XFail ({{X}}FAIL: [Custom(reason: test)]) // CHECK: expecting a crash, but the test did not crash // CHECK: [ XFAIL ] Assertions.expectCrashLater/XFail AssertionsTestSuite.test("UnexpectedCrash/RuntimeTrap") { let array: [Int] = _opaqueIdentity([]) _blackHole(array[0]) } // CHECK: [ RUN ] Assertions.UnexpectedCrash/RuntimeTrap // CHECK: err>>> CRASHED: SIG{{.*}} // CHECK: the test crashed unexpectedly // CHECK: [ FAIL ] Assertions.UnexpectedCrash/RuntimeTrap AssertionsTestSuite.test("UnexpectedCrash/NullPointerDereference") { let ptr: UnsafePointer<Int> = _opaqueIdentity(nil) _blackHole(ptr.pointee) } // CHECK: [ RUN ] Assertions.UnexpectedCrash/NullPointerDereference // CHECK: err>>> CRASHED: SIG{{.*}} // CHECK: the test crashed unexpectedly // CHECK: [ FAIL ] Assertions.UnexpectedCrash/NullPointerDereference var TestSuiteLifetimeTracked = TestSuite("TestSuiteLifetimeTracked") var leakMe: LifetimeTracked? = nil TestSuiteLifetimeTracked.test("failsIfLifetimeTrackedAreLeaked") { leakMe = LifetimeTracked(0) } // CHECK: [ RUN ] TestSuiteLifetimeTracked.failsIfLifetimeTrackedAreLeaked // CHECK-NEXT: out>>> check failed at {{.*}}.swift, line [[@LINE-4]] // CHECK: out>>> expected: 0 (of type Swift.Int) // CHECK: out>>> actual: 1 (of type Swift.Int) // CHECK: [ FAIL ] TestSuiteLifetimeTracked.failsIfLifetimeTrackedAreLeaked TestSuiteLifetimeTracked.test("passesIfLifetimeTrackedAreResetAfterFailure") {} // CHECK: [ RUN ] TestSuiteLifetimeTracked.passesIfLifetimeTrackedAreResetAfterFailure // CHECK: [ OK ] TestSuiteLifetimeTracked.passesIfLifetimeTrackedAreResetAfterFailure runAllTests()
apache-2.0
bit6/bit6-ios-sdk
CoreSamples/Bit6FullDemo-Swift/Bit6ChatDemo-Swift/ChatsTableViewController.swift
1
12646
// // ChatsTableViewController.swift // Bit6ChatDemo-Swift // // Created by Carlos Thurber Boaventura on 07/08/14. // Copyright (c) 2014 Bit6. All rights reserved. // import UIKit import MobileCoreServices import Bit6 class ChatsTableViewController: UITableViewController, UITextFieldDelegate { var conversation : Bit6Conversation! { didSet { Bit6.setCurrentConversation(conversation) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.messagesChangedNotification(_:)), name: Bit6MessagesChangedNotification, object: self.conversation) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.groupsChangedNotification(_:)), name: Bit6GroupsChangedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.typingBeginNotification(_:)), name: Bit6TypingDidBeginRtNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.typingEndNotification(_:)), name: Bit6TypingDidEndRtNotification, object: nil) } } var scroll : Bool var _messages : [Bit6Message]! var messages : [Bit6Message] { get { if _messages != nil{ return _messages } else { _messages = self.conversation.messages return _messages } } set { _messages = newValue } } @IBOutlet var typingBarButtonItem: UIBarButtonItem! required init?(coder aDecoder: NSCoder) { self.scroll = false super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let userIdentity = Bit6.session().activeIdentity { self.navigationItem.prompt = "Logged as \(userIdentity.uri)" } let callItem = UIBarButtonItem(image:UIImage(named:"bit6ui_phone"), style:.Plain, target:self, action:#selector(ChatsTableViewController.call)) self.navigationItem.rightBarButtonItem = callItem if let typingAddress = self.conversation.typingAddress { self.typingBarButtonItem.title = "\(typingAddress.uri) is typing..." } else { self.typingBarButtonItem.title = nil; } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setToolbarHidden(false, animated: true) if !self.scroll { self.scroll = true self.tableView.reloadData() self.tableView.setContentOffset(CGPointMake(0, CGFloat.max), animated: false) } } deinit { Bit6.setCurrentConversation(nil) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - TableView override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.messages.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let message = self.messages[indexPath.row] var cell : UITableViewCell if message.incoming { cell = tableView.dequeueReusableCellWithIdentifier("textInCell")! } else { cell = tableView.dequeueReusableCellWithIdentifier("textOutCell")! } return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let message = self.messages[indexPath.row] if let textLabel = cell.viewWithTag(1) as? UILabel { textLabel.text = ChatsTableViewController.textContentForMessage(message) } if let detailTextLabel = cell.viewWithTag(2) as? UILabel { if message.type == .Call { detailTextLabel.text = "" } else { switch message.status { case .New : detailTextLabel.text = "" case .Sending : detailTextLabel.text = "Sending" case .Sent : detailTextLabel.text = "Sent" case .Failed : detailTextLabel.text = "Failed" case .Delivered : detailTextLabel.text = "Delivered" case .Read : detailTextLabel.text = "Read" } } } } // MARK: - Calls //WARNING: change to Bit6CallMediaModeMix to enable recording during a call static let callMediaMode = Bit6CallMediaModeP2P func call() { let actionSheet = UIAlertController(title:nil, message: nil, preferredStyle: .ActionSheet) actionSheet.addAction(UIAlertAction(title: "Audio Call", style: .Default, handler:{(action :UIAlertAction) in Bit6.startCallTo(self.conversation.address, streams:[.Audio], mediaMode:ChatsTableViewController.callMediaMode, offnet: false) })) actionSheet.addAction(UIAlertAction(title: "Video Call", style: .Default, handler:{(action :UIAlertAction) in Bit6.startCallTo(self.conversation.address, streams:[.Audio,.Video], mediaMode:ChatsTableViewController.callMediaMode, offnet: false) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:nil)) self.navigationController?.presentViewController(actionSheet, animated: true, completion:nil) } // MARK: - Send Text @IBAction func touchedComposeButton(sender : UIBarButtonItem) { if !self.canChat() { let alert = UIAlertController(title:"You have left this group", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action :UIAlertAction) in })) self.navigationController?.presentViewController(alert, animated: true, completion:nil) return; } let alert = UIAlertController(title:"Type the message", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:{(action :UIAlertAction) in })) alert.addAction(UIAlertAction(title: "Done", style: .Default, handler:{(action :UIAlertAction) in let msgTextField = alert.textFields![0] guard let text = msgTextField.text else { return } self.sendTextMsg(text) })) alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in textField.placeholder = "Message" textField.delegate = self }) self.navigationController?.presentViewController(alert, animated: true, completion:nil) } func sendTextMsg(msg : NSString){ if msg.length > 0 { let message = Bit6OutgoingMessage(destination:self.conversation.address) message.content = msg as String message.sendWithCompletionHandler{ (response, error) in if error == nil { NSLog("Message Sent") } else { NSLog("Message Failed with Error: \(error?.localizedDescription)") } } } } // MARK: - Typing func typingBeginNotification(notification:NSNotification) { let userInfo = notification.userInfo! let fromAddress = userInfo[Bit6FromKey] as! Bit6Address let convervationAddress = notification.object as! Bit6Address if convervationAddress == self.conversation.address { self.typingBarButtonItem.title = "\(fromAddress.uri) is typing..." } } func typingEndNotification(notification:NSNotification) { let convervationAddress = notification.object as! Bit6Address if convervationAddress == self.conversation.address { self.typingBarButtonItem.title = nil } } // MARK: - Data Source changes //here we listen to changes in group members and group title func groupsChangedNotification(notification:NSNotification) { let userInfo = notification.userInfo! let object = userInfo[Bit6ObjectKey] as! Bit6Group let change = userInfo[Bit6ChangeKey] as! String if change == Bit6UpdatedKey && object.address == self.conversation.address { self.title = ConversationsViewController.titleForConversation(self.conversation) } } func messagesChangedNotification(notification:NSNotification) { var userInfo = notification.userInfo! let object = userInfo[Bit6ObjectKey] as! Bit6Message let change = userInfo[Bit6ChangeKey] as! String if change == Bit6AddedKey { let indexPath = NSIndexPath(forRow: self.messages.count, inSection: 0) self.messages.append(object) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic) self.scrollToBottomAnimated(true) } else if change == Bit6UpdatedKey { if let indexPath = findMessage(object) { let cell = self.tableView.cellForRowAtIndexPath(indexPath) if cell != nil { self.tableView(self.tableView, willDisplayCell:cell!, forRowAtIndexPath:indexPath) } } } else if change == Bit6DeletedKey { if let indexPath = findMessage(object) { self.messages.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic) } } } func findMessage(message:Bit6Message) -> NSIndexPath? { for x in (0..<self.messages.count).reverse() { if self.messages[x].isEqual(message) { return NSIndexPath(forRow:x, inSection:0) } } return nil } // MARK: - func scrollToBottomAnimated(animated:Bool){ if self.messages.count>0 { let section = 0 let row = self.tableView(self.tableView, numberOfRowsInSection: section)-1 let scrollIndexPath = NSIndexPath(forRow: row, inSection: section) self.tableView.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated) } } // MARK: - UITextFieldDelegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { Bit6.typingBeginToAddress(self.conversation.address) return true } // MARK: - Helpers func canChat() -> Bool { if let group = Bit6Group(conversation:self.conversation) { if group.hasLeft { return false } } return true } class func textContentForMessage(message:Bit6Message) -> String? { if message.type == .Call { var showDuration = false var status = "" switch message.callStatus { case .Answer: status = "Answer"; showDuration = true; case .Missed: status = "Missed"; case .Failed: status = "Failed"; case .NoAnswer: status = "No Answer"; } var channels = [String]() if message.callHasChannel(.Audio) { channels.append("Audio") } if message.callHasChannel(.Video) { channels.append("Video"); } if message.callHasChannel(.Data) { channels.append("Data"); } let channel = channels.joinWithSeparator(" + ") if showDuration { return "\(channel) Call - \(message.callDuration!.description)s" } else { return "\(channel) Call (\(status))" } } else if message.type == .Location { return "Location" } else if message.type == .Attachments { return "Attachment" } else { return message.content; } } }
mit
tkremenek/swift
test/Sema/availability_nonoverlapping.swift
13
11256
// RUN: not %target-swift-frontend -typecheck %s -swift-version 4 2> %t.4.txt // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-4 %s < %t.4.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.4.txt // RUN: not %target-swift-frontend -typecheck %s -swift-version 5 2> %t.5.txt // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-5 %s < %t.5.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.5.txt class NonOptToOpt { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonOptToOpt() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class NonOptToOptReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonOptToOptReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class OptToNonOpt { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = OptToNonOpt() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class OptToNonOptReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = OptToNonOptReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class NoChange { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class NoChangeReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class OptToOpt { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class OptToOptReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class ThreeWayA { @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayB { @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayC { @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayD { @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayE { @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayF { @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class DisjointThreeWay { @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.1, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.1) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class OverlappingVersions { @available(swift, obsoleted: 6.0) public init(a: ()) {} @available(swift 5.0) public init?(a: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(a:)' @available(swift 5.0) public init?(b: ()) {} @available(swift, obsoleted: 5.1) public init(b: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(b:)' public init(c: ()) {} @available(swift 5.0) public init?(c: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c:)' @available(swift 5.0) public init(c2: ()) {} public init?(c2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c2:)' @available(swift, obsoleted: 5.0) public init(d: ()) {} public init?(d: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d:)' public init(d2: ()) {} @available(swift, obsoleted: 5.0) public init?(d2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d2:)' @available(swift, obsoleted: 5.0) public init(e: ()) {} @available(swift 5.0) public init?(e: ()) {} @available(swift 5.0) public init!(e: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(e:)' @available(swift, obsoleted: 5.0) public init(f: ()) {} @available(swift 5.0) public init?(f: ()) {} @available(swift, obsoleted: 5.0) public init!(f: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(f:)' } class NonThrowingToThrowing { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonThrowingToThrowing() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = NonThrowingToThrowing.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class NonThrowingToThrowingReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonThrowingToThrowingReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = NonThrowingToThrowingReversed.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class ThrowingToNonThrowing { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = ThrowingToNonThrowing() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = ThrowingToNonThrowing.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class ThrowingToNonThrowingReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = ThrowingToNonThrowingReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = ThrowingToNonThrowingReversed.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class ChangePropertyType { // We don't allow this for stored properties. @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public var stored: Int16 = 0 @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public var stored: Int8 = 0 // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'stored' // OK for computed properties. @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public var computed: Int16 { get { } set { } } @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public var computed: Int8 { get { } set { } } // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = ChangePropertyType().computed // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0
apache-2.0
movem3nt/StreamBaseKit
StreamBaseKit/UnionStream.swift
2
4286
// // UnionStream.swift // StreamBaseKit // // Created by Steve Farrell on 8/31/15. // Copyright (c) 2015 Movem3nt, Inc. All rights reserved. // import Foundation /** Compose a stream out of other streams. Some example use cases are: - Placeholders - Multiple Firebase queries in one view It's ok for the keys to overlap, and for different substreams to have different types. The sort order of the first stream is used by the union stream. (The sort orders of the other streams is ignored.) */ public class UnionStream { private let sources: [StreamBase] // TODO StreamBaseProtocol private let delegates: [UnionStreamDelegate] private var timer: NSTimer? private var numStreamsFinished: Int? = 0 private var union = KeyedArray<BaseItem>() private var error: NSError? private var comparator: StreamBase.Comparator { get { return sources[0].comparator } } /** The delegate to notify as the merged stream is updated. */ weak public var delegate: StreamBaseDelegate? /** Construct a union stream from other streams. The sort order of the first substream is used for the union. :param: sources The substreams. */ public init(sources: StreamBase...) { precondition(sources.count > 0) self.sources = sources delegates = sources.map{ UnionStreamDelegate(source: $0) } for (s, d) in zip(sources, delegates) { d.union = self s.delegate = d } } private func update() { var newUnion = [BaseItem]() var seen = Set<String>() for source in sources { for item in source { if !seen.contains(item.key!) { newUnion.append(item) seen.insert(item.key!) } } } newUnion.sortInPlace(comparator) StreamBase.applyBatch(union, batch: newUnion, delegate: delegate) if numStreamsFinished == sources.count { numStreamsFinished = nil delegate?.streamDidFinishInitialLoad(error) } } func needsUpdate() { timer?.invalidate() timer = NSTimer.schedule(delay: 0.1) { [weak self] timer in self?.update() } } func didFinishInitialLoad(error: NSError?) { if let e = error where self.error == nil { self.error = e // Any additional errors are ignored. } numStreamsFinished?++ needsUpdate() } func changed(t: BaseItem) { if let row = union.find(t.key!) { delegate?.streamItemsChanged([NSIndexPath(forRow: row, inSection: 0)]) } } } extension UnionStream : Indexable { public typealias Index = Int public var startIndex: Index { return union.startIndex } public var endIndex: Index { return union.startIndex } public subscript(i: Index) -> BaseItem { return union[i] } } extension UnionStream : CollectionType { } extension UnionStream : StreamBaseProtocol { public func find(key: String) -> BaseItem? { if let row = union.find(key) { return union[row] } return nil } public func findIndexPath(key: String) -> NSIndexPath? { if let row = union.find(key) { return NSIndexPath(forRow: row, inSection: 0) } return nil } } private class UnionStreamDelegate: StreamBaseDelegate { weak var source: StreamBase? weak var union: UnionStream? init(source: StreamBase) { self.source = source } func streamWillChange() { } func streamDidChange() { union?.needsUpdate() } func streamItemsAdded(paths: [NSIndexPath]) { } func streamItemsDeleted(paths: [NSIndexPath]) { } func streamItemsChanged(paths: [NSIndexPath]) { for path in paths { if let t = source?[path.row] { union?.changed(t) } } } func streamDidFinishInitialLoad(error: NSError?) { union?.didFinishInitialLoad(error) } }
mit
alienorb/Vectorized
Vectorized/Parser/SVGPathCommand.swift
1
11308
//--------------------------------------------------------------------------------------- // The MIT License (MIT) // // Created by Arthur Evstifeev on 5/29/12. // Modified by Michael Redig 9/28/14 // Ported to Swift by Brian Christensen <brian@alienorb.com> // // Copyright (c) 2012 Arthur Evstifeev // Copyright (c) 2014 Michael Redig // Copyright (c) 2015 Seedling // Copyright (c) 2016 Alien Orb Software LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //--------------------------------------------------------------------------------------- import Foundation import CoreGraphics internal enum CommandType: Int { case Absolute case Relative } internal protocol SVGPathCommand { func processCommandString(commandString: String, withPrevCommand: String, forPath: SVGBezierPath, factoryIdentifier: String) } internal class SVGPathCommandImpl: SVGPathCommand { static let paramRegex = try! NSRegularExpression(pattern: "[-+]?[0-9]*\\.?[0-9]+", options: []) var prevCommand: String? func parametersForCommand(commandString: String) -> [CGFloat] { let matches = SVGPathCommandImpl.paramRegex.matchesInString(commandString, options: [], range: NSRange(location: 0, length: commandString.characters.count)) var results: [CGFloat] = [] for match in matches { let paramString = (commandString as NSString).substringWithRange(match.range) if let value = Float(paramString) { results.append(CGFloat(value)) } } return results } func isAbsoluteCommand(commandLetter: String) -> Bool { return commandLetter == commandLetter.uppercaseString } func processCommandString(commandString: String, withPrevCommand prevCommand: String, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { self.prevCommand = prevCommand let commandLetter = commandString.substringToIndex(commandString.startIndex.advancedBy(1)) let params = parametersForCommand(commandString) let commandType: CommandType = isAbsoluteCommand(commandLetter) ? .Absolute : .Relative performWithParams(params, commandType: commandType, forPath: path, factoryIdentifier: identifier) } func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { fatalError("You must override \(#function) in a subclass") } } internal class SVGMoveCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.moveToPoint(CGPoint(x: params[0], y: params[1])) } else { path.moveToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGLineToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addLineToPoint(CGPoint(x: params[0], y: params[1])) } else { path.addLineToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGHorizontalLineToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addLineToPoint(CGPoint(x: params[0], y: path.currentPoint.y)) } else { path.addLineToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y)) } } } internal class SVGVerticalLineToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addLineToPoint(CGPoint(x: path.currentPoint.x, y: params[0])) } else { path.addLineToPoint(CGPoint(x: path.currentPoint.x, y: path.currentPoint.y + params[0])) } } } internal class SVGCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addCurveToPoint(CGPoint(x: params[4], y: params[5]), controlPoint1: CGPoint(x: params[0], y: params[1]), controlPoint2: CGPoint(x: params[2], y: params[3])) } else { path.addCurveToPoint(CGPoint(x: path.currentPoint.x + params[4], y: path.currentPoint.y + params[5]), controlPoint1: CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1]), controlPoint2: CGPoint(x: path.currentPoint.x + params[2], y: path.currentPoint.y + params[3])) } } } internal class SVGSmoothCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { var firstControlPoint = path.currentPoint if let prevCommand = prevCommand { if prevCommand.characters.count > 0 { let prevCommandType = prevCommand.substringToIndex(prevCommand.startIndex.advancedBy(1)) let prevCommandTypeLowercase = prevCommandType.lowercaseString let isAbsolute = prevCommandType != prevCommandTypeLowercase if prevCommandTypeLowercase == "c" || prevCommandTypeLowercase == "s" { let prevParams = parametersForCommand(prevCommand) if prevCommandTypeLowercase == "c" { if isAbsolute { firstControlPoint = CGPoint(x: -1 * prevParams[2] + 2 * path.currentPoint.x, y: -1 * prevParams[3] + 2 * path.currentPoint.y) } else { let oldCurrentPoint = CGPoint(x: path.currentPoint.x - prevParams[4], y: path.currentPoint.y - prevParams[5]) firstControlPoint = CGPoint(x: -1 * (prevParams[2] + oldCurrentPoint.x) + 2 * path.currentPoint.x, y: -1 * (prevParams[3] + oldCurrentPoint.y) + 2 * path.currentPoint.y) } } else { if isAbsolute { firstControlPoint = CGPoint(x: -1 * prevParams[0] + 2 * path.currentPoint.x, y: -1 * prevParams[1] + 2 * path.currentPoint.y) } else { let oldCurrentPoint = CGPoint(x: path.currentPoint.x - prevParams[2], y: path.currentPoint.y - prevParams[3]) firstControlPoint = CGPoint(x: -1 * (prevParams[0] + oldCurrentPoint.x) + 2 * path.currentPoint.x, y: -1 * (prevParams[1] + oldCurrentPoint.y) + 2 * path.currentPoint.y) } } } } } if type == .Absolute { path.addCurveToPoint(CGPoint(x: params[2], y: params[3]), controlPoint1: CGPoint(x: firstControlPoint.x, y: firstControlPoint.y), controlPoint2: CGPoint(x: params[0], y: params[1])) } else { path.addCurveToPoint(CGPoint(x: path.currentPoint.x + params[2], y: path.currentPoint.y + params[3]), controlPoint1: CGPoint(x: firstControlPoint.x, y: firstControlPoint.y), controlPoint2: CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGQuadraticCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addQuadCurveToPoint(CGPoint(x: params[2], y: params[3]), controlPoint: CGPoint(x: params[0], y: params[1])) } else { path.addQuadCurveToPoint(CGPoint(x: path.currentPoint.x + params[2], y: path.currentPoint.y + params[3]), controlPoint: CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGSmoothQuadraticCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { var firstControlPoint = path.currentPoint if let prevCommand = prevCommand { if prevCommand.characters.count > 0 { let prevCommandType = prevCommand.substringToIndex(prevCommand.startIndex.advancedBy(1)) let prevCommandTypeLowercase = prevCommandType.lowercaseString let isAbsolute = prevCommandType != prevCommandTypeLowercase if prevCommandTypeLowercase == "q" { let prevParams = parametersForCommand(prevCommand) if isAbsolute { firstControlPoint = CGPoint(x: -1 * prevParams[0] + 2 * path.currentPoint.x, y: -1 * prevParams[1] + 2 * path.currentPoint.y) } else { let oldCurrentPoint = CGPoint(x: path.currentPoint.x - prevParams[2], y: path.currentPoint.y - prevParams[3]) firstControlPoint = CGPoint(x: -1 * (prevParams[0] + oldCurrentPoint.x) + 2 * path.currentPoint.x, y: -1 * (prevParams[1] + oldCurrentPoint.y) + 2 * path.currentPoint.y) } } } } if type == .Absolute { path.addQuadCurveToPoint(CGPoint(x: params[0], y: params[1]), controlPoint: firstControlPoint) } else { path.addQuadCurveToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1]), controlPoint: firstControlPoint) } } } internal class SVGClosePathCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { path.closePath() } } internal class SVGPathCommandFactory { static let defaultFactory = SVGPathCommandFactory() static var factories: [String: SVGPathCommandFactory] = [:] private var commands: [String: SVGPathCommand] = [:] class func factoryWithIdentifier(identifier: String) -> SVGPathCommandFactory { if identifier == "" { return defaultFactory } if let factory = factories[identifier] { return factory } factories[identifier] = SVGPathCommandFactory() return factories[identifier]! } init() { commands["m"] = SVGMoveCommand() commands["l"] = SVGLineToCommand() commands["h"] = SVGHorizontalLineToCommand() commands["v"] = SVGVerticalLineToCommand() commands["c"] = SVGCurveToCommand() commands["s"] = SVGSmoothCurveToCommand() commands["q"] = SVGQuadraticCurveToCommand() commands["t"] = SVGSmoothQuadraticCurveToCommand() commands["z"] = SVGClosePathCommand() } func commandForCommandLetter(commandLetter: String) -> SVGPathCommand? { return commands[commandLetter.lowercaseString] } }
mit
mac-cain13/DocumentStore
DocumentStore/Transaction/CoreDataTransaction.swift
1
8071
// // CoreDataTransaction.swift // DocumentStore // // Created by Mathijs Kadijk on 12-11-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation import CoreData class CoreDataTransaction: ReadWritableTransaction { private let context: NSManagedObjectContext private let validatedDocumentDescriptors: ValidatedDocumentDescriptors private let logger: Logger init(context: NSManagedObjectContext, documentDescriptors: ValidatedDocumentDescriptors, logTo logger: Logger) { self.context = context self.validatedDocumentDescriptors = documentDescriptors self.logger = logger } private func validateUseOfDocumentType<DocumentType: Document>(_: DocumentType.Type) throws { guard validatedDocumentDescriptors.documentDescriptors.contains(DocumentType.documentDescriptor) else { let error = DocumentStoreError( kind: .documentDescriptionNotRegistered, message: "The document description with identifier '\(DocumentType.documentDescriptor.name)' is not registered with the DocumentStore this transaction is associated with, please pass all DocumentDescriptions that are used to the DocumentStore initializer.", underlyingError: nil ) throw TransactionError.documentStoreError(error) } } func count<DocumentType>(matching query: Query<DocumentType>) throws -> Int { try validateUseOfDocumentType(DocumentType.self) let request: NSFetchRequest<NSNumber> = query.fetchRequest() do { return try convertExceptionToError { try context.count(for: request) } } catch let underlyingError { let error = DocumentStoreError( kind: .operationFailed, message: "Failed to count '\(DocumentType.documentDescriptor.name)' documents. This is an error in the DocumentStore library, please report this issue.", underlyingError: underlyingError ) logger.log(level: .error, message: "Error while performing count.", error: error) throw TransactionError.documentStoreError(error) } } func fetch<DocumentType>(matching query: Query<DocumentType>) throws -> [DocumentType] { try validateUseOfDocumentType(DocumentType.self) // Set up the fetch request let request: NSFetchRequest<NSManagedObject> = query.fetchRequest() request.returnsObjectsAsFaults = false // Perform the fetch let fetchResult: [NSManagedObject] do { fetchResult = try convertExceptionToError { try context.fetch(request) } } catch let underlyingError { let error = DocumentStoreError( kind: .operationFailed, message: "Failed to fetch '\(DocumentType.documentDescriptor.name)' documents. This is an error in the DocumentStore library, please report this issue.", underlyingError: underlyingError ) logger.log(level: .error, message: "Error while performing fetch.", error: error) throw TransactionError.documentStoreError(error) } // Deserialize documents return try fetchResult .compactMap { do { guard let documentData = $0.value(forKey: DocumentDataAttributeName) as? Data else { let error = DocumentStoreError( kind: .documentDataCorruption, message: "Failed to retrieve '\(DocumentDataAttributeName)' attribute contents and cast it to `Data` for a '\(DocumentType.documentDescriptor.name)' document. This is an error in the DocumentStore library, please report this issue.", underlyingError: nil ) logger.log(level: .error, message: "Encountered corrupt '\(DocumentDataAttributeName)' attribute.", error: error) throw DocumentDeserializationError(resolution: .skipDocument, underlyingError: error) } return try DocumentType.decode(from: documentData) } catch let error as DocumentDeserializationError { logger.log(level: .warn, message: "Deserializing '\(DocumentType.documentDescriptor.name)' document failed, recovering with '\(error.resolution)' resolution.", error: error.underlyingError) switch error.resolution { case .deleteDocument: context.delete($0) return nil case .skipDocument: return nil case .abortOperation: throw TransactionError.serializationFailed(error.underlyingError) } } catch let error { throw TransactionError.serializationFailed(error) } } } func insert<DocumentType: Document>(document: DocumentType, mode: InsertMode) throws -> Bool { try validateUseOfDocumentType(DocumentType.self) let identifierValue = DocumentType.documentDescriptor.identifier.resolver(document) let currentManagedObject = try fetchManagedObject(for: document, with: identifierValue) let managedObject: NSManagedObject switch (mode, currentManagedObject) { case (.replaceOnly, .none), (.addOnly, .some): return false case (.replaceOnly, let .some(currentManagedObject)), (.addOrReplace, let .some(currentManagedObject)): managedObject = currentManagedObject case (.addOnly, .none), (.addOrReplace, .none): managedObject = NSEntityDescription.insertNewObject(forEntityName: DocumentType.documentDescriptor.name, into: context) } do { let documentData = try DocumentType.encode(document) try convertExceptionToError { managedObject.setValue(documentData, forKey: DocumentDataAttributeName) managedObject.setValue(identifierValue, forKey: DocumentType.documentDescriptor.identifier.storageInformation.propertyName.keyPath) DocumentType.documentDescriptor.indices.forEach { managedObject.setValue($0.resolver(document), forKey: $0.storageInformation.propertyName.keyPath) } } return true } catch let error { throw TransactionError.serializationFailed(error) } } @discardableResult func delete<DocumentType>(matching query: Query<DocumentType>) throws -> Int { try validateUseOfDocumentType(DocumentType.self) let request: NSFetchRequest<NSManagedObject> = query.fetchRequest() request.includesPropertyValues = false do { let fetchResult = try convertExceptionToError { try context.fetch(request) } fetchResult.forEach(context.delete) return fetchResult.count } catch let underlyingError { let error = DocumentStoreError( kind: .operationFailed, message: "Failed to fetch '\(DocumentType.documentDescriptor.name)' documents. This is an error in the DocumentStore library, please report this issue.", underlyingError: underlyingError ) logger.log(level: .error, message: "Error while performing fetch.", error: error) throw TransactionError.documentStoreError(error) } } @discardableResult func delete<DocumentType: Document>(document: DocumentType) throws -> Bool { try validateUseOfDocumentType(DocumentType.self) guard let managedObject = try fetchManagedObject(for: document) else { return false } context.delete(managedObject) return true } func persistChanges() throws { if context.hasChanges { try context.save() } } private func fetchManagedObject<DocumentType: Document>(for document: DocumentType, with identifierValue: Any? = nil) throws -> NSManagedObject? { let identifierValue = identifierValue ?? DocumentType.documentDescriptor.identifier.resolver(document) let request = NSFetchRequest<NSManagedObject>(entityName: DocumentType.documentDescriptor.name) request.predicate = NSComparisonPredicate( leftExpression: NSExpression(forKeyPath: DocumentType.documentDescriptor.identifier.storageInformation.propertyName.keyPath), rightExpression: NSExpression(forConstantValue: identifierValue), modifier: .direct, type: .equalTo ) request.resultType = .managedObjectResultType return try convertExceptionToError { try context.fetch(request).first } } }
mit
jkolb/Shkadov
Sources/PlatformXCB/Output.swift
1
1553
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb 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 ShkadovXCB.RandR public struct Output { private let connection: OpaquePointer let instance: xcb_randr_output_t init(connection: OpaquePointer, instance: xcb_randr_output_t) { self.connection = connection self.instance = instance } public func getInfo(timestamp: xcb_timestamp_t = xcb_timestamp_t(XCB_CURRENT_TIME)) -> GetOutputInfo { return GetOutputInfo(connection: connection, output: instance, timestamp: timestamp) } }
mit
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/discovery/ServerLocator.swift
1
5900
// // ServerLocator.swift // Emby.ApiClient // // Created by Vedran Ozir on 03/11/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation import CocoaAsyncSocket public class ServerLocator: NSObject, ServerDiscoveryProtocol, GCDAsyncUdpSocketDelegate { private let logger: ILogger private let jsonSerializer: IJsonSerializer private var onSuccess: (([ServerDiscoveryInfo]) -> Void)? var serverDiscoveryInfo: Set<ServerDiscoveryInfo> = [] public init( logger: ILogger, jsonSerializer: IJsonSerializer) { self.logger = logger; self.jsonSerializer = jsonSerializer; } // MARK: - utility methods public func findServers(timeoutMs: Int, onSuccess: @escaping ([ServerDiscoveryInfo]) -> Void, onError: @escaping (Error) -> Void) { let udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main) /*do { try udpSocket.bind(toPort: 7359) } catch let error { print("Error binding: \(error)") } do { try udpSocket.beginReceiving() } catch let error{ print("Error receiving: \(error)") }*/ // Find the server using UDP broadcast do { self.onSuccess = onSuccess try udpSocket.enableBroadcast(true) let sendData = "who is EmbyServer?".data(using: String.Encoding.utf8); let host = "255.255.255.255" let port: UInt16 = 7359; udpSocket.send(sendData!, toHost: host, port: port, withTimeout: TimeInterval(Double(timeoutMs)/1000.0), tag: 1) print("ServerLocator >>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch { print("Error sending DatagramPacket \(error)") onError(error) } } @objc func finished() { print("Found \(serverDiscoveryInfo.count) servers"); self.onSuccess?(Array(serverDiscoveryInfo)) } private func Receive(c: GCDAsyncUdpSocket, timeoutMs: UInt, onResponse: @escaping ([ServerDiscoveryInfo]) -> Void) throws { serverDiscoveryInfo = [] let timeout = TimeInterval(Double(timeoutMs) / 1000.0) Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(ServerLocator.finished), userInfo: nil, repeats: false) do { try c.beginReceiving() } catch { print (error) } } // MARK: - GCDAsyncUdpSocketDelegate /** * By design, UDP is a connectionless protocol, and connecting is not needed. * However, you may optionally choose to connect to a particular host for reasons * outlined in the documentation for the various connect methods listed above. * * This method is called if one of the connect methods are invoked, and the connection is successful. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) { print("didConnectToAddress") } /** * By design, UDP is a connectionless protocol, and connecting is not needed. * However, you may optionally choose to connect to a particular host for reasons * outlined in the documentation for the various connect methods listed above. * * This method is called if one of the connect methods are invoked, and the connection fails. * This may happen, for example, if a domain name is given for the host and the domain name is unable to be resolved. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) { print("didNotConnect") } /** * Called when the datagram with the given tag has been sent. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) { print("didSendDataWithTag") do { try self.Receive(c: sock, timeoutMs: UInt(1000), onResponse: { (serverDiscoveryInfo: [ServerDiscoveryInfo]) -> Void in print("serverDiscoveryInfo \(serverDiscoveryInfo)") }) } catch { print("\(error)") } } /** * Called if an error occurs while trying to send a datagram. * This could be due to a timeout, or something more serious such as the data being too large to fit in a sigle packet. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) { print("didNotSendDataWithTag") } /** * Called when the socket has received the requested datagram. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { let json = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) as String? // We have a response print("ServerLocator >>> Broadcast response from server: \(String(describing: sock.localAddress())): \(String(describing: json))") do { if let serverInfo: ServerDiscoveryInfo = try! JSONDecoder().decode(ServerDiscoveryInfo.self, from: data) { self.serverDiscoveryInfo.insert(serverInfo) } } catch { print("\(error)") } } /** * Called when the socket is closed. **/ @objc public func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { print("udpSocketDidClose") } }
mit
thomasmeagher/TimeMachine
TimeMachine/Controllers/DataController.swift
2
1991
// // DataController.swift // HuntTimehop // // Created by thomas on 12/23/14. // Copyright (c) 2014 thomas. All rights reserved. // import Foundation import UIKit class DataController { class func jsonTokenParser(json: NSDictionary) -> Token? { var token: Token? if let json = json["access_token"] { let key: String = json as! String let expiryDate: NSDate = NSDate().plusDays(60) token = Token(key: key, expiryDate: expiryDate) } return token } class func jsonPostsParser(json: NSDictionary) -> [Product] { var products: [Product] = [] if let json = json["posts"] { let posts: [AnyObject] = json as! [AnyObject] for post in posts { let id: Int = post["id"]! as! Int let name: String = post["name"]! as! String let tagline: String = post["tagline"]! as! String let comments: Int = post["comments_count"]! as! Int let votes: Int = post["votes_count"]! as! Int let phURL: String = post["discussion_url"]! as! String let screenshotDictionary = post["screenshot_url"] as! NSDictionary let screenshotUrl: String = screenshotDictionary["850px"]! as! String let makerInside: Bool = post["maker_inside"]! as! Bool var exclusive: Bool? if let exclusiveDictionary = post["exclusive"] as? NSDictionary { let exclusiveNumber = exclusiveDictionary["exclusive"]! as! Int exclusive = Bool.init(exclusiveNumber) } else { exclusive = false } let userDictionary = post["user"] as! NSDictionary let hunter: String = userDictionary["name"]! as! String let product = Product(id: id, name: name, tagline: tagline, comments: comments, votes: votes, phURL: phURL, screenshotUrl: screenshotUrl, makerInside: makerInside, exclusive: exclusive!, hunter: hunter) products += [product] } } return products } }
mit
naokits/my-programming-marathon
NCMB_iOSAppDemo/NCMB_iOSAppDemo/Config.swift
1
793
// // Config.swift // NCMB_iOSAppDemo // // Created by Naoki Tsutsui on 1/30/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import Foundation import NCMB /** アプリケーションキー及び、クライアントキーはご自身のものをご利用ください。 */ // アプリケーションキー) let applicationKey = "c951b57a31dafc86f076fa9f1baea6e9859bc1dd7f740c77799c051617e7b020" // クライアントキー let clientKey = "16a39a0a6515afff7ecff9acd16482804ecba67ca36801fe1d49bd737694fd5e" func setupBaaS() { // NCMBSubclassingに準拠しているクラスのセットアップ User.registerSubclass() Location.registerSubclass() // NCMBのセットアップ NCMB.setApplicationKey(applicationKey, clientKey: clientKey) }
mit
LarsStegman/helios-for-reddit
Sources/Model/Thing.swift
1
396
// // Thing.swift // Helios // // Created by Lars Stegman on 29-12-16. // Copyright © 2016 Stegman. All rights reserved. // import Foundation public protocol Thing: Decodable, Kindable { var id: String { get } var fullname: String { get } static var kind: Kind { get } } extension Thing { public var fullname: String { return "\(Self.kind.rawValue)_\(id)" } }
mit
HackMobile/music-interval-app
GymJamsV2/GymJamsV2/PlayerViewController.swift
1
3986
// // PlayerViewController.swift // GymJamsV2 // // Created by Kyle on 7/8/17. // Copyright © 2017 Kevin Nguyen. All rights reserved. // import UIKit class PlayerViewController: UIViewController, SPTAudioStreamingPlaybackDelegate, SPTAudioStreamingDelegate{ @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var sliderValueLabel: UILabel! @IBOutlet weak var updateAlbum: UILabel! @IBAction func sliderValueChanged(_ sender: UISlider) { var currentValue = Int(sender.value) sliderValueLabel.text = "\(currentValue)" sliderVal = currentValue } @IBOutlet weak var updateName: UILabel! func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didChange metadata: SPTPlaybackMetadata!) { player?.seek(to: 30, callback: {(error) in if error != nil { print("Error: couldn't skip"); } else { print ("Skipping Previous") } }); updateName.text = metadata.currentTrack?.name; updateAlbum.text = metadata.currentTrack?.artistName; var cover = metadata.currentTrack?.albumCoverArtURL; if (cover != nil) { imageView.setImageFromURl(stringImageUrl: cover!) } imageView.reloadInputViews() } var timer_ = Timer() @IBAction func playButtonPressed(_ sender: Any) { if (player?.playbackState.isPlaying)! { player?.setIsPlaying(false, callback: {(error) in if error != nil { print("Error: couldn't pause"); } else { print ("Pausing") } }); timer.invalidate() } else { player?.setIsPlaying(true, callback: {(error) in if error != nil { print("Error: couldn't start"); } else { print ("Starting") } }); setTimer() } } @IBAction func prevButtonPressed(_ sender: Any) { player?.skipPrevious({(error) in if error != nil { print("Error: couldn't skip"); } else { print ("Skipping Previous") } }); counter = sliderVal } @IBAction func skipButtonPressed(_ sender: Any) { player?.skipNext({(error) in if error != nil { print("Error: couldn't skip"); } else { print ("Skipping next") } }); counter = sliderVal } @IBOutlet weak var timerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() timerLabel.text = String(counter) player?.setShuffle(true, callback: {(error) in if error != nil { print("Error: couldn't shuffle") } else { print ("Shuffling") } }); player!.playbackDelegate = self player!.delegate = self as SPTAudioStreamingDelegate // Do any additional setup after loading the view. timer_ = Timer.scheduledTimer(timeInterval: 0.5, target:self, selector: #selector(PlayerViewController.updateCounter), userInfo: nil, repeats: true) } func updateCounter() { timerLabel.text = String(counter) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
VernierSoftwareTechnology/UIAlertWrapper
UIAlertWrapper.swift
1
11791
// // UIAlertWrapper.swift // UIAlertWrapper // // Created by Ruben Niculcea on 8/20/14. // Copyright (c) 2014 Vernier Software & Technology. All rights reserved. // import Foundation import UIKit private enum PresententionStyle { case Rect (CGRect) case BarButton (UIBarButtonItem) } private let alertDelegate = AlertDelegate() private var clickedButtonAtIndexBlock:(Int -> Void)? class AlertDelegate : NSObject, UIAlertViewDelegate, UIActionSheetDelegate { func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { clickedButtonAtIndexBlock!(buttonIndex) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if UIDevice.currentDevice().userInterfaceIdiom == .Pad { clickedButtonAtIndexBlock!(buttonIndex + 1) } else { clickedButtonAtIndexBlock!(buttonIndex) } } } /** UIAlertWrapper is a wrapper around UIAlertView/UIActionSheet and UIAlertController in order to simplify supporting both iOS 7 and iOS 8. It is not meant to be an exhaustive wrapper, it merely covers the common use cases around Alert Views and Action Sheets. */ class UIAlertWrapper : NSObject { private class func topViewController () -> UIViewController { let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController assert(rootViewController != nil, "App has no keyWindow, cannot present Alert/Action Sheet.") return UIAlertWrapper.topVisibleViewController(rootViewController!) } private class func topVisibleViewController(viewController: UIViewController) -> UIViewController { if viewController is UITabBarController { return UIAlertWrapper.topVisibleViewController((viewController as! UITabBarController).selectedViewController!) } else if viewController is UINavigationController { return UIAlertWrapper.topVisibleViewController((viewController as! UINavigationController).visibleViewController!) } else if viewController.presentedViewController != nil { return UIAlertWrapper.topVisibleViewController(viewController.presentedViewController!) } else if viewController.childViewControllers.count > 0 { return UIAlertWrapper.topVisibleViewController(viewController.childViewControllers.last!) } return viewController } /** Initializes and presents a new Action Sheet from a Bar Button Item on iPad or modally on iPhone - parameter title: The title of the Action Sheet - parameter cancelButtonTitle: The cancel button title - parameter destructiveButtonTitle: The destructive button title - parameter otherButtonTitles: An array of other button titles - parameter barButtonItem: The Bar Button Item to present from - parameter clickedButtonAtIndex: A closure that returns the buttonIndex of the button that was pressed. An index of 0 is always the cancel button or tapping outside of the popover on iPad. */ class func presentActionSheet(title title: String?, cancelButtonTitle: String, destructiveButtonTitle: String?, otherButtonTitles: [String], barButtonItem:UIBarButtonItem, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { self.presentActionSheet(title, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle, otherButtonTitles: otherButtonTitles, presententionStyle: .BarButton(barButtonItem), clickedButtonAtIndex: clickedButtonAtIndex) } /** Initializes and presents a new Action Sheet from a Frame on iPad or modally on iPhone - parameter title: The title of the Action Sheet - parameter cancelButtonTitle: The cancel button title - parameter destructiveButtonTitle: The destructive button title - parameter otherButtonTitles: An array of other button titles - parameter frame: The Frame to present from - parameter clickedButtonAtIndex: A closure that returns the buttonIndex of the button that was pressed. An index of 0 is always the cancel button or tapping outside of the popover on iPad. */ class func presentActionSheet(title title: String?, cancelButtonTitle: String, destructiveButtonTitle:String?, otherButtonTitles: [String], frame:CGRect, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { self.presentActionSheet(title, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle, otherButtonTitles: otherButtonTitles, presententionStyle: .Rect(frame), clickedButtonAtIndex: clickedButtonAtIndex) } private class func presentActionSheet(title: String?, cancelButtonTitle: String, destructiveButtonTitle:String?, otherButtonTitles: [String], presententionStyle:PresententionStyle, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { let currentViewController = UIAlertWrapper.topViewController() if #available(iOS 8.0, *) { var buttonOffset = 1 let alert = UIAlertController(title: title, message: nil, preferredStyle: .ActionSheet) alert.addAction(UIAlertAction(title: cancelButtonTitle, style: .Cancel, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: 0) } })) if let _destructiveButtonTitle = destructiveButtonTitle { alert.addAction(UIAlertAction(title: _destructiveButtonTitle, style: .Destructive, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: 1) } })) buttonOffset += 1 } for (index, string) in otherButtonTitles.enumerate() { alert.addAction(UIAlertAction(title: string, style: .Default, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: index + buttonOffset) } })) } if UIDevice.currentDevice().userInterfaceIdiom == .Pad { switch presententionStyle { case let .Rect(rect): alert.popoverPresentationController?.sourceView = currentViewController.view alert.popoverPresentationController?.sourceRect = rect case let .BarButton(barButton): alert.popoverPresentationController?.barButtonItem = barButton } } currentViewController.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIActionSheet() if let _title = title { alert.title = _title } if UIDevice.currentDevice().userInterfaceIdiom == .Phone { alert.cancelButtonIndex = 0 alert.addButtonWithTitle(cancelButtonTitle) } if let _destructiveButtonTitle = destructiveButtonTitle { alert.destructiveButtonIndex = UIDevice.currentDevice().userInterfaceIdiom == .Phone ? 1 : 0 alert.addButtonWithTitle(_destructiveButtonTitle) } for string in otherButtonTitles { alert.addButtonWithTitle(string) } if let _clickedButtonAtIndex = clickedButtonAtIndex { clickedButtonAtIndexBlock = _clickedButtonAtIndex alert.delegate = alertDelegate } if UIDevice.currentDevice().userInterfaceIdiom == .Phone { alert.showInView(currentViewController.view) } else { switch presententionStyle { case let .Rect(rect): alert.showFromRect(rect, inView: currentViewController.view, animated: true) case let .BarButton(barButton): alert.showFromBarButtonItem(barButton, animated: true) } } } } /** Initializes and presents a new Alert - parameter title: The title of the Alert - parameter message: The message of the Alert - parameter cancelButtonTitle: The cancel button title - parameter otherButtonTitles: An array of other button titles - parameter clickedButtonAtIndex: A closure that returns the buttonIndex of the button that was pressed. An index of 0 is always the cancel button. */ class func presentAlert(title title: String, message: String, cancelButtonTitle: String, otherButtonTitles: [String]? = nil, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { if #available(iOS 8.0, *) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: cancelButtonTitle, style: .Cancel, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: 0) } })) if let _otherButtonTitles = otherButtonTitles { for (index, string) in _otherButtonTitles.enumerate() { alert.addAction(UIAlertAction(title: string, style: .Default, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: index + 1) } })) } } let currentViewController = UIAlertWrapper.topViewController() currentViewController.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIAlertView() alert.addButtonWithTitle(cancelButtonTitle); alert.cancelButtonIndex = 0 alert.title = title alert.message = message if let _otherButtonTitles = otherButtonTitles { for string in _otherButtonTitles { alert.addButtonWithTitle(string) } } if let _clickedButtonAtIndex = clickedButtonAtIndex { clickedButtonAtIndexBlock = _clickedButtonAtIndex alert.delegate = alertDelegate } alert.show() } } }
mit
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Search/ResultResponse/SEResponseRepos.swift
1
606
// // ObjSearchReposResponse.swift // BeeFun // // Created by WengHengcong on 4/9/16. // Copyright © 2016 JungleSong. All rights reserved. // import UIKit import ObjectMapper class SEResponseRepos: NSObject, Mappable { var totalCount: Int? var incompleteResults: Bool? var items: [ObjRepos]? override init() { super.init() } required init?(map: Map) { } func mapping(map: Map) { // super.mapping(map) totalCount <- map["total_count"] incompleteResults <- map["incomplete_results"] items <- map["items"] } }
mit
gkgy/smallios
changelabel/changelabel/AppDelegate.swift
1
2168
// // AppDelegate.swift // changelabel // // Created by 高坤 on 2017/4/15. // Copyright © 2017年 gkgy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
gpl-3.0
kevin00223/iOS-demo
rac_demo/Pods/ReactiveSwift/Sources/ValidatingProperty.swift
2
9976
import Result /// A mutable property that validates mutations before committing them. /// /// If the property wraps an arbitrary mutable property, changes originated from /// the inner property are monitored, and would be automatically validated. /// Note that these would still appear as committed values even if they fail the /// validation. /// /// ``` /// let root = MutableProperty("Valid") /// let outer = ValidatingProperty(root) { /// $0 == "Valid" ? .valid : .invalid(.outerInvalid) /// } /// /// outer.result.value // `.valid("Valid") /// /// root.value = "🎃" /// outer.result.value // `.invalid("🎃", .outerInvalid)` /// ``` public final class ValidatingProperty<Value, ValidationError: Swift.Error>: MutablePropertyProtocol { private let getter: () -> Value private let setter: (Value) -> Void /// The result of the last attempted edit of the root property. public let result: Property<Result> /// The current value of the property. /// /// The value could have failed the validation. Refer to `result` for the /// latest validation result. public var value: Value { get { return getter() } set { setter(newValue) } } /// A producer for Signals that will send the property's current value, /// followed by all changes over time, then complete when the property has /// deinitialized. public let producer: SignalProducer<Value, NoError> /// A signal that will send the property's changes over time, /// then complete when the property has deinitialized. public let signal: Signal<Value, NoError> /// The lifetime of the property. public let lifetime: Lifetime /// Create a `ValidatingProperty` that presents a mutable validating /// view for an inner mutable property. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - note: `inner` is retained by the created property. /// /// - parameters: /// - inner: The inner property which validated values are committed to. /// - validator: The closure to invoke for any proposed value to `self`. public init<Inner: ComposableMutablePropertyProtocol>( _ inner: Inner, _ validator: @escaping (Value) -> Decision ) where Inner.Value == Value { getter = { inner.value } producer = inner.producer signal = inner.signal lifetime = inner.lifetime // This flag temporarily suspends the monitoring on the inner property for // writebacks that are triggered by successful validations. var isSettingInnerValue = false (result, setter) = inner.withValue { initial in let mutableResult = MutableProperty(Result(initial, validator(initial))) mutableResult <~ inner.signal .filter { _ in !isSettingInnerValue } .map { Result($0, validator($0)) } return (Property(capturing: mutableResult), { input in // Acquire the lock of `inner` to ensure no modification happens until // the validation logic here completes. inner.withValue { _ in let writebackValue: Value? = mutableResult.modify { result in result = Result(input, validator(input)) return result.value } if let value = writebackValue { isSettingInnerValue = true inner.value = value isSettingInnerValue = false } } }) } } /// Create a `ValidatingProperty` that validates mutations before /// committing them. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - parameters: /// - initial: The initial value of the property. It is not required to /// pass the validation as specified by `validator`. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init( _ initial: Value, _ validator: @escaping (Value) -> Decision ) { self.init(MutableProperty(initial), validator) } /// Create a `ValidatingProperty` that presents a mutable validating /// view for an inner mutable property. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - note: `inner` is retained by the created property. /// /// - parameters: /// - inner: The inner property which validated values are committed to. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<Other: PropertyProtocol>( _ inner: MutableProperty<Value>, with other: Other, _ validator: @escaping (Value, Other.Value) -> Decision ) { // Capture a copy that reflects `other` without influencing the lifetime of // `other`. let other = Property(other) self.init(inner) { input in return validator(input, other.value) } // When `other` pushes out a new value, the resulting property would react // by revalidating itself with its last attempted value, regardless of // success or failure. other.signal .take(during: lifetime) .observeValues { [weak self] _ in guard let s = self else { return } switch s.result.value { case let .invalid(value, _): s.value = value case let .coerced(_, value, _): s.value = value case let .valid(value): s.value = value } } } /// Create a `ValidatingProperty` that validates mutations before /// committing them. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - parameters: /// - initial: The initial value of the property. It is not required to /// pass the validation as specified by `validator`. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<Other: PropertyProtocol>( _ initial: Value, with other: Other, _ validator: @escaping (Value, Other.Value) -> Decision ) { self.init(MutableProperty(initial), with: other, validator) } /// Create a `ValidatingProperty` which validates mutations before /// committing them. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - note: `inner` is retained by the created property. /// /// - parameters: /// - initial: The initial value of the property. It is not required to /// pass the validation as specified by `validator`. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<U, E>( _ initial: Value, with other: ValidatingProperty<U, E>, _ validator: @escaping (Value, U) -> Decision ) { self.init(MutableProperty(initial), with: other, validator) } /// Create a `ValidatingProperty` that presents a mutable validating /// view for an inner mutable property. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - parameters: /// - inner: The inner property which validated values are committed to. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<U, E>( _ inner: MutableProperty<Value>, with other: ValidatingProperty<U, E>, _ validator: @escaping (Value, U) -> Decision ) { // Capture only `other.result` but not `other`. let otherValidations = other.result self.init(inner) { input in let otherValue: U switch otherValidations.value { case let .valid(value): otherValue = value case let .coerced(_, value, _): otherValue = value case let .invalid(value, _): otherValue = value } return validator(input, otherValue) } // When `other` pushes out a new validation result, the resulting property // would react by revalidating itself with its last attempted value, // regardless of success or failure. otherValidations.signal .take(during: lifetime) .observeValues { [weak self] _ in guard let s = self else { return } switch s.result.value { case let .invalid(value, _): s.value = value case let .coerced(_, value, _): s.value = value case let .valid(value): s.value = value } } } /// Represents a decision of a validator of a validating property made on a /// proposed value. public enum Decision { /// The proposed value is valid. case valid /// The proposed value is invalid, but the validator coerces it into a /// replacement which it deems valid. case coerced(Value, ValidationError?) /// The proposed value is invalid. case invalid(ValidationError) } /// Represents the result of the validation performed by a validating property. public enum Result { /// The proposed value is valid. case valid(Value) /// The proposed value is invalid, but the validator was able to coerce it /// into a replacement which it deemed valid. case coerced(replacement: Value, proposed: Value, error: ValidationError?) /// The proposed value is invalid. case invalid(Value, ValidationError) /// Whether the value is invalid. public var isInvalid: Bool { if case .invalid = self { return true } else { return false } } /// Extract the valid value, or `nil` if the value is invalid. public var value: Value? { switch self { case let .valid(value): return value case let .coerced(value, _, _): return value case .invalid: return nil } } /// Extract the error if the value is invalid. public var error: ValidationError? { if case let .invalid(_, error) = self { return error } else { return nil } } fileprivate init(_ value: Value, _ decision: Decision) { switch decision { case .valid: self = .valid(value) case let .coerced(replacement, error): self = .coerced(replacement: replacement, proposed: value, error: error) case let .invalid(error): self = .invalid(value, error) } } } }
mit
SeptAi/Cooperate
Cooperate/Cooperate/Class/View/Message/MessageCell.swift
1
1475
// // MessageCell.swift // Cooperate // // Created by J on 2017/1/17. // Copyright © 2017年 J. All rights reserved. // import UIKit class MessageCell: UITableViewCell { // 视图模型 var viewModel:MessageViewModel?{ didSet{ // 设置图像 // 设置内容 title.text = viewModel?.title author.text = viewModel?.author content.attributedText = viewModel?.normalAttrText } } @IBOutlet weak var msgImageView: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var author: UILabel! @IBOutlet weak var content: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code // Initialization code // 离屏渲染 - 消耗CPU换取速度 self.layer.drawsAsynchronously = true // 栅格化 - 异步绘制之后,会生成一张独立图像,在cell滚动时,实质滚动的是这张图片 // cell优化-减少图层的数量 // 停止滚动后,接收监听 self.layer.shouldRasterize = true // 栅格化 -- 必须制定分辨率,否则会模糊 self.layer.rasterizationScale = UIScreen.main.scale } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
openhab/openhab.ios
openHABWatch Extension/ComplicationController.swift
1
6480
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import ClockKit import DeviceKit import WatchKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Complication Configuration func getComplicationDescriptors(handler: @escaping ([CLKComplicationDescriptor]) -> Void) { // watchOS7: replacing depreciated CLKComplicationSupportedFamilies let descriptors = [ CLKComplicationDescriptor(identifier: "complication", displayName: Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String, supportedFamilies: CLKComplicationFamily.allCases) // Multiple complication support can be added here with more descriptors ] handler(descriptors) } func handleSharedComplicationDescriptors(_ complicationDescriptors: [CLKComplicationDescriptor]) { // Do any necessary work to support these newly shared complication descriptors } // MARK: - Timeline Configuration func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) { handler([]) } func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(nil) } func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(nil) } func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) { handler(.showOnLockScreen) } // MARK: - Timeline Population func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { // Call the handler with the current timeline entry let template = getTemplate(complication: complication) if template != nil { handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template!)) } } func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Placeholder Templates func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached handler(getTemplate(complication: complication)) } func getPlaceholderTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { handler(getTemplate(complication: complication)) } private func getTemplate(complication: CLKComplication) -> CLKComplicationTemplate? { // default ist circularSmall var template: CLKComplicationTemplate? switch complication.family { case .modularSmall: template = CLKComplicationTemplateModularSmallRingImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage()), fillFraction: 1, ringStyle: CLKComplicationRingStyle.closed) case .utilitarianSmall: template = CLKComplicationTemplateUtilitarianSmallRingImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage()), fillFraction: 1, ringStyle: CLKComplicationRingStyle.closed) case .circularSmall: template = CLKComplicationTemplateCircularSmallRingImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage()), fillFraction: 1, ringStyle: CLKComplicationRingStyle.closed) case .extraLarge: template = CLKComplicationTemplateExtraLargeSimpleImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage())) case .graphicCorner: template = CLKComplicationTemplateGraphicCornerTextImage(textProvider: CLKSimpleTextProvider(text: "openHAB"), imageProvider: CLKFullColorImageProvider(fullColorImage: getGraphicCornerImage())) case .graphicBezel: let modTemplate = CLKComplicationTemplateGraphicCircularImage(imageProvider: CLKFullColorImageProvider(fullColorImage: getGraphicCornerImage())) template = CLKComplicationTemplateGraphicBezelCircularText(circularTemplate: modTemplate, textProvider: CLKSimpleTextProvider(text: "openHAB")) case .graphicCircular: template = CLKComplicationTemplateGraphicCircularImage(imageProvider: CLKFullColorImageProvider(fullColorImage: getGraphicCircularImage())) default: break } return template } private func getGraphicCornerImage() -> UIImage { let dimension: CGFloat = Device.current.diagonal < 2.0 ? 20 : 22 return getGraphicImage(withSize: CGSize(width: dimension, height: dimension)) } private func getGraphicCircularImage() -> UIImage { let dimension: CGFloat = Device.current.diagonal < 2.0 ? 42 : 47 return getGraphicImage(withSize: CGSize(width: dimension, height: dimension)) } private func getGraphicImage(withSize size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, WKInterfaceDevice.current().screenScale) if let image = UIImage(named: "OHIcon") { image.draw(in: rect.insetBy(dx: -(rect.width / 10), dy: -(rect.height / 10))) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? UIImage() } }
epl-1.0
ResearchSuite/ResearchSuiteExtensions-iOS
Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Step Providers/Generators/RSTBBaseStepGenerator.swift
1
1591
// // RSTBBaseStepGenerator.swift // Pods // // Created by James Kizer on 1/9/17. // // import ResearchKit import Gloss public protocol RSTBBaseStepGenerator: RSTBStepGenerator { var supportedTypes: [String]! {get} } public extension RSTBBaseStepGenerator { public func supportsType(type: String) -> Bool { return self.supportedTypes.contains(type) } public func supportedStepTypes() -> [String] { return self.supportedTypes } public func generateStep(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKStep? { return nil } func generateSteps(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> [ORKStep]? { let step = self.generateStep(type: type, jsonObject: jsonObject, helper: helper) return step == nil ? [] : [step!] } func generateSteps(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper, identifierPrefix: String) -> [ORKStep]? { let splicedJSON: JSON = { if identifierPrefix == "" { return jsonObject } else { if let identifier: String = "identifier" <~~ jsonObject { var newJSON = jsonObject newJSON["identifier"] = "\(identifierPrefix).\(identifier)" return newJSON } else { return jsonObject } } }() return self.generateSteps(type: type, jsonObject: splicedJSON, helper: helper) } }
apache-2.0
jefflinwood/volunteer-recognition-ios
APASlapApp/APASlapApp/Login/LoginViewController.swift
1
1960
// // LoginViewController.swift // APASlapApp // // Created by Jeffrey Linwood on 6/3/17. // Copyright © 2017 Jeff Linwood. All rights reserved. // import UIKit import Firebase class LoginViewController: BaseViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! func showNewsFeed() { let storyboard = UIStoryboard.init(name: "NewsFeed", bundle: nil) if let vc = storyboard.instantiateInitialViewController() { present(vc, animated: false, completion: nil) } } override func viewWillAppear(_ animated: Bool) { if let auth = FIRAuth.auth() { if auth.currentUser != nil { showNewsFeed() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(_ sender: Any) { if (emailTextField.text == "") { showErrorMessage(errorMessage:"Email can not be blank.") return } if (passwordTextField.text == "") { showErrorMessage(errorMessage:"Password can not be blank.") return } let email = emailTextField.text! let password = passwordTextField.text! if let auth = FIRAuth.auth() { auth.signIn(withEmail: email, password: password, completion: { (user, error) in if let error = error { self.showErrorMessage(errorMessage:error.localizedDescription) return } else { self.showNewsFeed() } }) } } }
mit
OhioVR/SwiftVideoFileFilterer
SwiftVideoFileFilterer/filterSelectViewController.swift
1
1298
// // filterSelectViewController.swift // SwiftVideoFileFilterer // // Created by Scott Yannitell on 10/22/15. // Copyright © 2015 Scott Yannitell. All rights reserved. // import UIKit protocol ContainerDelegateProtocol { func CloseFilterSelector() } class filterSelectViewController: UIViewController, UITableViewDelegate { var delegate:ContainerDelegateProtocol? @IBAction func Close(sender: AnyObject) { delegate?.CloseFilterSelector() } @IBOutlet var tableView: UITableView! var cellContent = ["Sharpen", "Brightness", "Hue", "Saturation", "gaussian blur", "pixelate"] override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellContent.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") cell.textLabel?.text = cellContent[indexPath.row] return cell } }
mit
grzegorzleszek/algorithms-swift
Sources/Sort.swift
1
3448
// // GraphTests.swift // // Copyright © 2018 Grzegorz.Leszek. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. func mergeSort(elements: [Int]) -> [Int] { if (elements.count <= 1) { return elements } var left = [Int]() var right = [Int]() for (i, x) in elements.enumerated() { if i < elements.count / 2 { left.append(x) } else { right.append(x) } } left = mergeSort(elements: left) right = mergeSort(elements: right) return merge(left, right) } private func merge(_ left: [Int], _ right: [Int]) -> [Int] { var result = [Int]() var l = left var r = right while !l.isEmpty && !r.isEmpty { if l.first! <= r.first! { result.append(l.first!) l = [Int](l.dropFirst(1)) } else { result.append(r.first!) r = [Int](r.dropFirst(1)) } } while !l.isEmpty { result.append(l.first!) l = [Int](l.dropFirst(1)) } while !r.isEmpty { result.append(r.first!) r = [Int](r.dropFirst(1)) } return result } func quickSort(_ A: inout [Int], _ lo: Int, _ hi: Int) { if lo < hi { let p = partition(&A, lo, hi) quickSort(&A, lo, p - 1 ) quickSort(&A, p + 1, hi) } } private func partition(_ A: inout [Int], _ lo: Int, _ hi: Int) -> Int { let pivot = A[hi] var i = lo - 1 (lo...(hi - 1)).forEach { let j = $0 if A[j] < pivot { i = i + 1 A.swapAt(i, j) } } if A[hi] < A[i + 1] { A.swapAt(i + 1, hi) } return i + 1 } func bucketSort(_ arr: inout [Int], _ n: Int) { var b = [[Int]](repeatElement([Int](), count: n)) (0..<n).forEach { i in let bi = msbits(arr[i], n) b[bi].append(arr[i]) } (0..<n).forEach { i in insertionSort(&b[i]) } var index = 0 (0..<n).forEach { let i = $0 (0..<b[i].count).forEach { j in arr[index] = b[i][j]; index += 1 } } } private func msbits(_ x: Int, _ k: Int) -> Int { return min(abs(x), k - 1) } func insertionSort(_ A: inout [Int]) { var i = 1 while i < A.count { var j = i while j > 0 && A[j-1] > A[j] { A.swapAt(j, j-1) j = j - 1 } i = i + 1 } }
mit
DavidSkrundz/Lua
Sources/Lua/Value/Number.swift
1
3913
// // Number.swift // Lua // /// Represents a Lua numeric value since Lua does not make a distinction between /// `Int` and `Double` public final class Number { public let intValue: Int public let uintValue: UInt32 public let doubleValue: Double public let isInt: Bool public var hashValue: Int { if self.isInt { return self.intValue.hashValue } return self.doubleValue.hashValue } /// Create a new `Number` by popping the top value from the stack internal init(lua: Lua) { self.intValue = lua.raw.getInt(atIndex: TopIndex)! self.uintValue = lua.raw.getUInt(atIndex: TopIndex)! self.doubleValue = lua.raw.getDouble(atIndex: TopIndex)! lua.raw.pop(1) self.isInt = Double(self.intValue) == self.doubleValue } } extension Number: Equatable, Comparable {} public func ==(lhs: Number, rhs: Number) -> Bool { return lhs.doubleValue == rhs.doubleValue } public func <(lhs: Number, rhs: Number) -> Bool { return lhs.doubleValue < rhs.doubleValue } // Int public func ==(lhs: Number, rhs: Int) -> Bool { return lhs.intValue == rhs } public func !=(lhs: Number, rhs: Int) -> Bool { return lhs.intValue != rhs } public func < (lhs: Number, rhs: Int) -> Bool { return lhs.intValue < rhs } public func > (lhs: Number, rhs: Int) -> Bool { return lhs.intValue > rhs } public func <=(lhs: Number, rhs: Int) -> Bool { return lhs.intValue <= rhs } public func >=(lhs: Number, rhs: Int) -> Bool { return lhs.intValue >= rhs } public func ==(lhs: Int, rhs: Number) -> Bool { return lhs == rhs.intValue } public func !=(lhs: Int, rhs: Number) -> Bool { return lhs != rhs.intValue } public func < (lhs: Int, rhs: Number) -> Bool { return lhs < rhs.intValue } public func > (lhs: Int, rhs: Number) -> Bool { return lhs > rhs.intValue } public func <=(lhs: Int, rhs: Number) -> Bool { return lhs <= rhs.intValue } public func >=(lhs: Int, rhs: Number) -> Bool { return lhs >= rhs.intValue } // UInt32 public func ==(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue == rhs } public func !=(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue != rhs } public func < (lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue < rhs } public func > (lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue > rhs } public func <=(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue <= rhs } public func >=(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue >= rhs } public func ==(lhs: UInt32, rhs: Number) -> Bool { return lhs == rhs.uintValue } public func !=(lhs: UInt32, rhs: Number) -> Bool { return lhs != rhs.uintValue } public func < (lhs: UInt32, rhs: Number) -> Bool { return lhs < rhs.uintValue } public func > (lhs: UInt32, rhs: Number) -> Bool { return lhs > rhs.uintValue } public func <=(lhs: UInt32, rhs: Number) -> Bool { return lhs <= rhs.uintValue } public func >=(lhs: UInt32, rhs: Number) -> Bool { return lhs >= rhs.uintValue } // Double public func ==(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue == rhs } public func !=(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue != rhs } public func < (lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue < rhs } public func > (lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue > rhs } public func <=(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue <= rhs } public func >=(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue >= rhs } public func ==(lhs: Double, rhs: Number) -> Bool { return lhs == rhs.doubleValue } public func !=(lhs: Double, rhs: Number) -> Bool { return lhs != rhs.doubleValue } public func < (lhs: Double, rhs: Number) -> Bool { return lhs < rhs.doubleValue } public func > (lhs: Double, rhs: Number) -> Bool { return lhs > rhs.doubleValue } public func <=(lhs: Double, rhs: Number) -> Bool { return lhs <= rhs.doubleValue } public func >=(lhs: Double, rhs: Number) -> Bool { return lhs >= rhs.doubleValue }
lgpl-3.0
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/ManagedPerson.swift
1
4437
import Foundation import CoreData import WordPressKit public typealias Person = RemotePerson // MARK: - Reflects a Person, stored in Core Data // class ManagedPerson: NSManagedObject { func updateWith<T: Person>(_ person: T) { let canonicalAvatarURL = person.avatarURL.flatMap { Gravatar($0)?.canonicalURL } avatarURL = canonicalAvatarURL?.absoluteString displayName = person.displayName firstName = person.firstName lastName = person.lastName role = person.role siteID = Int64(person.siteID) userID = Int64(person.ID) linkedUserID = Int64(person.linkedUserID) username = person.username isSuperAdmin = person.isSuperAdmin kind = Int16(type(of: person).kind.rawValue) } func toUnmanaged() -> Person { switch Int(kind) { case PersonKind.user.rawValue: return User(managedPerson: self) case PersonKind.viewer.rawValue: return Viewer(managedPerson: self) case PersonKind.emailFollower.rawValue: return EmailFollower(managedPerson: self) default: return Follower(managedPerson: self) } } } // MARK: - Extensions // extension Person { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: managedPerson.role, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension User { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: managedPerson.role, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension Follower { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: RemoteRole.follower.slug, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension Viewer { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: RemoteRole.viewer.slug, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension EmailFollower { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: RemoteRole.follower.slug, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } }
gpl-2.0
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/Tab Navigation/ReaderTabView.swift
1
13906
import UIKit class ReaderTabView: UIView { private let mainStackView: UIStackView private let buttonsStackView: UIStackView private let tabBar: FilterTabBar private let filterButton: PostMetaButton private let resetFilterButton: UIButton private let horizontalDivider: UIView private let containerView: UIView private var loadingView: UIView? private let viewModel: ReaderTabViewModel private var filteredTabs: [(index: Int, topic: ReaderAbstractTopic)] = [] private var previouslySelectedIndex: Int = 0 private var discoverIndex: Int? { return tabBar.items.firstIndex(where: { ($0 as? ReaderTabItem)?.content.topicType == .discover }) } private var p2Index: Int? { return tabBar.items.firstIndex(where: { (($0 as? ReaderTabItem)?.content.topic as? ReaderTeamTopic)?.organizationID == SiteOrganizationType.p2.rawValue }) } init(viewModel: ReaderTabViewModel) { mainStackView = UIStackView() buttonsStackView = UIStackView() tabBar = FilterTabBar() filterButton = PostMetaButton(type: .custom) resetFilterButton = UIButton(type: .custom) horizontalDivider = UIView() containerView = UIView() self.viewModel = viewModel super.init(frame: .zero) viewModel.didSelectIndex = { [weak self] index in self?.tabBar.setSelectedIndex(index) self?.toggleButtonsView() } viewModel.onTabBarItemsDidChange { [weak self] tabItems, index in self?.tabBar.items = tabItems self?.tabBar.setSelectedIndex(index) self?.configureTabBarElements() self?.hideGhost() self?.addContentToContainerView() } setupViewElements() NotificationCenter.default.addObserver(self, selector: #selector(topicUnfollowed(_:)), name: .ReaderTopicUnfollowed, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(siteFollowed(_:)), name: .ReaderSiteFollowed, object: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI setup extension ReaderTabView { /// Call this method to set the title of the filter button private func setFilterButtonTitle(_ title: String) { WPStyleGuide.applyReaderFilterButtonTitle(filterButton, title: title) } private func setupViewElements() { backgroundColor = .filterBarBackground setupMainStackView() setupTabBar() setupButtonsView() setupFilterButton() setupResetFilterButton() setupHorizontalDivider(horizontalDivider) activateConstraints() } private func setupMainStackView() { mainStackView.translatesAutoresizingMaskIntoConstraints = false mainStackView.axis = .vertical addSubview(mainStackView) mainStackView.addArrangedSubview(tabBar) mainStackView.addArrangedSubview(buttonsStackView) mainStackView.addArrangedSubview(horizontalDivider) mainStackView.addArrangedSubview(containerView) } private func setupTabBar() { tabBar.tabBarHeight = Appearance.barHeight WPStyleGuide.configureFilterTabBar(tabBar) tabBar.addTarget(self, action: #selector(selectedTabDidChange(_:)), for: .valueChanged) viewModel.fetchReaderMenu() } private func configureTabBarElements() { guard let tabItem = tabBar.currentlySelectedItem as? ReaderTabItem else { return } previouslySelectedIndex = tabBar.selectedIndex buttonsStackView.isHidden = tabItem.shouldHideButtonsView horizontalDivider.isHidden = tabItem.shouldHideButtonsView } private func setupButtonsView() { buttonsStackView.translatesAutoresizingMaskIntoConstraints = false buttonsStackView.isLayoutMarginsRelativeArrangement = true buttonsStackView.axis = .horizontal buttonsStackView.alignment = .fill buttonsStackView.addArrangedSubview(filterButton) buttonsStackView.addArrangedSubview(resetFilterButton) buttonsStackView.isHidden = true } private func setupFilterButton() { filterButton.translatesAutoresizingMaskIntoConstraints = false filterButton.contentEdgeInsets = Appearance.filterButtonInsets filterButton.imageEdgeInsets = Appearance.filterButtonimageInsets filterButton.titleEdgeInsets = Appearance.filterButtonTitleInsets filterButton.contentHorizontalAlignment = .leading filterButton.titleLabel?.font = Appearance.filterButtonFont WPStyleGuide.applyReaderFilterButtonStyle(filterButton) setFilterButtonTitle(Appearance.defaultFilterButtonTitle) filterButton.addTarget(self, action: #selector(didTapFilterButton), for: .touchUpInside) filterButton.accessibilityIdentifier = Accessibility.filterButtonIdentifier } private func setupResetFilterButton() { resetFilterButton.translatesAutoresizingMaskIntoConstraints = false resetFilterButton.contentEdgeInsets = Appearance.resetButtonInsets WPStyleGuide.applyReaderResetFilterButtonStyle(resetFilterButton) resetFilterButton.addTarget(self, action: #selector(didTapResetFilterButton), for: .touchUpInside) resetFilterButton.isHidden = true resetFilterButton.accessibilityIdentifier = Accessibility.resetButtonIdentifier resetFilterButton.accessibilityLabel = Accessibility.resetFilterButtonLabel } private func setupHorizontalDivider(_ divider: UIView) { divider.translatesAutoresizingMaskIntoConstraints = false divider.backgroundColor = Appearance.dividerColor } private func addContentToContainerView() { guard let controller = self.next as? UIViewController, let childController = viewModel.makeChildContentViewController(at: tabBar.selectedIndex) else { return } containerView.translatesAutoresizingMaskIntoConstraints = false childController.view.translatesAutoresizingMaskIntoConstraints = false controller.children.forEach { $0.remove() } controller.add(childController) containerView.pinSubviewToAllEdges(childController.view) if viewModel.shouldShowCommentSpotlight { let title = NSLocalizedString("Comment to start making connections.", comment: "Hint for users to grow their audience by commenting on other blogs.") childController.displayNotice(title: title) } } private func activateConstraints() { pinSubviewToAllEdges(mainStackView) NSLayoutConstraint.activate([ buttonsStackView.heightAnchor.constraint(equalToConstant: Appearance.barHeight), resetFilterButton.widthAnchor.constraint(equalToConstant: Appearance.resetButtonWidth), horizontalDivider.heightAnchor.constraint(equalToConstant: Appearance.dividerWidth), horizontalDivider.widthAnchor.constraint(equalTo: mainStackView.widthAnchor) ]) } func applyFilter(for selectedTopic: ReaderAbstractTopic?) { guard let selectedTopic = selectedTopic else { return } let selectedIndex = self.tabBar.selectedIndex // Remove any filters for selected index, then add new filter to array. self.filteredTabs.removeAll(where: { $0.index == selectedIndex }) self.filteredTabs.append((index: selectedIndex, topic: selectedTopic)) self.resetFilterButton.isHidden = false self.setFilterButtonTitle(selectedTopic.title) } } // MARK: - Actions private extension ReaderTabView { /// Tab bar @objc func selectedTabDidChange(_ tabBar: FilterTabBar) { // If the tab was previously filtered, refilter it. // Otherwise reset the filter. if let existingFilter = filteredTabs.first(where: { $0.index == tabBar.selectedIndex }) { if previouslySelectedIndex == discoverIndex { // Reset the container view to show a feed's content. addContentToContainerView() } viewModel.setFilterContent(topic: existingFilter.topic) resetFilterButton.isHidden = false setFilterButtonTitle(existingFilter.topic.title) } else { addContentToContainerView() } previouslySelectedIndex = tabBar.selectedIndex viewModel.showTab(at: tabBar.selectedIndex) toggleButtonsView() } func toggleButtonsView() { guard let tabItems = tabBar.items as? [ReaderTabItem] else { return } // hide/show buttons depending on the selected tab. Do not execute the animation if not necessary. guard buttonsStackView.isHidden != tabItems[tabBar.selectedIndex].shouldHideButtonsView else { return } let shouldHideButtons = tabItems[self.tabBar.selectedIndex].shouldHideButtonsView self.buttonsStackView.isHidden = shouldHideButtons self.horizontalDivider.isHidden = shouldHideButtons } /// Filter button @objc func didTapFilterButton() { /// Present from the image view to align to the left hand side viewModel.presentFilter(from: filterButton.imageView ?? filterButton) { [weak self] selectedTopic in guard let self = self else { return } self.applyFilter(for: selectedTopic) } } /// Reset filter button @objc func didTapResetFilterButton() { filteredTabs.removeAll(where: { $0.index == tabBar.selectedIndex }) setFilterButtonTitle(Appearance.defaultFilterButtonTitle) resetFilterButton.isHidden = true guard let tabItem = tabBar.currentlySelectedItem as? ReaderTabItem else { return } viewModel.resetFilter(selectedItem: tabItem) } @objc func topicUnfollowed(_ notification: Foundation.Notification) { guard let userInfo = notification.userInfo, let topic = userInfo[ReaderNotificationKeys.topic] as? ReaderAbstractTopic, let existingFilter = filteredTabs.first(where: { $0.topic == topic }) else { return } filteredTabs.removeAll(where: { $0 == existingFilter }) if existingFilter.index == tabBar.selectedIndex { didTapResetFilterButton() } } @objc func siteFollowed(_ notification: Foundation.Notification) { guard let userInfo = notification.userInfo, let site = userInfo[ReaderNotificationKeys.topic] as? ReaderSiteTopic, site.organizationType == .p2, p2Index == nil else { return } // If a P2 is followed but the P2 tab is not in the Reader tab bar, // refresh the Reader menu to display it. viewModel.fetchReaderMenu() } } // MARK: - Ghost private extension ReaderTabView { /// Build the ghost tab bar func makeGhostTabBar() -> FilterTabBar { let ghostTabBar = FilterTabBar() ghostTabBar.items = Appearance.ghostTabItems ghostTabBar.isUserInteractionEnabled = false ghostTabBar.tabBarHeight = Appearance.barHeight ghostTabBar.dividerColor = .clear return ghostTabBar } /// Show the ghost tab bar func showGhost() { let ghostTabBar = makeGhostTabBar() tabBar.addSubview(ghostTabBar) tabBar.pinSubviewToAllEdges(ghostTabBar) loadingView = ghostTabBar ghostTabBar.startGhostAnimation(style: GhostStyle(beatDuration: GhostStyle.Defaults.beatDuration, beatStartColor: .placeholderElement, beatEndColor: .placeholderElementFaded)) } /// Hide the ghost tab bar func hideGhost() { loadingView?.stopGhostAnimation() loadingView?.removeFromSuperview() loadingView = nil } struct GhostTabItem: FilterTabBarItem { var title: String let accessibilityIdentifier = "" } } // MARK: - Appearance private extension ReaderTabView { enum Appearance { static let barHeight: CGFloat = 48 static let tabBarAnimationsDuration = 0.2 static let defaultFilterButtonTitle = NSLocalizedString("Filter", comment: "Title of the filter button in the Reader") static let filterButtonMaxFontSize: CGFloat = 28.0 static let filterButtonFont = WPStyleGuide.fontForTextStyle(.headline, fontWeight: .regular) static let filterButtonInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) static let filterButtonimageInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) static let filterButtonTitleInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0) static let resetButtonWidth: CGFloat = 32 static let resetButtonInsets = UIEdgeInsets(top: 1, left: -4, bottom: -1, right: 4) static let dividerWidth: CGFloat = .hairlineBorderWidth static let dividerColor: UIColor = .divider // "ghost" titles are set to the default english titles, as they won't be visible anyway static let ghostTabItems = [GhostTabItem(title: "Following"), GhostTabItem(title: "Discover"), GhostTabItem(title: "Likes"), GhostTabItem(title: "Saved")] } } // MARK: - Accessibility extension ReaderTabView { private enum Accessibility { static let filterButtonIdentifier = "ReaderFilterButton" static let resetButtonIdentifier = "ReaderResetButton" static let resetFilterButtonLabel = NSLocalizedString("Reset filter", comment: "Accessibility label for the reset filter button in the reader.") } }
gpl-2.0
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Index/Index+Settings.swift
1
3685
// // Index+Settings.swift // // // Created by Vladislav Fitc on 03/03/2020. // import Foundation public extension Index { // MARK: - Get Settings /** Get the Settings of an index. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Async operation */ @discardableResult func getSettings(requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<Settings>) -> Operation & TransportTask { let command = Command.Settings.GetSettings(indexName: name, requestOptions: requestOptions) return execute(command, completion: completion) } /** Get the Settings of an index. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Settings object */ func getSettings(requestOptions: RequestOptions? = nil) throws -> Settings { let command = Command.Settings.GetSettings(indexName: name, requestOptions: requestOptions) return try execute(command) } // Set settings /** Create or change an index’s Settings. Only non-null settings are overridden; null settings are left unchanged Performance wise, it’s better to setSettings before pushing the data. - Parameter settings: The Settings to be set. - Parameter resetToDefault: Reset a settings to its default value. - Parameter forwardToReplicas: Whether to forward the same settings to the replica indices. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Async operation */ @discardableResult func setSettings(_ settings: Settings, resetToDefault: [Settings.Key] = [], forwardToReplicas: Bool? = nil, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask { let command = Command.Settings.SetSettings(indexName: name, settings: settings, resetToDefault: resetToDefault, forwardToReplicas: forwardToReplicas, requestOptions: requestOptions) return execute(command, completion: completion) } /** Create or change an index’s Settings. Only non-null settings are overridden; null settings are left unchanged Performance wise, it’s better to setSettings before pushing the data. - Parameter settings: The Settings to be set. - Parameter resetToDefault: Reset a settings to its default value. - Parameter forwardToReplicas: Whether to forward the same settings to the replica indices. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: RevisionIndex object */ @discardableResult func setSettings(_ settings: Settings, resetToDefault: [Settings.Key] = [], forwardToReplicas: Bool? = nil, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> { let command = Command.Settings.SetSettings(indexName: name, settings: settings, resetToDefault: resetToDefault, forwardToReplicas: forwardToReplicas, requestOptions: requestOptions) return try execute(command) } }
mit
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/About/Settings/SettingsViewController.swift
1
5881
// // SettingsViewController.swift // EclipseSoundscapes // // Created by Arlindo Goncalves on 7/18/17. // // Copyright © 2017 Arlindo Goncalves. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see [http://www.gnu.org/licenses/]. // // For Contact email: arlindo@eclipsesoundscapes.org import Eureka import RxSwift import RxCocoa class SettingsViewController: BaseViewController, TypedRowControllerType, UITableViewDelegate, UITableViewDataSource { var row: RowOf<String>! var onDismissCallback: ((UIViewController) -> Void)? lazy var headerView : ShrinkableHeaderView = { let view = ShrinkableHeaderView(title: localizedString(key: "SettingsHeaderTitle"), titleColor: .black) view.backgroundColor = SoundscapesColor.NavBarColor view.maxHeaderHeight = 60 view.isShrinkable = false return view }() lazy var backBtn : UIButton = { var btn = UIButton(type: .system) btn.addSqueeze() btn.setImage(#imageLiteral(resourceName: "left-small").withRenderingMode(.alwaysTemplate), for: .normal) btn.tintColor = .black btn.addTarget(self, action: #selector(close), for: .touchUpInside) btn.accessibilityLabel = localizedString(key: "Back") return btn }() private let tableView = UITableView(frame: .zero, style: .grouped) private let disposeBag = DisposeBag() private let viewModel = SettingsViewModel() override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { setupViews() setupTableView() setupViewModel() } private func setupViews() { view.backgroundColor = headerView.backgroundColor view.addSubviews(headerView, tableView) headerView.headerHeightConstraint = headerView.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: headerView.maxHeaderHeight).last headerView.addSubviews(backBtn) backBtn.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true backBtn.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: 10).isActive = true tableView.anchorWithConstantsToTop(headerView.bottomAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0) } private func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.register(ToggleCell.self, forCellReuseIdentifier: ToggleCell.identifier) tableView.register(LanguageCell.self, forCellReuseIdentifier: LanguageCell.identifier) tableView.register(TextHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: TextHeaderFooterView.identifier) tableView.tableFooterView = UIView() tableView.estimatedSectionHeaderHeight = 60 } private func setupViewModel() { viewModel.showAlertSignal .emit(to: rx.presentAlert(preferredStyle: .alert)) .disposed(by: disposeBag) } func numberOfSections(in tableView: UITableView) -> Int { return viewModel.sectionCount } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.getSettingsSection(for: section)?.itemCount ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let item = viewModel.getSettingsSection(for: indexPath.section)?.getItem(at: indexPath.row) else { fatalError("No Setting at at indexPath: \(indexPath)") } let cell = tableView.dequeueReusableCell(withIdentifier: item.cellIdentifier, for: indexPath) if let cell = cell as? SettingCell { cell.configure(with: item) } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let section = viewModel.getSettingsSection(for: section) as? SettingsHeaderSection else { return nil } let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: section.headerIdentifier) if let textHeaderSection = section as? SettingTextHeaderSection { guard let textHeader = view as? TextHeaderFooterView else { return nil } textHeader.configure(with: textHeaderSection.headerText) } return view } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let section = viewModel.getSettingsSection(for: section) as? SettingsFooterSection else { return nil } let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: section.footerIdentifier) if let textFooterSection = section as? SettingTextFooterSection { guard let textHeader = view as? TextHeaderFooterView else { return nil } textHeader.configure(with: textFooterSection.footerText) } return view } @objc private func close() { self.dismiss(animated: true, completion: nil) } }
gpl-3.0
GermanCentralLibraryForTheBlind/LargePrintMusicNotes
LargePrintMusicNotesViewer/AppDelegate.swift
1
7478
// Created by Lars Voigt. // //The MIT License (MIT) //Copyright (c) 2016 German Central Library for the Blind (DZB) //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] UIBarButtonItem.appearance().tintColor = UIColor.white UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().tintColor = UIColor.white return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "de.lv.LargePrintMusicNotesViewer" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "LargePrintMusicNotesViewer", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
DesignatedInitializer/XcodeProjectTemplates
Swift framework without dependencies/PROJECT_TEMPLATE/PRODUCT_PLACEHOLDER iOS Example/Sources/FirstViewController.swift
1
346
// // FirstViewController.swift // PRODUCT_PLACEHOLDER iOS Example // // Created by AUTHOR_PLACEHOLDER on DATE_PLACEHOLDER. // Copyright (c) YEAR_PLACEHOLDER ORGANIZATION_PLACEHOLDER. All rights reserved. // import UIKit class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
mit
finder39/Swimgur
SWNetworking/Comment.swift
1
1981
// // Comment.swift // Swimgur // // Created by Joseph Neuman on 11/2/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation public class Comment { public var id: Int! public var imageID: String? public var comment: String? public var author: String? public var authorID: String? public var onAlbum: Bool? public var albumCover: String? public var ups: Int? public var downs: Int? public var points: Int? public var datetime: Int = 0 public var parentID: String? public var deleted: Bool? public var vote: String? public var children: [Comment] = [] // expansion management in table public var expanded = false public var depth = 0 public init(dictionary:Dictionary<String, AnyObject>, depth theDepth:Int) { id = dictionary["id"] as AnyObject! as Int! imageID = dictionary["image_id"] as AnyObject? as? String comment = dictionary["comment"] as AnyObject? as? String author = dictionary["author"] as AnyObject? as? String authorID = dictionary["author_id"] as AnyObject? as? String onAlbum = dictionary["on_album"] as AnyObject? as? Bool albumCover = dictionary["album_cover"] as AnyObject? as? String ups = dictionary["ups"] as AnyObject? as? Int downs = dictionary["downs"] as AnyObject? as? Int points = dictionary["points"] as AnyObject? as? Int datetime = dictionary["datetime"] as AnyObject! as Int! parentID = dictionary["parent_id"] as AnyObject? as? String deleted = dictionary["deleted"] as AnyObject? as? Bool vote = dictionary["vote"] as AnyObject? as? String depth = theDepth if let children = (dictionary["children"] as AnyObject?) as? [Dictionary<String, AnyObject>] { for child in children { self.children.append(Comment(dictionary: child, depth:depth+1)) } } } public convenience init(dictionary:Dictionary<String, AnyObject>) { self.init(dictionary: dictionary, depth:0) } }
mit
Kiandr/CrackingCodingInterview
Swift/Ch 15. Threads and Locks/Ch 15. Threads and Locks.playground/Pages/15.3 Dining Philoslophers.xcplaygroundpage/Contents.swift
1
4725
import Foundation /*: 15.3 Dining Philosophers: In the famouse dining philosophers problem, a bunch of philosophers are sitting around a circular table with one chopstick between them. A philosopher needs both chopsticks to eat and always picks up the left chopstick before the right one. A deadlock could potentially occur if all of the philosophers reached for the left chopstick at the same time. Using threads and locks, implement a simulation of the dining philosophers problem that prevents deadlock. */ struct Fork { let number: Int fileprivate var _state = State.Initial let serialQueue = DispatchQueue(label: "Fork") enum State { case Initial case InUse case Free } init(number: Int) { self.number = number } } extension Fork: CustomStringConvertible { var state: State { get { var state = State.Initial serialQueue.sync { state = self._state } return state } set(newState) { serialQueue.sync { self._state = newState } } } var description: String { return "fork \(number) state \(state)" } } final class PhilosopherOp: Operation { let philosopher: String fileprivate(set) var _state = State.Initial fileprivate(set) var left: Fork fileprivate(set) var right: Fork fileprivate let serialQueue = DispatchQueue(label: "Operation") enum State { case Initial case Thinking case Eating } init(name: String, left: Fork, right: Fork) { self.philosopher = name self.left = left self.right = right } } extension PhilosopherOp { func usLeft() { left.state = .InUse updateState() } func useRight() { right.state = .InUse updateState() } func useBoth() { left.state = .InUse right.state = .InUse updateState() } func wait() { right.state = .Free left.state = .Free updateState() } private func updateState() { guard case left.state = Fork.State.InUse, case right.state = Fork.State.InUse else { return state = .Thinking } state = .Eating } override var isExecuting: Bool { return _state == .Eating } override var isFinished: Bool { return false } fileprivate var state: State { get { var state = State.Initial serialQueue.sync { state = self._state } return state } set(newState) { serialQueue.sync { self._state = newState } } } override var description: String { return "\(philosopher): state = \(state) left = \(left), right = \(right)" } } func runPhilosophers(philosophers: [PhilosopherOp], forks: [Fork]) { precondition(forks.count == philosophers.count, "number of forks must equal number of philosophers") let operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = forks.count / 2 operationQueue.addOperations(philosophers, waitUntilFinished: false) var philosophers = philosophers var eatingPhilosphers = [PhilosopherOp]() let useRight: (PhilosopherOp) -> () = { p in p.useRight() } let useLeft: (PhilosopherOp) -> () = { p in p.usLeft() } let useBoth: (PhilosopherOp) -> () = { p in p.useBoth() } let wait: (PhilosopherOp) -> () = { p in p.wait() } let funcs = [useRight, useLeft, wait, useBoth, wait] for _ in 0..<forks.count { eatingPhilosphers.forEach { p in p.wait() } eatingPhilosphers.removeAll() funcs.enumerated().forEach { i, f in f(philosophers[i]) } philosophers.forEach { p in if p.state == .Eating { eatingPhilosphers.append(p) } } philosophers.forEach { p in print("\(p)") } let p = philosophers.remove(at: 0) philosophers.append(p) } } let forkCount = 5 var forks = (0..<forkCount).map { Fork(number: $0) } var philosopherNames = ["b", "c", "d", "e"] let firstPhilosopher = PhilosopherOp(name: "a", left: forks[0], right: forks.last!) var philosophers = [firstPhilosopher] for (i, _) in philosopherNames.enumerated() { let philosopher = PhilosopherOp(name: philosopherNames[i], left: forks[i + 1], right: forks[i]) philosophers.append(philosopher) } runPhilosophers(philosophers: philosophers, forks: forks)
mit
alexey-kubas-appus/ADPPhotoPicker
Example/ADPPhotoPicker/ViewController.swift
1
624
// // ViewController.swift // ADPPhotoPicker // // Created by /Users/dmitry.pashinskiy/Desktop/ForFrameworks/Example/.git/config on 11/07/2015. // Copyright (c) 2015 /Users/dmitry.pashinskiy/Desktop/ForFrameworks/Example/.git/config. 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. } }
mit
milseman/swift
stdlib/public/core/Zip.swift
8
5446
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Creates a sequence of pairs built out of two underlying sequences. /// /// In the `Zip2Sequence` instance returned by this function, the elements of /// the *i*th pair are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the two sequences passed to `zip(_:_:)` are different lengths, the /// resulting sequence is the same length as the shorter sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The first sequence or collection to zip. /// - sequence2: The second sequence or collection to zip. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. public func zip<Sequence1, Sequence2>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2) } /// An iterator for `Zip2Sequence`. public struct Zip2Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Iterator1.Element, Iterator2.Element) /// Creates an instance around a pair of underlying iterators. internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip2Sequence` instance, /// use the `zip(_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> : Sequence { @available(*, deprecated, renamed: "Sequence1.Iterator") public typealias Stream1 = Sequence1.Iterator @available(*, deprecated, renamed: "Sequence2.Iterator") public typealias Stream2 = Sequence2.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip2Iterator<Sequence1.Iterator, Sequence2.Iterator> @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 } extension Zip2Sequence { @available(*, unavailable, message: "use zip(_:_:) free function instead") public init(_ sequence1: Sequence1, _ sequence2: Sequence2) { Builtin.unreachable() } }
apache-2.0