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
peferron/algo
EPI/Parallel Computing/The readers-writers problem/swift/test.swift
1
511
if #available(OSX 10.10, *) { var expected = 1 for _ in 0...50000 { if arc4random_uniform(2) == 0 { write() expected += 1 } else { read() } } concurrentQueue.sync(execute: DispatchWorkItem(qos: .default, flags: .barrier) { guard data == expected else { print("Expected data to be \(expected), but was \(data)") exit(1) } }) } else { print("Requires OS X 10.10 or newer") exit(1) }
mit
younata/X
X/GestureRecognizer.swift
1
446
// // GestureRecognizer.swift // X // // Created by Sam Soffes on 4/28/15. // Copyright (c) 2015 Sam Soffes. All rights reserved. // #if os(iOS) import UIKit.UIGestureRecognizer public typealias GestureRecognizerStateType = UIGestureRecognizerState #else import AppKit.NSGestureRecognizer public typealias GestureRecognizerStateType = NSGestureRecognizerState #endif public typealias GestureRecognizerState = GestureRecognizerStateType
mit
coppercash/Anna
CoreJS/Module.swift
1
5749
// // Module.swift // Anna_iOS // // Created by William on 2018/6/27. // import Foundation import JavaScriptCore class Module { let fileManager :FileManaging, core :Set<String>, global :Set<URL> init( fileManager :FileManaging, core :Set<String>, global :Set<URL> ) { self.fileManager = fileManager self.core = core self.global = global } func resolve( x :String, from module :URL? ) throws -> String { let core = self.core if core.contains(x) { return x } // // x is not a core module let isAbsolute = x.hasPrefix("/"), base :URL if isAbsolute { base = URL(fileURLWithPath: "/") } else { guard let module = module else { throw ResolveError.noBase } base = module } guard isAbsolute || x.hasPrefix("./") || x.hasPrefix("../") else { let resolved = try self.resolve( nodeModule: x, with: base.deletingLastPathComponent() ).standardized.path return resolved } // // x is not a node module let absolute = base.appendingPathComponent( isAbsolute ? String(x.dropFirst()) : x ) guard let resolved = (try? self.resolve(file: absolute)) ?? (try? self.resolve(directory: absolute)) else { throw ResolveError.notFound } return resolved.standardized.path } func resolve( file :URL ) throws -> URL { let fs = self.fileManager var isDirecotry = false as ObjCBool if fs.fileExists( atPath: file.path, isDirectory: &isDirecotry ) { if isDirecotry.boolValue == false { return file } } return try self.resolve( file: file, extending: ["js", "json", "node"] ) } func resolve( file :URL, extending extensions:[String] ) throws -> URL { let fs = self.fileManager for ext in extensions { let extended = file.appendingPathExtension(ext) var isDirecotry = false as ObjCBool if fs.fileExists( atPath: extended.path, isDirectory: &isDirecotry ) { if isDirecotry.boolValue == false { return extended } } } throw ResolveError.notFound } func resolve( directory :URL ) throws -> URL { return try self.resolveIndex(in: directory) } func resolveIndex( in directory :URL ) throws -> URL { return try self.resolve( file: directory.appendingPathComponent("index"), extending: ["js", "json", "node"] ) } func resolve( nodeModule :String, with start :URL ) throws -> URL { let dirs = self.nodeModulesPaths(with: start) for dir in dirs { let absolute = dir.appendingPathComponent(nodeModule) if let resolved = (try? resolve(file: absolute)) ?? (try? resolve(directory: absolute)) { return resolved } } throw ResolveError.notFound } func nodeModulesPaths( with start :URL ) -> [URL] { var paths = Array(self.global) func _backtrack( _ current :URL, _ paths : inout [URL] ) { let tail = current.lastPathComponent guard tail != "/" else { return } if tail != "node_modules" { paths.append(current.appendingPathComponent("node_modules")) } _backtrack( current.deletingLastPathComponent(), &paths ) } _backtrack(start, &paths) return paths } func loadScript( at url :URL, to context :JSContext, exports :JSValue, require :JSValue, module :JSValue ) { let fs = self.fileManager, path = url.path guard let data = fs.contents(atPath: path), let script = String(data: data, encoding: .utf8) else { context.exception = JSValue( newErrorFromMessage: "Cannot read file at path \(path)!).", in: context ) return } let decorated = String(format: (""" (function () { return ( function (exports, require, module, __filename, __dirname) { %@ } ); })(); """), script) let _ = context .evaluateScript( decorated, withSourceURL: url ) .call(withArguments: [ exports, require, module, path, url.deletingLastPathComponent().path ] ) } } enum ResolveError : Error { case noBase, notFound } extension String { func fileURL() -> URL { return URL(fileURLWithPath: self) } }
mit
wireapp/wire-ios-sync-engine
Source/UserSession/ZMUserSession+SecurityClassification.swift
1
1606
// // Wire // Copyright (C) 2022 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 Foundation public enum SecurityClassification { case none case classified case notClassified } extension ZMUserSession { public func classification(with users: [UserType]) -> SecurityClassification { guard isSelfClassified else { return .none } let isClassified = users.allSatisfy { classification(with: $0) == .classified } return isClassified ? .classified : .notClassified } private func classification(with user: UserType) -> SecurityClassification { guard isSelfClassified else { return .none } guard let otherDomain = user.domain else { return .notClassified } return classifiedDomainsFeature.config.domains.contains(otherDomain) ? .classified : .notClassified } private var isSelfClassified: Bool { classifiedDomainsFeature.status == .enabled && selfUser.domain != nil } }
gpl-3.0
benlangmuir/swift
test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift
14
2763
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]OySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5Value[[UNIQUE_ID_1]]OySiGWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 513, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.*}}$s4main5Value[[UNIQUE_ID_1]]OMn{{.*}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] fileprivate enum Value<First> { case first(First) } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main5Value[[UNIQUE_ID_1]]OySiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Value.first(13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]OMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE]], // CHECK-SAME: i8* undef, // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main5Value[[UNIQUE_ID_1]]OMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
delba/JASON
Source/JSON.swift
1
4571
// // JSON.swift // // Copyright (c) 2015-2019 Damien (http://delba.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. // import Foundation // MARK: - Initializers public struct JSON { /// The date formatter used for date conversions public static var dateFormatter = DateFormatter() /// The object on which any subsequent method operates public let object: AnyObject? /** Creates an instance of JSON from AnyObject. - parameter object: An instance of any class - returns: the created JSON */ public init(_ object: Any?) { self.init(object: object) } /** Creates an instance of JSON from NSData. - parameter data: An instance of NSData - returns: the created JSON */ public init(_ data: Data?) { self.init(object: JSON.objectWithData(data)) } /** Creates an instance of JSON from a string. - parameter data: A string - returns: the created JSON */ public init(_ string: String?) { self.init(string?.data(using: String.Encoding.utf8)) } /** Creates an instance of JSON from AnyObject. Takes an explicit parameter name to prevent calls to init(_:) with NSData? when nil is passed. - parameter object: An instance of any class - returns: the created JSON */ internal init(object: Any?) { self.object = object as AnyObject? } } // MARK: - Subscript extension JSON { /** Creates a new instance of JSON. - parameter index: A string - returns: a new instance of JSON or itself if its object is nil. */ public subscript(index: String) -> JSON { if object == nil { return self } if let nsDictionary = nsDictionary { return JSON(nsDictionary[index]) } return JSON(object: nil) } /** Creates a new instance of JSON. - parameter index: A string - returns: a new instance of JSON or itself if its object is nil. */ public subscript(index: Int) -> JSON { if object == nil { return self } if let nsArray = nsArray { return JSON(nsArray[safe: index]) } return JSON(object: nil) } /** Creates a new instance of JSON. - parameter indexes: Any - returns: a new instance of JSON or itself if its object is nil */ public subscript(path indexes: Any...) -> JSON { return self[indexes] } internal subscript(indexes: [Any]) -> JSON { if object == nil { return self } var json = self for index in indexes { if let string = index as? String, let object = json.nsDictionary?[string] { json = JSON(object) continue } if let int = index as? Int, let object = json.nsArray?[safe: int] { json = JSON(object) continue } else { json = JSON(object: nil) break } } return json } } // MARK: - Private extensions private extension JSON { /** Converts an instance of NSData to AnyObject. - parameter data: An instance of NSData or nil - returns: An instance of AnyObject or nil */ static func objectWithData(_ data: Data?) -> Any? { guard let data = data else { return nil } return try? JSONSerialization.jsonObject(with: data) } }
mit
thedanpan/Perspective
Perspective/Perspective/AppDelegate.swift
2
2833
// // AppDelegate.swift // Perspective // // Created by Apprentice on 2/13/15. // Copyright (c) 2015 Dev Bootcamp. 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. Parse.setApplicationId("", clientKey: "") let credentialsProvider = AWSCognitoCredentialsProvider.credentialsWithRegionType( AWSRegionType.USEast1, accountId: "", identityPoolId: "", unauthRoleArn: "", authRoleArn: "") let defaultServiceConfiguration = AWSServiceConfiguration( region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider) AWSServiceManager.defaultServiceManager().setDefaultServiceConfiguration(defaultServiceConfiguration) let dash = DashboardVC() let navController = UINavigationController(rootViewController: dash) 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
tiagomartinho/webhose-cocoa
webhose-cocoa/WebhoseTests/OHHTTPStubsSwift.swift
1
6731
// swiftlint:disable line_length /*********************************************************************************** * * Copyright (c) 2012 Olivier Halligon * * 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. * ***********************************************************************************/ /** * Swift Helpers */ import OHHTTPStubs // MARK: Syntaxic Sugar for OHHTTPStubs /** * Helper to return a `OHHTTPStubsResponse` given a fixture path, status code and optional headers. * * - Parameter filePath: the path of the file fixture to use for the response * - Parameter status: the status code to use for the response * - Parameter headers: the HTTP headers to use for the response * * - Returns: The `OHHTTPStubsResponse` instance that will stub with the given status code * & headers, and use the file content as the response body. */ public func fixture(_ filePath: String, status: Int32 = 200, headers: [AnyHashable: Any]?) -> OHHTTPStubsResponse { return OHHTTPStubsResponse(fileAtPath: filePath, statusCode: status, headers: headers) } /** * Helper to call the stubbing function in a more concise way? * * - Parameter condition: the matcher block that determine if the request will be stubbed * - Parameter response: the stub reponse to use if the request is stubbed * * - Returns: The opaque `OHHTTPStubsDescriptor` that uniquely identifies the stub * and can be later used to remove it with `removeStub:` */ public func stub(_ condition: @escaping OHHTTPStubsTestBlock, response: @escaping OHHTTPStubsResponseBlock) -> OHHTTPStubsDescriptor { return OHHTTPStubs.stubRequests(passingTest: condition, withStubResponse: response) } // MARK: Create OHHTTPStubsTestBlock matchers /** * Matcher for testing an `NSURLRequest`'s **scheme**. * * - Parameter scheme: The scheme to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has the given scheme */ public func isScheme(_ scheme: String) -> OHHTTPStubsTestBlock { return { req in req.url?.scheme == scheme } } /** * Matcher for testing an `NSURLRequest`'s **host**. * * - Parameter host: The host to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has the given host */ public func isHost(_ host: String) -> OHHTTPStubsTestBlock { return { req in req.url?.host == host } } /** * Matcher for testing an `NSURLRequest`'s **path**. * * - Parameter path: The path to match * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request * has exactly the given path * * - Note: URL paths are usually absolute and thus starts with a '/' (which you * should include in the `path` parameter unless you're testing relative URLs) */ public func isPath(_ path: String) -> OHHTTPStubsTestBlock { return { req in req.url?.path == path } } /** * Matcher for testing an `NSURLRequest`'s **path extension**. * * - Parameter ext: The file extension to match (without the dot) * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds only if the request path * ends with the given extension */ public func isExtension(_ ext: String) -> OHHTTPStubsTestBlock { return { req in req.url?.pathExtension == ext } } /** * Matcher for testing an `NSURLRequest`'s **query parameters**. * * - Parameter params: The dictionary of query parameters to check the presence for * * - Returns: a matcher (OHHTTPStubsTestBlock) that succeeds if the request contains * the given query parameters with the given value. * * - Note: There is a difference between: * (1) using `[q:""]`, which matches a query parameter "?q=" with an empty value, and * (2) using `[q:nil]`, which matches a query parameter "?q" without a value at all */ @available(iOS 8.0, OSX 10.10, *) public func containsQueryParams(_ params: [String:String?]) -> OHHTTPStubsTestBlock { return { req in if let url = req.url { let comps = URLComponents(url: url, resolvingAgainstBaseURL: true) if let queryItems = comps?.queryItems { for (k, v) in params { if queryItems.filter({ qi in qi.name == k && qi.value == v }).count == 0 { return false } } return true } } return false } } // MARK: Operators on OHHTTPStubsTestBlock /** * Combine different `OHHTTPStubsTestBlock` matchers with an 'OR' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`OHHTTPStubsTestBlock`) that succeeds if either of the given matchers succeeds */ public func || (lhs: @escaping OHHTTPStubsTestBlock, rhs: @escaping OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in lhs(req) || rhs(req) } } /** * Combine different `OHHTTPStubsTestBlock` matchers with an 'AND' operation. * * - Parameter lhs: the first matcher to test * - Parameter rhs: the second matcher to test * * - Returns: a matcher (`OHHTTPStubsTestBlock`) that only succeeds if both of the given matchers succeeds */ public func && (lhs: @escaping OHHTTPStubsTestBlock, rhs: @escaping OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in lhs(req) && rhs(req) } } /** * Create the opposite of a given `OHHTTPStubsTestBlock` matcher. * * - Parameter expr: the matcher to negate * * - Returns: a matcher (OHHTTPStubsTestBlock) that only succeeds if the expr matcher fails */ public prefix func ! (expr: @escaping OHHTTPStubsTestBlock) -> OHHTTPStubsTestBlock { return { req in !expr(req) } } // swiftlint:enable line_length
mit
wireapp/wire-ios
Wire-iOS/Sources/Authentication/Delegates/AuthenticationCoordinatedViewController.swift
1
1768
// 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 Foundation /** * Actions that can be performed by the view controllers when authentication fails. */ enum AuthenticationErrorFeedbackAction: Int { /// The view should display a guidance dot to indicate user input is invalid. case showGuidanceDot /// The view should clear the input fields. case clearInputFields } /// A view controller that is managed by an authentication coordinator. protocol AuthenticationCoordinatedViewController: AnyObject { /// The object that coordinates authentication. var authenticationCoordinator: AuthenticationCoordinator? { get set } /// The view controller should execute the action to indicate authentication failure. /// /// - Parameter feedbackAction: The action to execute to provide feedback to the user. func executeErrorFeedbackAction(_ feedbackAction: AuthenticationErrorFeedbackAction) /// The view controller should display information about the specified error. /// /// - Parameter error: The error to present to the user. func displayError(_ error: Error) }
gpl-3.0
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Components/Controllers/DigitalSignatureVerificationViewController.swift
1
4130
// // 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 UIKit import Foundation import WebKit import WireUtilities // MARK: - Error states public enum DigitalSignatureVerificationError: Error { case postCodeRetry case authenticationFailed case otherError } class DigitalSignatureVerificationViewController: UIViewController { typealias DigitalSignatureCompletion = ((_ result: VoidResult) -> Void) // MARK: - Private Property private var completion: DigitalSignatureCompletion? private var webView = WKWebView(frame: .zero) private var url: URL? // MARK: - Init init(url: URL, completion: DigitalSignatureCompletion? = nil) { self.url = url self.completion = completion super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupWebView() loadURL() } // MARK: - Private Method private func setupWebView() { webView.translatesAutoresizingMaskIntoConstraints = false webView.navigationDelegate = self updateButtonMode() view.addSubview(webView) webView.fitIn(view: view) } private func updateButtonMode() { let buttonItem = UIBarButtonItem(title: "general.done".localized, style: .done, target: self, action: #selector(onClose)) buttonItem.accessibilityIdentifier = "DoneButton" buttonItem.accessibilityLabel = "general.done".localized buttonItem.tintColor = UIColor.black navigationItem.leftBarButtonItem = buttonItem } private func loadURL() { guard let url = url else { return } let request = URLRequest(url: url) webView.load(request) } @objc private func onClose() { dismiss(animated: true, completion: nil) } } // MARK: - WKNavigationDelegate extension DigitalSignatureVerificationViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url, let response = parseVerificationURL(url) else { decisionHandler(.allow) return } switch response { case .success: completion?(.success) decisionHandler(.cancel) case .failure(let error): completion?(.failure(error)) decisionHandler(.cancel) } } func parseVerificationURL(_ url: URL) -> VoidResult? { let urlComponents = URLComponents(string: url.absoluteString) let postCode = urlComponents?.queryItems? .first(where: { $0.name == "postCode" }) guard let postCodeValue = postCode?.value else { return nil } switch postCodeValue { case "sas-success": return .success case "sas-error-authentication-failed": return .failure(DigitalSignatureVerificationError.authenticationFailed) default: return .failure(DigitalSignatureVerificationError.otherError) } } }
gpl-3.0
sachin004/firefox-ios
Utils/Extensions/ArrayExtensions.swift
8
855
/* 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 public extension Array { // Laughably inefficient, but good enough for a handful of items. func sameElements(arr: [Element], f: (Element, Element) -> Bool) -> Bool { return self.count == arr.count && every { arr.contains($0, f: f) } } func contains(x: Element, f: (Element, Element) -> Bool) -> Bool { for y in self { if f(x, y) { return true } } return false } func every(f: (Element) -> Bool) -> Bool { for x in self { if !f(x) { return false } } return true } }
mpl-2.0
sashakid/Chickens
Source/Chickens/Helpers/PriceService.swift
1
2658
// // PriceService.swift // Chickens // // Created by Aleksey Gorbachevskiy on 21/03/17. // Copyright © 2017 Alexander Yakovlev. All rights reserved. // import UIKit import Money final class PriceService { static let shared: PriceService = PriceService() var price: Money { get { if let numberPrice = settings!.value(forKey: "Price") as? Double { return Money(numberPrice) } else { return 0 } } set { settings?["Price"] = newValue } } private var settings: NSMutableDictionary? { get { if let path = Bundle.main.path(forResource: "Settings", ofType: "plist") { if let dict = NSMutableDictionary(contentsOfFile: path) { return dict } } return nil } } func updatePrice() { if let url = URL.init(string:"https://e-dostavka.by/catalog/item_440852.html") { if let data = NSData.init(contentsOf: url) { let doc = TFHpple(htmlData: data as Data!) if let elements = doc?.search(withXPathQuery: "//div[@class='right']/div[@class='services_wrap']/div[@class='prices_block']/div[@class='price_byn']/div[@class='price']") as? [TFHppleElement] { for element in elements { let components = element.content.components(separatedBy:".") var stringPrice = "" for (i, component) in components.enumerated() { if let newComponent = Int(component.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")) { if component.characters.count > 0 { switch i { case 0: stringPrice.append("\(newComponent).") case 1: stringPrice.append("\(newComponent)") default: break } } } } price = Money(Double(stringPrice)!) //print("[PriceService]: \(price.formatted(withStyle: .currencyPlural, forLocale: .Belarusian))") print("[PriceService]: \(price.decimal)") } } } } } }
mit
BlenderSleuth/Unlokit
Unlokit/Nodes/Blocks/GlueBlockNode.swift
1
6036
// // GlueBlockNode.swift // Unlokit // // Created by Ben Sutherland on 25/1/17. // Copyright © 2017 blendersleuthdev. All rights reserved. // import SpriteKit class GlueBlockNode: BlockNode { weak var gameScene: GameScene! // Side that are connected var connected: [Side : Bool] = [.up: false, .down: false, .left: false, .right: false, .centre: false] #if DEBUG var circles = [SKShapeNode]() #endif required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) physicsBody?.categoryBitMask = Category.gluBlock physicsBody?.collisionBitMask = Category.all ^ Category.tools if physicsBody!.isDynamic { physicsBody?.fieldBitMask = Category.fields } } override func setup(scene: GameScene) { super.setup(scene: scene) gameScene = scene checkConnected() } func checkConnected() { for child in children { // Modify connected array to include pre-added nodes let side: Side switch child.position { case up: connected[.up] = true side = .up case down: connected[.down] = true side = .down case left: connected[.left] = true side = .left case right: connected[.right] = true side = .right case centre: // For gravity connected[.centre] = true side = .centre default: print("Couldn't find side at \(child.position)") continue } if child.name == "fanPlaceholder" && side != .centre { // Make sure connected side is false connected[side] = false // Get fan node from file let fanNode = SKNode(fileNamed: "FanRef")?.children.first as! FanNode fanNode.removeFromParent() if add(node: fanNode, to: side) { // Fan setup after it has been added fanNode.setup(scene: gameScene, block: self, side: side) // Removes the placeholder child.removeFromParent() } } } // Detect blocks around so as to remove the possiblity of a fan inbetween blocks let rect = CGRect(origin: frame.origin, size: frame.size) var transform = CGAffineTransform(translationX: 0, y: frame.height) let pathUp = CGPath(rect: rect, transform: &transform) let regionUp = SKRegion(path: pathUp) transform = CGAffineTransform(translationX: 0, y: -frame.height) let pathDown = CGPath(rect: rect, transform: &transform) let regionDown = SKRegion(path: pathDown) transform = CGAffineTransform(translationX: -frame.height, y: 0) let pathLeft = CGPath(rect: rect, transform: &transform) let regionLeft = SKRegion(path: pathLeft) transform = CGAffineTransform(translationX: frame.height, y: 0) let pathRight = CGPath(rect: rect, transform: &transform) let regionRight = SKRegion(path: pathRight) gameScene.enumerateChildNodes(withName: "//*Block") { child, _ in if child is SKSpriteNode { let position = self.parent!.convert(child.position, from: child.parent!) func addBlock(to side: Side) { self.connected[side] = true if var breakable = child as? Breakable { breakable.glueBlock = self breakable.side = side } } if regionUp.contains(position) { addBlock(to: .up) } else if regionDown.contains(position) { addBlock(to: .down) } else if regionLeft.contains(position) { addBlock(to: .left) } else if regionRight.contains(position) { addBlock(to: .right) } } } //debugConnected() } func remove(for side: Side) { connected[side] = false //debugConnected() } #if DEBUG func debugConnected() { for circle in circles { circle.removeFromParent() } for (connect, yes) in connected { if yes { let circle = SKShapeNode(circleOfRadius: 10) circle.fillColor = .blue circle.strokeColor = .blue circle.position = connect.position circle.zPosition = 100 circles.append(circle) addChild(circle) } } } #endif func getSideIfConnected(contact: SKPhysicsContact) -> Side? { let side = super.getSide(contact: contact) // Check if side is connected if connected[side]! { return nil } return side } // Add a node, based on side. Returns true if successful func add(node: SKSpriteNode, to side: Side) -> Bool { // Make sure there isn't already one on that side guard connected[side] == false else { return false } let position: CGPoint let zRotation: CGFloat switch side { case .up: position = up zRotation = CGFloat(0).degreesToRadians() case .down: position = down zRotation = CGFloat(180).degreesToRadians() case .left: position = left zRotation = CGFloat(90).degreesToRadians() case .right: position = right zRotation = CGFloat(270).degreesToRadians() case .centre: position = centre zRotation = CGFloat(0).degreesToRadians() } connected[side] = true if node.parent == nil { node.position = position node.zRotation = zRotation addChild(node) } else { node.move(toParent: self) node.run(SKAction.move(to: position, duration: 0.1)) { // Check if the physics body is dynamic if self.physicsBody!.isDynamic { if let body1 = node.physicsBody, let body2 = self.physicsBody, let scene = self.scene, let parent = node.parent { node.physicsBody?.contactTestBitMask ^= Category.gluBlock let anchor = scene.convert(node.position, from: parent) let joint = SKPhysicsJointPin.joint(withBodyA: body1, bodyB: body2, anchor: anchor) scene.physicsWorld.add(joint) } } else { node.physicsBody?.isDynamic = false } } } if var breakable = node as? Breakable { breakable.glueBlock = self breakable.side = side } //debugConnected() return true } func add(gravityNode: GravityNode) -> Bool { // Check there are no other nodes guard connected[.centre] == false else { return false } // Precaution gravityNode.removeFromParent() gravityNode.position = centre addChild(gravityNode) connected[.centre] = true //debugConnected() return true } func update() { print("Glue block") } }
gpl-3.0
RobinChao/Hacking-with-Swift
HackingWithSwift-08/HackingWithSwift-08/AppDelegate.swift
1
2142
// // AppDelegate.swift // HackingWithSwift-08 // // Created by Robin on 2/26/16. // Copyright © 2016 Robin. 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
DouKing/WYListView
WYListViewController/Demo/AddressViewController.swift
1
6704
// // DetailViewController.swift // WYListViewController // // Created by iosci on 2016/10/24. // Copyright © 2016年 secoo. All rights reserved. // import UIKit class AddressViewController: UIViewController { enum AddressType: Int { case province, city, area } var sectionDataSource: [String?] = [nil] var selectedRows: [Int?] = [nil, nil, nil] let name = "n" let code = "c" lazy var dataSource: NSDictionary = { let path = Bundle.main.path(forResource: "test", ofType: "plist") let info = NSDictionary(contentsOfFile: path!) return info! }() lazy var provinces: [[String: String]] = { let provinces = self.dataSource["provinces"] return provinces! as! [[String : String]] }() lazy var cities: [String: [[String: String]]] = { let provinces = self.dataSource["cities"] return provinces! as! [String : [[String : String]]] }() lazy var areas: [String: [[String: String]]] = { let provinces = self.dataSource["areas"] return provinces! as! [String : [[String : String]]] }() var province: String? var city: String? var area: String? @IBOutlet weak var contentView: UIView! override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false let listVC = WYListView() listVC.dataSource = self listVC.delegate = self listVC.view.frame = self.contentView.bounds self.addChildViewController(listVC) self.contentView.addSubview(listVC.view) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - WYListViewDataSource - extension AddressViewController: WYListViewDataSource, WYListViewDelegate { func numberOfSections(in listView: WYListView) -> Int { return self.sectionDataSource.count } func listView(_ listView: WYListView, numberOfRowsInSection section: Int) -> Int { guard let type = AddressType(rawValue: section) else { return 0 } switch type { case .province: return self.provinces.count case .city: guard let index = self.selectedRows[AddressType.province.rawValue] else { return 0 } guard let code = self.provinces[index][self.code] else { return 0 } guard let cities = self.cities[code] else { return 0 } return cities.count case .area: guard let index = self.selectedRows[AddressType.province.rawValue] else { return 0 } guard let code = self.provinces[index][self.code] else { return 0 } guard let cities = self.cities[code] else { return 0 } guard let idx = self.selectedRows[AddressType.city.rawValue] else { return 0 } guard let c = cities[idx][self.code] else { return 0 } guard let areas = self.areas[c] else { return 0 } return areas.count } } func listView(_ listView: WYListView, titleForSection section: Int) -> String? { return self.sectionDataSource[section] } func listView(_ listView: WYListView, titleForRowAtIndexPath indexPath: IndexPath) -> String? { guard let type = AddressType(rawValue: indexPath.section) else { return nil } switch type { case .province: return self.provinces[indexPath.row][self.name] case .city: guard let index = self.selectedRows[AddressType.province.rawValue] else { return nil } guard let code = self.provinces[index][self.code] else { return nil } guard let cities = self.cities[code] else { return nil } return cities[indexPath.row][self.name] case .area: guard let index = self.selectedRows[AddressType.province.rawValue] else { return nil } guard let code = self.provinces[index][self.code] else { return nil } guard let cities = self.cities[code] else { return nil } guard let idx = self.selectedRows[AddressType.city.rawValue] else { return nil } guard let c = cities[idx][self.code] else { return nil } guard let areas = self.areas[c] else { return nil } return areas[indexPath.row][self.name] } } func listView(_ listView: WYListView, didSelectRowAtIndexPath indexPath: IndexPath) { let row = self.selectedRows[indexPath.section] self.selectedRows[indexPath.section] = indexPath.row self.sectionDataSource[indexPath.section] = self.listView(listView, titleForRowAtIndexPath: indexPath) if let selectedRow = row, selectedRow == indexPath.row { } else { self.selectedRows.remove(after: indexPath.section) self.sectionDataSource.remove(after: indexPath.section) if indexPath.section < AddressType.area.rawValue { self.sectionDataSource.append(nil) for _ in (indexPath.section + 1)...AddressType.area.rawValue { self.selectedRows.append(nil) } } } var selectedIndexPaths: [IndexPath] = [] for (idx, row) in self.selectedRows.enumerated() { if row != nil { selectedIndexPaths.append(IndexPath(row: row!, section: idx)) } } listView.reloadData(selectRowsAtIndexPaths: selectedIndexPaths) listView.scroll(to: min(indexPath.section + 1, AddressType.area.rawValue), animated: true, after: 0.3) if let type = AddressType(rawValue: indexPath.section) { switch type { case .province: self.province = self.listView(listView, titleForRowAtIndexPath: indexPath) case .city: self.city = self.listView(listView, titleForRowAtIndexPath: indexPath) case .area: self.area = self.listView(listView, titleForRowAtIndexPath: indexPath) let address = "\(self.province) \(self.city) \(self.area)" let alert = UIAlertController(title: address, message: nil, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) } } } } extension Array { mutating func remove(after index: Int) { while self.count > index + 1 { self.removeLast() } } }
mit
semonchan/LearningSwift
语法/4.Swift基础语法.playground/Contents.swift
1
1847
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" class Vehicle { var numberOfWheels = 0 var description: String { return"\(numberOfWheels)wheel(s)" } } let vehicle = Vehicle() class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } // 指定构造器和便利构造器 // 一般便利构造器是为了方便构造拥有默认值属性的实例 class Food { var name: String // 这个类的指定构造器 init(name: String) { self.name = name } // 这个类的便利构造器 convenience init() { self.init(name: "[Unnamed]") } } class Recipelngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init (name: String) { self.init(name: name, quantity: 1) } } let x = Recipelngredient() class ShoppingListItem: Recipelngredient { var purchased = false var description: String { var output = "\(quantity)x\(name)" output += purchased ? "✅" : "❎" return output } } var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6) ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } class Bank { static var coinslnBank = 10_000 static func distribute(coins numberOfCoinsRequested: Int) -> Int { let numberOfCoinsToVend = min(numberOfCoinsRequested, coinslnBank) coinslnBank -= numberOfCoinsToVend return numberOfCoinsToVend } static func receive(coins: Int) { coinslnBank += coins } }
mit
MessageKit/MessageKit
Sources/Controllers/MessagesViewController+PanGesture.swift
1
3317
// MIT License // // Copyright (c) 2017-2022 MessageKit // // 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 extension MessagesViewController { // MARK: Internal /// Display time of message by swiping the cell func addPanGesture() { panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:))) guard let panGesture = panGesture else { return } panGesture.delegate = self messagesCollectionView.addGestureRecognizer(panGesture) messagesCollectionView.clipsToBounds = false } func removePanGesture() { guard let panGesture = panGesture else { return } panGesture.delegate = nil self.panGesture = nil messagesCollectionView.removeGestureRecognizer(panGesture) messagesCollectionView.clipsToBounds = true } // MARK: Private @objc private func handlePanGesture(_ gesture: UIPanGestureRecognizer) { guard let parentView = gesture.view else { return } switch gesture.state { case .began, .changed: messagesCollectionView.showsVerticalScrollIndicator = false let translation = gesture.translation(in: view) let minX = -(view.frame.size.width * 0.35) let maxX: CGFloat = 0 var offsetValue = translation.x offsetValue = max(offsetValue, minX) offsetValue = min(offsetValue, maxX) parentView.frame.origin.x = offsetValue case .ended: messagesCollectionView.showsVerticalScrollIndicator = true UIView.animate( withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: { parentView.frame.origin.x = 0 }, completion: nil) default: break } } } // MARK: - MessagesViewController + UIGestureRecognizerDelegate extension MessagesViewController: UIGestureRecognizerDelegate { /// Check Pan Gesture Direction: open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard let panGesture = gestureRecognizer as? UIPanGestureRecognizer else { return false } let velocity = panGesture.velocity(in: messagesCollectionView) return abs(velocity.x) > abs(velocity.y) } }
mit
tagspaces/tagspaces
cordova/platforms/ios/TagSpaces/Plugins/com.whebcraft.cordova.plugin.downloader/Downloader.swift
1
2537
import Foundation @objc(Downloader) class Downloader : CDVPlugin { func download(_ command: CDVInvokedUrlCommand) { var pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR ) var isError = false let args = command.arguments[0] as! NSDictionary let url = URL(string: args["url"] as! String) let targetFile = args["path"] as! String let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL? let destinationUrl = documentsUrl?.appendingPathComponent(targetFile) if FileManager().fileExists(atPath: destinationUrl!.path) { print("file already exists [\(destinationUrl?.path)]") do { try FileManager().removeItem(atPath: destinationUrl!.path) } catch let error as NSError { pluginResult = CDVPluginResult( status: CDVCommandStatus_ERROR, messageAs: error.localizedDescription ) self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) isError = true } } if !(isError) { let sessionConfig = URLSessionConfiguration.default let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil) var request = URLRequest(url: url!) request.httpMethod = "GET" let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in if (error == nil) { if let response = response as? HTTPURLResponse { if response.statusCode == 200 { if (try? data!.write(to: destinationUrl!, options: [.atomic])) != nil { pluginResult = CDVPluginResult( status: CDVCommandStatus_OK, messageAs: documentsUrl?.path ) self.commandDelegate!.send( pluginResult, callbackId: command.callbackId ) } } } } }) task.resume() } } }
agpl-3.0
SwiftFS/Swift-FS-China
Sources/SwiftFSChina/router/Search.swift
1
2609
// // Search.swift // PerfectChina // // Created by mubin on 2017/8/10. // // import Foundation import PerfectHTTP import PerfectLib class Search { static func query(data: [String:Any]) throws -> RequestHandler { return { request, response in do{ guard let q = request.param(name: "q") else { response.render(template: "search") return } let page_size = page_config.index_topic_page_size let page_no = request.param(name: "page_no")?.int ?? 1 let total_count = try SearchServer.quert_cout(query: q) let total_page = Utils.total_page(total_count: total_count, page_size: page_size) let result_topic = try SearchServer.query_by_topic(query:q) let result_user = try SearchServer.query_by_user(query: q) let user_count = result_user.count let user_json_encoded = try? encoder.encode(result_user) let topic_json_encoded = try? encoder.encode(result_topic) if user_json_encoded != nil && topic_json_encoded != nil { guard let user_json = encodeToString(data: user_json_encoded!) else{ return } guard let topic_json = encodeToString(data: topic_json_encoded!) else{ return } guard let user_json_decoded = try user_json.jsonDecode() as? [[String:Any]] else{ return } guard let topic_json_decoded = try topic_json.jsonDecode() as? [[String:Any]] else{ return } let content:[String:Any] = ["total_count":total_count + user_count ,"q":q ,"useritems":user_json_decoded ,"topicitems":topic_json_decoded] response.render(template: "search/search", context: content) } }catch{ Log.error(message: "\(error)") } } } } private extension String { func positionOf(sub:String)->Int { var pos = -1 if let range = range(of:sub) { if !range.isEmpty { pos = characters.distance(from:startIndex, to:range.lowerBound) } } return pos } }
mit
MagicTheGathering/mtg-sdk-swift
TestApplication/AppDelegate.swift
1
509
// // AppDelegate.swift // TestApplication // // Created by Reed Carson on 3/14/18. // Copyright © 2018 Reed Carson. 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 } }
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/07401-swift-sourcemanager-getmessage.swift
11
260
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension A { struct B { { } func a { Int ( { class A { protocol A { enum b { class case ,
mit
natecook1000/swift-compiler-crashes
fixed/25438-swift-parser-parsedecl.swift
7
198
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {let a{extension{class case,
mit
Glucosio/glucosio-ios
glucosio/Classes/Watch/Timeline.swift
2
3151
import Foundation public class TimelineItem : NSObject /*, Equatable */ { public var timestamp : Date public var value: String public var unit: String public var desc : String @objc public init(date: Date, value: String, unit: String, description: String) { timestamp = date self.value = value self.unit = unit desc = description } @objc public override var description: String { return "TimelineItem: \(timestamp) \(value) \(unit) \(desc)" } // MARK: Equality static func == (lhs: TimelineItem, rhs: TimelineItem) -> Bool { return lhs.timestamp == rhs.timestamp && lhs.value == rhs.value && lhs.unit == rhs.unit && lhs.description == rhs.description } // MARK: Dictionary (de)serialization @objc convenience init(d: Dictionary<String, String>) { //TODO: how to use reflection here? self.init(date: Date(timeIntervalSince1970 : Double(d["timestamp"] ?? "") ?? 0.0), value: d["value"] ?? "", unit: d["unit"] ?? "", description: d["desc"] ?? "") } public func toDictionary() -> Dictionary<String, String> { var d = Dictionary<String, String>.init() let mirror = Mirror(reflecting: self) for (name, value) in mirror.children { guard let name = name else { continue } if(value is Date) { d[name] = String(describing: (value as! Date).timeIntervalSince1970) } else { d[name]=value as? String } } return d } } public class DayTimeline : NSObject /*, Equatable */ { public var elements : Array<TimelineItem> @objc public init(items : Array<TimelineItem>) { elements = items // print(elements) } // MARK: UserDefaults (de)serialization public convenience override init() { self.init(UserDefaults.init()) } public convenience init(_ def: UserDefaults) { self.init(def, key: "timeline") } public convenience init(_ def: UserDefaults, key: String) { self.init(d: def.dictionary(forKey: key) ?? Dictionary.init()) } public func toUserDefaults(_ def : UserDefaults) { toUserDefaults(def, key: "timeline") } public func toUserDefaults(_ def : UserDefaults, key: String) { def.setValue(toDictionary(), forKey: key); } // MARK: Dictionary (de)serialization public convenience init(d: Dictionary<String, Any>) { if let rawElements = d["elements"] { let elements = (rawElements as! Array<Dictionary>).map { d in TimelineItem.init(d: d) } self.init(items: elements) } else { self.init(items: []) } } //d[elements] = Array[Dictionary<String,String>] @objc public func toDictionary() -> Dictionary<String, Array<Dictionary<String, String>>> { var d = Dictionary<String, Array<Dictionary<String, String>>>.init() d["elements"] = elements.map { t in t.toDictionary() } return d } }
gpl-3.0
jwfriese/FrequentFlyer
FrequentFlyer/Jobs/JobsGroupSection.swift
1
269
import RxDataSources struct JobGroupSection: SectionModelType { typealias Item = Job var items: [Item] init() { self.items = [] } init(original: JobGroupSection, items: [Item]) { self = original self.items = items } }
apache-2.0
imfree-jdcastro/Evrythng-iOS-SDK
Evrythng-iOS/ScopeResource.swift
1
848
// // ScopeResource.swift // EvrythngiOS // // Created by JD Castro on 22/05/2017. // Copyright © 2017 ImFree. All rights reserved. // import UIKit import Moya_SwiftyJSONMapper import SwiftyJSON open class ScopeResource { var users: Array<String>? var projects: Array<String>? var jsonData: JSON? = nil public init() { } required public init?(jsonData:JSON){ self.jsonData = jsonData self.users = jsonData["allU"].arrayObject as? [String] self.projects = jsonData["allP"].arrayObject as? [String] } public class func toString() -> NSString? { let data = try! JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) return string } }
apache-2.0
6ag/AppScreenshots
AppScreenshots/Classes/Module/Home/View/JFPhotoCollectionViewCell.swift
1
6635
// // JFPhotoCollectionViewCell.swift // AppScreenshots // // Created by zhoujianfeng on 2017/2/4. // Copyright © 2017年 zhoujianfeng. All rights reserved. // import UIKit class JFPhotoCollectionViewCell: UICollectionViewCell { var materialParameter: JFMaterialParameter? { didSet { guard let materialParameter = materialParameter else { return } // 模板图片 imageView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: materialParameter.sourceImageName ?? "", ofType: nil) ?? "") // 配图 accessoryView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: materialParameter.accessoryImageName ?? "", ofType: nil) ?? "") // 遮罩 coverView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: materialParameter.coverImageName ?? "", ofType: nil) ?? "") // 是否正在编辑 selectedIconView.isHidden = !materialParameter.isSelected // 应用截图 screenShotImageView.image = materialParameter.screenShotImage // 标题 titleLabel.text = materialParameter.title titleLabel.font = UIFont(name: "PingFangSC-Semibold", size: SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.titleFontSize)) titleLabel.textColor = UIColor.colorWithHexString(materialParameter.titleTextColorHex ?? "") // 副标题 subtitleLabel.text = materialParameter.subtitle subtitleLabel.font = UIFont(name: "PingFangSC-Semibold", size: SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.subtitleFontSize)) subtitleLabel.textColor = UIColor.colorWithHexString(materialParameter.subtitleTextColorHex ?? "") titleLabel.snp.updateConstraints { (make) in make.centerX.equalTo(contentView) make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.titleY)) } subtitleLabel.snp.updateConstraints { (make) in make.centerX.equalTo(contentView) make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.subtitleY)) } screenShotImageView.snp.updateConstraints { (make) in make.left.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.screenShotX)) make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.screenShotY)) make.width.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.screenShotWidth)) make.height.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.screenShotHeight)) } accessoryView.snp.updateConstraints { (make) in make.left.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.accessoryX)) make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.accessoryY)) make.width.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.accessoryWidth)) make.height.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.accessoryHeight)) } coverView.snp.updateConstraints { (make) in make.left.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.coverX)) make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.coverY)) make.width.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.coverWidth)) make.height.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.coverHeight)) } } } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 懒加载 /// 展示图 fileprivate lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.layer.cornerRadius = layoutHorizontal(iPhone6: 2) imageView.layer.masksToBounds = true return imageView }() /// 选中图标 lazy var selectedIconView: UIImageView = { let imageView = UIImageView(image: UIImage(named: "img_select")) return imageView }() /// 标题 fileprivate lazy var titleLabel: UILabel = { let label = UILabel() return label }() /// 副标题 fileprivate lazy var subtitleLabel: UILabel = { let label = UILabel() return label }() /// 上传的屏幕截图 fileprivate lazy var screenShotImageView: UIImageView = { let imageView = UIImageView() return imageView }() /// 配图 fileprivate lazy var accessoryView: UIImageView = { let imageView = UIImageView() return imageView }() /// 遮罩 fileprivate lazy var coverView: UIImageView = { let imageView = UIImageView() return imageView }() } // MARK: - 设置界面 extension JFPhotoCollectionViewCell { fileprivate func prepareUI() { contentView.addSubview(imageView) contentView.addSubview(selectedIconView) contentView.addSubview(titleLabel) contentView.addSubview(subtitleLabel) contentView.addSubview(screenShotImageView) contentView.addSubview(coverView) contentView.addSubview(accessoryView) imageView.snp.makeConstraints { (make) in make.edges.equalTo(self.contentView) } selectedIconView.snp.makeConstraints { (make) in make.top.equalTo(layoutVerticalX(iPhone6: -5)) make.size.equalTo(CGSize( width: layoutHorizontal(iPhone6: 15), height: layoutVerticalX(iPhone6: 15))) make.right.equalTo(layoutHorizontal(iPhone6: 5)) } } }
mit
xuzhou524/Convenient-Swift
Controller/HomeViewController.swift
1
12878
// // HomeViewController.swift // Convenient-Swift // // Created by gozap on 16/3/2. // Copyright © 2016年 xuzhou. All rights reserved. // import UIKit import Alamofire import SnapKit import KVOController import ObjectMapper import AlamofireObjectMapper import TMCache import SVProgressHUD let kTMCacheWeatherArray = "kTMCacheWeatherArray" typealias cityHomeViewbackfunc=(_ weatherModel:WeatherModel)->Void class HomeViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var HomeWeatherMdoel = WeatherModel() var requCityName = XZClient.sharedInstance.username! var weatherArray = NSMutableArray() var weatherlocalArray = NSMutableArray() //var alamofireManager : Manager? var xxWeiHaoArray = NSMutableArray() var cityNameButton : UIButton? var cityIconImageView : UIImageView? fileprivate var _tableView : UITableView! fileprivate var tableView :UITableView{ get{ if _tableView == nil{ _tableView = UITableView() _tableView.backgroundColor = XZSwiftColor.convenientBackgroundColor _tableView.separatorStyle = UITableViewCell.SeparatorStyle.none _tableView.delegate = self _tableView.dataSource = self self.tableView.register(Weather_titleTabeleViewCell.self, forCellReuseIdentifier: "Weather_titleTabeleViewCell") self.tableView.register(WeatherTabeleViewCell.self, forCellReuseIdentifier: "WeatherTabeleViewCell") self.tableView.register(Weather_LineTabeleViewCell.self, forCellReuseIdentifier: "Weather_LineTabeleViewCell") self.tableView.register(Weather_TimeTabeleViewCell.self, forCellReuseIdentifier: "Weather_TimeTabeleViewCell") self.tableView.register(Weather_WeekTabeleViewCell.self, forCellReuseIdentifier: "Weather_WeekTabeleViewCell") } return _tableView } } override func viewDidLoad() { super.viewDidLoad() cityNameButton = UIButton() cityNameButton!.setImage(UIImage(named: ""), for: UIControl.State()) cityNameButton!.adjustsImageWhenHighlighted = false if (HomeWeatherMdoel.life == nil) { cityNameButton!.setTitle(XZClient.sharedInstance.username!, for: UIControl.State()) }else{ cityNameButton!.setTitle(HomeWeatherMdoel.realtime!.city_name! as String, for: UIControl.State()) } cityNameButton!.addTarget(self, action: #selector(HomeViewController.cityClick), for: .touchUpInside) cityIconImageView = UIImageView() cityIconImageView?.isUserInteractionEnabled = true cityIconImageView?.image = UIImage.init(named: "fujindizhi") cityNameButton!.addSubview(cityIconImageView!) cityIconImageView?.snp.makeConstraints({ (make) in make.centerY.equalTo(cityNameButton!); make.right.equalTo(cityNameButton!.snp.left).offset(-5) make.width.height.equalTo(28) }); self.navigationItem.titleView = cityNameButton self.view.addSubview(self.tableView); self.tableView.snp.makeConstraints{ (make) -> Void in make.top.right.bottom.left.equalTo(self.view); } let leftButton = UIButton() leftButton.frame = CGRect(x: 0, y: 0, width: 35, height: 30) leftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0) leftButton.setImage(UIImage(named: "bank"), for: UIControl.State()) leftButton.adjustsImageWhenHighlighted = false self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton) leftButton.addTarget(self, action: #selector(leftClick), for: .touchUpInside) if (self.HomeWeatherMdoel.life == nil) { self.requCityName = XZClient.sharedInstance.username! }else{ self.requCityName = self.HomeWeatherMdoel.realtime?.city_name ?? "" } self.cityNameButton?.setTitle(self.requCityName, for: UIControl.State()) self.asyncRequestData() if TMCache.shared().object(forKey: kTMCacheWeatherArray) != nil{ self.weatherlocalArray = TMCache.shared().object(forKey: kTMCacheWeatherArray) as! NSMutableArray } if self.weatherlocalArray.count > 0 { self.HomeWeatherMdoel = self.weatherlocalArray[0] as! WeatherModel } } @objc func leftClick(){ self.dismiss(animated: true, completion: nil) } @objc func cityClick(){ let cityVC = CityViewController() // cityVC.cityViewBack { (weatherModel) -> Void in // self.HomeWeatherMdoel = weatherModel // self.requCityName = weatherModel.realtime!.city_name! as String // self.cityNameButton!.setTitle(self.HomeWeatherMdoel.realtime!.city_name! as String, for: UIControlState()) // self.asyncRequestData() // self.myHomeFunc!(weatherModel: weatherModel); // } self.navigationController?.pushViewController(cityVC, animated: true) } func asyncRequestData() -> Void{ //根据城市名称 获取城市ID //http://apistore.baidu.com/microservice/cityinfo?cityname=北京 //得到ID 获取天气图标对应的值 //http://tq.91.com/api/?act=210&city=101180712&sv=3.15.3 //搜索城市 //http://zhwnlapi.etouch.cn/Ecalender/api/city?keyword=%E6%B8%85%E8%BF%9C&timespan=1457518656.715996&type=search //获取天气信息 let urlString = "https://op.juhe.cn/onebox/weather/query" let prames = [ "cityname" : self.requCityName, "key" : "af34bbdd7948b379a0d218fc2c59c8ba" ] AF.request(urlString, method: .post, parameters: prames, encoder: URLEncodedFormParameterEncoder.default, headers: nil, interceptor: nil).responseJSON { (response) in if response.error == nil { if let dict = response.value as? NSDictionary { if let dicts = dict["result"] as? NSDictionary { if let dictss = dicts["data"] as? NSDictionary { if let model = WeatherModel.init(JSON: dictss as! [String : Any]) { print(model); self.HomeWeatherMdoel = model if (TMCache.shared().object(forKey: kTMCacheWeatherArray) != nil){ self.weatherArray = TMCache.shared().object(forKey: kTMCacheWeatherArray) as! NSMutableArray } //去重 var tempBool = true for i in 0 ..< self.weatherArray.count { let model = self.weatherArray[i] as! WeatherModel if model.realtime?.city_code == self.HomeWeatherMdoel.realtime?.city_code || model.realtime?.city_name == self.HomeWeatherMdoel.realtime?.city_name{ self.weatherArray.removeObject(at: i) self.weatherArray.insert(self.HomeWeatherMdoel, at: i) tempBool = false break } } if tempBool{ self.weatherArray.add(self.HomeWeatherMdoel) } // TMCache.shared().setObject(self.weatherArray, forKey: kTMCacheWeatherArray) let date = Date() let timeFormatter = DateFormatter() timeFormatter.dateFormat = "MM-dd HH:mm" let strNowTime = timeFormatter.string(from: date) as String XZSetting.sharedInstance[KweatherTefurbishTime] = strNowTime; var listData: NSDictionary = NSDictionary() let filePath = Bundle.main.path(forResource: "TailRestrictions.plist", ofType:nil ) listData = NSDictionary(contentsOfFile: filePath!)! let cityId = listData.object(forKey: self.requCityName) as? String if (cityId != nil) { self.asyncRequestXianXingData(cityId!) }else{ self.tableView.reloadData() } } } } } } } } func asyncRequestXianXingData(_ string:String) -> Void{ let urlString = "http://forecast.sina.cn/app/lifedex/v3/html/channel.php?" let prames = [ "ch_id" : "3", "citycode" : string, "pt" : "3010" ] AF.request(urlString, method: .get, parameters: prames).responseString {response in switch response.result { case .success: debugPrint(response.result) let dataImage = response.value?.data(using: String.Encoding.utf8) let xpathParser = type(of: TFHpple()).init(htmlData: dataImage) let elements = xpathParser?.search(withXPathQuery: "//html//body//div//div//div//div[@class='number']") if (elements?.count)! > 0{ let temp = elements?.first as! TFHppleElement for i in 0 ..< self.weatherArray.count { let model = self.weatherArray[i] as! WeatherModel if (model.realtime?.city_code == self.HomeWeatherMdoel.realtime?.city_code){ self.weatherArray.removeObject(at: i) self.HomeWeatherMdoel.xxweihao = temp.content self.weatherArray.insert(self.HomeWeatherMdoel, at: i) // TMCache.shared().setObject(self.weatherArray, forKey: kTMCacheWeatherArray) } } } self.tableView .reloadData() break case .failure(let error): debugPrint(error) break } self.tableView .reloadData() } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (self.HomeWeatherMdoel.life) != nil { return 5 } return 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return [40,320,35,120,35][(indexPath as NSIndexPath).row] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let titleCell = getCell(tableView, cell: Weather_titleTabeleViewCell.self, indexPath: indexPath) titleCell.bind(self.HomeWeatherMdoel) titleCell.selectionStyle = .none return titleCell }else if indexPath.row == 1 { let weatherCell = getCell(tableView, cell: WeatherTabeleViewCell.self, indexPath: indexPath) weatherCell.selectionStyle = .none weatherCell.bind(self.HomeWeatherMdoel) return weatherCell }else if indexPath.row == 2 { let weatherTimeCell = getCell(tableView, cell: Weather_TimeTabeleViewCell.self, indexPath: indexPath) weatherTimeCell.selectionStyle = .none weatherTimeCell.bind(self.HomeWeatherMdoel) return weatherTimeCell } else if (indexPath as NSIndexPath).row == 3{ let lineCell = getCell(tableView, cell: Weather_LineTabeleViewCell.self, indexPath: indexPath) lineCell.selectionStyle = .none if let array = self.HomeWeatherMdoel.weather { lineCell.weakWeatherArray = array lineCell.configUI() } lineCell.backgroundColor = UIColor.white return lineCell } else if (indexPath as NSIndexPath).row == 4{ let weekTimeCell = getCell(tableView, cell: Weather_WeekTabeleViewCell.self, indexPath: indexPath) weekTimeCell.selectionStyle = .none weekTimeCell.binde(self.HomeWeatherMdoel) return weekTimeCell } return UITableViewCell() } }
mit
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Maps/Presenter Tests/WhenSelectingMap_MapsPresenterShould.swift
1
623
import XCTest class WhenSelectingMap_MapsPresenterShould: XCTestCase { func testTellTheDelegateToShowDetailsForMapWithItsIdentifier() { let viewModel = FakeMapsViewModel() let interactor = FakeMapsInteractor(viewModel: viewModel) let context = MapsPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() let mapViewModel = viewModel.maps.randomElement() context.simulateSceneDidSelectMap(at: mapViewModel.index) XCTAssertEqual(viewModel.identifierForMap(at: mapViewModel.index), context.delegate.capturedMapIdentifierToPresent) } }
mit
lzc1104/Payment
Example/Payment/ViewController.swift
1
2163
// // ViewController.swift // Payment // // Created by lzc1104 on 09/07/2017. // Copyright (c) 2017 lzc1104. All rights reserved. // import UIKit import Payment class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /// 支付宝暂时不用注册账号 - 现在支付宝使用的是旧版本SDK - PaymentManagers.registerAccount(PaymentManagers.Account.alipay(appID: "???")) /// 微信必须注册账号 PaymentManagers.registerAccount(PaymentManagers.Account.wechat(appID: "", appKey: "")) } @IBAction func wechatPay(_ sender: Any) { let req = PaymentManagers.WechatPayRequest( partnerId: "", prepayId: "", nonceStr: "", timeStamp: 0, package: "", sign: "" ) let order = PaymentManagers.Order.weChat(req: req) PaymentManagers.deliver(order) { (result) in switch result { case .success: debugPrint("FUCK YOU") break case .error(let error): switch error { case .cancel: debugPrint("FUCK YOU CANCEL???") default: debugPrint("FUCK ME") } break } } } @IBAction func alipay(_ sender: Any) { //RESERVER //此处的模板为 观赛日支付模板 let req = PaymentManagers.AlipayRequest(payOrderString : "",scheme: "") let order = PaymentManagers.Order.alipay(req: req) PaymentManagers.deliver(order, completionHandler: { result in switch result { case .success: debugPrint("FUCK YOU") break case .error(let error): switch error { case .cancel: debugPrint("FUCK YOU CANCEL???") default: debugPrint("FUCK ME") } break } }) } }
mit
minsOne/DigitClockInSwift
Analytics/AnalyticsTests/AnalyticsTests.swift
1
905
// // AnalyticsTests.swift // AnalyticsTests // // Created by minsone on 2019/09/28. // Copyright © 2019 minsone. All rights reserved. // import XCTest @testable import Analytics class AnalyticsTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
SoneeJohn/WWDC
WWDC/AppCoordinator+UserActivity.swift
1
724
// // AppCoordinator+UserActivity.swift // WWDC // // Created by Guilherme Rambo on 06/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import RealmSwift import RxSwift import ConfCore import PlayerUI extension AppCoordinator { func updateCurrentActivity(with item: UserActivityRepresentable?) { guard let item = item else { currentActivity?.invalidate() currentActivity = nil return } let activity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb) activity.title = item.title activity.webpageURL = item.webUrl activity.becomeCurrent() currentActivity = activity } }
bsd-2-clause
joshdholtz/Few.swift
Few-iOS/Image.swift
1
1337
// // Image.swift // Few // // Created by Coen Wessels on 13-03-15. // Copyright (c) 2015 Josh Abernathy. All rights reserved. // import UIKit public class Image: Element { public var image: UIImage? public var scaling: UIViewContentMode public var clipsToBounds: Bool public init(_ image: UIImage?, scaling: UIViewContentMode = .ScaleAspectFit, clipsToBounds: Bool = false) { self.image = image self.scaling = scaling self.clipsToBounds = clipsToBounds let size = image?.size ?? CGSize(width: Node.Undefined, height: Node.Undefined) super.init(frame: CGRect(origin: CGPointZero, size: size)) } // MARK: Element public override func applyDiff(old: Element, realizedSelf: RealizedElement?) { super.applyDiff(old, realizedSelf: realizedSelf) if let view = realizedSelf?.view as? UIImageView { if view.contentMode != scaling { view.contentMode = scaling } if view.image != image { view.image = image realizedSelf?.markNeedsLayout() } if view.clipsToBounds != clipsToBounds { view.clipsToBounds = clipsToBounds } } } public override func createView() -> ViewType { let view = UIImageView(frame: frame) view.alpha = alpha view.hidden = hidden view.image = image view.contentMode = scaling view.clipsToBounds = clipsToBounds return view } }
mit
universeroc/Scannar
Scannar/ScannarUITests/ScannarUITests.swift
1
1021
// // ScannarUITests.swift // ScannarUITests // // Created by zhangyupeng on 8/1/15. // Copyright © 2015 universeroc. All rights reserved. // import XCTest class ScannarUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
Drusy/auvergne-webcams-ios
AuvergneWebcams/DownloadManager.swift
1
2358
// // DownloadManager.swift // AuvergneWebcams // // Created by Drusy on 23/02/2017. // // import Foundation import Kingfisher import RealmSwift import ObjectMapper class DownloadManager { static let shared = DownloadManager() lazy var realm: Realm = { return try! Realm() }() private init() { ImageDownloader.default.delegate = self } // MARK: - func bootstrapRealmDevelopmentData() { print(">>> Bootstraping developement configuration JSON") guard let path = Bundle.main.path(forResource: Configuration.localJSONConfigurationFileDev, ofType: "json") else { return } if let json = try? String(contentsOfFile: path, encoding: String.Encoding.utf8) { if let webcamSectionsResponse = Mapper<WebcamSectionResponse>().map(JSONString: json) { // Delete all sections & webcams let sections = realm.objects(WebcamSection.self) let webcams = realm.objects(Webcam.self) try! realm.write { realm.delete(sections) realm.delete(webcams) realm.add(webcamSectionsResponse.sections, update: .all) } QuickActionsService.shared.registerQuickActions() } } } func bootstrapRealmData() { print(">>> Bootstraping configuration JSON") guard let path = Bundle.main.path(forResource: Configuration.localJSONConfigurationFile, ofType: "json") else { return } if let json = try? String(contentsOfFile: path, encoding: String.Encoding.utf8) { if let webcamSectionsResponse = Mapper<WebcamSectionResponse>().map(JSONString: json) { try! realm.write { realm.add(webcamSectionsResponse.sections, update: .all) } QuickActionsService.shared.registerQuickActions() } } } } // MARK: - ImageDownloaderDelegate extension DownloadManager: ImageDownloaderDelegate { func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) { DispatchQueue.main.async { ImageDownloaderUtils.updateDate(for: url, with: response) } } }
apache-2.0
maletzt/Alien-Adventure
Alien Adventure/TotalBaseValue.swift
1
529
// // TotalBaseValue.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func totalBaseValue(inventory: [UDItem]) -> Int { return inventory.reduce(0) {$0 + $1.baseValue } } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 7"
mit
dooch/mySwiftStarterApp
SwiftWeather/LatestPostsTableViewCell.swift
1
664
// // LatestPostsTableViewCell.swift // SwiftWeather // // Created by CB on 4/02/2016. // Copyright © 2016 Jake Lin. All rights reserved. // import UIKit class LatestPostsTableViewCell: UITableViewCell { @IBOutlet weak var postTitle: UILabel! @IBOutlet weak var postDate: UILabel! @IBOutlet weak var postImage: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
ahoppen/swift
test/IRGen/virtual-function-elimination-generics-exec.swift
4
1397
// Tests that under -enable-llvm-vfe, LLVM GlobalDCE is able to remove unused // virtual methods, and that used virtual methods are not removed (by running // the program). // RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -enable-llvm-vfe %s -Onone -emit-ir -o %t/main.ll // RUN: %target-clang %t/main.ll -isysroot %sdk -L%swift_obj_root/lib/swift/%target-sdk-name -flto -o %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %llvm-nm --defined-only %t/main | %FileCheck %s --check-prefix=NM // REQUIRES: executable_test // FIXME(mracek): More work needed to get this to work on non-Apple platforms. // REQUIRES: VENDOR=apple // For LTO, the linker dlopen()'s the libLTO library, which is a scenario that // ASan cannot work in ("Interceptors are not working, AddressSanitizer is // loaded too late"). // REQUIRES: no_asan class MyClass { func foo() { print("MyClass.foo") } func bar() { print("MyClass.bar") } } class MyDerivedClass<T>: MyClass { override func foo() { print("MyDerivedClass<T>.foo, T=\(type(of: T.self))") } override func bar() { print("MyDerivedClass<T>.bar, T=\(type(of: T.self))") } } let o: MyClass = MyDerivedClass<Int>() o.foo() // CHECK: MyDerivedClass<T>.foo, T=Int.Type // NM-NOT: $s4main14MyDerivedClassC3baryyF // NM: $s4main14MyDerivedClassC3fooyyF // NM-NOT: $s4main7MyClassC3baryyF // NM: $s4main7MyClassC3fooyyF
apache-2.0
bingoogolapple/SwiftNote-PartOne
UIApplication/UIApplication/ViewController.swift
1
1496
// // ViewController.swift // UIApplication // // Created by bingoogol on 14/9/6. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() println("viewDidLoad") } @IBAction func clickMe() { // 一般来讲,所有shared开头创建的对象,都是单例 var app = UIApplication.sharedApplication() // 设置图标右上角显示的数字 // 提醒:在设置数字时,要谨慎,对于强迫症患者 //app.applicationIconBadgeNumber = 10 // 显示联网状态的提示,一般有网络请求,会自动显示 //app.networkActivityIndicatorVisible = true //在iOS中,很多东西都可以通过URL来访问,例如:电话、短信、电子邮件等 //var url = NSURL(string: "http://www.baidu.com") // 电话会直接呼出 //var url = NSURL(string: "tel://10086") // 会跳出短信发送界面,等待用户编辑并发送短信 //var url = NSURL(string: "sms://10086") //app.openURL(url) // 阻止屏幕变暗,慎重使用,缺省为false app.idleTimerDisabled = true } // 当应用程序出现内存警告时,控制器可以在此方法中释放自己的资源 override func didReceiveMemoryWarning() { } }
apache-2.0
ahoppen/swift
validation-test/compiler_crashers_fixed/28821-isa-protocoldecl-nominal-cannot-be-a-protocol.swift
42
450
// 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 -emit-ir protocol A{{}protocol A{func a:Self.a}typealias e:A.a
apache-2.0
yurevich1/LineRow
Example/Tests/Tests.swift
1
757
import UIKit import XCTest import LineRow class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
mit
leschlogl/Programming-Contests
Hackerrank/30 Days of Code/day17.swift
1
378
// Start of class Calculator class Calculator { // Start of function power func power(n: Int, p: Int) throws -> Int { // Add your code here if n < 0 || p < 0 { throw RangeError.NotInRange("n and p should be non-negative") } return Int(pow(Double(n), Double(p))) } // End of function power } // End of class Calculator
mit
emilstahl/swift
validation-test/compiler_crashers_fixed/0967-getselftypeforcontainer.swift
13
294
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol B { protocol b : a { func a() ->() -> String { } } } static let f = B
apache-2.0
ben-ng/swift
test/DebugInfo/linetable-do.swift
14
1230
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle %s -emit-ir -g -o - | %FileCheck %s // RUN: %target-swift-frontend -Xllvm -sil-full-demangle %s -emit-sil -emit-verbose-sil -g -o - | %FileCheck -check-prefix=CHECK-SIL %s import StdlibUnittest class Obj {} func foo (_ a : Int64) throws -> Void { _blackHole(a) } // CHECK-SIL: // main.testDoStmt () throws -> () func testDoStmt() throws -> Void { _blackHole(23) // CHECK-NOT: !DILocation(line: [[@LINE+1]] do { let obj = Obj() _blackHole(obj) try foo(100) // CHECK-SIL: bb{{.*}}(%{{[0-9]+}} : $()): // CHECK-SIL-NEXT: strong_release {{.*}}: $Obj{{.*}} line:[[@LINE+1]]:3:cleanup } // CHECK-SIL-NEXT: = tuple () // CHECK-SIL-NEXT: return {{.*}} line:[[@LINE+1]] } try testDoStmt() // CHECK-SIL: // main.testDoWhileStmt () -> () func testDoWhileStmt() -> Void { // CHECK-NOT: !DILocation(line: [[@LINE+1]] do { try foo(100) // CHECK-SIL: bb{{.*}}(%{{[0-9]+}} : $()): // CHECK-SIL-NEXT: br [[RETURN_BB:bb[0-9]+]]{{.*}} line:[[@LINE+1]]:3:cleanup } // CHECK-SIL: [[RETURN_BB]]: // CHECK-SIL-NEXT: = tuple () // CHECK-SIL-NEXT: return catch (let e) { _blackHole(e) } }
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/27192-swift-dependentmembertype-get.swift
1
459
// 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 class A{ let s=Int func a{ { class A?{ class a{ enum S<T:T.e
apache-2.0
darofar/lswc
p4-media-naranja/MediaNaranja/AppDelegate.swift
1
2162
// // AppDelegate.swift // MediaNaranja // // Created by Javier De La Rubia on 29/4/15. // Copyright (c) 2015 Javier De La Rubia. 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:. } }
apache-2.0
ColinConduff/BlocFit
BlocFit/Supporting Files/Supporting Models/BFFormatter.swift
1
1261
// // BFFormatter.swift // BlocFit // // Created by Colin Conduff on 11/9/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import Foundation struct BFFormatter { static let numberFormatter = NumberFormatter() static let dateFormatter = DateFormatter() static let dateIntervalFormatter = DateIntervalFormatter() static func stringFrom(number: Double, maxDigits: Int = 2) -> String { numberFormatter.numberStyle = .decimal numberFormatter.maximumFractionDigits = maxDigits numberFormatter.roundingMode = .up return numberFormatter.string(from: (number as NSNumber))! } static func stringFrom(totalSeconds: Double) -> String { let time = BFUnitConverter.hoursMinutesAndSecondsFrom(totalSeconds: totalSeconds) let hours = Int(time.hours) let minutes = Int(time.minutes) let seconds = Int(time.seconds) if totalSeconds >= 3600 { return String(format: "%02i:%02i:%02i", hours, minutes, seconds) } else if minutes > 9 { return String(format: "%02i:%02i", minutes, seconds) } else { return String(format: "%0i:%02i", minutes, seconds) } } }
mit
PhillipEnglish/TIY-Assignments
Forecaster/Forecaster/ModalZipCodeViewController.swift
1
5596
// // ModalZipCodeViewController.swift // Forecaster // // Created by Phillip English on 10/30/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreLocation class ModalZipCodeViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate { @IBOutlet weak var zipCodeTextfield: UITextField! // @IBOutlet weak var currentLocationButton: UIButton! let locationManager = CLLocationManager() let geocoder = CLGeocoder() var delegate: modalZipCodeViewControllerDelegate? var location: String = "" var zipCode: String = "" var cities = [City]() override func viewDidLoad() { super.viewDidLoad() //currentLocationButton.enabled = false configureLocationManager() navigationController?.navigationBar.barTintColor = UIColor.purpleColor() zipCodeTextfield.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: -UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if zipCodeTextfield.text != "" { if validateZipCode(textField.text!) { zipCode = textField.text! textField.resignFirstResponder() rc = true delegate?.zipCodeWasChosen(Int(zipCode)!) } else { textField.text = "" textField.becomeFirstResponder() } } return rc } func validateZipCode(zip: String) -> Bool { let characterSet = NSCharacterSet(charactersInString: "0123456789") if zip.characters.count == 5 && zip.rangeOfCharacterFromSet(characterSet)?.count == 1 { return true } else { return false } } func configureLocationManager() { if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined { locationManager.requestWhenInUseAuthorization() } else { //currentLocationButton.enabled = true } } } @IBAction func findCity(sender: UIButton) { if validateZipCode(zipCodeTextfield.text!) { search(Int(zipCodeTextfield.text!)!) } } func search(zip: Int) { delegate?.zipCodeWasChosen(zip) self.dismissViewControllerAnimated(true, completion: nil) } // func search(zip: String) // { // delegate?.zipCodeWasChosen(zip) // } // func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) // { // currentLocationButton.enabled = true // } // // func locationManager(manager: CLLocationManager, didFailWithError error: NSError) // { // print(error.localizedDescription) // } // // func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) //location array orders locations as they are updated // { // let location = locations.last // geocoder.reverseGeocodeLocation(location!, completionHandler: {(placemark: [CLPlacemark]?, error: NSError?) -> Void in // // if error != nil // { // print(error?.localizedDescription) // } // else // { // self.locationManager.stopUpdatingLocation() // let cityName = placemark?[0].locality // let zipCode = placemark?[0].postalCode // //self.locationTextField.text = zipCode! // let lat = location?.coordinate.latitude // let lng = location?.coordinate.longitude // //let aCity = City(cityName: cityName!, lat: lat!, long: lng!) // //self.delegate?.cityWasFound(aCity) // here the delegate is in the main tableview controller // } // } //MARK: - Action Handlers // @IBAction func addCity(sender: UIButton) // { // search(zipCodeTextfield.text!) // self.dismissViewControllerAnimated(true, completion: nil) // } // // @IBAction func useLocationTapped(sender: UIButton) // { // locationManager.startUpdatingLocation() //asks gps chip where the user is and updates the location // } // MARK: - CLLocation related methods // func configureLocationManager() // { // if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted // { // locationManager.delegate = self // locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters // if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined // { // locationManager.requestWhenInUseAuthorization() // } // else // { // //currentLocationButton.enabled = true // } // } // } }
cc0-1.0
lieonCX/Hospital
Hospital/Hospital/ViewModel/News/GithubSignupViewModel.swift
1
4172
// // GithubSignupViewModel.swift // Hospital // // Created by lieon on 2017/5/9. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import Foundation import RxCocoa import RxSwift enum ValidateResult { case ok(message: String) case failed(message: String) case validating case empty } extension ValidateResult { var isValid: Bool { switch self { case .ok: return true default: return false } } struct ValidationColors { static let okColor = UIColor(red: 138.0 / 255.0, green: 221.0 / 255.0, blue: 109.0 / 255.0, alpha: 1.0) static let errorColor = UIColor.red } var description: String { switch self { case let .ok(message): return message case .empty: return "" case .validating: return "validating ..." case let .failed(message): return message } } var textColor: UIColor { switch self { case .ok: return ValidationColors.okColor case .empty: return UIColor.black case .validating: return UIColor.black case .failed: return ValidationColors.errorColor } } } class GithubSignupViewModel { let validatedUsername: Observable<ValidateResult> let validatedPassword: Observable<ValidateResult> let validatedRepeatPassword: Observable<ValidateResult> let signupEnable: Observable<Bool> let signedin: Observable<Bool> let signingin: Observable<Bool> init(input: ( username: Observable<String>, password: Observable<String>, repeatPassword: Observable<String>, signupTaps: Observable<Void> ), dependency: ( API: GithubAPI, service: GithubValidationService )) { /// flatMapLatest 中的闭包是返回一个observble的序列 validatedUsername = input.username .flatMapLatest({ String -> Observable<ValidateResult> in /// observeOn 指定在某一线程中观察序列 return dependency.service.validateUsername(String).observeOn(MainScheduler.instance) /// 发生错误时直接返回错误信息 .catchErrorJustReturn(ValidateResult.failed(message: "Error contacting server")) }) .shareReplay(1) validatedPassword = input.password /// map 闭包直接取出序列中的真实值,进行操作 .map({ password -> ValidateResult in return dependency.service.validtePassword(password) }) .shareReplay(1) validatedRepeatPassword = Observable.combineLatest(input.password, input.repeatPassword, resultSelector: { (password, repearPassword) in return dependency.service.validteRepeatedPassword(password, repeatePassword: repearPassword) }).shareReplay(1) let usernameAndPassword = Observable.combineLatest(input.username, input.password) { (username, password) in return(username, password) }.shareReplay(1) let signingIn = ActivityIndicator() self.signingin = signingIn.asObservable() /// withLatestFrom 将连个序列合成一个序列,合成的序列中一第二个序列的值为主 signedin = input.signupTaps.withLatestFrom(usernameAndPassword).flatMapLatest { (username, password) in return dependency.API.signup(username: username, password: password).observeOn(MainScheduler.instance) .catchErrorJustReturn(false) .trackActivity(signingIn) }.shareReplay(1) signupEnable = Observable.combineLatest(validatedUsername, validatedPassword, validatedRepeatPassword, signingin.asObservable(), resultSelector: { (username, password, repeatedPassword, signingIn) -> Bool in return username.isValid && password.isValid && repeatedPassword.isValid && !signingIn }).distinctUntilChanged() .shareReplay(1) } }
mit
Vaseltior/SFCore
SFCore/sources/_extensions/Int+SFBoundi.swift
1
1607
// // The MIT License (MIT) // // Copyright (c) 2015 Samuel GRAU // // 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. // // // SFCore : Int+SFBoundi.swift // // Created by Samuel Grau on 02/03/2015. // Copyright (c) 2015 Samuel Grau. All rights reserved. // import Foundation extension Int { public static func boundi(value: Int, min: Int, max: Int) -> Int { var iMax = max if (max < min) { iMax = min } var bounded = value if (bounded > iMax) { bounded = iMax } if (bounded < min) { bounded = min } return bounded } }
mit
springware/cloudsight-swift
Example-swift/Pods/CloudSight/CloudSight/CloudSightQueryDelegate.swift
2
503
// // CloudSightQueryDelegate.swift // CloudSight // // Created by OCR Labs on 3/7/17. // Copyright © 2017 OCR Labs. All rights reserved. // import UIKit public protocol CloudSightQueryDelegate { func cloudSightQueryDidFinishIdentifying(query: CloudSightQuery) func cloudSightQueryDidFail(query: CloudSightQuery, withError error: NSError) func cloudSightQueryDidUpdateTag(query: CloudSightQuery) func cloudSightQueryDidFinishUploading(query: CloudSightQuery) }
mit
artsy/eigen
ios/ArtsyWidget/FullBleed/FullBleed+Timeline.swift
1
667
import WidgetKit extension FullBleed { struct Timeline { static func generate(context: TimelineProviderContext, completion: @escaping (WidgetKit.Timeline<Entry>) -> ()) { ArtworkStore.fetch(context: context) { artworks in let schedule = Schedule() let updateTimesToArtworks = Array(zip(schedule.updateTimes, artworks)) let entries = updateTimesToArtworks.map() { (date, artwork) in Entry(artwork: artwork, date: date) } let timeline = WidgetKit.Timeline(entries: entries, policy: .after(schedule.nextUpdate)) completion(timeline) } } } }
mit
KoheiKanagu/hogehoge
EndTermExamAdder/EndTermExamAdder/ViewController.swift
1
7589
// // ViewController.swift // EndTermExamAdder // // Created by Kohei on 2014/12/09. // Copyright (c) 2014年 KoheiKanagu. All rights reserved. // import Cocoa import EventKit class ViewController: NSViewController { @IBOutlet var myTextField: NSTextField? @IBOutlet var myComboBox: NSComboBox? let eventStore = EKEventStore() var calEventList: NSArray? override func viewDidLoad() { super.viewDidLoad() calEventList = eventStore.calendarsForEntityType(EKEntityTypeEvent) for var i=0; i<calEventList?.count; i++ { myComboBox?.insertItemWithObjectValue((calEventList![i] as EKCalendar).title, atIndex: (myComboBox?.numberOfItems)!) } } @IBAction func addButtonAction(sender: AnyObject) { if myComboBox?.indexOfSelectedItem == -1 { println("ComboBox未選択") return } let contents = loadHTML((myTextField?.stringValue)!) if contents == nil { println("HTMLが見つかりません") return } let year = (formalWithRule("<td align=\"right\" width=\"...\"><b>(.*)</b></td>", content: contents! as NSString)!)[0] as NSString let subjects = formalWithRule("<tr bgcolor=\"#FFFFFF\">\\n(.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n).*\"center\">", content: contents!)! for string in subjects{ let dateAndTimeRaw = formalWithRule("<td width=\"200\" align=\"center\">(.*)</td>", content: string as NSString) let dateAndTime = (dateAndTimeRaw![0] as NSString).componentsSeparatedByString("/") let date = dateAndTime[0] as NSString let time = dateAndTime[1] as NSString let name = (formalWithRule("<td name=\"rsunam_r\" width=\"286\">(.*)</td>", content: string as NSString)!)[0] as NSString let clas = (formalWithRule("<td name=\"clas\" align=\"center\" >(.*)</td>", content: string as NSString)!)[0] as NSString let teacher = (formalWithRule("<td name=\"kyoin\" width=\"162\">(.*)<br></td>", content: string as NSString)!)[0] as NSString let convertedDate = convertDate(rawYearString: year, rawDateString: date, rawTimeString: time) makeCalender(eventStore, title: name + clas, startDate: convertedDate.startTime, endDate: convertedDate.endTime, calendar: calEventList![myComboBox!.indexOfSelectedItem] as EKCalendar, notes: teacher) } } func convertDate(#rawYearString: NSString, rawDateString: NSString, rawTimeString: NSString) -> (startTime: NSDate, endTime: NSDate) { let calender = NSCalendar.currentCalendar() let components = NSDateComponents() let year = convertYear(rawYearString) components.year = year let array = rawDateString.componentsSeparatedByString("(") let array2 = (array[0] as NSString).componentsSeparatedByString("/") components.month = (array2[0] as NSString).integerValue components.day = (array2[1] as NSString).integerValue var convertedTime = convertTime(rawTimeString) components.hour = convertedTime.startTime!.hour components.minute = convertedTime.startTime!.minute let startTime = calender.dateFromComponents(components) components.hour = convertedTime.endTime!.hour components.minute = convertedTime.endTime!.minute let endTime = calender.dateFromComponents(components) return (startTime!, endTime!) } func convertYear(yearRawString: NSString) -> (Int) { let array = yearRawString.componentsSeparatedByString("&") var year: Int = ((array[0] as NSString).stringByReplacingOccurrencesOfString("年度", withString: "") as NSString).integerValue if (array[1] as NSString).hasSuffix("後期") { year++ } return year } func convertTime(rawTimeString: NSString) -> (startTime: NSDateComponents?, endTime: NSDateComponents?) { switch rawTimeString { case "1時限": return (makeNSDateComponents(hour: 9, minute: 30), makeNSDateComponents(hour: 10, minute: 30)) case "2時限": return (makeNSDateComponents(hour: 11, minute: 00), makeNSDateComponents(hour: 12, minute: 00)) case "3時限": return (makeNSDateComponents(hour: 13, minute: 30), makeNSDateComponents(hour: 14, minute: 30)) case "4時限": return (makeNSDateComponents(hour: 15, minute: 00), makeNSDateComponents(hour: 16, minute: 00)) case "5時限": return (makeNSDateComponents(hour: 16, minute: 30), makeNSDateComponents(hour: 17, minute: 30)) case "6時限": return (makeNSDateComponents(hour: 18, minute: 30), makeNSDateComponents(hour: 19, minute: 30)) case "7時限": return (makeNSDateComponents(hour: 20, minute: 00), makeNSDateComponents(hour: 21, minute: 00)) default: return (nil, nil) } } func makeNSDateComponents(#hour: Int, minute: Int) -> (NSDateComponents) { let components = NSDateComponents() components.hour = hour components.minute = minute return components } func loadHTML(pathString: NSString) -> (NSString?) { if pathString.length == 0 { return nil } let url: NSURL = NSURL(fileURLWithPath: pathString)! let contents = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: nil) return contents } func formalWithRule(rule:NSString, content:NSString) -> (NSArray?) { var resultArray = [NSString]() var error:NSError? let regex = NSRegularExpression(pattern: rule, options: NSRegularExpressionOptions.CaseInsensitive, error: &error); if error != nil { return nil } var matches = (regex?.matchesInString(content, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, content.length))) as Array<NSTextCheckingResult> for match:NSTextCheckingResult in matches { resultArray.append(content.substringWithRange(match.rangeAtIndex(1))) } return resultArray } func makeCalender(eventStore: EKEventStore, title: NSString, startDate: NSDate, endDate: NSDate, calendar: EKCalendar, notes: NSString) { eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted, error) -> Void in if !granted { println("カレンダーにアクセスできません") println("セキュリティとプライバシーからカレンダーへのアクセスを許可してください") return } let event = EKEvent(eventStore: eventStore) event.title = title event.startDate = startDate event.endDate = endDate event.calendar = calendar event.notes = notes var error: NSErrorPointer = nil if eventStore.saveEvent(event, span: EKSpanThisEvent, commit: true, error: error) { NSLog("%@に%@を%@から%@までの予定として追加しました", calendar.title, title, startDate, endDate) }else{ println("\(title)を追加できませんでした.") } }) } }
mit
DanielZakharin/Shelfie
Shelfie/ProductBrand+CoreDataClass.swift
1
527
// // ProductBrand+CoreDataClass.swift // Shelfie // // Created by iosdev on 23.11.2017. // Copyright © 2017 Group-6. All rights reserved. // // import Foundation import CoreData /* ####################################################### # FOR FUTURE KNOWLEDGE # # to get correct coredata classes, set module to # # current project and codegen to manual/none # ####################################################### */ public class ProductBrand: NSManagedObject { }
gpl-3.0
chicio/Sales-Taxes
SalesTaxesSwift/Model/Tax/TaxCalculationStrategy.swift
1
642
// // TaxCalculationStrategy.swift // SalesTaxes // // Created by Fabrizio Duroni on 20/11/2016. // Copyright © 2016 Fabrizio Duroni. All rights reserved. // import Foundation /** A protocol that all tax algorithm strategy classes must adopt. */ protocol TaxCalculationStrategy: class { /** Calculate tax using a specific algorithm. All implementation of this method will contain a specific algorithm for tax calculation. - parameter product: product on which taxes will be calculated. - returns: the amount of taxes to be paid. */ func calculateTax(product:Product) -> Float }
mit
whereuat/whereuat-ios
whereuat-ios/Views/RegisterView/RegisterViewController.swift
1
7722
// // RegisterViewController.swift // whereuat-ios // // Created by Raymond Jacobson on 3/1/16. // Copyright © 2016 whereu@. All rights reserved. // import UIKit import Alamofire import SlideMenuControllerSwift class RegisterViewController: UIViewController, RegisterViewDelegate, UITextFieldDelegate { var verificationRequested = false var registerView: RegisterView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.registerView = RegisterView() self.registerView.delegate = self view.addSubview(self.registerView) registerForKeyboardNotifications() self.registerView.areaCodeView.delegate = self self.registerView.lineNumberView.delegate = self self.registerView.verificationCodeView.delegate = self } func registerForKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RegisterViewController.keyboardWillBeShown(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RegisterViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillBeShown(aNotification: NSNotification) { let frame = (aNotification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() UIView.animateWithDuration(0.25, animations: { self.registerView.frame.origin.y = -(frame.height-20) }, completion: { (value: Bool) in }) } func keyboardWillBeHidden(aNotification: NSNotification) { self.registerView.frame.origin.y = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* * goButtonClickHandler handles clicks on the registration view. * since the same button is used for submitting phone number as well as submitting verification code, * there are two code paths to take. */ func goButtonClickHandler() { // Fade the button out and disable it UIView.animateWithDuration(1.0) { self.registerView.goButton.alpha = 0.3 self.registerView.goButton.backgroundColor = ColorWheel.darkGray self.registerView.goButton.enabled = false } if (self.verificationRequested) { // We have sent a phone number to the server already and are now sending a verification code self.sendVerificationCode() } else { // We are submitting a phone number self.sendPhoneNumber() } } /* * sendVerificationCode sends a verification code to the server to get validated */ func sendVerificationCode() { let verificationCode = String(self.registerView.verificationCodeView.text!) let phoneNumber = NSUserDefaults.standardUserDefaults().stringForKey("phoneNumber")! let gcmToken = NSUserDefaults.standardUserDefaults().stringForKey("gcmToken")! let verificationParameters = [ "phone-#" : phoneNumber, "gcm-token" : gcmToken, "verification-code" : verificationCode, "client-os" : "IOS" ] Alamofire.request(.POST, Global.serverURL + "/account/new", parameters: verificationParameters, encoding: .JSON) .validate() .responseString { response in switch response.result { case .Success: debugPrint(response) NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isRegistered") let storyBoard = UIStoryboard(name: "Main", bundle: nil) // Instantiate view controllers for main views let contactsViewController = storyBoard.instantiateViewControllerWithIdentifier("ContactsViewController") as! ContactsViewController let drawerViewController = storyBoard.instantiateViewControllerWithIdentifier("DrawerViewController") as! DrawerViewController // Instantiate navigation bar view, which wraps the contactsView let nvc: UINavigationController = UINavigationController(rootViewController: contactsViewController) drawerViewController.homeViewController = nvc // Instantiate the slide menu, which wraps the navigation controller SlideMenuOptions.contentViewScale = 1.0 let controller = SlideMenuController(mainViewController: nvc, leftMenuViewController: drawerViewController) self.presentViewController(controller, animated: true, completion: nil) case .Failure(let error): print("Request failed with error: \(error)") self.verificationRequested = false; self.registerView.changeToPhoneNumberUI() } } } /* * sendPhoneNumber sends a phone number to the server to request an account (via verification code) */ func sendPhoneNumber() { let phoneNumber = "+1" + self.registerView.areaCodeView.text! + self.registerView.lineNumberView.text! let requestAuthParameters = [ "phone-#": phoneNumber ] Alamofire.request(.POST, Global.serverURL + "/account/request", parameters: requestAuthParameters, encoding: .JSON) .responseString { response in debugPrint(response) switch response.result { case .Success(_): NSUserDefaults.standardUserDefaults().setObject(phoneNumber, forKey: "phoneNumber") // The next time goButtonClickHandler() is invoked, we are going to be requesting a verification self.verificationRequested = true; self.registerView.changeToVerificationUI() case .Failure(let error): print("Request failed with error: \(error)") } } } /* * Set max length of input fields */ func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { var allowedLength: Int switch textField.tag { case RegisterView.areaCodeViewTag: allowedLength = Global.areaCodeLength if textField.text?.characters.count == allowedLength && string.characters.count != 0 { self.registerView.lineNumberView.becomeFirstResponder() allowedLength = Global.lineNumberLength } case RegisterView.lineNumberViewTag: allowedLength = Global.lineNumberLength if textField.text?.characters.count == 0 && string.characters.count == 0 && self.registerView.lineNumberView.text?.characters.count == 0 { self.registerView.areaCodeView.becomeFirstResponder() allowedLength = Global.areaCodeLength } case RegisterView.verificationCodeViewTag: allowedLength = Global.verificationCodeLength default: allowedLength = 255 } if textField.text?.characters.count >= allowedLength && range.length == 0 { // Change not allowed return false } else { // Change allowed return true } } }
apache-2.0
visualitysoftware/swift-sdk
CloudBoostTests/CloudGeoPointTest.swift
1
6499
// // CloudGeoPointTest.swift // CloudBoost // // Created by Randhir Singh on 08/04/16. // Copyright © 2016 Randhir Singh. All rights reserved. // import XCTest @testable import CloudBoost class CloudGeoPointTest: XCTestCase { override func setUp() { super.setUp() let app = CloudApp.init(appID: "xckzjbmtsbfb", appKey: "345f3324-c73c-4b15-94b5-9e89356c1b4e") app.setIsLogging(true) app.setMasterKey("f5cc5cb3-ba0d-446d-9e51-e09be23c540d") // 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() } // savelatitude and longitude with integer func testSaveLatLong() { let exp = expectationWithDescription("Save latitude and longitude") let point = try! CloudGeoPoint(latitude: 17.7, longitude: 18.9) let locationTest = CloudObject(tableName: "LocationTest") locationTest.set("location", value: point) locationTest.save({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } // should create a geo point with 0,0 func testGeo00(){ let exp = expectationWithDescription("Save latitude and longitude") let point = try! CloudGeoPoint(latitude: 0, longitude: 0) let locationTest = CloudObject(tableName: "LocationTest") locationTest.set("location", value: point) locationTest.save({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } // latitude and longitude when passing a valid numeric data as string type does not apply for swift SDK // should get data from server for near function func testNearFunction() { let exp = expectationWithDescription("testing near function") let query = CloudQuery(tableName: "LocationTest") let point = try! CloudGeoPoint(latitude: 17.7, longitude: 18.3) query.near("location", geoPoint: point, maxDistance: 400000, minDistance: 0) try! query.find({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } // should get list of CloudGeoPoint Object from server Polygon type geoWithin func testGeoWithinList() { let exp = expectationWithDescription("testing geo within function") let query = CloudQuery(tableName: "LocationTest") let loc1 = try! CloudGeoPoint(latitude: 18.4, longitude: 78.9) let loc2 = try! CloudGeoPoint(latitude: 17.4, longitude: 78.4) let loc3 = try! CloudGeoPoint(latitude: 17.7, longitude: 80.4) query.geoWithin("location", geoPoints: [loc1,loc2,loc3]) try! query.find({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } // should get list of CloudGeoPoint Object from server Polygon type geoWithin + limit func testGeoWithinListLimit() { let exp = expectationWithDescription("testing geo within function with limit") let query = CloudQuery(tableName: "LocationTest") let loc1 = try! CloudGeoPoint(latitude: 18.4, longitude: 78.9) let loc2 = try! CloudGeoPoint(latitude: 17.4, longitude: 78.4) let loc3 = try! CloudGeoPoint(latitude: 17.7, longitude: 80.4) query.geoWithin("location", geoPoints: [loc1,loc2,loc3]) query.limit = 4 try! query.find({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } //should get list of CloudGeoPoint Object from server for Circle type geoWithin func testGeoWithinRadius() { let exp = expectationWithDescription("testing geo within function with radius") let query = CloudQuery(tableName: "LocationTest") let loc = try! CloudGeoPoint(latitude: 17.3, longitude: 78.3) query.geoWithin("location", geoPoint: loc, radius: 1000) try! query.find({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } //should get list of CloudGeoPoint Object from server for Circle type geoWithin with limits func testGeoWithinRadiusLimit() { let exp = expectationWithDescription("testing geo within function with radius and limit") let query = CloudQuery(tableName: "LocationTest") let loc = try! CloudGeoPoint(latitude: 17.3, longitude: 78.3) query.geoWithin("location", geoPoint: loc, radius: 1000) query.limit = 4 try! query.find({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) waitForExpectationsWithTimeout(30, handler: nil) } // should update a saved GeoPoint func testUpdateGeoPoint() { let exp = expectationWithDescription("update saved GeoPoint") let point = try! CloudGeoPoint(latitude: 17.7, longitude: 79.9) let locationTest = CloudObject(tableName: "LocationTest") locationTest.set("location", value: point) locationTest.save({ (response: CloudBoostResponse) in if let point2 = locationTest.getGeoPoint("location") { try! point2.setLatitude(55) locationTest.set("location", value: point2) locationTest.save({ (response: CloudBoostResponse) in response.log() XCTAssert(response.success) exp.fulfill() }) } }) waitForExpectationsWithTimeout(60, handler: nil) } }
mit
flypaper0/ethereum-wallet
ethereum-wallet/Classes/PresentationLayer/Wallet/Send/Router/SendRouter.swift
1
1418
// Copyright © 2018 Conicoin LLC. All rights reserved. // Created by Artur Guseinov import UIKit class SendRouter { var app: Application! } // MARK: - SendRouterInput extension SendRouter: SendRouterInput { func presentScan(from: UIViewController, output: ScanModuleOutput) { ScanModule.create(app: app).present(from: from, output: output) } func presentChooseCurrency(from: UIViewController, selectedIso: String, output: ChooseCurrencyModuleOutput) { ChooseCurrencyModule.create(app: app).present(from: from, selectedIso: selectedIso, output: output) } func presentPin(from: UIViewController, amount: String, address: String, postProcess: PinPostProcess?) { let addressString = address[0..<4] + "..." + address[address.count - 4..<address.count] let pinModule = PinModule.create(app: app, state: .send(amount: amount, address: addressString)) pinModule.present(from: from, postProcess: postProcess) { pinVC in let popupModule = PopupModule.create(app: self.app, state: .txSent(amount: amount, address: address)) popupModule.present(from: pinVC) { popupVC in popupVC.popToRoot() } } } func presentSendSettings(from: UIViewController, settings: SendSettings, coin: AbstractCoin, output: SendSettingsModuleOutput?) { SendSettingsModule.create(app: app).present(from: from, settings: settings, coin: coin, output: output) } }
gpl-3.0
xwu/swift
test/IRGen/objc_bridge.swift
8
11035
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation // CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = internal constant { i32, i32, [17 x { i8*, i8*, i8* }] } { // CHECK: i32 24, // CHECK: i32 17, // CHECK: [17 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strRealPropSSvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strRealPropSSvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strFakePropSSvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strFakePropSSvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvgTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC9strResultSSyFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC6strArg1sySS_tFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCACycfcTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfDTo" to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0), // CHECK: i8* bitcast (void (%3*, i8*, %4*)* @"$s11objc_bridge3BasC9acceptSetyyShyACGFTo" to i8*) // CHECK: } // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @{{.*}}, i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfETo" to i8*) // CHECK: } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = internal constant { i32, i32, [5 x { i8*, i8* }] } { // CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [8 x i8] c"T@?,N,C\00" // CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = internal constant {{.*}} [[OBJC_BLOCK_PROPERTY]] func getDescription(_ o: NSObject) -> String { return o.description } func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { f.setFoo(s) } // NSString *bar(int); func callBar() -> String { return bar(0) } // void setBar(NSString *s); func callSetBar(_ s: String) { setBar(s) } var NSS : NSString = NSString() // -- NSString methods don't convert 'self' extension NSString { // CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { // CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc var nsstrFakeProp : NSString { get { return NSS } set {} } // CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE11nsstrResultAByFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { @objc func nsstrResult() -> NSString { return NSS } // CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE8nsstrArg1syAB_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc func nsstrArg(s s: NSString) { } } class Bas : NSObject { // CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strRealPropSSvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { // CHECK: define internal void @"$s11objc_bridge3BasC11strRealPropSSvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc var strRealProp : String // CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strFakePropSSvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { // CHECK: define internal void @"$s11objc_bridge3BasC11strFakePropSSvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc var strFakeProp : String { get { return "" } set {} } // CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { // CHECK: define internal void @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc var nsstrRealProp : NSString // CHECK: define hidden swiftcc %TSo8NSStringC* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvg"(%T11objc_bridge3BasC* swiftself %0) {{.*}} { // CHECK: define internal void @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc var nsstrFakeProp : NSString { get { return NSS } set {} } // CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC9strResultSSyFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { @objc func strResult() -> String { return "" } // CHECK: define internal void @"$s11objc_bridge3BasC6strArg1sySS_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc func strArg(s s: String) { } // CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} { @objc func nsstrResult() -> NSString { return NSS } // CHECK: define internal void @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} { @objc func nsstrArg(s s: NSString) { } override init() { strRealProp = String() nsstrRealProp = NSString() super.init() } deinit { var x = 10 } override var hash: Int { return 0 } @objc func acceptSet(_ set: Set<Bas>) { } } func ==(lhs: Bas, rhs: Bas) -> Bool { return true } class OptionalBlockProperty: NSObject { @objc var x: (([AnyObject]) -> [AnyObject])? }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/23077-bool.swift
11
227
// 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 P{let c{class B<T where g:a{class B<T where g:r<D>{}}
mit
erduoniba/FDDUITableViewDemoSwift
FDDUITableViewDemoSwift/FDDBaseRepo/FDDBaseCellModel.swift
1
1066
// // FDDBaseCellModel.swift // FDDUITableViewDemoSwift // // Created by denglibing on 2017/2/9. // Copyright © 2017年 denglibing. All rights reserved. // Demo: https://github.com/erduoniba/FDDUITableViewDemoSwift // import UIKit open class FDDBaseCellModel: NSObject { open var cellData: AnyObject? open var cellClass: AnyClass? open weak var delegate: AnyObject? open var cellHeight: Float = 44 open var staticCell: UITableViewCell? open var cellReuseIdentifier: String? override init() { super.init() } public convenience init(cellClass: AnyClass?, cellHeight: Float, cellData: AnyObject?) { self.init() self.cellClass = cellClass self.cellHeight = cellHeight self.cellData = cellData } open class func modelWithCellClass(_ cellClass: AnyClass?, cellHeight: Float, cellData: AnyObject?) -> FDDBaseCellModel { let cellModel: FDDBaseCellModel = FDDBaseCellModel(cellClass: cellClass, cellHeight: cellHeight, cellData: cellData) return cellModel } }
mit
michael-yuji/BLE-Hacker
BLE HackerUITests/BLE_HackerUITests.swift
1
1242
// // BLE_HackerUITests.swift // BLE HackerUITests // // Created by 悠二 on 10/17/15. // Copyright © 2015 Yuji. All rights reserved. // import XCTest class BLE_HackerUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
gpl-2.0
radex/swift-compiler-crashes
crashes-fuzzing/07411-swift-constraints-constraintsystem-getfixedtyperecursive.swift
11
211
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b{func a[{}protocol A{typealias e:A.e
mit
yanyuqingshi/ios-charts
Charts/Classes/Data/BubbleChartDataEntry.swift
1
1226
// // BubbleDataEntry.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation public class BubbleChartDataEntry: ChartDataEntry { /// The size of the bubble. public var size = CGFloat(0.0) /// :xIndex: The index on the x-axis. /// :val: The value on the y-axis. /// :size: The size of the bubble. public init(xIndex: Int, value: Double, size: CGFloat) { super.init(value: value, xIndex: xIndex) self.size = size } /// :xIndex: The index on the x-axis. /// :val: The value on the y-axis. /// :size: The size of the bubble. /// :data: Spot for additional data this Entry represents. public init(xIndex: Int, value: Double, size: CGFloat, data: AnyObject?) { super.init(value: value, xIndex: xIndex, data: data) self.size = size } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { var copy = super.copyWithZone(zone) as! BubbleChartDataEntry; copy.size = size; return copy; } }
apache-2.0
Asura19/My30DaysOfSwift
TumblrMenu/TumblrMenu/MainViewController.swift
1
590
// // MainViewController.swift // TumblrMenu // // Created by Phoenix on 2017/4/7. // Copyright © 2017年 Wolkamo. All rights reserved. // import UIKit class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true } override var preferredStatusBarStyle : UIStatusBarStyle { return UIStatusBarStyle.lightContent } @IBAction func unwindToMain(_ sender: UIStoryboardSegue) { self.dismiss(animated: true, completion: nil) } }
mit
qutheory/vapor
Sources/XCTVapor/XCTHTTPRequest.swift
2
2072
public struct XCTHTTPRequest { public var method: HTTPMethod public var url: URI public var headers: HTTPHeaders public var body: ByteBuffer private struct _ContentContainer: ContentContainer { var body: ByteBuffer var headers: HTTPHeaders var contentType: HTTPMediaType? { return self.headers.contentType } mutating func encode<E>(_ encodable: E, using encoder: ContentEncoder) throws where E : Encodable { try encoder.encode(encodable, to: &self.body, headers: &self.headers) } func decode<D>(_ decodable: D.Type, using decoder: ContentDecoder) throws -> D where D : Decodable { fatalError("Decoding from test request is not supported.") } mutating func encode<C>(_ content: C, using encoder: ContentEncoder) throws where C : Content { var content = content try content.beforeEncode() try encoder.encode(content, to: &self.body, headers: &self.headers) } } public var content: ContentContainer { get { _ContentContainer(body: self.body, headers: self.headers) } set { let content = (newValue as! _ContentContainer) self.body = content.body self.headers = content.headers } } private struct _URLQueryContainer: URLQueryContainer { var url: URI func decode<D>(_ decodable: D.Type, using decoder: URLQueryDecoder) throws -> D where D: Decodable { fatalError("Decoding from test request is not supported.") } mutating func encode<E>(_ encodable: E, using encoder: URLQueryEncoder) throws where E: Encodable { try encoder.encode(encodable, to: &self.url) } } public var query: URLQueryContainer { get { _URLQueryContainer(url: url) } set { let query = (newValue as! _URLQueryContainer) self.url = query.url } } }
mit
debugsquad/Hyperborea
Hyperborea/View/Recent/VRecentHeader.swift
1
1239
import UIKit class VRecentHeader:UICollectionReusableView { private weak var label:UILabel! private let kLabelMargin:CGFloat = 10 private let kLabelHeight:CGFloat = 34 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear isUserInteractionEnabled = false let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.regular(size:15) label.textColor = UIColor(white:0.3, alpha:1) self.label = label addSubview(label) NSLayoutConstraint.bottomToBottom( view:label, toView:self) NSLayoutConstraint.height( view:label, constant:kLabelHeight) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelMargin) } required init?(coder:NSCoder) { return nil } //MARK: public func config(model:MRecentDay) { label.text = model.title } }
mit
WeirdMath/SwiftyHaru
Tests/SwiftyHaruTests/GridTests.swift
1
14241
// // GridTests.swift // SwiftyHaru // // Created by Sergej Jaskiewicz on 05.11.16. // // import XCTest import Foundation @testable import SwiftyHaru final class GridTests: TestCase { static let allTests = [ ("testDrawDefaultGrid", testDrawDefaultGrid), ("testCustomVerticalMajorLines", testCustomVerticalMajorLines), ("testCustomHorizontalMajorLines", testCustomHorizontalMajorLines), ("testCustomVerticalMinorLines", testCustomVerticalMinorLines), ("testCustomHorizontalMinorLines", testCustomHorizontalMinorLines), ("testCustomTopSerifs", testCustomTopSerifs), ("testCustomBottomSerifs", testCustomBottomSerifs), ("testCustomLeftSerifs", testCustomLeftSerifs), ("testCustomRightSerifs", testCustomRightSerifs), ("testCustomTopLabels", testCustomTopLabels), ("testCustomBottomLabels", testCustomBottomLabels), ("testCustomLeftLabels", testCustomLeftLabels), ("testCustomRightLabels", testCustomRightLabels) ] func testDrawDefaultGrid() throws { // Given let grid = Grid(width: 400, height: 600) // When try document.addPage { context in try context.draw(grid, x: 100, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomVerticalMajorLines() throws { // Given let parameters = Grid.MajorLineParameters(lineWidth: 3, lineSpacing: 20, lineColor: #colorLiteral(red: 0.1215686277, green: 0.01176470611, blue: 0.4235294163, alpha: 1)) let lines1 = Grid.Lines(verticalMajor: parameters, drawVerticalMajorLinesFirst: true) let gridWithVerticalMajorLinesDrawnFirst = Grid(width: 200, height: 200, lines: lines1) let lines2 = Grid.Lines(verticalMajor: parameters, drawVerticalMajorLinesFirst: false) let gridWithVerticalMajorLinesDrawnLater = Grid(width: 200, height: 200, lines: lines2) // When try document.addPage { context in try context.draw(gridWithVerticalMajorLinesDrawnFirst, x: 100, y: 100) try context.draw(gridWithVerticalMajorLinesDrawnLater, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomHorizontalMajorLines() throws { // Given let parameters = Grid.MajorLineParameters(lineWidth: 3, lineSpacing: 30, lineColor: #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)) let lines1 = Grid.Lines(horizontalMajor: parameters, drawVerticalMajorLinesFirst: false) let gridWithHorizontalMajorLinesDrawnFirst = Grid(width: 200, height: 200, lines: lines1) let lines2 = Grid.Lines(horizontalMajor: parameters, drawVerticalMajorLinesFirst: true) let gridWithHorizontalMajorLinesDrawnLater = Grid(width: 200, height: 200, lines: lines2) // When try document.addPage { context in try context.draw(gridWithHorizontalMajorLinesDrawnFirst, x: 100, y: 100) try context.draw(gridWithHorizontalMajorLinesDrawnLater, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomVerticalMinorLines() throws { // Given let parameters = Grid.MinorLineParameters(lineWidth: 1, minorSegmentsPerMajorSegment: 3, lineColor: #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)) let lines1 = Grid.Lines(verticalMinor: parameters, drawVerticalMinorLinesFirst: true) let gridWithVerticalMinorLinesDrawnFirst = Grid(width: 200, height: 200, lines: lines1) let lines2 = Grid.Lines(verticalMinor: parameters, drawVerticalMinorLinesFirst: false) let gridWithVerticalMinorLinesDrawnLater = Grid(width: 200, height: 200, lines: lines2) // When try document.addPage { context in try context.draw(gridWithVerticalMinorLinesDrawnFirst, x: 100, y: 100) try context.draw(gridWithVerticalMinorLinesDrawnLater, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomHorizontalMinorLines() throws { // Given let parameters = Grid.MinorLineParameters(lineWidth: 0.7, minorSegmentsPerMajorSegment: 4, lineColor: #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)) let lines1 = Grid.Lines(horizontalMinor: parameters, drawVerticalMinorLinesFirst: false) let gridWithHorizontalMinorLinesDrawnFirst = Grid(width: 200, height: 200, lines: lines1) let lines2 = Grid.Lines(horizontalMinor: parameters, drawVerticalMinorLinesFirst: true) let gridWithHorizontalMinorLinesDrawnLater = Grid(width: 200, height: 200, lines: lines2) // When try document.addPage { context in try context.draw(gridWithHorizontalMinorLinesDrawnFirst, x: 100, y: 100) try context.draw(gridWithHorizontalMinorLinesDrawnLater, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomTopSerifs() throws { // Given let parameters = Grid.SerifParameters(frequency: 2, width: 2, length: 10, color: #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)) let serifs = Grid.Serifs(top: parameters, bottom: nil, left: nil, right: nil) let grid = Grid(width: 200, height: 200, serifs: serifs) // When try document.addPage { context in try context.draw(grid, x: 100, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomBottomSerifs() throws { // Given let parameters = Grid.SerifParameters(frequency: 2, width: 2, length: 10, color: #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)) let serifs = Grid.Serifs(top: nil, bottom: parameters, left: nil, right: nil) let grid = Grid(width: 200, height: 200, serifs: serifs) // When try document.addPage { context in try context.draw(grid, x: 100, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomLeftSerifs() throws { // Given let parameters = Grid.SerifParameters(frequency: 2, width: 2, length: 10, color: #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)) let serifs = Grid.Serifs(top: nil, bottom: nil, left: parameters, right: nil) let grid = Grid(width: 200, height: 200, serifs: serifs) // When try document.addPage { context in try context.draw(grid, x: 100, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomRightSerifs() throws { // Given let parameters = Grid.SerifParameters(frequency: 2, width: 2, length: 10, color: #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)) let serifs = Grid.Serifs(top: nil, bottom: nil, left: nil, right: parameters) let grid = Grid(width: 200, height: 200, serifs: serifs) // When try document.addPage { context in try context.draw(grid, x: 100, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomTopLabels() throws { // Given let parametersNonReversed = Grid.LabelParameters(sequence: ["", "1", "10", "100", "1000"], font: .timesBold, fontSize: 5, fontColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1), frequency: 2, offset: Vector(dx: 2, dy: -10), reversed: false) var parametersReversed = parametersNonReversed parametersReversed.reversed = true let labelsNonReversed = Grid.Labels(top: parametersNonReversed, bottom: nil, left: nil, right: nil) let labelsReversed = Grid.Labels(top: parametersReversed, bottom: nil, left: nil, right: nil) let gridWithNonReversedLabels = Grid(width: 200, height: 200, labels: labelsNonReversed) let gridWithReversedLabels = Grid(width: 200, height: 200, labels: labelsReversed) // When try document.addPage { context in try context.draw(gridWithNonReversedLabels, x: 100, y: 100) try context.draw(gridWithReversedLabels, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomBottomLabels() throws { // Given let parametersNonReversed = Grid.LabelParameters(sequence: ["A", "B", "C", "D", "E"], font: .timesBold, fontSize: 5, fontColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1), frequency: 2, offset: Vector(dx: -2, dy: -7), reversed: false) var parametersReversed = parametersNonReversed parametersReversed.reversed = true let labelsNonReversed = Grid.Labels(top: nil, bottom: parametersNonReversed, left: nil, right: nil) let labelsReversed = Grid.Labels(top: nil, bottom: parametersReversed, left: nil, right: nil) let gridWithNonReversedLabels = Grid(width: 200, height: 200, labels: labelsNonReversed) let gridWithReversedLabels = Grid(width: 200, height: 200, labels: labelsReversed) // When try document.addPage { context in try context.draw(gridWithNonReversedLabels, x: 100, y: 100) try context.draw(gridWithReversedLabels, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomLeftLabels() throws { // Given let sequence1 = sequence(first: 0.1, next: { $0 + 0.1 }).lazy.map { String(format: "%.1f", $0) } let sequence2 = sequence(first: 0.1, next: { $0 + 0.1 }).lazy.map { String(format: "%.1f", $0) } let parametersNonReversed = Grid.LabelParameters(sequence: "" + sequence1, font: .timesBold, fontSize: 5, fontColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1), frequency: 1, offset: Vector(dx: 5, dy: 0), reversed: false) var parametersReversed = parametersNonReversed parametersReversed.sequence = "" + sequence2 parametersReversed.reversed = true let labelsNonReversed = Grid.Labels(top: nil, bottom: nil, left: parametersNonReversed, right: nil) let labelsReversed = Grid.Labels(top: nil, bottom: nil, left: parametersReversed, right: nil) let gridWithNonReversedLabels = Grid(width: 200, height: 200, labels: labelsNonReversed) let gridWithReversedLabels = Grid(width: 200, height: 200, labels: labelsReversed) // When try document.addPage { context in try context.draw(gridWithNonReversedLabels, x: 100, y: 100) try context.draw(gridWithReversedLabels, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } func testCustomRightLabels() throws { // Given let parametersNonReversed = Grid.LabelParameters(sequence: ["0", "1", "2"], font: .timesBold, fontSize: 5, fontColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1), frequency: 2, offset: Vector(dx: 5, dy: 0), reversed: false) var parametersReversed = parametersNonReversed parametersReversed.reversed = true let labelsNonReversed = Grid.Labels(top: nil, bottom: nil, left: nil, right: parametersNonReversed) let labelsReversed = Grid.Labels(top: nil, bottom: nil, left: nil, right: parametersReversed) let gridWithNonReversedLabels = Grid(width: 200, height: 200, labels: labelsNonReversed) let gridWithReversedLabels = Grid(width: 200, height: 200, labels: labelsReversed) // When try document.addPage { context in try context.draw(gridWithNonReversedLabels, x: 100, y: 100) try context.draw(gridWithReversedLabels, x: 350, y: 100) } // Then assertPDFSnapshot() assertPDFImageSnapshot(page: 1, named: "1") } }
mit
Bunn/macGist
macGist/GistCell.swift
1
1971
// // GistCell.swift // macGist // // Created by Fernando Bunn on 09/01/2018. // Copyright © 2018 Fernando Bunn. All rights reserved. // // import Cocoa class GistCell: NSTableCellView { @IBOutlet private weak var titleLabel: NSTextField! @IBOutlet private weak var subtitleLabel: NSTextField! @IBOutlet private weak var lockImageView: NSImageView! static var dateFormatter: DateFormatter = { var dateFormatter = DateFormatter() dateFormatter.dateStyle = .short dateFormatter.timeStyle = .short return dateFormatter }() var selected: Bool = false { didSet { if oldValue != selected { setupColors() } } } var gist: Gist? { didSet { if let gist = gist { if gist.description.count == 0 { if let file = gist.gistFiles.first { titleLabel.stringValue = file.name } } else { titleLabel.stringValue = gist.description } subtitleLabel.stringValue = "Created at: \(GistCell.dateFormatter.string(from: gist.createdAt))" lockImageView.image = gist.publicItem ? #imageLiteral(resourceName: "lock_opened") : #imageLiteral(resourceName: "lock_closed") setupColors() } } } private func setupColors() { if selected { titleLabel.textColor = .white subtitleLabel.textColor = .white lockImageView.image = lockImageView.image?.tinting(with: .white) } else { titleLabel.textColor = .darkGray subtitleLabel.textColor = .darkGray lockImageView.image = lockImageView.image?.tinting(with: .darkGray) } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) } }
mit
ashetty1/kedge
vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-generator/examples/bookstore/Sources/Server/main.swift
131
4133
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Bookstore class Server : Service { private var shelves : [Int64:Shelf] = [:] private var books : [Int64:[Int64:Book]] = [:] private var lastShelfIndex : Int64 = 0 private var lastBookIndex : Int64 = 0 // Return all shelves in the bookstore. func listShelves () throws -> ListShelvesResponses { let responses = ListShelvesResponses() let response = ListShelvesResponse() var shelves : [Shelf] = [] for pair in self.shelves { shelves.append(pair.value) } response.shelves = shelves responses.ok = response return responses } // Create a new shelf in the bookstore. func createShelf (_ parameters : CreateShelfParameters) throws -> CreateShelfResponses { lastShelfIndex += 1 let shelf = parameters.shelf shelf.name = "shelves/\(lastShelfIndex)" shelves[lastShelfIndex] = shelf let responses = CreateShelfResponses() responses.ok = shelf return responses } // Delete all shelves. func deleteShelves () throws { shelves = [:] books = [:] lastShelfIndex = 0 lastBookIndex = 0 } // Get a single shelf resource with the given ID. func getShelf (_ parameters : GetShelfParameters) throws -> GetShelfResponses { let responses = GetShelfResponses() if let shelf : Shelf = shelves[parameters.shelf] { responses.ok = shelf } else { let err = Error() err.code = 404 err.message = "not found" responses.error = err } return responses } // Delete a single shelf with the given ID. func deleteShelf (_ parameters : DeleteShelfParameters) throws { shelves[parameters.shelf] = nil books[parameters.shelf] = nil } // Return all books in a shelf with the given ID. func listBooks (_ parameters : ListBooksParameters) throws -> ListBooksResponses { let responses = ListBooksResponses() let response = ListBooksResponse() var books : [Book] = [] if let shelfBooks = self.books[parameters.shelf] { for pair in shelfBooks { books.append(pair.value) } } response.books = books responses.ok = response return responses } // Create a new book on the shelf. func createBook (_ parameters : CreateBookParameters) throws -> CreateBookResponses { let responses = CreateBookResponses() lastBookIndex += 1 let shelf = parameters.shelf let book = parameters.book book.name = "shelves/\(shelf)/books/\(lastBookIndex)" if var shelfBooks = self.books[shelf] { shelfBooks[lastBookIndex] = book self.books[shelf] = shelfBooks } else { var shelfBooks : [Int64:Book] = [:] shelfBooks[lastBookIndex] = book self.books[shelf] = shelfBooks } responses.ok = book return responses } // Get a single book with a given ID from a shelf. func getBook (_ parameters : GetBookParameters) throws -> GetBookResponses { let responses = GetBookResponses() if let shelfBooks = self.books[parameters.shelf], let book = shelfBooks[parameters.book] { responses.ok = book } else { let err = Error() err.code = 404 err.message = "not found" responses.error = err } return responses } // Delete a single book with a given ID from a shelf. func deleteBook (_ parameters : DeleteBookParameters) throws { if var shelfBooks = self.books[parameters.shelf] { shelfBooks[parameters.book] = nil self.books[parameters.shelf] = shelfBooks } } } initialize(service:Server(), port:8080) run()
apache-2.0
Guanzhangpeng/ZPSegmentBar
ZPSegmentBar/Classes/ZPSegmentBarView.swift
1
1727
// // ZPSegmentBarView.swift // ZPSegmentBar // // Created by 管章鹏 on 17/3/9. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit public class ZPSegmentBarView: UIView { var titles :[String] var style :ZPStyle var childVcs :[UIViewController] var parentVc : UIViewController public init(frame:CGRect,titles:[String],style : ZPStyle,childVcs:[UIViewController],parentVc:UIViewController ) { self.titles=titles self.style=style self.childVcs=childVcs self.parentVc=parentVc super.init(frame: frame) setupUI() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK - UI布局 extension ZPSegmentBarView { fileprivate func setupUI() { //1.0 创建TitleView let titleFrame = CGRect(x: 0, y: 64, width: bounds.width, height: style.titleHeight) let titleView = ZPTitleView(frame: titleFrame, titles: titles, style: style) addSubview(titleView) titleView.backgroundColor = style.titleViewBackgroundColor //2.0 创建ContentView let contentFrame = CGRect(x: 0, y: titleView.frame.maxY, width: bounds.width, height: bounds.height-style.titleHeight) let contentView = ZPContentView(frame: contentFrame, childVcs: childVcs, parentVc: parentVc) addSubview(contentView) // 3.0 让ContentView成为titleView的代理 titleView.delegate = contentView contentView.delegate = titleView //3.0 设置TitleView和ContentView之间的关联 } }
mit
szpnygo/firefox-ios
StorageTests/SyncCommandsTests.swift
5
9650
/* 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 XCTest func byValue(a: SyncCommand, b: SyncCommand) -> Bool { return a.value < b.value } func byClient(a: RemoteClient, b: RemoteClient) -> Bool{ return a.guid! < b.guid! } class SyncCommandsTests: XCTestCase { var clients: [RemoteClient] = [RemoteClient]() var clientsAndTabs: SQLiteRemoteClientsAndTabs! var shareItems = [ShareItem]() var multipleCommands: [ShareItem] = [ShareItem]() var wipeCommand: SyncCommand! var db: BrowserDB! override func setUp() { let files = MockFiles() files.remove("browser.db") db = BrowserDB(filename: "browser.db", files: files) // create clients let now = NSDate.now() let client1GUID = Bytes.generateGUID() let client2GUID = Bytes.generateGUID() let client3GUID = Bytes.generateGUID() self.clients.append(RemoteClient(guid: client1GUID, name: "Test client 1", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS")) self.clients.append(RemoteClient(guid: client2GUID, name: "Test client 2", modified: (now - OneHourInMilliseconds), type: "desktop", formfactor: "laptop", os: "Darwin")) self.clients.append(RemoteClient(guid: client3GUID, name: "Test local client", modified: (now - OneMinuteInMilliseconds), type: "mobile", formfactor: "largetablet", os: "iOS")) clientsAndTabs = SQLiteRemoteClientsAndTabs(db: db) clientsAndTabs.insertOrUpdateClients(clients) shareItems.append(ShareItem(url: "http://mozilla.com", title: "Mozilla", favicon: nil)) shareItems.append(ShareItem(url: "http://slashdot.org", title: "Slashdot", favicon: nil)) shareItems.append(ShareItem(url: "http://news.bbc.co.uk", title: "BBC News", favicon: nil)) shareItems.append(ShareItem(url: "http://news.bbc.co.uk", title: nil, favicon: nil)) wipeCommand = SyncCommand(value: "{'command':'wipeAll', 'args':[]}") } override func tearDown() { clientsAndTabs.deleteCommands() clientsAndTabs.clear() } func testCreateSyncCommandFromShareItem(){ let action = "testcommand" let shareItem = shareItems[0] let syncCommand = SyncCommand.fromShareItem(shareItem, withAction: action) XCTAssertNil(syncCommand.commandID) XCTAssertNotNil(syncCommand.value) let jsonObj:[String: AnyObject] = [ "command": action, "args": [shareItem.url, shareItem.title ?? ""] ] XCTAssertEqual(JSON.stringify(jsonObj, pretty: false), syncCommand.value) } func testInsertWithNoURLOrTitle() { // Test insert command to table for let e = self.expectationWithDescription("Insert.") clientsAndTabs.insertCommand(self.wipeCommand, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(3, $0.successValue!) var error2: NSError? = nil let commandCursor = self.db.withReadableConnection(&error2) { (connection, err) -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands)" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } XCTAssertNil(error2) XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(3, commandCursor[0]!) e.fulfill() } self.waitForExpectationsWithTimeout(5, handler: nil) } func testInsertWithURLOnly() { let action = "testcommand" let shareItem = shareItems[3] let syncCommand = SyncCommand.fromShareItem(shareItem, withAction: action) let e = self.expectationWithDescription("Insert.") clientsAndTabs.insertCommand(syncCommand, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(3, $0.successValue!) var error: NSError? = nil let commandCursor = self.db.withReadableConnection(&error) { (connection, err) -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands)" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } XCTAssertNil(error) XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(3, commandCursor[0]!) e.fulfill() } self.waitForExpectationsWithTimeout(5, handler: nil) } func testInsertWithMultipleCommands() { let action = "testcommand" let e = self.expectationWithDescription("Insert.") let syncCommands = shareItems.map { item in return SyncCommand.fromShareItem(item, withAction: action) } clientsAndTabs.insertCommands(syncCommands, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(12, $0.successValue!) var error: NSError? = nil let commandCursor = self.db.withReadableConnection(&error) { (connection, err) -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands)" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } XCTAssertNil(error) XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(12, commandCursor[0]!) e.fulfill() } self.waitForExpectationsWithTimeout(5, handler: nil) } func testGetForAllClients() { let action = "testcommand" let syncCommands = shareItems.map { item in return SyncCommand.fromShareItem(item, withAction: action) }.sorted(byValue) clientsAndTabs.insertCommands(syncCommands, forClients: clients) let b = self.expectationWithDescription("Get for invalid client.") clientsAndTabs.getCommands().upon({ result in XCTAssertTrue(result.isSuccess) if let clientCommands = result.successValue { XCTAssertEqual(clientCommands.count, self.clients.count) for client in clientCommands.keys { XCTAssertEqual(syncCommands, clientCommands[client]!.sorted(byValue)) } } else { XCTFail("Expected no commands!") } b.fulfill() }) self.waitForExpectationsWithTimeout(5, handler: nil) } func testDeleteForValidClient() { let action = "testcommand" let syncCommands = shareItems.map { item in return SyncCommand.fromShareItem(item, withAction: action) }.sorted(byValue) var client = self.clients[0] let a = self.expectationWithDescription("delete for client.") let b = self.expectationWithDescription("Get for deleted client.") let c = self.expectationWithDescription("Get for not deleted client.") clientsAndTabs.insertCommands(syncCommands, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(12, $0.successValue!) let result = self.clientsAndTabs.deleteCommands(client.guid!).value XCTAssertTrue(result.isSuccess) a.fulfill() var error: NSError? = nil let commandCursor = self.db.withReadableConnection(&error) { (connection, err) -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands) WHERE client_guid = '\(client.guid!)'" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } XCTAssertNil(error) XCTAssertNotNil(commandCursor[0]) XCTAssertEqual(0, commandCursor[0]!) b.fulfill() client = self.clients[1] let commandCursor2 = self.db.withReadableConnection(&error) { (connection, err) -> Cursor<Int> in let select = "SELECT COUNT(*) FROM \(TableSyncCommands) WHERE client_guid = '\(client.guid!)'" return connection.executeQuery(select, factory: IntFactory, withArgs: nil) } XCTAssertNil(error) XCTAssertNotNil(commandCursor2[0]) XCTAssertEqual(4, commandCursor2[0]!) c.fulfill() } self.waitForExpectationsWithTimeout(5, handler: nil) } func testDeleteForAllClients() { let action = "testcommand" let syncCommands = shareItems.map { item in return SyncCommand.fromShareItem(item, withAction: action) } let a = self.expectationWithDescription("Wipe for all clients.") let b = self.expectationWithDescription("Get for clients.") clientsAndTabs.insertCommands(syncCommands, forClients: clients).upon { XCTAssertTrue($0.isSuccess) XCTAssertEqual(12, $0.successValue!) let result = self.clientsAndTabs.deleteCommands().value XCTAssertTrue(result.isSuccess) a.fulfill() self.clientsAndTabs.getCommands().upon({ result in XCTAssertTrue(result.isSuccess) if let clientCommands = result.successValue { XCTAssertEqual(0, clientCommands.count) } else { XCTFail("Expected no commands!") } b.fulfill() }) } self.waitForExpectationsWithTimeout(5, handler: nil) } }
mpl-2.0
YoungGary/30daysSwiftDemo
day3/day3/day3/AppDelegate.swift
1
2130
// // AppDelegate.swift // day3 // // Created by YOUNG on 16/9/26. // Copyright © 2016年 Young. 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
ptsochantaris/trailer-cli
Sources/trailer/Data/Models/Review.swift
1
6861
// // Review.swift // trailer // // Created by Paul Tsochantaris on 18/08/2017. // Copyright © 2017 Paul Tsochantaris. All rights reserved. // import Foundation enum ReviewState: String, Codable { case pending, commented, approved, changes_requested, dimissed init?(rawValue: String) { switch rawValue.lowercased() { case "pending": self = ReviewState.pending case "commented": self = ReviewState.commented case "approved": self = ReviewState.approved case "changes_requested": self = ReviewState.changes_requested case "dimissed": self = ReviewState.dimissed default: return nil } } } struct Review: Item, Announceable { var id: String var parents: [String: [Relationship]] var syncState: SyncState var elementType: String static var allItems = [String: Review]() static let idField = "id" var state = ReviewState.pending var body = "" var viewerDidAuthor = false var createdAt = Date.distantPast var updatedAt = Date.distantPast var syncNeedsComments = false var comments: [Comment] { children(field: "comments") } private enum CodingKeys: CodingKey { case id case parents case elementType case state case body case viewerDidAuthor case createdAt case updatedAt } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) parents = try c.decode([String: [Relationship]].self, forKey: .parents) elementType = try c.decode(String.self, forKey: .elementType) state = ReviewState(rawValue: try c.decode(String.self, forKey: .state)) ?? ReviewState.pending body = try c.decode(String.self, forKey: .body) viewerDidAuthor = try c.decode(Bool.self, forKey: .viewerDidAuthor) createdAt = try c.decode(Date.self, forKey: .createdAt) updatedAt = try c.decode(Date.self, forKey: .updatedAt) syncState = .none } func encode(to encoder: Encoder) throws { var c = encoder.container(keyedBy: CodingKeys.self) try c.encode(id, forKey: .id) try c.encode(parents, forKey: .parents) try c.encode(elementType, forKey: .elementType) try c.encode(state, forKey: .state) try c.encode(body, forKey: .body) try c.encode(viewerDidAuthor, forKey: .viewerDidAuthor) try c.encode(createdAt, forKey: .createdAt) try c.encode(updatedAt, forKey: .updatedAt) } mutating func apply(_ node: [AnyHashable: Any]) -> Bool { guard node.keys.count > 5 else { return false } syncNeedsComments = (node["comments"] as? [AnyHashable: Any])?["totalCount"] as? Int ?? 0 > 0 state = ReviewState(rawValue: node["state"] as? String ?? "PENDING") ?? ReviewState.pending body = node["body"] as? String ?? "" createdAt = GHDateFormatter.parseGH8601(node["createdAt"] as? String) ?? Date.distantPast updatedAt = GHDateFormatter.parseGH8601(node["updatedAt"] as? String) ?? Date.distantPast viewerDidAuthor = node["viewerDidAuthor"] as? Bool ?? false return true } init?(id: String, type: String, node: [AnyHashable: Any]) { self.id = id parents = [String: [Relationship]]() elementType = type syncState = .new if !apply(node) { return nil } } func announceIfNeeded(notificationMode: NotificationMode) { if notificationMode != .consoleCommentsAndReviews || syncState != .new { return } if viewerDidAuthor { return } if let p = pullRequest, p.syncState != .new, let re = pullRequest?.repo, let a = p.author?.login, re.syncState != .new { let r = re.nameWithOwner let d: String switch state { case .approved: d = "[\(r)] @\(a) reviewed [G*(approving)*]" case .changes_requested: d = "[\(r)] @\(a) reviewed [R*(requesting changes)*]" case .commented where body.hasItems: d = "[\(r)] @\(a) reviewed" default: return } Notifications.notify(title: d, subtitle: "PR #\(p.number) \(p.title))", details: body, relatedDate: createdAt) } } private func printHeader() { if let a = author?.login { switch state { case .approved: log("[![*@\(a)*] \(agoFormat(prefix: "[G*Approved Changes*] ", since: createdAt))!]") case .changes_requested: log("[![*@\(a)*] \(agoFormat(prefix: "[R*Requested Changes*] ", since: createdAt))!]") default: log("[![*@\(a)*] \(agoFormat(prefix: "Reviewed ", since: createdAt))!]") } } } func printDetails() { printHeader() if body.hasItems { log(body.trimmingCharacters(in: .whitespacesAndNewlines), unformatted: true) log() } } func printSummaryLine() { printHeader() log() } var pullRequest: PullRequest? { if let parentId = parents["PullRequest:reviews"]?.first?.parentId { return PullRequest.allItems[parentId] } return nil } var author: User? { children(field: "author").first } mutating func setChildrenSyncStatus(_ status: SyncState) { if var u = author { u.setSyncStatus(status, andChildren: true) User.allItems[u.id] = u } for c in comments { var C = c C.setSyncStatus(status, andChildren: true) Comment.allItems[c.id] = C } } var mentionsMe: Bool { if body.localizedCaseInsensitiveContains(config.myLogin) { return true } return comments.contains { $0.mentionsMe } } func includes(text: String) -> Bool { if body.localizedCaseInsensitiveContains(text) { return true } return comments.contains { $0.includes(text: text) } } static let fragment = Fragment(name: "reviewFields", on: "PullRequestReview", elements: [ Field.id, Field(name: "body"), Field(name: "state"), Field(name: "viewerDidAuthor"), Field(name: "createdAt"), Field(name: "updatedAt"), Group(name: "author", fields: [User.fragment]), Group(name: "comments", fields: [Field(name: "totalCount")]) ]) static let commentsFragment = Fragment(name: "ReviewCommentsFragment", on: "PullRequestReview", elements: [ Field.id, // not using fragment, no need to re-parse Group(name: "comments", fields: [Comment.fragmentForReviews], paging: .largePage) ]) }
mit
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Views/Main/ZXCVisitorView.swift
1
4925
// // ZXCVisitorView.swift // WeiBo // // Created by Aioria on 2017/3/27. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit import SnapKit class ZXCVisitorView: UIView { private lazy var cycleImageView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) var loginOrRegisterClosure: (()->())? private lazy var maskImageView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) private lazy var homeImageView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) private lazy var messageLabel: UILabel = { let lab = UILabel() lab.numberOfLines = 2 lab.textColor = UIColor.gray lab.font = UIFont.systemFont(ofSize: 12) lab.textAlignment = .center lab.text = "111111111111111" return lab }() private lazy var btnRegister: UIButton = { let btn = UIButton() btn.setTitle("注册", for: .normal) btn.addTarget(self, action: #selector(loginAndRegisterAction), for: .touchUpInside) btn.setTitleColor(UIColor.darkGray, for: .normal) btn.setTitleColor(UIColor.orange, for: .highlighted) btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .normal) btn.adjustsImageWhenHighlighted = false btn.titleLabel?.font = UIFont.systemFont(ofSize: 14) return btn }() private lazy var btnLogin: UIButton = { let btn = UIButton() btn.setTitle("登陆", for: .normal) btn.addTarget(self, action: #selector(loginAndRegisterAction), for: .touchUpInside) btn.setTitleColor(UIColor.darkGray, for: .normal) btn.setTitleColor(UIColor.orange, for: .highlighted) btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .normal) btn.adjustsImageWhenHighlighted = false btn.titleLabel?.font = UIFont.systemFont(ofSize: 14) return btn }() override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { addSubview(cycleImageView) addSubview(maskImageView) addSubview(homeImageView) addSubview(messageLabel) addSubview(btnRegister) addSubview(btnLogin) cycleImageView.snp.makeConstraints { (make) in make.center.equalTo(self) } maskImageView.snp.makeConstraints { (make) in make.center.equalTo(cycleImageView) } homeImageView.snp.makeConstraints { (make) in make.center.equalTo(maskImageView) } messageLabel.snp.makeConstraints { (make) in make.centerX.equalTo(homeImageView) make.top.equalTo(maskImageView.snp.bottom) make.width.equalTo(224) } btnRegister.snp.makeConstraints { (make) in make.left.equalTo(messageLabel) make.top.equalTo(messageLabel.snp.bottom).offset(10) make.size.equalTo(CGSize(width: 80, height: 35)) } btnLogin.snp.makeConstraints { (make) in make.right.equalTo(messageLabel) make.top.equalTo(btnRegister) make.size.equalTo(btnRegister) } // startAnimation() // cycleImageView.translatesAutoresizingMaskIntoConstraints = false // // addConstraint(NSLayoutConstraint(item: cycleImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) // addConstraint(NSLayoutConstraint(item: cycleImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) } private func startAnimation() { let animation = CABasicAnimation(keyPath: "transform.rotation") animation.toValue = 2 * Double.pi animation.duration = 20 animation.repeatCount = MAXFLOAT animation.isRemovedOnCompletion = false cycleImageView.layer.add(animation, forKey: nil) } func updateVisitorInfo(imgName: String?, message: String?) { if let imageName = imgName, let msg = message { homeImageView.image = UIImage(named: imageName) messageLabel.text = msg cycleImageView.isHidden = true } else { startAnimation() } } @objc private func loginAndRegisterAction() { loginOrRegisterClosure?() } }
mit
apple/swift-package-manager
Sources/Workspace/ManagedDependency.swift
2
9069
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2020 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 // //===----------------------------------------------------------------------===// import Basics import PackageGraph import PackageModel import SourceControl import TSCBasic extension Workspace { /// An individual managed dependency. /// /// Each dependency will have a checkout containing the sources at a /// particular revision, and may have an associated version. public struct ManagedDependency: Equatable { /// Represents the state of the managed dependency. public indirect enum State: Equatable, CustomStringConvertible { /// The dependency is a local package on the file system. case fileSystem(AbsolutePath) /// The dependency is a managed source control checkout. case sourceControlCheckout(CheckoutState) /// The dependency is downloaded from a registry. case registryDownload(version: Version) /// The dependency is in edited state. /// /// If the path is non-nil, the dependency is managed by a user and is /// located at the path. In other words, this dependency is being used /// for top of the tree style development. case edited(basedOn: ManagedDependency?, unmanagedPath: AbsolutePath?) case custom(version: Version, path: AbsolutePath) public var description: String { switch self { case .fileSystem(let path): return "fileSystem (\(path))" case .sourceControlCheckout(let checkoutState): return "sourceControlCheckout (\(checkoutState))" case .registryDownload(let version): return "registryDownload (\(version))" case .edited: return "edited" case .custom: return "custom" } } } /// The package reference. public let packageRef: PackageReference /// The state of the managed dependency. public let state: State /// The checked out path of the dependency on disk, relative to the workspace checkouts path. public let subpath: RelativePath internal init( packageRef: PackageReference, state: State, subpath: RelativePath ) { self.packageRef = packageRef self.subpath = subpath self.state = state } /// Create an editable managed dependency based on a dependency which /// was *not* in edit state. /// /// - Parameters: /// - subpath: The subpath inside the editable directory. /// - unmanagedPath: A custom absolute path instead of the subpath. public func edited(subpath: RelativePath, unmanagedPath: AbsolutePath?) throws -> ManagedDependency { guard case .sourceControlCheckout = self.state else { throw InternalError("invalid dependency state: \(self.state)") } return ManagedDependency( packageRef: self.packageRef, state: .edited(basedOn: self, unmanagedPath: unmanagedPath), subpath: subpath ) } /// Create a dependency present locally on the filesystem. public static func fileSystem( packageRef: PackageReference ) throws -> ManagedDependency { switch packageRef.kind { case .root(let path), .fileSystem(let path), .localSourceControl(let path): return ManagedDependency( packageRef: packageRef, state: .fileSystem(path), // FIXME: This is just a fake entry, we should fix it. subpath: RelativePath(packageRef.identity.description) ) default: throw InternalError("invalid package type: \(packageRef.kind)") } } /// Create a source control dependency checked out public static func sourceControlCheckout( packageRef: PackageReference, state: CheckoutState, subpath: RelativePath ) throws -> ManagedDependency { switch packageRef.kind { case .localSourceControl, .remoteSourceControl: return ManagedDependency( packageRef: packageRef, state: .sourceControlCheckout(state), subpath: subpath ) default: throw InternalError("invalid package type: \(packageRef.kind)") } } /// Create a registry dependency downloaded public static func registryDownload( packageRef: PackageReference, version: Version, subpath: RelativePath ) throws -> ManagedDependency { guard case .registry = packageRef.kind else { throw InternalError("invalid package type: \(packageRef.kind)") } return ManagedDependency( packageRef: packageRef, state: .registryDownload(version: version), subpath: subpath ) } /// Create an edited dependency public static func edited( packageRef: PackageReference, subpath: RelativePath, basedOn: ManagedDependency?, unmanagedPath: AbsolutePath? ) -> ManagedDependency { return ManagedDependency( packageRef: packageRef, state: .edited(basedOn: basedOn, unmanagedPath: unmanagedPath), subpath: subpath ) } } } extension Workspace.ManagedDependency: CustomStringConvertible { public var description: String { return "<ManagedDependency: \(self.packageRef.identity) \(self.state)>" } } // MARK: - ManagedDependencies extension Workspace { /// A collection of managed dependencies. final public class ManagedDependencies { private var dependencies: [PackageIdentity: ManagedDependency] init() { self.dependencies = [:] } init(_ dependencies: [ManagedDependency]) throws { // rdar://86857825 do not use Dictionary(uniqueKeysWithValues:) as it can crash the process when input is incorrect such as in older versions of SwiftPM self.dependencies = [:] for dependency in dependencies { if self.dependencies[dependency.packageRef.identity] != nil { throw StringError("\(dependency.packageRef.identity) already exists in managed dependencies") } self.dependencies[dependency.packageRef.identity] = dependency } } public subscript(identity: PackageIdentity) -> ManagedDependency? { return self.dependencies[identity] } // When loading manifests in Workspace, there are cases where we must also compare the location // as it may attempt to load manifests for dependencies that have the same identity but from a different location // (e.g. dependency is changed to a fork with the same identity) public subscript(comparingLocation package: PackageReference) -> ManagedDependency? { if let dependency = self.dependencies[package.identity], dependency.packageRef.equalsIncludingLocation(package) { return dependency } return .none } public func add(_ dependency: ManagedDependency) { self.dependencies[dependency.packageRef.identity] = dependency } public func remove(_ identity: PackageIdentity) { self.dependencies[identity] = nil } } } extension Workspace.ManagedDependencies: Collection { public typealias Index = Dictionary<PackageIdentity, Workspace.ManagedDependency>.Index public typealias Element = Workspace.ManagedDependency public var startIndex: Index { self.dependencies.startIndex } public var endIndex: Index { self.dependencies.endIndex } public subscript(index: Index) -> Element { self.dependencies[index].value } public func index(after index: Index) -> Index { self.dependencies.index(after: index) } } extension Workspace.ManagedDependencies: CustomStringConvertible { public var description: String { "<ManagedDependencies: \(Array(self.dependencies.values))>" } }
apache-2.0
vakoc/particle-swift-cli
Sources/CliSecureStorage.swift
1
3825
// This source file is part of the vakoc.com open source project(s) // // Copyright © 2016 Mark Vakoc. All rights reserved. // Licensed under Apache License v2.0 // // See http://www.vakoc.com/LICENSE.txt for license information import Foundation import ParticleSwift /// Simple implementation of a secure storage delegate to use a plain text json file at /// ~/.particle-swift to manage OAuth /// /// This class contains variables for username, password, OAuth client id, and OAuth secret /// that can be programatically set. This is typically used only with the createToken command. /// /// Creating a token once with this command will perist the token in the ~/.particle-swift file /// such that credentials are not subsequently required /// /// The ~/.particle-swift json file will look like /// /// { /// "oauthToken" : { /// "created_at" : "2016-07-04T23:44:22.136-0700", /// "token_type" : "bearer", /// "refresh_token" : "23443q4aw4aw34w34w34w3a4aw34wa34w34w34w34", /// "access_token" : "2342342asr23423wsr234aw4234235rqaw353w5w35w", /// "expires_in" : 31536000 /// } /// } /// class CliSecureStorage: SecureStorage { var username: String? var password: String? var client = "particle" var secret = "particle" var accessTokenOverride: String? static let shared = CliSecureStorage() lazy var dotFile: String = { ("~/.particle-swift" as NSString).expandingTildeInPath }() func username(_ realm: String) -> String? { return self.username } func password(_ realm: String) -> String? { return self.password } func oauthClientId(_ realm: String) -> String? { return self.client } func oauthClientSecret(_ realm: String) -> String? { return self.secret } func oauthToken(_ realm: String) -> OAuthToken? { if let accessToken = accessTokenOverride { return OAuthToken(with: [ "created_at" : "2016-06-27T22:58:52.579-0600", "token_type" : "bearer", "refresh_token" : "invalid-" + accessToken, "access_token" : accessToken, "expires_in" : 3153600000000 ]) } guard realm == ParticleSwiftInfo.realm && FileManager.default.fileExists(atPath: dotFile) == true, let data = try? Data(contentsOf: URL(fileURLWithPath: dotFile), options: []), let json = try? JSONSerialization.jsonObject(with: data, options: []), let dict = json as? [String : Any] else { return nil } if let tokenDict = dict["oauthToken"] as? [String : Any], let token = OAuthToken(with: tokenDict) { return token } return nil } func updateOAuthToken(_ token: OAuthToken?, forRealm realm: String) { guard realm == ParticleSwiftInfo.realm else { return } var dotFileDict = [String : Any]() if FileManager.default.fileExists(atPath: dotFile) == true, let data = try? Data(contentsOf: URL(fileURLWithPath: dotFile), options: []), let json = try? JSONSerialization.jsonObject(with: data, options: []), let dict = json as? [String : AnyObject] { dotFileDict = dict } dotFileDict["oauthToken"] = token?.dictionary ?? nil do { let savedData = try JSONSerialization.data(withJSONObject: dotFileDict, options: [.prettyPrinted]) try savedData.write(to: URL(fileURLWithPath: dotFile)) } catch { warn("Failed to save updated oauth token to \(dotFile) with error \(error)") } } }
apache-2.0
iOS-Swift-Developers/Swift
CacheSwift/CacheDemo_userDefault/CacheDemo1/ViewController.swift
1
3354
// // ViewController.swift // CacheDemo1 // // Created by 韩俊强 on 2017/8/24. // Copyright © 2017年 HaRi. All rights reserved. // import UIKit class ViewController: UIViewController,UITextFieldDelegate { var textFiled = UITextField() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "NSUserDefault" let saveItem = UIBarButtonItem(title: "save", style: .done, target: self, action: #selector(save)) let readItem = UIBarButtonItem(title: "read", style: .done, target: self, action: #selector(ViewController.readInfo)) let deleteItem = UIBarButtonItem(title: "del", style: .done, target: self, action: #selector(ViewController.deleteInfo)) self.navigationItem.rightBarButtonItems = [saveItem, readItem, deleteItem] setupUI() } override func loadView() { super.loadView() self.view.backgroundColor = UIColor.white if self.responds(to: #selector(getter: UIViewController.edgesForExtendedLayout)) { self.edgesForExtendedLayout = UIRectEdge() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - 保存 func saveInfo(_ name : String){ if 0 <= name.characters.count { let userDefault = UserDefaults.standard userDefault.set(name, forKey: "name") userDefault.synchronize() let alert = UIAlertController(title: nil, message: "保存成功", preferredStyle: .alert) let okAction = UIAlertAction(title: "ok", style: .cancel, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } // MARK: - 读取 func readInfo() -> String { let userDefault = UserDefaults.standard let name = userDefault.object(forKey: "name") as? String let alert = UIAlertController(title: nil, message: "读取成功:\(name)", preferredStyle: .alert) let okAction = UIAlertAction(title: "ok", style: .cancel, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) if (name != nil) { return name! } return "" } // MARK: - 删除 func deleteInfo() { let userDefault = UserDefaults.standard userDefault.removeObject(forKey: "name") let alert = UIAlertController(title: nil, message: "删除成功", preferredStyle: .alert) let okAction = UIAlertAction(title: "ok", style: .cancel, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } func setupUI(){ textFiled = UITextField(frame: CGRect(x: 10, y: 10, width: 200, height: 30)) self.view.addSubview(textFiled) textFiled.clearButtonMode = .whileEditing textFiled.returnKeyType = .done textFiled.delegate = self textFiled.textColor = UIColor.red textFiled.layer.borderColor = UIColor.black.cgColor textFiled.layer.borderWidth = 1.0 } func save() { self.saveInfo(textFiled.text!) } }
mit
duycao2506/SASCoffeeIOS
SAS Coffee/View/MeaningTableViewCell.swift
1
1623
// // MeaningTableViewCell.swift // SAS Coffee // // Created by Duy Cao on 9/10/17. // Copyright © 2017 Duy Cao. All rights reserved. // import UIKit class MeaningTableViewCell: SuperTableViewCell { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBOutlet weak var lblExTitle: UILabel! @IBOutlet weak var lblDeftitle: UILabel! @IBOutlet weak var meaningtitle: UILabel! @IBOutlet weak var wordType: UILabel! @IBOutlet weak var phienam: UILabel! @IBOutlet weak var definition: UILabel! @IBOutlet weak var example: 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 } override func updateData(number : Int, str : String, obj : SuperModel){ } override func updateData(anyObj : Any){ let data = anyObj as! DictionaryModel self.meaningtitle.text = data.word self.wordType.text = data.type self.phienam.text = data.pronun self.definition.text = data.def self.lblDeftitle.text = (self.definition.text?.isEmpty)! ? "" : "Definition".localize() self.example.text = data.example self.lblExTitle.text = (self.example.text?.isEmpty)! ? "" : "Examples".localize() } }
gpl-3.0
mathewsheets/SwiftLearning
SwiftLearning.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
1
15364
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - # Collection Types * callout(Session Overview): Often times in programs you need to group data into a single container where the number of items is unknown. Swift provides 3 main containers known as *collection types* for storing collections of values. *Arrays* are ordered collections of values, *Sets* are unordered collections of unique values, and *Dictionaries* are unordered collections of key-value associations. Please visit the Swift Programming Language Guide section on [Collection Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105) for more detail on collection types. - - - */ import Foundation /*: ## When you're allowed to change or *mutate* collections Before we dive into detail on collection types, there's a suttle but easy way to indicate if you can mutate your collection type. We have already seen this with simple data types such as `Int` and `String`, you use `let` and `var`. */ let unmutableArray: [String] = ["One", "Two"] //unmutableArray.append("Three") var mutableArray: [Int] = [1, 2] mutableArray.append(3) //: > **Experiment**: Uncomment the unmutableArray.append statement. /*: ## Arrays An *Array* stores values of the same type, `Int`s, `String`s, ect. in ordered manner. The same value of the type can appear multiple times at different positions of the array. */ /*: ### Creating Arrays Swift's *arrays* need to know what type of elements it will contain. You can create an empty array, create an array with a default size and values for each element, create an array by adding multiple arrays together and create arrays using literals. */ /*: **A new empty Array** > You can create an array explicitly with the type or when appropriate use type inference. */ var array: [Int] = [Int]() array = [] print("array has \(array.count) items.") //: The above statements show two ways to create a new array, allowing only to store `Int`s and print the number of elements. /*: **A new Array with default values** >You can create an array with default values by using the *initializer* that accepts a default value and a repeat count of how many elements the array should contain */ let nineNines = [Int](repeating: 9, count: 9) print("nineNines has \(nineNines.count) items.") //: The above statements creates an array nine `Int`s all with a value of 9 and print the number of elements nineNines contains. /*: **A new Array by adding Arrays together** >You can create an array by taking two *arrays* of the same type and adding them together usng the addition operator `+`. The new array's type is inferred from the type of the two arrays added together. */ let twoTwos = [Int](repeating: 2, count: 2) let threeThrees = [Int](repeating: 3, count: 3) let twosAndThrees = twoTwos + threeThrees print("twosAndThrees has \(twosAndThrees.count) items.") let threesAndTwos = threeThrees + twoTwos print("threesAndTwos has \(threesAndTwos.count) items.") //: The above statements creates two arrays by adding two other arrays together. /*: **A new Array using Array literal** >You can create an array by using the literal syntax such as creating an array of `Ints` like `[1, 2, 3, 4, 5]`. */ let numbers = [1, 2, 3, 4, 5] //: The above statement creates an array of numbers containing `Int` data types. /*: ### Accessing data in an `Array` You can access information and elements in an array by using the methods and properties provided by the `Array` collection type. */ print("numbers has \(numbers.count) elements") if numbers.isEmpty { print("numbers is empty") } else { print("numbers is not empty") } var firstNumber = numbers.first var lastNumber = numbers.last //: The above statements use properties of the `Array` collection type for count, empty, first element, and last element. var secondNumber = numbers[1] var thirdNumber = numbers[2] //: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the array. var oneTo4 = numbers[0...3] //: You can also get a subset of elements using ranges. let startIndex = numbers.startIndex let endIndex = numbers.endIndex numbers[numbers.index(after: startIndex)] // Get the element after the startIndex numbers[numbers.index(before: endIndex)] // Get the element before the endIndex numbers[numbers.index(startIndex, offsetBy: 1)] // Get the element using the startIndex as a starting point with an offset of 1 numbers[numbers.index(endIndex, offsetBy: -4)] // Get the element using the endIndex as a starting point with an offset of -4 //: And much like a String, you can use the various index methods to get elements. /*: ### Modifying `Array`s Using methods such as `append` and `remove` let you mutate an array. */ var mutableNumbers = numbers mutableNumbers.append(6) mutableNumbers.append(7) mutableNumbers.append(8) mutableNumbers.removeFirst() mutableNumbers.removeLast() mutableNumbers.remove(at: 0) mutableNumbers.removeSubrange(mutableNumbers.index(mutableNumbers.startIndex, offsetBy: 2)..<mutableNumbers.endIndex) mutableNumbers[0] = 1 mutableNumbers[1] = 2 mutableNumbers.append(3) mutableNumbers.append(4) mutableNumbers.append(5) mutableNumbers[0...4] = [5, 6, 7, 8, 9] mutableNumbers.insert(10, at: mutableNumbers.endIndex) print(mutableNumbers) //: The above statements using the `append`, `insert`, `remove` methods, *subscript syntax* as well as using a range to replace values of indexes. /*: ### Iterating over elements in an `Array` You use the `for-in` loop to iterate over elements in an `Array` */ for number in numbers { print(number) } for (index, number) in numbers.enumerated() { print("Item \(index + 1): \(number)") } //: The first `for-in` loop just pulls out the value for each element in the array, but the second `for-in` loops pulls out the index and value. //: > **Experiment**: Use an `_` underscore instead of `name` in the above for loop. What happens? /*: ## Sets The `Set` collection type stores unique value of the same data type with no defined ordering. You use a `Set` instead of an `Array` when you need to ensure that an element only appears once. */ /*: ### Hash Values for Set Types For a `Set` to ensure that it contains only unique values, each element must provide a value called the *hash value*. A *hash value* is an `Int` that is calulated and is the same for all objects that compare equally. Simple types such as `Int`s, `Double`s, `String`s, and `Bool`s all provide a *hash value* by default. */ let one = 1 let two = "two" let three = Double.pi let four = false one.hashValue two.hashValue three.hashValue four.hashValue /*: ### Creating Sets You create a new set collection type by specifing the data type for the element as in `Set<Element>` where `Element` is the data type the set is allowed to store. */ var alphabet = Set<Character>() alphabet = [] /*: The above statements create an empty set that is only allowed to store the Character data type. The second statment assigns *alphabet* to an empty array using the array literal and type inference. */ //: **A new Set using Array literal** var alphabet1: Set<Character> = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] var alphabet2: Set = ["j", "k", "l", "m", "n", "o", "p", "q", "r"] //: You can create a new `Set` using the array literal, but you need to type the variable or constant. `alphabet2` is a shorter way to create a `Set` because it can be inferred that all the values are of the same type, in this case `String`s. Notice that `alphabet1` and `alphabet2` are not of the same type. /*: ### Accessing data in a `Set` Similar to the `Array` collection type, you access information and elements in an `Set` using properties and methods of the `Set` collection type. */ alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] print("alphabet has \(alphabet.count) elements") if alphabet.isEmpty { print("alphabet is empty") } else { print("alphabet is not empty") } var firstLetter = alphabet.first //: The above statements use properties of the `Set` collection type for count, empty, and first element. var secondLetter = alphabet[alphabet.index(alphabet.startIndex, offsetBy: 1)] var thirdLetter = alphabet[alphabet.index(alphabet.startIndex, offsetBy: 2)] //: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the set. /*: ### Modifying elements in a Set Using methods such as `insert` and `remove` let you mutate a set. */ alphabet.insert("n") alphabet.insert("o") alphabet.insert("p") alphabet.removeFirst() alphabet.remove(at: alphabet.startIndex) alphabet.remove("o") print(alphabet) //: The above statements using the `insert` and `remove` methods to mutate the `Set`. /*: ### Iterating over elements in a Set You use the `for-in` loop to iterate over elements in an `Set` */ for letter in alphabet { print(letter) } for (index, value) in alphabet.enumerated() { print("index: \(index) - value: \(value)") } //: The first `for-in` loop just pulls out the value for each element in the set, but the second `for-in` first sorts the set before the looping starts. /*: ### Set Operations With the `Set` collection type, you can perform set operations in the mathematical sense. */ alphabet = ["a", "b", "c", "d", "e", "v", "w", "x", "y", "z"] var vowels : Set<Character> = ["a", "e", "i", "o", "u"] //: **intersection(_:)** creates a new `Set` of only those values both sets have in common. let intersection = vowels.intersection(alphabet) //: **symmetricDifference(_:)** creates a new `Set` of values from either set, but not from both. let symmetricDifference = vowels.symmetricDifference(alphabet) //: **union(_:)** creates a new `Set` with all values from both sets. let union = vowels.union(alphabet) //: **subtracting(_:)** creates a new `Set` with values not in the specified set. let subtracting = vowels.subtracting(alphabet) /*: ### Set Membership and Equality With the `Set` collection type, you can determine the membership of a set and if one set is equal to another. */ let family : Set = ["Matt", "Annie", "Samuel", "Jack", "Hudson", "Oliver"] let parents : Set = ["Matt", "Annie"] let children : Set = ["Samuel", "Jack", "Hudson", "Oliver"] //: **“is equal” operator (==)** tests if one set is equal to another set. family == parents.union(children) parents == children //: **isSubset(of:)** tests if all of the values of a set are contained in another set. children.isSubset(of: family) family.isSubset(of: children) //: **isSuperset(of:)** test if a set contains all of the values in another set. family.isSuperset(of: parents) family.isSuperset(of: children) children.isSuperset(of: family) //: **isStrictSubset(of:) or isStrictSuperset(of:)** test if a set is a subset or superset, but not equal to, another set. let old = parents old.isStrictSubset(of: parents) let boys: Set = ["Matt", "Samuel", "Jack", "Hudson", "Oliver"] boys.isStrictSubset(of: family) //: **isDisjoint(with:)** test if two sets have any values in common. parents.isDisjoint(with: children) family.isDisjoint(with: children) /*: ## Dictionaries A `Dictionary` stores associations or mappings between keys of the same data type and values of the same data type in a container with no defined ordering. The value of each element is tied to a unique *key*. It's this unique *key* that enables you to lookup values based on an identifer, just like a real dictionary having the word be the key and the definition the value. */ /*: ### Creating Dictionaries Much like the `Array` and `Set` collection types, you need to specify the data type that the `Dictionary` is allowed to store. Unlike `Array`s and `Set`s, you need to specify the data type for the *Key* and the *Value*. */ var longhand: Dictionary<String, String>? = nil var shorthand: [String: String]? = nil /*: Above shows a long and short way to create a dictionary. */ //: **A new empty Dictionary** var titles = [String: String]() titles["dad"] = "Matt" titles = [:] /*: Above creates an empty `Dictionary`, adds an entry into `titles` and then assigns `titles` to an empty dictionary using the shorthand form and type inference. */ //: **A new Dictionary using Dictionary literal** titles = ["dad": "Matt", "mom": "Annie", "child_1": "Sam", "child_2": "Jack", "child_3": "Hudson", "child_4": "Oliver"] /*: Above creates a `Dictionary` using the literal syntax. Notice the *key: value* mapping separated by a comma, all surrounded by square brackets. */ /*: ### Accessing data in a Dictionary Like the `Array` and `Set` collection types, the `Dictionary` also has the `count` and `isEmpty` properties, but unlike arrays and sets, you access elements using a *key*. */ print("titles has \(titles.count) elements") if titles.isEmpty { print("titles is empty") } else { print("titles is not empty") } var dad = titles["dad"] if dad != nil { print(dad!) } /*: Above statements use the `count` and `isEmpty` properties, as well as use the *key* to retrive a value. It's possible that you use a *key* that does not exist in the dictionary. The `Dictionary` collection type will always return the value as an *Optional*. You then next would need to check for `nil` and *unwrap* the optional to obtain the real value. */ /*: ### Modifying elements in a Dictionary There are two techniques to add/update entries for the `Dictionary` collection type, by using the *subscript syntax* or using a method. */ titles["dog"] = "Carson" titles["child_1"] = "Samuel" var father = titles.updateValue("Mathew", forKey: "dad") var cat = titles.updateValue("Fluffy", forKey: "cat") titles["dog"] = nil cat = titles.removeValue(forKey: "cat") if cat != nil { print("removed \(cat!)") } /*: The above statements use both the *subscript syntax* and methods for add, updating, and removing entries of a dictionary. Notice that with the method technique, you are returned a value if if the entry exists in the dictionary. */ /*: ### Iterating over elements in a Dictionary Just like the `Array` and `Set` collection types, you iterate over a dictionary using a `for-in` loop. */ for element in titles { print("\(element.0): \(element.1)") } for (key, value) in titles { print("\(key): \(value)") } for title in titles.keys { print("title: \(title)") } for name in titles.values { print("name: \(name)") } let titleNames = [String](titles.keys) let names = [String](titles.values) /*: Above statements use the `for-in` loop to iterate over the `titles` giving you access to the *key* and *value*. You can also access only the *keys* or *values*. */ //: > **Experiment**: Create a array of dictionaries and iterate over the array printing the key and value of each dictionary /*: * callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC - [Guide: Collection Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105) - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
duycao2506/SASCoffeeIOS
Pods/PopupDialog/PopupDialog/Classes/PopupDialogDefaultView.swift
1
5764
// // PopupDialogView.swift // // Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk) // Author - Martin Wildfeuer (http://www.mwfire.de) // // 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 /// The main view of the popup dialog final public class PopupDialogDefaultView: UIView { // MARK: - Appearance /// The font and size of the title label @objc public dynamic var titleFont: UIFont { get { return titleLabel.font } set { titleLabel.font = newValue } } /// The color of the title label @objc public dynamic var titleColor: UIColor? { get { return titleLabel.textColor } set { titleLabel.textColor = newValue } } /// The text alignment of the title label @objc public dynamic var titleTextAlignment: NSTextAlignment { get { return titleLabel.textAlignment } set { titleLabel.textAlignment = newValue } } /// The font and size of the body label @objc public dynamic var messageFont: UIFont { get { return messageLabel.font } set { messageLabel.font = newValue } } /// The color of the message label @objc public dynamic var messageColor: UIColor? { get { return messageLabel.textColor } set { messageLabel.textColor = newValue} } /// The text alignment of the message label @objc public dynamic var messageTextAlignment: NSTextAlignment { get { return messageLabel.textAlignment } set { messageLabel.textAlignment = newValue } } // MARK: - Views /// The view that will contain the image, if set internal lazy var imageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView }() /// The title label of the dialog internal lazy var titleLabel: UILabel = { let titleLabel = UILabel(frame: .zero) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.numberOfLines = 0 titleLabel.textAlignment = .center titleLabel.textColor = UIColor(white: 0.4, alpha: 1) titleLabel.font = UIFont.boldSystemFont(ofSize: 14) return titleLabel }() /// The message label of the dialog internal lazy var messageLabel: UILabel = { let messageLabel = UILabel(frame: .zero) messageLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.numberOfLines = 0 messageLabel.textAlignment = .center messageLabel.textColor = UIColor(white: 0.6, alpha: 1) messageLabel.font = UIFont.systemFont(ofSize: 14) return messageLabel }() /// The height constraint of the image view, 0 by default internal var imageHeightConstraint: NSLayoutConstraint? // MARK: - Initializers internal override init(frame: CGRect) { super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View setup internal func setupViews() { // Self setup translatesAutoresizingMaskIntoConstraints = false // Add views addSubview(imageView) addSubview(titleLabel) addSubview(messageLabel) // Layout views let views = ["imageView": imageView, "titleLabel": titleLabel, "messageLabel": messageLabel] as [String: Any] var constraints = [NSLayoutConstraint]() constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[imageView]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[titleLabel]-(==20@900)-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[messageLabel]-(==20@900)-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[imageView]-(==30@900)-[titleLabel]-(==8@900)-[messageLabel]-(==30@900)-|", options: [], metrics: nil, views: views) // ImageView height constraint imageHeightConstraint = NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 0, constant: 0) if let imageHeightConstraint = imageHeightConstraint { constraints.append(imageHeightConstraint) } // Activate constraints NSLayoutConstraint.activate(constraints) } }
gpl-3.0
apple/swift-argument-parser
Tests/ArgumentParserEndToEndTests/RepeatingEndToEndTests.swift
1
11531
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import XCTest import ArgumentParserTestHelpers import ArgumentParser final class RepeatingEndToEndTests: XCTestCase { } // MARK: - fileprivate struct Bar: ParsableArguments { @Option() var name: [String] = [] } extension RepeatingEndToEndTests { func testParsing_repeatingString() throws { AssertParse(Bar.self, []) { bar in XCTAssertTrue(bar.name.isEmpty) } AssertParse(Bar.self, ["--name", "Bar"]) { bar in XCTAssertEqual(bar.name.count, 1) XCTAssertEqual(bar.name.first, "Bar") } AssertParse(Bar.self, ["--name", "Bar", "--name", "Foo"]) { bar in XCTAssertEqual(bar.name.count, 2) XCTAssertEqual(bar.name.first, "Bar") XCTAssertEqual(bar.name.last, "Foo") } } } // MARK: - fileprivate struct Foo: ParsableArguments { @Flag() var verbose: Int } extension RepeatingEndToEndTests { func testParsing_incrementInteger() throws { AssertParse(Foo.self, []) { options in XCTAssertEqual(options.verbose, 0) } AssertParse(Foo.self, ["--verbose"]) { options in XCTAssertEqual(options.verbose, 1) } AssertParse(Foo.self, ["--verbose", "--verbose"]) { options in XCTAssertEqual(options.verbose, 2) } } } // MARK: - fileprivate struct Baz: ParsableArguments { @Flag var verbose: Bool = false @Option(parsing: .remaining) var names: [String] = [] } extension RepeatingEndToEndTests { func testParsing_repeatingStringRemaining_1() { AssertParse(Baz.self, []) { baz in XCTAssertFalse(baz.verbose) XCTAssertTrue(baz.names.isEmpty) } } func testParsing_repeatingStringRemaining_2() { AssertParse(Baz.self, ["--names"]) { baz in XCTAssertFalse(baz.verbose) XCTAssertTrue(baz.names.isEmpty) } } func testParsing_repeatingStringRemaining_3() { AssertParse(Baz.self, ["--names", "one"]) { baz in XCTAssertFalse(baz.verbose) XCTAssertEqual(baz.names, ["one"]) } } func testParsing_repeatingStringRemaining_4() { AssertParse(Baz.self, ["--names", "one", "two"]) { baz in XCTAssertFalse(baz.verbose) XCTAssertEqual(baz.names, ["one", "two"]) } } func testParsing_repeatingStringRemaining_5() { AssertParse(Baz.self, ["--verbose", "--names", "one", "two"]) { baz in XCTAssertTrue(baz.verbose) XCTAssertEqual(baz.names, ["one", "two"]) } } func testParsing_repeatingStringRemaining_6() { AssertParse(Baz.self, ["--names", "one", "two", "--verbose"]) { baz in XCTAssertFalse(baz.verbose) XCTAssertEqual(baz.names, ["one", "two", "--verbose"]) } } func testParsing_repeatingStringRemaining_7() { AssertParse(Baz.self, ["--verbose", "--names", "one", "two", "--verbose"]) { baz in XCTAssertTrue(baz.verbose) XCTAssertEqual(baz.names, ["one", "two", "--verbose"]) } } func testParsing_repeatingStringRemaining_8() { AssertParse(Baz.self, ["--verbose", "--names", "one", "two", "--verbose", "--other", "three"]) { baz in XCTAssertTrue(baz.verbose) XCTAssertEqual(baz.names, ["one", "two", "--verbose", "--other", "three"]) } } } // MARK: - fileprivate struct Outer: ParsableCommand { static let configuration = CommandConfiguration(subcommands: [Inner.self]) } fileprivate struct Inner: ParsableCommand { @Flag var verbose: Bool = false @Argument(parsing: .captureForPassthrough) var files: [String] = [] } extension RepeatingEndToEndTests { func testParsing_subcommandRemaining() { AssertParseCommand( Outer.self, Inner.self, ["inner", "--verbose", "one", "two", "--", "three", "--other"]) { inner in XCTAssertTrue(inner.verbose) XCTAssertEqual(inner.files, ["one", "two", "--", "three", "--other"]) } } } // MARK: - fileprivate struct Qux: ParsableArguments { @Option(parsing: .upToNextOption) var names: [String] = [] @Flag var verbose: Bool = false @Argument() var extra: String? } extension RepeatingEndToEndTests { func testParsing_repeatingStringUpToNext() throws { AssertParse(Qux.self, []) { qux in XCTAssertFalse(qux.verbose) XCTAssertTrue(qux.names.isEmpty) XCTAssertNil(qux.extra) } AssertParse(Qux.self, ["--names", "one"]) { qux in XCTAssertFalse(qux.verbose) XCTAssertEqual(qux.names, ["one"]) XCTAssertNil(qux.extra) } AssertParse(Qux.self, ["--names", "one", "two", "--verbose", "--names", "three", "--names", "four"]) { qux in XCTAssertTrue(qux.verbose) XCTAssertEqual(qux.names, ["one", "two", "three", "four"]) XCTAssertNil(qux.extra) } AssertParse(Qux.self, ["extra", "--names", "one", "--names", "two", "--verbose", "--names", "three", "four"]) { qux in XCTAssertTrue(qux.verbose) XCTAssertEqual(qux.names, ["one", "two", "three", "four"]) XCTAssertEqual(qux.extra, "extra") } AssertParse(Qux.self, ["--names", "one", "two"]) { qux in XCTAssertFalse(qux.verbose) XCTAssertEqual(qux.names, ["one", "two"]) XCTAssertNil(qux.extra) } AssertParse(Qux.self, ["--names", "one", "two", "--verbose"]) { qux in XCTAssertTrue(qux.verbose) XCTAssertEqual(qux.names, ["one", "two"]) XCTAssertNil(qux.extra) } AssertParse(Qux.self, ["--names", "one", "two", "--verbose", "three"]) { qux in XCTAssertTrue(qux.verbose) XCTAssertEqual(qux.names, ["one", "two"]) XCTAssertEqual(qux.extra, "three") } AssertParse(Qux.self, ["--verbose", "--names", "one", "two"]) { qux in XCTAssertTrue(qux.verbose) XCTAssertEqual(qux.names, ["one", "two"]) XCTAssertNil(qux.extra) } } func testParsing_repeatingStringUpToNext_Fails() throws { XCTAssertThrowsError(try Qux.parse(["--names", "one", "--other"])) XCTAssertThrowsError(try Qux.parse(["--names", "one", "two", "--other"])) XCTAssertThrowsError(try Qux.parse(["--names", "--other"])) XCTAssertThrowsError(try Qux.parse(["--names", "--verbose"])) XCTAssertThrowsError(try Qux.parse(["--names", "--verbose", "three"])) } } // MARK: - fileprivate struct Wobble: ParsableArguments { struct WobbleError: Error {} struct Name: Equatable { var value: String init(_ value: String) throws { if value == "bad" { throw WobbleError() } self.value = value } } @Option(transform: Name.init) var names: [Name] = [] @Option(parsing: .upToNextOption, transform: Name.init) var moreNames: [Name] = [] @Option(parsing: .remaining, transform: Name.init) var evenMoreNames: [Name] = [] } extension RepeatingEndToEndTests { func testParsing_repeatingWithTransform() throws { let names = ["--names", "one", "--names", "two"] let moreNames = ["--more-names", "three", "four", "five"] let evenMoreNames = ["--even-more-names", "six", "--seven", "--eight"] AssertParse(Wobble.self, []) { wobble in XCTAssertTrue(wobble.names.isEmpty) XCTAssertTrue(wobble.moreNames.isEmpty) XCTAssertTrue(wobble.evenMoreNames.isEmpty) } AssertParse(Wobble.self, names) { wobble in XCTAssertEqual(wobble.names.map { $0.value }, ["one", "two"]) XCTAssertTrue(wobble.moreNames.isEmpty) XCTAssertTrue(wobble.evenMoreNames.isEmpty) } AssertParse(Wobble.self, moreNames) { wobble in XCTAssertTrue(wobble.names.isEmpty) XCTAssertEqual(wobble.moreNames.map { $0.value }, ["three", "four", "five"]) XCTAssertTrue(wobble.evenMoreNames.isEmpty) } AssertParse(Wobble.self, evenMoreNames) { wobble in XCTAssertTrue(wobble.names.isEmpty) XCTAssertTrue(wobble.moreNames.isEmpty) XCTAssertEqual(wobble.evenMoreNames.map { $0.value }, ["six", "--seven", "--eight"]) } AssertParse(Wobble.self, Array([names, moreNames, evenMoreNames].joined())) { wobble in XCTAssertEqual(wobble.names.map { $0.value }, ["one", "two"]) XCTAssertEqual(wobble.moreNames.map { $0.value }, ["three", "four", "five"]) XCTAssertEqual(wobble.evenMoreNames.map { $0.value }, ["six", "--seven", "--eight"]) } AssertParse(Wobble.self, Array([moreNames, names, evenMoreNames].joined())) { wobble in XCTAssertEqual(wobble.names.map { $0.value }, ["one", "two"]) XCTAssertEqual(wobble.moreNames.map { $0.value }, ["three", "four", "five"]) XCTAssertEqual(wobble.evenMoreNames.map { $0.value }, ["six", "--seven", "--eight"]) } AssertParse(Wobble.self, Array([moreNames, evenMoreNames, names].joined())) { wobble in XCTAssertTrue(wobble.names.isEmpty) XCTAssertEqual(wobble.moreNames.map { $0.value }, ["three", "four", "five"]) XCTAssertEqual(wobble.evenMoreNames.map { $0.value }, ["six", "--seven", "--eight", "--names", "one", "--names", "two"]) } } func testParsing_repeatingWithTransform_Fails() throws { XCTAssertThrowsError(try Wobble.parse(["--names", "one", "--other"])) XCTAssertThrowsError(try Wobble.parse(["--more-names", "one", "--other"])) XCTAssertThrowsError(try Wobble.parse(["--names", "one", "--names", "bad"])) XCTAssertThrowsError(try Wobble.parse(["--more-names", "one", "two", "bad", "--names", "one"])) XCTAssertThrowsError(try Wobble.parse(["--even-more-names", "one", "two", "--names", "one", "bad"])) } } // MARK: - fileprivate struct Weazle: ParsableArguments { @Flag var verbose: Bool = false @Argument() var names: [String] = [] } extension RepeatingEndToEndTests { func testParsing_repeatingArgument() throws { AssertParse(Weazle.self, ["one", "two", "three", "--verbose"]) { weazle in XCTAssertTrue(weazle.verbose) XCTAssertEqual(weazle.names, ["one", "two", "three"]) } AssertParse(Weazle.self, ["--verbose", "one", "two", "three"]) { weazle in XCTAssertTrue(weazle.verbose) XCTAssertEqual(weazle.names, ["one", "two", "three"]) } AssertParse(Weazle.self, ["one", "two", "three", "--", "--other", "--verbose"]) { weazle in XCTAssertFalse(weazle.verbose) XCTAssertEqual(weazle.names, ["one", "two", "three", "--other", "--verbose"]) } } } // MARK: - struct PerformanceTest: ParsableCommand { @Option(name: .short) var bundleIdentifiers: [String] = [] mutating func run() throws { print(bundleIdentifiers) } } fileprivate func argumentGenerator(_ count: Int) -> [String] { Array((1...count).map { ["-b", "bundle-id\($0)"] }.joined()) } fileprivate func time(_ body: () -> Void) -> TimeInterval { let start = Date() body() return Date().timeIntervalSince(start) } extension RepeatingEndToEndTests { // A regression test against array parsing performance going non-linear. func testParsing_repeatingPerformance() throws { let timeFor20 = time { AssertParse(PerformanceTest.self, argumentGenerator(100)) { test in XCTAssertEqual(100, test.bundleIdentifiers.count) } } let timeFor40 = time { AssertParse(PerformanceTest.self, argumentGenerator(200)) { test in XCTAssertEqual(200, test.bundleIdentifiers.count) } } XCTAssertLessThan(timeFor40, timeFor20 * 10) } }
apache-2.0
SPECURE/rmbt-ios-client
Sources/QOS/Helpers/UDPStreamSender.swift
1
9465
/***************************************************************************************************** * Copyright 2014-2016 SPECURE GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************************************/ import Foundation import CocoaAsyncSocket /// struct UDPStreamSenderSettings { var host: String var port: UInt16 = 0 var delegateQueue: DispatchQueue var sendResponse: Bool = false var maxPackets: UInt16 = 5 var timeout: UInt64 = 10_000_000_000 var delay: UInt64 = 10_000 var writeOnly: Bool = false var portIn: UInt16? } /// class UDPStreamSender: NSObject { /// fileprivate let streamSenderQueue = DispatchQueue(label: "com.specure.rmbt.udp.streamSenderQueue", attributes: DispatchQueue.Attributes.concurrent) /// fileprivate var udpSocket: GCDAsyncUdpSocket? /// fileprivate let countDownLatch = CountDownLatch() /// fileprivate var running = AtomicBoolean() fileprivate var isStopped = true // /// weak var delegate: UDPStreamSenderDelegate? /// fileprivate let settings: UDPStreamSenderSettings // /// fileprivate var packetsReceived: UInt16 = 0 /// fileprivate var packetsSent: UInt16 = 0 /// fileprivate let delayMS: UInt64 /// fileprivate let timeoutMS: UInt64 /// fileprivate let timeoutSec: Double /// fileprivate var lastSentTimestampMS: UInt64 = 0 /// fileprivate var usleepOverhead: UInt64 = 0 // deinit { defer { if self.isStopped == false { self.stop() } } } /// required init(settings: UDPStreamSenderSettings) { self.settings = settings delayMS = settings.delay / NSEC_PER_MSEC timeoutMS = settings.timeout / NSEC_PER_MSEC timeoutSec = nsToSec(settings.timeout) } /// func stop() { _ = running.testAndSet(false) close() } /// fileprivate func connect() { Log.logger.debug("connecting udp socket") stop() udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: streamSenderQueue) udpSocket?.setupSocket() isStopped = false // do { if let portIn = settings.portIn { try udpSocket?.bind(toPort: portIn) } try udpSocket?.connect(toHost: settings.host, onPort: settings.port) _ = countDownLatch.await(200 * NSEC_PER_MSEC) // if !settings.writeOnly { try udpSocket?.beginReceiving() } } catch { self.stop() Log.logger.debug("bindToPort error?: \(error)") Log.logger.debug("connectToHost error?: \(error)") // TODO: check error (i.e. fail if error) Log.logger.debug("receive error?: \(error)") // TODO: check error (i.e. fail if error) } } /// fileprivate func close() { isStopped = true Log.logger.debug("closing udp socket") udpSocket?.close()//AfterSending() udpSocket?.setDelegate(nil) udpSocket?.setDelegateQueue(nil) udpSocket = nil } /// func send() -> Bool { connect() let startTimeMS = UInt64.currentTimeMillis() let stopTimeMS: UInt64 = (timeoutMS > 0) ? timeoutMS + startTimeMS : 0 // var dataToSend = NSMutableData() var shouldSend = false // var hasTimeout = false _ = running.testAndSet(true) while (running.boolValue && (self.udpSocket != nil)) { //////////////////////////////////// // check if should stop if stopTimeMS > 0 && stopTimeMS < UInt64.currentTimeMillis() { Log.logger.debug("stopping because of stopTimeMS") hasTimeout = true break } //////////////////////////////////// // check delay Log.logger.verbose("currentTimeMS: \(UInt64.currentTimeMillis()), lastSentTimestampMS: \(self.lastSentTimestampMS)") var currentDelay = UInt64.currentTimeMillis() - lastSentTimestampMS + usleepOverhead Log.logger.verbose("current delay: \(currentDelay)") currentDelay = (currentDelay > delayMS) ? 0 : delayMS - currentDelay Log.logger.verbose("current delay2: \(currentDelay)") if currentDelay > 0 { let sleepMicroSeconds = UInt32(currentDelay * 1000) let sleepDelay = UInt64.currentTimeMillis() usleep(sleepMicroSeconds) // TODO: usleep has an average overhead of about 0-5ms! let usleepCurrentOverhead = UInt64.currentTimeMillis() - sleepDelay if usleepCurrentOverhead > 20 { usleepOverhead = usleepCurrentOverhead - currentDelay } else { usleepOverhead = 0 } Log.logger.verbose("usleep for \(currentDelay)ms took \(usleepCurrentOverhead)ms (overhead \(self.usleepOverhead))") } //////////////////////////////////// // send packet if packetsSent < settings.maxPackets { dataToSend = NSMutableData() shouldSend = self.delegate?.udpStreamSender(self, willSendPacketWithNumber: self.packetsSent, data: &dataToSend) ?? false if shouldSend { lastSentTimestampMS = UInt64.currentTimeMillis() udpSocket?.send(dataToSend as Data, withTimeout: timeoutSec, tag: Int(packetsSent)) // TAG == packet number packetsSent += 1 //lastSentTimestampMS = currentTimeMillis() } } //////////////////////////////////// // check for stop if settings.writeOnly { if packetsSent >= settings.maxPackets { Log.logger.debug("stopping because packetsSent >= settings.maxPackets") break } } else { if packetsSent >= settings.maxPackets && packetsReceived >= settings.maxPackets { Log.logger.debug("stopping because packetsSent >= settings.maxPackets && packetsReceived >= settings.maxPackets") break } } } if hasTimeout { stop() } Log.logger.debug("UDP AFTER SEND RETURNS \(!hasTimeout)") return !hasTimeout } /// fileprivate func receivePacket(_ dataReceived: Data, fromAddress address: Data) { // TODO: use dataReceived if packetsReceived < settings.maxPackets { packetsReceived += 1 // call callback settings.delegateQueue.async { let _ = self.delegate?.udpStreamSender(self, didReceivePacket: dataReceived) return } } } } // MARK: GCDAsyncUdpSocketDelegate methods /// extension UDPStreamSender: GCDAsyncUdpSocketDelegate { /// func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) { Log.logger.debug("didConnectToAddress: address: \(address)") Log.logger.debug("didConnectToAddress: local port: \(self.udpSocket?.localPort() ?? 0)") settings.delegateQueue.async { self.delegate?.udpStreamSender(self, didBindToPort: self.udpSocket?.localPort() ?? 0) return } countDownLatch.countDown() } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) { Log.logger.debug("didNotConnect: \(String(describing: error))") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) { // Log.logger.debug("didSendDataWithTag: \(tag)") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) { Log.logger.debug("didNotSendDataWithTag: \(String(describing: error))") } /// func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { // Log.logger.debug("didReceiveData: \(data)") // dispatch_async(streamSenderQueue) { if self.running.boolValue { self.receivePacket(data, fromAddress: address) } // } } /// func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { // crashes if NSError is used without questionmark Log.logger.debug("udpSocketDidClose: \(String(describing: error))") settings.delegateQueue.async { self.delegate?.udpStreamSenderDidClose(self, with: error) return } } }
apache-2.0
tahseen0amin/TZSegmentedControl
TZSegmentedControl/Classes/TZScrollView.swift
1
912
// // TZScrollView.swift // Pods // // Created by Tasin Zarkoob on 05/05/17. // // import UIKit class TZScrollView: UIScrollView { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if !self.isDragging{ self.next?.touchesBegan(touches, with: event) } else { super.touchesBegan(touches, with: event) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if !self.isDragging{ self.next?.touchesMoved(touches, with: event) } else { super.touchesMoved(touches, with: event) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if !self.isDragging{ self.next?.touchesEnded(touches, with: event) } else { super.touchesEnded(touches, with: event) } } }
mit
lukekavanagh/Building-Core-Data-Menu-App-in-Swift
CoreDataSamplerUITests/CoreDataSamplerUITests.swift
1
1097
// // CoreDataSamplerUITests.swift // CoreDataSamplerUITests // // Created by Aprentice on 15/07/15. // Copyright © 2015 Aprentice. All rights reserved. // import Foundation import XCTest class CoreDataSamplerUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
apache-2.0
TwoRingSoft/SemVer
Vendor/Swiftline/Package.swift
4
72
import PackageDescription let package = Package( name: "Swiftline" )
apache-2.0
keithrdavis/Camping-Directory
Camping Directory/UIViewControllerExt.swift
1
1302
// // UIViewControllerExt.swift // Camping Directory // // 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 2 // 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, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Created by Keith Davis on 9/28/16. // Copyright © 2016 ZuniSoft. All rights reserved. // import UIKit extension UIViewController { func alert(message: String, title: String = "") { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } }
gpl-2.0
MastodonKit/MastodonKit
Sources/MastodonKit/Payload.swift
1
1245
// // Payload.swift // MastodonKit // // Created by Ornithologist Coder on 4/28/17. // Copyright © 2017 MastodonKit. All rights reserved. // import Foundation enum Payload { case parameters([Parameter]?) case media(MediaAttachment?) case empty } extension Payload { var items: [URLQueryItem]? { switch self { case .parameters(let parameters): return parameters?.compactMap(toQueryItem) case .media: return nil case .empty: return nil } } var data: Data? { switch self { case .parameters(let parameters): return parameters? .compactMap(toString) .joined(separator: "&") .data(using: .utf8) case .media(let mediaAttachment): return mediaAttachment.flatMap(Data.init) case .empty: return nil } } var type: String? { switch self { case .parameters(let parameters): return parameters.map { _ in "application/x-www-form-urlencoded; charset=utf-8" } case .media(let mediaAttachment): return mediaAttachment.map { _ in "multipart/form-data; boundary=MastodonKitBoundary" } case .empty: return nil } } }
mit
irealme/MapManager
MapManager.swift
1
20432
// // MapManager.swift // // // Created by Jimmy Jose on 14/08/14. // // 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 CoreLocation import MapKit typealias DirectionsCompletionHandler = ((route:MKPolyline?, directionInformation:NSDictionary?, boundingRegion:MKMapRect?, error:String?)->())? // TODO: Documentation class MapManager: NSObject{ private var directionsCompletionHandler:DirectionsCompletionHandler private let errorNoRoutesAvailable = "No routes available"// add more error handling private let errorDictionary = ["NOT_FOUND" : "At least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded", "ZERO_RESULTS":"No route could be found between the origin and destination", "MAX_WAYPOINTS_EXCEEDED":"Too many waypointss were provided in the request The maximum allowed waypoints is 8, plus the origin, and destination", "INVALID_REQUEST":"The provided request was invalid. Common causes of this status include an invalid parameter or parameter value", "OVER_QUERY_LIMIT":"Service has received too many requests from your application within the allowed time period", "REQUEST_DENIED":"Service denied use of the directions service by your application", "UNKNOWN_ERROR":"Directions request could not be processed due to a server error. Please try again"] override init(){ super.init() } func directions(#from:CLLocationCoordinate2D,to:NSString,directionCompletionHandler:DirectionsCompletionHandler){ self.directionsCompletionHandler = directionCompletionHandler var geoCoder = CLGeocoder() geoCoder.geocodeAddressString(to as String, completionHandler: { (placemarksObject, error) -> Void in if(error != nil){ self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription) }else{ var placemarks = placemarksObject as NSArray var placemark = placemarks.lastObject as! CLPlacemark var placemarkSource = MKPlacemark(coordinate: from, addressDictionary: nil) var source = MKMapItem(placemark: placemarkSource) var placemarkDestination = MKPlacemark(placemark: placemark) var destination = MKMapItem(placemark: placemarkDestination) self.directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler) } }) } func directionsFromCurrentLocation(#to:NSString,directionCompletionHandler:DirectionsCompletionHandler){ self.directionsCompletionHandler = directionCompletionHandler var geoCoder = CLGeocoder() geoCoder.geocodeAddressString(to as String, completionHandler: { (placemarksObject, error) -> Void in if(error != nil){ self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription) }else{ var placemarks = placemarksObject as NSArray var placemark = placemarks.lastObject as! CLPlacemark var source = MKMapItem.mapItemForCurrentLocation() var placemarkDestination = MKPlacemark(placemark: placemark) var destination = MKMapItem(placemark: placemarkDestination) self.directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler) } }) } func directionsFromCurrentLocation(#to:CLLocationCoordinate2D,directionCompletionHandler:DirectionsCompletionHandler){ var directionRequest = MKDirectionsRequest() var source = MKMapItem.mapItemForCurrentLocation() var placemarkDestination = MKPlacemark(coordinate: to, addressDictionary: nil) var destination = MKMapItem(placemark: placemarkDestination) directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler) } func directions(#from:CLLocationCoordinate2D, to:CLLocationCoordinate2D,directionCompletionHandler:DirectionsCompletionHandler){ var directionRequest = MKDirectionsRequest() var placemarkSource = MKPlacemark(coordinate: from, addressDictionary: nil) var source = MKMapItem(placemark: placemarkSource) var placemarkDestination = MKPlacemark(coordinate: to, addressDictionary: nil) var destination = MKMapItem(placemark: placemarkDestination) directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler) } private func directionsFor(#source:MKMapItem, destination:MKMapItem,directionCompletionHandler:DirectionsCompletionHandler){ self.directionsCompletionHandler = directionCompletionHandler var directionRequest = MKDirectionsRequest() directionRequest.setSource(source) directionRequest.setDestination(destination) directionRequest.transportType = MKDirectionsTransportType.Any directionRequest.requestsAlternateRoutes = true var directions = MKDirections(request: directionRequest) directions.calculateDirectionsWithCompletionHandler({ (response:MKDirectionsResponse!, error:NSError!) -> Void in if (error != nil) { self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription) }else if(response.routes.isEmpty){ self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: self.errorNoRoutesAvailable) }else{ let route: MKRoute = response.routes[0] as! MKRoute let steps = route.steps as NSArray var stop = false var end_address = route.name var distance = route.distance.description var duration = route.expectedTravelTime.description var source = response.source.placemark.coordinate var destination = response.destination.placemark.coordinate var start_location = ["lat":source.latitude,"lng":source.longitude] var end_location = ["lat":destination.latitude,"lng":destination.longitude] var stepsFinalArray = NSMutableArray() steps.enumerateObjectsUsingBlock({ (obj, idx, stop) -> Void in var step:MKRouteStep = obj as! MKRouteStep var distance = step.distance.description var instructions = step.instructions var stepsDictionary = NSMutableDictionary() stepsDictionary.setObject(distance, forKey: "distance") stepsDictionary.setObject("", forKey: "duration") stepsDictionary.setObject(instructions, forKey: "instructions") stepsFinalArray.addObject(stepsDictionary) }) var stepsDict = NSMutableDictionary() stepsDict.setObject(distance, forKey: "distance") stepsDict.setObject(duration, forKey: "duration") stepsDict.setObject(end_address, forKey: "end_address") stepsDict.setObject(end_location, forKey: "end_location") stepsDict.setObject("", forKey: "start_address") stepsDict.setObject(start_location, forKey: "start_location") stepsDict.setObject(stepsFinalArray, forKey: "steps") self.directionsCompletionHandler!(route: route.polyline,directionInformation: stepsDict, boundingRegion: route.polyline.boundingMapRect, error: nil) } }) } /** Get directions using Google API by passing source and destination as string. :param: from Starting point of journey :param: to Ending point of journey :returns: directionCompletionHandler: Completion handler contains polyline,dictionary,maprect and error */ func directionsUsingGoogle(#from:NSString, to:NSString,directionCompletionHandler:DirectionsCompletionHandler){ getDirectionsUsingGoogle(origin: from, destination: to, directionCompletionHandler: directionCompletionHandler) } func directionsUsingGoogle(#from:CLLocationCoordinate2D, to:CLLocationCoordinate2D,directionCompletionHandler:DirectionsCompletionHandler){ var originLatLng = "\(from.latitude),\(from.longitude)" var destinationLatLng = "\(to.latitude),\(to.longitude)" getDirectionsUsingGoogle(origin: originLatLng, destination: destinationLatLng, directionCompletionHandler: directionCompletionHandler) } func directionsUsingGoogle(#from:CLLocationCoordinate2D, to:NSString,directionCompletionHandler:DirectionsCompletionHandler){ var originLatLng = "\(from.latitude),\(from.longitude)" getDirectionsUsingGoogle(origin: originLatLng, destination: to, directionCompletionHandler: directionCompletionHandler) } private func getDirectionsUsingGoogle(#origin:NSString, destination:NSString,directionCompletionHandler:DirectionsCompletionHandler){ self.directionsCompletionHandler = directionCompletionHandler var path = "http://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)" performOperationForURL(path) } private func performOperationForURL(urlString:NSString){ let urlEncoded = urlString.stringByReplacingOccurrencesOfString(" ", withString: "%20") let url:NSURL? = NSURL(string:urlEncoded) let request:NSURLRequest = NSURLRequest(URL:url!) let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request,queue:queue,completionHandler:{response,data,error in if(error != nil){ println(error.localizedDescription) self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription) }else{ let dataAsString: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)! var err: NSError let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary let routes = jsonResult.objectForKey("routes") as! NSArray let status = jsonResult.objectForKey("status") as! NSString let route = routes.lastObject as! NSDictionary //first object? if(status.isEqualToString("OK") && route.allKeys.count>0){ let legs = route.objectForKey("legs") as! NSArray let steps = legs.firstObject as! NSDictionary let directionInformation = self.parser(steps) as NSDictionary let overviewPolyline = route.objectForKey("overview_polyline") as! NSDictionary let points = overviewPolyline.objectForKey("points") as! NSString var locations = self.decodePolyLine(points) as Array var coordinates = locations.map({ (location: CLLocation) -> CLLocationCoordinate2D in return location.coordinate }) var polyline = MKPolyline(coordinates: &coordinates, count: locations.count) self.directionsCompletionHandler!(route: polyline,directionInformation:directionInformation, boundingRegion: polyline.boundingMapRect, error: nil) }else{ var errorMsg = self.errorDictionary[status as String] if(errorMsg == nil){ errorMsg = self.errorNoRoutesAvailable } self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: errorMsg) } } } ) } private func decodePolyLine(encodedStr:NSString)->Array<CLLocation>{ var array = Array<CLLocation>() let len = encodedStr.length var range = NSMakeRange(0, len) var strpolyline = encodedStr var index = 0 var lat = 0 as Int32 var lng = 0 as Int32 strpolyline = encodedStr.stringByReplacingOccurrencesOfString("\\\\", withString: "\\", options: NSStringCompareOptions.LiteralSearch, range: range) while(index<len){ var b = 0 var shift = 0 var result = 0 do{ var numUnichar = strpolyline.characterAtIndex(index++) var num = NSNumber(unsignedShort: numUnichar) var numInt = num.integerValue b = numInt - 63 result |= (b & 0x1f) << shift shift += 5 }while(b >= 0x20) var dlat = 0 if((result & 1) == 1){ dlat = ~(result >> 1) }else{ dlat = (result >> 1) } lat += dlat shift = 0 result = 0 do{ var numUnichar = strpolyline.characterAtIndex(index++) var num = NSNumber(unsignedShort: numUnichar) var numInt = num.integerValue b = numInt - 63 result |= (b & 0x1f) << shift shift += 5 }while(b >= 0x20) var dlng = 0 if((result & 1) == 1){ dlng = ~(result >> 1) }else{ dlng = (result >> 1) } lng += dlng var latitude = NSNumber(int:lat).doubleValue * 1e-5 var longitude = NSNumber(int:lng).doubleValue * 1e-5 var location = CLLocation(latitude: latitude, longitude: longitude) array.append(location) } return array } private func parser(data:NSDictionary)->NSDictionary{ var dict = NSMutableDictionary() var distance = (data.objectForKey("distance") as! NSDictionary).objectForKey("text") as! NSString var duration = (data.objectForKey("duration") as! NSDictionary).objectForKey("text") as! NSString var end_address = data.objectForKey("end_address") as! NSString var end_location = data.objectForKey("end_location") as! NSDictionary var start_address = data.objectForKey("start_address") as! NSString var start_location = data.objectForKey("start_location") as! NSDictionary var stepsArray = data.objectForKey("steps") as! NSArray var stepsDict = NSMutableDictionary() var stop = false var stepsFinalArray = NSMutableArray() stepsArray.enumerateObjectsUsingBlock { (obj, idx, stop) -> Void in var stepDict = obj as! NSDictionary var distance = (stepDict.objectForKey("distance") as! NSDictionary).objectForKey("text") as! NSString var duration = (stepDict.objectForKey("duration") as! NSDictionary).objectForKey("text") as! NSString var html_instructions = stepDict.objectForKey("html_instructions") as! NSString var end_location = stepDict.objectForKey("end_location") as! NSDictionary var instructions = self.removeHTMLTags((stepDict.objectForKey("html_instructions") as! NSString)) var start_location = stepDict.objectForKey("start_location") as! NSDictionary var stepsDictionary = NSMutableDictionary() stepsDictionary.setObject(distance, forKey: "distance") stepsDictionary.setObject(duration, forKey: "duration") stepsDictionary.setObject(html_instructions, forKey: "html_instructions") stepsDictionary.setObject(end_location, forKey: "end_location") stepsDictionary.setObject(instructions, forKey: "instructions") stepsDictionary.setObject(start_location, forKey: "start_location") stepsFinalArray.addObject(stepsDictionary) } stepsDict.setObject(distance, forKey: "distance") stepsDict.setObject(duration, forKey: "duration") stepsDict.setObject(end_address, forKey: "end_address") stepsDict.setObject(end_location, forKey: "end_location") stepsDict.setObject(start_address, forKey: "start_address") stepsDict.setObject(start_location, forKey: "start_location") stepsDict.setObject(stepsFinalArray, forKey: "steps") return stepsDict } private func removeHTMLTags(source:NSString)->NSString{ var range = NSMakeRange(0, 0) let HTMLTags = "<[^>]*>" var sourceString = source while( sourceString.rangeOfString(HTMLTags, options: NSStringCompareOptions.RegularExpressionSearch).location != NSNotFound){ range = sourceString.rangeOfString(HTMLTags, options: NSStringCompareOptions.RegularExpressionSearch) sourceString = sourceString.stringByReplacingCharactersInRange(range, withString: "") } return sourceString; } }
mit
nathawes/swift
validation-test/IDE/crashers_fixed/rdar50666427.swift
22
194
// RUN: %target-swift-ide-test -code-completion -code-completion-token=COMPLETE -source-filename=%s struct SD { var array: [Int] = [] } func test(sd: SD) { _ = sd[\.array[#^COMPLETE^#]] }
apache-2.0
davidbutz/ChristmasFamDuels
iOS/Boat Aware/RangeSliderTrackLayer.swift
1
2312
// // RangeSliderTrackLayer.swift // Boat Aware // // Created by Dave Butz on 6/1/16. // Copyright © 2016 Thrive Engineering. All rights reserved. // import UIKit import QuartzCore class RangeSliderTrackLayer: CALayer { weak var rangeSlider: RangeSlider? override func drawInContext(ctx: CGContext) { if let slider = rangeSlider { // Clip let cornerRadius = bounds.height * slider.curvaceousness / 2.0 let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius) CGContextAddPath(ctx, path.CGPath) // Fill the track CGContextSetFillColorWithColor(ctx, slider.trackTintColor.CGColor) CGContextAddPath(ctx, path.CGPath) CGContextFillPath(ctx) // Fill the highlighted range CGContextSetFillColorWithColor(ctx, slider.trackHighlightYellowColor.CGColor) let lowerValuePosition = CGFloat(slider.positionForValue(slider.firstValue)) let upperValuePosition = CGFloat(slider.positionForValue(slider.secondValue)) let rect = CGRect(x: lowerValuePosition, y: 0.0, width: upperValuePosition - lowerValuePosition, height: bounds.height) CGContextFillRect(ctx, rect) CGContextSetFillColorWithColor(ctx, slider.trackHighlightGreenColor.CGColor) let lowerValuePosition2 = CGFloat(slider.positionForValue(slider.secondValue)) let upperValuePosition2 = CGFloat(slider.positionForValue(slider.thirdValue)) let rect2 = CGRect(x: lowerValuePosition2, y: 0.0, width: upperValuePosition2 - lowerValuePosition2, height: bounds.height) CGContextFillRect(ctx, rect2) CGContextSetFillColorWithColor(ctx, slider.trackHighlightYellowColor.CGColor) let lowerValuePosition3 = CGFloat(slider.positionForValue(slider.thirdValue)) let upperValuePosition3 = CGFloat(slider.positionForValue(slider.fourthValue)) let rect3 = CGRect(x: lowerValuePosition3, y: 0.0, width: upperValuePosition3 - lowerValuePosition3, height: bounds.height) CGContextFillRect(ctx, rect3) } } }
mit
jatoben/RocksDB
Sources/DBIterator.swift
1
2129
/* * DBIterator.swift * Copyright (c) 2016 Ben Gollmer. * * 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 CRocksDB public class DBIterator: IteratorProtocol { private var iter: OpaquePointer fileprivate init(_ iter: OpaquePointer, _ keyPrefix: String? = nil) { self.iter = iter if let prefix = keyPrefix { rocksdb_iter_seek(iter, prefix, prefix.utf8.count) } else { rocksdb_iter_seek_to_first(self.iter) } } deinit { rocksdb_iter_destroy(iter) } public func next() -> (DBEntry, DBEntry)? { guard rocksdb_iter_valid(iter) != 0 else { return nil } var keyLength: Int = 0 var valLength: Int = 0 let k = rocksdb_iter_key(iter, &keyLength) let v = rocksdb_iter_value(iter, &valLength) guard let key = k, let val = v else { return nil } defer { rocksdb_iter_next(iter) } let keyPointer = UnsafeBufferPointer(start: key, count: keyLength) let valPointer = UnsafeBufferPointer(start: val, count: valLength) return (DBEntry(dbValue: [Int8](keyPointer)), DBEntry(dbValue: [Int8](valPointer))) } } extension Database: Sequence { public func makeIterator(_ opts: DBReadOptions, keyPrefix prefix: String? = nil) -> DBIterator { let i = rocksdb_create_iterator(db, opts.opts) guard let iter = i else { preconditionFailure("Could not create database iterator") } return DBIterator(iter, prefix) } public func makeIterator(keyPrefix prefix: String) -> DBIterator { return makeIterator(readOptions, keyPrefix: prefix) } public func makeIterator() -> DBIterator { return makeIterator(readOptions) } }
apache-2.0
killerpsyco/Parameter-Calculator-of-Transistor
TFT Performance/PerformanceCalculator.swift
1
1359
// // PerformanceCalculator.swift // TFT Performance // // Created by dyx on 15/6/16. // Copyright (c) 2015年 dyx. All rights reserved. // import Foundation class PerformanceCalculator { func sqrtGradient(cu1: Double, cu2: Double, voltage1: Double, voltage2: Double) -> Double? { let sqrtCu1 = sqrt(cu1) let sqrtCu2 = sqrt(cu2) return (sqrtCu2 - sqrtCu1) / (voltage2 - voltage1) } func thresholdVoltage(cu1: Double, voltage1: Double, gradient: Double) -> Double? { let sqrtCu1 = sqrt(cu1) let intercept = sqrtCu1 - gradient * voltage1 if gradient != 0 { let thVoltage = -(intercept / gradient) println("\(thVoltage)") return thVoltage } else { return 0.0 } } func mobility(length: Double, width: Double, capacity: Double, gradient: Double) -> Double? { return 2 * (length * 1e-6) * (gradient * gradient * 1e-6) * 1e4 / (width * 1e-2 * capacity * 1e-5) } func onOffRatio(Ion: Double, Ioff: Double) -> Double { return Ion / Ioff } func thresholdSwing(cu1: Double, cu2: Double, voltage1: Double, voltage2: Double) -> Double? { let log1 = log10(cu1) let log2 = log10(cu2) return (voltage1 - voltage2) / (log1 - log2) } }
epl-1.0
practicalswift/swift
validation-test/compiler_crashers_fixed/00527-swift-constraints-constraintsystem-gettypeofmemberreference.swift
65
526
// 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 class func g<T) { class A { struct c { func b: A? = nil var d = b<c: T>(c() protocol b = D> Void>(v: A"A"""") init(f) func b.in
apache-2.0
practicalswift/swift
test/decl/protocol/resilient_defaults.swift
6
605
// RUN: %target-typecheck-verify-swift -enable-resilience public struct Wrapper<T: P>: P { } extension Wrapper: Q where T: Q { } public protocol PBase { associatedtype AssocType } public protocol P: PBase { override associatedtype AssocType: P = Wrapper<Self> // expected-note@-1{{associated type 'AssocType' has default type 'Wrapper<Self>' written here}} } public protocol Q: P where Self.AssocType: Q { } public protocol R: Q where Self.AssocType: R { } // expected-warning@-1{{default type 'Wrapper<Self>' for associated type 'AssocType' does not satisfy constraint 'Self.AssocType': 'R'}}
apache-2.0
robrix/SwiftCheck
SwiftCheck/Check.swift
1
4940
// // Check.swift // SwiftCheck // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015 TypeLift. All rights reserved. // /// The main interface for the SwiftCheck testing mechanism. `property` notation is used to define /// a property that SwiftCheck can generate test cases for and a human-readable label for debugging /// output. A simple property test might look like the following: /// /// property("reflexitivity") <- forAll { (i : Int8) in /// return i == i /// } /// /// SwiftCheck will report all failures through the XCTest mechanism like a normal testing assert, /// but with the minimal failing case reported as well. /// /// If necessary, arguments can be provided to this function to change the behavior of the testing /// mechanism: /// /// let args = CheckerArguments( replay: Optional.Some((newStdGen(), 10)) // Replays all tests with a new generator of size 10 /// , maxAllowableSuccessfulTests: 200 // Requires twice the normal amount of successes to pass. /// , maxAllowableDiscardedTests: 0 // Discards are not allowed anymore. /// , maxTestCaseSize: 1000 // Increase the size of tested values by 10x. /// ) /// /// property("reflexitivity", arguments: args) <- forAll { (i : Int8) in /// return i == i /// } /// /// If no arguments are provided, or nil is given, SwiftCheck will select an internal default. public func property(msg : String, arguments : CheckerArguments? = nil, file : String = __FILE__, line : UInt = __LINE__) -> AssertiveQuickCheck { return AssertiveQuickCheck(msg: msg, file: file, line: line, args: arguments ?? stdArgs(msg)) } public struct AssertiveQuickCheck { let msg : String let file : String let line : UInt let args : CheckerArguments private init(msg : String, file : String, line : UInt, args : CheckerArguments) { self.msg = msg self.file = file self.line = line self.args = { var chk = args; chk.name = msg; return chk }() } } /// The interface for properties to be run through SwiftCheck without an XCTest assert. The /// property will still generate console output during testing. public func reportProperty(msg : String, arguments : CheckerArguments? = nil, file : String = __FILE__, line : UInt = __LINE__) -> ReportiveQuickCheck { return ReportiveQuickCheck(msg: msg, file: file, line: line, args: arguments ?? stdArgs(msg)) } public struct ReportiveQuickCheck { let msg : String let file : String let line : UInt let args : CheckerArguments private init(msg : String, file : String, line : UInt, args : CheckerArguments) { self.msg = msg self.file = file self.line = line self.args = { var chk = args; chk.name = msg; return chk }() } } /// Represents the arguments the test driver will use while performing testing, shrinking, and /// printing results. public struct CheckerArguments { /// Provides a way of re-doing a test at the given size with a new generator. let replay : Optional<(StdGen, Int)> /// The maximum number of test cases that must pass before the property itself passes. /// /// The default value of this property is 100. In general, some tests may require more than /// this amount, but less is rare. If you need a value less than or equal to 1, use `.once` /// on the property instead. let maxAllowableSuccessfulTests : Int /// The maximum number of tests cases that can be discarded before testing gives up on the /// property. /// /// The default value of this property is 500. In general, most tests will require less than /// this amount. `Discard`ed test cases do not affect the passing or failing status of the /// property as a whole. let maxAllowableDiscardedTests : Int /// The limit to the size of all generators in the test. /// /// The default value of this property is 100. If "large" values, in magnitude or /// size, are necessary then increase this value, else keep it relatively near the default. If /// it becomes too small the samples present in the test case will lose diversity. let maxTestCaseSize : Int public init( replay : Optional<(StdGen, Int)> , maxAllowableSuccessfulTests : Int , maxAllowableDiscardedTests : Int , maxTestCaseSize : Int) { self = CheckerArguments(replay: replay, maxAllowableSuccessfulTests: maxAllowableSuccessfulTests, maxAllowableDiscardedTests: maxAllowableDiscardedTests, maxTestCaseSize: maxTestCaseSize, name: "") } internal init( replay : Optional<(StdGen, Int)> , maxAllowableSuccessfulTests : Int , maxAllowableDiscardedTests : Int , maxTestCaseSize : Int , name : String) { self.replay = replay self.maxAllowableSuccessfulTests = maxAllowableSuccessfulTests self.maxAllowableDiscardedTests = maxAllowableDiscardedTests self.maxTestCaseSize = maxTestCaseSize self.name = name } internal var name : String }
mit
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/Bitcoin/BTCOnChainTxEngineState.swift
1
778
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation struct BTCOnChainTxEngineState<Token: BitcoinChainToken> { private(set) var transactionCandidate: NativeBitcoinTransactionCandidate? private(set) var context: NativeBitcoinTransactionContext? init( transactionCandidate: NativeBitcoinTransactionCandidate? = nil, context: NativeBitcoinTransactionContext? = nil ) { self.transactionCandidate = transactionCandidate self.context = context } mutating func add(transactionCandidate: NativeBitcoinTransactionCandidate) { self.transactionCandidate = transactionCandidate } mutating func add(context: NativeBitcoinTransactionContext) { self.context = context } }
lgpl-3.0
kosicki123/WWDC
WWDC/PreferencesWindowController.swift
1
4901
// // PreferencesWindowController.swift // WWDC // // Created by Guilherme Rambo on 01/05/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa class PreferencesWindowController: NSWindowController { let prefs = Preferences.SharedPreferences() convenience init() { self.init(windowNibName: "PreferencesWindowController") } @IBOutlet weak var downloadProgressIndicator: NSProgressIndicator! override func windowDidLoad() { super.windowDidLoad() populateFontsPopup() downloadsFolderLabel.stringValue = prefs.localVideoStoragePath automaticRefreshEnabledCheckbox.state = prefs.automaticRefreshEnabled ? NSOnState : NSOffState if let familyName = prefs.transcriptFont.familyName { fontPopUp.selectItemWithTitle(familyName) } let size = "\(Int(prefs.transcriptFont.pointSize))" sizePopUp.selectItemWithTitle(size) textColorWell.color = prefs.transcriptTextColor bgColorWell.color = prefs.transcriptBgColor } // MARK: Downloads folder @IBOutlet weak var downloadsFolderLabel: NSTextField! @IBAction func changeDownloadsFolder(sender: NSButton) { let panel = NSOpenPanel() panel.directoryURL = NSURL(fileURLWithPath: Preferences.SharedPreferences().localVideoStoragePath) panel.canChooseDirectories = true panel.canChooseFiles = false panel.canCreateDirectories = true panel.prompt = "Choose" panel.beginSheetModalForWindow(window!) { result in if result > 0 { if let path = panel.URL?.path { Preferences.SharedPreferences().localVideoStoragePath = path self.downloadsFolderLabel.stringValue = path } } } } @IBAction func downloadAllSessions(sender: AnyObject) { let completionHandler: DataStore.fetchSessionsCompletionHandler = { success, sessions in dispatch_async(dispatch_get_main_queue()) { let sessions2015 = sessions.filter{(session) in return session.year == 2015 && !VideoStore.SharedStore().hasVideo(session.hd_url!) } println("Videos fetched, start downloading") DownloadVideosBatch.SharedDownloader().sessions = sessions2015 DownloadVideosBatch.SharedDownloader().startDownloading() } } DataStore.SharedStore.fetchSessions(completionHandler, disableCache: true) if let appDelegate = NSApplication.sharedApplication().delegate as? AppDelegate { appDelegate.showDownloadsWindow(appDelegate) } } @IBAction func revealInFinder(sender: NSButton) { let path = Preferences.SharedPreferences().localVideoStoragePath let root = path.stringByDeletingLastPathComponent NSWorkspace.sharedWorkspace().selectFile(path, inFileViewerRootedAtPath: root) } // MARK: Session refresh @IBOutlet weak var automaticRefreshEnabledCheckbox: NSButton! @IBAction func automaticRefreshCheckboxAction(sender: NSButton) { prefs.automaticRefreshEnabled = (sender.state == NSOnState) } // MARK: Transcript appearance @IBOutlet weak var fontPopUp: NSPopUpButton! @IBOutlet weak var sizePopUp: NSPopUpButton! @IBOutlet weak var textColorWell: NSColorWell! @IBOutlet weak var bgColorWell: NSColorWell! @IBAction func fontPopUpAction(sender: NSPopUpButton) { if let newFont = NSFont(name: fontPopUp.selectedItem!.title, size: prefs.transcriptFont.pointSize) { prefs.transcriptFont = newFont } } @IBAction func sizePopUpAction(sender: NSPopUpButton) { let size = NSString(string: sizePopUp.selectedItem!.title).doubleValue prefs.transcriptFont = NSFont(name: prefs.transcriptFont.fontName, size: CGFloat(size))! } @IBAction func textColorWellAction(sender: NSColorWell) { prefs.transcriptTextColor = textColorWell.color } @IBAction func bgColorWellAction(sender: NSColorWell) { prefs.transcriptBgColor = bgColorWell.color } func populateFontsPopup() { fontPopUp.addItemsWithTitles(NSFontManager.sharedFontManager().availableFontFamilies) } private func hideProgressIndicator() { self.downloadProgressIndicator.hidden = true downloadProgressIndicator.stopAnimation(nil) } private func showProgressIndicator() { self.downloadProgressIndicator.hidden = false downloadProgressIndicator.startAnimation(nil) } }
bsd-2-clause
M2Mobi/Marky-Mark
Example/Tests/MarkDown Items/HeaderMarkDownItemTests.swift
1
575
// // Created by Jim van Zummeren on 28/04/16. // Copyright © 2016 M2mobi. All rights reserved. // import XCTest @testable import markymark class HeaderMarkDownItemTests: XCTestCase { private var sut: HeaderMarkDownItem! override func setUp() { super.setUp() sut = HeaderMarkDownItem(lines: ["Line one"], content: "Line one", level: 1) } func testMarkDownItemHasCorrectText() { XCTAssertEqual(sut.content, "Line one") } func testMarkDownItemHasCorrectLines() { XCTAssertEqual(sut.lines, ["Line one"]) } }
mit
CoderST/XMLYDemo
XMLYDemo/XMLYDemo/Class/Category/Extension/UIToolbar + Extension.swift
1
1091
// // UIToolbar + Extension.swift // XMLYDemo // // Created by xiudou on 2016/12/30. // Copyright © 2016年 CoderST. All rights reserved. // import Foundation import UIKit extension UIToolbar { /// 隐藏头部线 func hideHairline() { let navigationBarImageView = hairlineImageViewInToolbar(view: self) navigationBarImageView!.isHidden = true } /// 显示头部线 func showHairline() { let navigationBarImageView = hairlineImageViewInToolbar(view: self) navigationBarImageView!.isHidden = false } /// 实现方法 private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? { if view.isKind(of : UIImageView.self) && view.bounds.height <= 1.0 { return (view as! UIImageView) } let subviews = (view.subviews as [UIView]) for subview: UIView in subviews { if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) { return imageView } } return nil } }
mit
recruit-lifestyle/Smile-Lock
SmileLock-Example/SmileLock-ExampleTests/SmileLock_ExampleTests.swift
2
1023
// // SmileLock_ExampleTests.swift // SmileLock-ExampleTests // // Created by yuchen liu on 4/24/16. // Copyright © 2016 Recruit Lifestyle Co., Ltd. All rights reserved. // import XCTest @testable import SmileLock_Example class SmileLock_ExampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
apache-2.0