repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pawel-sp/AppFlowController | refs/heads/master | iOS-Example/AlphaTransition.swift | mit | 1 | //
// AlphaTransition.swift
// iOS-Example
//
// Created by Paweł Sporysz on 02.10.2016.
// Copyright © 2016 Paweł Sporysz. All rights reserved.
//
import UIKit
import AppFlowController
class AlphaTransition: NSObject, UIViewControllerAnimatedTransitioning, FlowTransition, UINavigationControllerDelegate {
// MARK: - UIViewControllerAnimatedTransitioning
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) else { return }
guard let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return }
let containerView = transitionContext.containerView
guard let toView = toVC.view else { return }
guard let fromView = fromVC.view else { return }
let animationDuration = transitionDuration(using: transitionContext)
toView.alpha = 0
containerView.addSubview(toView)
UIView.animate(withDuration: animationDuration, animations: {
toView.alpha = 1
}) { finished in
if (transitionContext.transitionWasCancelled) {
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
// MARK: - FlowTransition
func performForwardTransition(animated: Bool, completion: @escaping () -> ()) -> ForwardTransition.ForwardTransitionAction {
return { navigationController, viewController in
let previousDelegate = navigationController.delegate
navigationController.delegate = self
navigationController.pushViewController(viewController, animated: animated){
navigationController.delegate = previousDelegate
completion()
}
}
}
func performBackwardTransition(animated: Bool, completion: @escaping () -> ()) -> BackwardTransition.BackwardTransitionAction {
return { viewController in
let navigationController = viewController.navigationController
let previousDelegate = navigationController?.delegate
navigationController?.delegate = self
let _ = navigationController?.popViewController(animated: animated) {
navigationController?.delegate = previousDelegate
completion()
}
}
}
// MARK: - UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
| 31eb536579b48ff6a8b17b3d0c8853f8 | 40.835616 | 246 | 0.69057 | false | false | false | false |
derrickhunt/unsApp | refs/heads/master | UNS/UNS/ViewController.swift | mit | 1 | //
// ViewController.swift
// UNS
//
// Created by Student on 4/30/15.
// Copyright (c) 2015 Derrick Hunt. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var URLHistory = NSMutableArray()
@IBOutlet weak var myBackBtn: UIBarButtonItem!
@IBOutlet weak var myActionBtn: UIBarButtonItem!
@IBOutlet weak var myToolbar: UIToolbar!
@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "University News"
//set up web view
webView = WKWebView()
webView.navigationDelegate = self
resizeWebView()
let url = NSURL(string: "http://www.rit.edu/news/")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
view.addSubview(webView)
webView.hidden = true
//handle device rotation
UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resizeWebView", name: UIDeviceOrientationDidChangeNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func resizeWebView() {
var navBarOffset = self.navigationController!.navigationBar.frame.height + UIApplication.sharedApplication().statusBarFrame.height
var toolBarOffset = myToolbar.frame.height + 1
webView.frame = CGRectMake(0, navBarOffset, view.frame.width, view.frame.height - navBarOffset - toolBarOffset)
}
//MARK: - Nav Bar Actions -
@IBAction func goBack(sender: AnyObject) {
if (URLHistory.count <= 1) {
return
}
//get URL
let request = NSURLRequest(URL: URLHistory[URLHistory.count - 2] as NSURL)
//update array and button
URLHistory.removeLastObject()
URLHistory.removeLastObject()
if (URLHistory.count <= 1) {
myBackBtn.enabled = false
}
//go back
webView.loadRequest(request)
println(URLHistory)
println(request)
}
@IBAction func goShare(sender: AnyObject) {
let urlString = URLHistory[URLHistory.count - 1] as NSURL
//let shareString = "RIT News: " + urlString
let activity = UIActivityViewController(activityItems: [urlString], applicationActivities: nil)
activity.popoverPresentationController?.barButtonItem = sender as UIBarButtonItem //attaches view to btn
presentViewController(activity, animated: true, completion: nil)
}
//MARK: - Toolbar Actions -
@IBAction func goHome(sender: AnyObject) {
let url = NSURL(string: "http://www.rit.edu/news/")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
@IBAction func goMag(sender: AnyObject) {
let url = NSURL(string: "http://www.rit.edu/news/magazine.php")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
@IBAction func goAth(sender: AnyObject) {
let url = NSURL(string: "http://www.rit.edu/news/athenaeum.php")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
@IBAction func goSports(sender: AnyObject) {
let url = NSURL(string: "http://www.ritathletics.com/")
let request = NSURLRequest(URL: url!)
if (request != webView.URL!){
webView.loadRequest(request)
}
}
//MARK: - WKNavigation Methods -
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
webView.hidden = true
myActivityIndicator.hidden = false
myActivityIndicator.startAnimating()
//update URL list and button
URLHistory.addObject(webView.URL!)
if (URLHistory.count > 1) {
myBackBtn.enabled = true
}
println(URLHistory)
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
myActivityIndicator.stopAnimating()
//update nav title
if (webView.URL! == NSURL(string: "http://www.rit.edu/news/")) {
self.title = "University News"
}
if (webView.URL! == NSURL(string: "http://www.rit.edu/news/magazine.php")) {
self.title = "University Magazine"
}
if (webView.URL! == NSURL(string: "http://www.rit.edu/news/athenaeum.php")) {
self.title = "Athenaeum"
}
if (webView.URL! == NSURL(string: "http://www.ritathletics.com/")) {
self.title = "Athletics"
}
webView.hidden = false
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
myActivityIndicator.stopAnimating()
//display error message
let errorMsg = UIAlertView(title: "Error", message: "An error occurred while processing your request. \n\nPlease make sure you are connected to the Internet and try again.", delegate: self, cancelButtonTitle: "Okay")
errorMsg.show()
//log error to console
println("Failed to load: \(error)")
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
myActivityIndicator.stopAnimating()
//display error message
let errorMsg = UIAlertView(title: "Error", message: "An error occurred while processing your request. \n\nPlease make sure you are connected to the Internet and try again.", delegate: self, cancelButtonTitle: "Okay")
errorMsg.show()
//log error to console
println("Failed to load: \(error)")
}
}
| c06a13749353f0b18b3e8401c7224b0e | 32.879781 | 224 | 0.616774 | false | false | false | false |
dedeexe/tmdb_example | refs/heads/master | tmdb/Classes/Common/Rest/FuckingRequest.swift | mit | 1 | //
// FuckingRequest.swift
// FuckTheRest
//
// Created by Fabrício Santos on 1/24/17.
// Copyright © 2017 dede.exe. All rights reserved.
//
import Foundation
open class FuckingRequest {
let url:URL
let method : String
var parameters : [String:String] = [:]
var headers : [String:String] = [:]
fileprivate var request : URLRequest
{
var fieldParams:[String] = []
var urlRequest = URLRequest(url: self.url)
urlRequest.httpMethod = method
for (key,value) in headers {
urlRequest.addValue(value, forHTTPHeaderField: key)
}
for (key,value) in parameters {
let paramValue = "\(key)=\(value)"
fieldParams.append(paramValue)
}
let paramsString = fieldParams.joined(separator: "&")
if method == FuckingMethod.get.rawValue && fieldParams.count > 0 {
let urlString = url.absoluteString + "?" + paramsString
let getURL = URL(string: urlString)
urlRequest.url = getURL
return urlRequest
}
urlRequest.httpBody = paramsString.data(using:.utf8)
return urlRequest
}
public init(url:String, methodName:String) {
self.url = URL(string:url)!
self.method = methodName
}
convenience public init(url:String, method:FuckingMethod) {
self.init(url:url, methodName:method.rawValue)
}
open func header(_ fields:[String:String]) {
self.headers = fields
}
open func addHeader(_ key:String, value:String) -> FuckingRequest {
self.headers[key] = value
return self
}
open func parameters(_ fields:[String:String]) {
self.headers = fields
}
open func addParameter(_ key:String, value:String) -> FuckingRequest {
self.parameters[key] = value
return self
}
}
extension FuckingRequest
{
open func response(completion:@escaping (FuckingResult<Data>) -> Void) {
let requestEntity = self.request
let responseEntity = FuckingResponse(request: requestEntity)
responseEntity.getData(completion: completion)
}
open func responseString(completion:@escaping (FuckingResult<String>) -> Void) {
let requestEntity = self.request
let responseEntity = FuckingResponse(request: requestEntity)
responseEntity.getData { (resultData) in
let stringResult = resultData.map(extractStringFromData)
completion(stringResult)
}
}
}
| 546f1e32cc3e7ad9d24f8a2855b5209e | 27.648352 | 84 | 0.60491 | false | false | false | false |
breadwallet/breadwallet-ios | refs/heads/master | breadwalletWidget/Services/WidgetService.swift | mit | 1 | //
// WidgetService.swift
// breadwalletIntentHandler
//
// Created by stringcode on 11/02/2021.
// Copyright © 2021 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import CoinGecko
typealias CurrencyHandler = (Result<[Currency], Error>) -> Void
typealias AssetOptionHandler = (Result<[AssetOption], Error>) -> Void
typealias ColorOptionHandler = (Result<[ColorOption], Error>) -> Void
typealias CurrencyInfoHandler = (CurrencyInfoResult) -> Void
typealias CurrencyInfoResult = Result<([Currency], [CurrencyId: MarketInfo]), Error>
protocol WidgetService {
func fetchCurrenciesAndMarketInfo(for assetOptions: [AssetOption],
quote: String,
interval: IntervalOption,
handler: @escaping CurrencyInfoHandler)
func fetchCurrencies(handler: @escaping CurrencyHandler)
func fetchAssetOptions(handler: @escaping AssetOptionHandler)
func fetchBackgroundColorOptions(handler: ColorOptionHandler)
func fetchTextColorOptions(handler: ColorOptionHandler)
func fetchChartUpColorOptions(handler: ColorOptionHandler)
func fetchChartDownColorOptions(handler: ColorOptionHandler)
func defaultBackgroundColor() -> ColorOption
func defaultTextColor() -> ColorOption
func defaultChartUpOptions() -> ColorOption
func defaultChartDownOptions() -> ColorOption
func defaultAssetOptions() -> [AssetOption]
func defaultCurrencies() throws -> [Currency]
func quoteCurrencyCode() -> String
}
enum WidgetServiceError: Error {
case failedToLoadCurrenciesFile
}
// MARK: - DefaultAssetsOptionsService
class DefaultWidgetService: WidgetService {
let widgetDataShareService: WidgetDataShareService?
let coinGeckoClient = CoinGeckoClient()
private(set) var currenciesCache: [Currency] = []
init(widgetDataShareService: WidgetDataShareService?,
imageStoreService: ImageStoreService?) {
self.widgetDataShareService = widgetDataShareService
imageStoreService?.loadImagesIfNeeded()
}
func fetchCurrenciesAndMarketInfo(for assetOptions: [AssetOption],
quote: String,
interval: IntervalOption,
handler: @escaping CurrencyInfoHandler) {
let uids = assetOptions.map { $0.identifier }
fetchCurrencies { [weak self] result in
switch result {
case let .success(currencies):
let selected = currencies.filter { uids.contains($0.uid.rawValue) }
self?.fetchPriceListAndChart(for: selected,
quote: quote,
interval: interval,
handler: handler)
case let .failure(error):
handler(.failure(error))
}
}
}
func fetchCurrencies(handler: @escaping CurrencyHandler) {
if !currenciesCache.isEmpty {
handler(.success(currenciesCache))
return
}
do {
let currencies = try defaultCurrencies()
handler(.success(currencies))
} catch {
handler(.failure(error))
}
}
func fetchAssetOptions(handler: @escaping AssetOptionHandler) {
fetchCurrencies { result in
switch result {
case let .success(currencies):
handler(.success(currencies.map { $0.assetOption() }))
case let .failure(error):
handler(.failure(error))
}
}
}
func defaultAssetOptions() -> [AssetOption] {
return ((try? defaultCurrencies()) ?? [])
.filter { Constant.defaultCurrencyCodes.contains($0.code.uppercased()) }
.map { $0.assetOption() }
}
func fetchBackgroundColorOptions(handler: ColorOptionHandler) {
let currenciesColors = ((try? defaultCurrencies()) ?? []).map {
ColorOption(currency: $0)
}
let colorOptions = [ColorOption.autoBackground]
+ ColorOption.backgroundColors()
+ ColorOption.basicColors()
+ currenciesColors
handler(.success(colorOptions))
}
func defaultBackgroundColor() -> ColorOption {
return ColorOption.autoBackground
}
func fetchTextColorOptions(handler: ColorOptionHandler) {
let colorOptions = [ColorOption.autoTextColor]
+ ColorOption.textColors()
+ ColorOption.basicColors()
+ ColorOption.backgroundColors()
handler(.success(colorOptions))
}
func defaultTextColor() -> ColorOption {
return ColorOption.autoTextColor
}
func fetchChartUpColorOptions(handler: ColorOptionHandler) {
let options = ColorOption.basicColors()
+ ColorOption.textColors()
+ ColorOption.backgroundColors()
handler(.success(options))
}
func defaultChartUpOptions() -> ColorOption {
return ColorOption.green
}
func fetchChartDownColorOptions(handler: ColorOptionHandler) {
let options = ColorOption.basicColors()
+ ColorOption.textColors()
+ ColorOption.backgroundColors()
handler(.success(options))
}
func defaultChartDownOptions() -> ColorOption {
return ColorOption.red
}
func defaultCurrencies() throws -> [Currency] {
guard currenciesCache.isEmpty else {
return currenciesCache
}
guard let url = Constant.currenciesURL else {
throw WidgetServiceError.failedToLoadCurrenciesFile
}
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let meta = try decoder.decode([CurrencyMetaData].self, from: data)
let currencies = meta
.map { Currency(metaData: $0)}
.filter { $0.isSupported }
.sorted { $0.metaData.isPreferred && !$1.metaData.isPreferred }
.sorted { $0.isEthereum && !$1.isEthereum }
.sorted { $0.isBitcoin && !$1.isBitcoin }
currenciesCache = currencies
return currencies
}
}
func quoteCurrencyCode() -> String {
return widgetDataShareService?.quoteCurrencyCode ?? "USD"
}
}
// MARK: - Loading chart and simple price
private extension DefaultWidgetService {
typealias MarketChartResult = Result<MarketChart, CoinGeckoError>
typealias PriceListResult = Result<PriceList, CoinGeckoError>
func fetchPriceListAndChart(for currencies: [Currency],
quote: String,
interval: IntervalOption,
handler: @escaping (CurrencyInfoResult) -> Void) {
let group = DispatchGroup()
var priceList: PriceList = []
var charts: [CurrencyId: MarketChart] = [:]
var error: Error?
let codes = currencies.compactMap { $0.coinGeckoId }
group.enter()
self.priceList(codes: codes, base: quote) { result in
switch result {
case let .success(list):
priceList = list
case let .failure(err):
error = err
}
group.leave()
}
for currency in currencies {
guard let code = currency.coinGeckoId else {
continue
}
group.enter()
chart(code: code, quote: quote, interval: interval.resources) { result in
switch result {
case let .success(chartData):
charts[currency.uid] = chartData
case let .failure(error):
print(error)
}
group.leave()
}
}
group.notify(queue: DispatchQueue.global()) {
if let error = error {
handler(.failure(error))
return
}
let info = self.marketInfo(currencies, priceList: priceList, charts: charts)
handler(.success((currencies, info)))
}
}
func priceList(codes: [String], base: String, handler: @escaping (PriceListResult) -> Void) {
let prices = Resources.simplePrice(ids: codes,
vsCurrency: base,
options: SimplePriceOptions.allCases,
handler)
coinGeckoClient.load(prices)
}
func chart(code: String,
quote: String,
interval: Resources.Interval,
handler: @escaping (MarketChartResult) -> Void) {
let chart = Resources.chart(base: code,
quote: quote,
interval: interval,
callback: handler)
coinGeckoClient.load(chart)
}
func marketInfo(_ currencies: [Currency],
priceList: PriceList,
charts: [CurrencyId: MarketChart]) -> [CurrencyId: MarketInfo] {
var result = [CurrencyId: MarketInfo]()
for currency in currencies {
let coinGeckoId = currency.coinGeckoId ?? "error"
let simplePrice = priceList.first(where: { $0.id == coinGeckoId})
let amount = widgetDataShareService?.amount(for: currency.uid)
if let price = simplePrice {
result[currency.uid] = MarketInfo(id: currency.uid,
amount: amount,
simplePrice: price,
chart: charts[currency.uid])
}
}
return result
}
}
// MARK: - Utilities
private extension DefaultWidgetService {
enum Constant {
static let defaultCurrencyCodes = ["BTC", "ETH", "BRD"]
static let currenciesURL = Bundle.main.url(forResource: "currencies",
withExtension: "json")
}
}
| 4e4adeed3f94e60e5a002642951309fa | 34.037162 | 97 | 0.569376 | false | false | false | false |
machelix/Lightbox | refs/heads/master | Source/LightboxViewCell.swift | mit | 1 | import UIKit
public class LightboxViewCell: UICollectionViewCell {
public static let reuseIdentifier: String = "LightboxViewCell"
var constraintsAdded = false
weak var parentViewController: LightboxController?
public lazy var lightboxView: LightboxView = { [unowned self] in
let lightboxView = LightboxView(frame: self.bounds)
lightboxView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(lightboxView)
return lightboxView
}()
public override func layoutSubviews() {
super.layoutSubviews()
setupConstraints()
lightboxView.updateViewLayout()
}
public func setupTransitionManager() {
guard let controller = parentViewController else { return }
controller.transitionManager.sourceViewCell = self
controller.transitionManager.animator = UIDynamicAnimator(referenceView: lightboxView)
}
private func setupConstraints() {
if !constraintsAdded {
let layoutAttributes: [NSLayoutAttribute] = [.Leading, .Trailing, .Top, .Bottom]
for layoutAttribute in layoutAttributes {
addConstraint(NSLayoutConstraint(item: lightboxView, attribute: layoutAttribute,
relatedBy: .Equal, toItem: contentView, attribute: layoutAttribute,
multiplier: 1, constant: 0))
}
constraintsAdded = true
}
}
}
| 12a2aa9c43e45a8e423ea747e5f598ee | 30.046512 | 90 | 0.740075 | false | false | false | false |
somegeekintn/SimDirs | refs/heads/main | SimDirs/Views/DescriptiveToggle.swift | mit | 1 | //
// DescriptiveToggle.swift
// SimDirs
//
// Created by Casey Fleser on 8/7/22.
//
import SwiftUI
protocol ToggleDescriptor {
var isOn : Bool { get }
var titleKey : LocalizedStringKey { get }
var text : String { get }
var image : Image { get }
}
extension ToggleDescriptor {
var circleColor : Color { isOn ? .accentColor : Color("CircleSymbolBkgOff") }
}
struct DescriptiveToggle<T: ToggleDescriptor>: View {
@Binding var isOn : Bool
var descriptor : T
var subtitled : Bool
init(_ descriptor: T, isOn: Binding<Bool>, subtitled: Bool = true) {
self._isOn = isOn
self.descriptor = descriptor
self.subtitled = subtitled
}
var body: some View {
Toggle(descriptor.titleKey, isOn: _isOn)
.toggleStyle(DescriptiveToggleStyle(descriptor, subtitled: subtitled))
}
}
struct DescriptiveToggle_Previews: PreviewProvider {
struct DarkMode: ToggleDescriptor {
var isOn : Bool = true
var titleKey : LocalizedStringKey { "Dark Mode" }
var text : String { isOn ? "On" : "Off" }
var image : Image { Image(systemName: "circle.circle") }
}
@State static var toggle = DarkMode()
static var previews: some View {
DescriptiveToggle(DarkMode(), isOn: $toggle.isOn)
.disabled(true)
}
}
| 02dc3bd4203e48d6eaef9a59436f51ec | 26.134615 | 82 | 0.603118 | false | false | false | false |
taji-taji/TJExtensions | refs/heads/master | TJExtensions/Sources/UIViewExtensions.swift | mit | 1 | //
// UIViewExtensions.swift
// TJExtension
//
// Created by tajika on 2015/12/08.
// Copyright © 2015年 Tajika. All rights reserved.
//
import UIKit
public enum TJViewBorderPosition {
case top
case right
case bottom
case left
}
public extension UIView {
/**
Extended by TJExtensions
*/
public func border(borderWidth: CGFloat, borderColor: UIColor?, borderRadius: CGFloat?) {
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor?.cgColor
if let _ = borderRadius {
self.layer.cornerRadius = borderRadius!
}
self.layer.masksToBounds = true
}
/**
Extended by TJExtensions
*/
public func border(_ positions: Set<TJViewBorderPosition>, borderWidth: CGFloat, borderColor: UIColor?) {
self.layer.sublayers = nil
if positions.contains(.top) {
borderTop(borderWidth, borderColor: borderColor)
}
if positions.contains(.left) {
borderLeft(borderWidth, borderColor: borderColor)
}
if positions.contains(.bottom) {
borderBottom(borderWidth, borderColor: borderColor)
}
if positions.contains(.right) {
borderRight(borderWidth, borderColor: borderColor)
}
}
fileprivate func borderTop(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: 0.0, y: 0.0, width: self.frame.width, height: borderWidth)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func borderBottom(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: 0.0, y: self.frame.height - borderWidth, width: self.frame.width, height: borderWidth)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func borderLeft(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: 0.0, y: 0.0, width: borderWidth, height: self.frame.height)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func borderRight(_ borderWidth: CGFloat, borderColor: UIColor?) {
let rect = CGRect(x: self.frame.width - borderWidth, y: 0.0, width: borderWidth, height: self.frame.height)
addBorderWithRect(borderWidth, borderColor: borderColor, rect: rect)
}
fileprivate func addBorderWithRect(_ borderWidth: CGFloat, borderColor: UIColor?, rect: CGRect) {
let line = CALayer()
let defaultBorderColor = UIColor.white
var CGBorderColor: CGColor
self.layer.masksToBounds = true
if let _ = borderColor {
CGBorderColor = borderColor!.cgColor
} else {
CGBorderColor = defaultBorderColor.cgColor
}
line.frame = rect
line.backgroundColor = CGBorderColor
self.layer.addSublayer(line)
self.setNeedsDisplay()
}
/**
Extended by TJExtensions
*/
@IBInspectable
var borderWidth: CGFloat {
get {
return self.layer.borderWidth
}
set {
self.layer.borderWidth = newValue
}
}
/**
Extended by TJExtensions
*/
@IBInspectable
var borderColor: UIColor? {
get {
if let _ = self.layer.borderColor {
return UIColor(cgColor: self.layer.borderColor!)
}
return nil
}
set {
self.layer.borderColor = newValue?.cgColor
}
}
/**
Extended by TJExtensions
*/
@IBInspectable
var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
}
}
}
| 908abf675c760f21d9c27de4c6747bc6 | 28.389313 | 115 | 0.604416 | false | false | false | false |
JohnSundell/Wrap | refs/heads/master | Tests/WrapTests/WrapTests.swift | mit | 1 | /**
* Wrap
*
* Copyright (c) 2015 - 2017 John Sundell. Licensed under the MIT license, as follows:
*
* 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 XCTest
import Wrap
// MARK: - Tests
class WrapTests: XCTestCase {
func testBasicStruct() {
struct Model {
let string = "A string"
let int = 15
let double = 7.6
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "A string",
"int" : 15,
"double" : 7.6
])
} catch {
XCTFail(error.toString())
}
}
func testOptionalProperties() {
struct Model {
let string: String? = "A string"
let int: Int? = 5
let missing: String? = nil
let missingNestedOptional: Optional<Optional<String>> = .some(.none)
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "A string",
"int" : 5
])
} catch {
XCTFail(error.toString())
}
}
func testSpecificNonOptionalProperties() {
struct Model {
let some: String = "value"
let Some: Int = 1
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"some" : "value",
"Some" : 1
])
} catch {
XCTFail(error.toString())
}
}
func testSpecificNonOptionalValues() {
struct Model {
let string: String = "nil"
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "nil"
])
} catch {
XCTFail(error.toString())
}
}
func testProtocolProperties() {
struct NestedModel: MockProtocol {
let constantString = "Another string"
var mutableInt = 27
}
struct Model: MockProtocol {
let constantString = "A string"
var mutableInt = 15
let nested: MockProtocol = NestedModel()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"constantString" : "A string",
"mutableInt" : 15,
"nested": [
"constantString" : "Another string",
"mutableInt" : 27
]
])
} catch {
XCTFail(error.toString())
}
}
func testRootEnum() {
enum Enum {
case first
case second(String)
}
do {
try verify(dictionary: wrap(Enum.first), againstDictionary: [:])
try verify(dictionary: wrap(Enum.second("Hello")), againstDictionary: [
"second" : "Hello"
])
} catch {
XCTFail(error.toString())
}
}
func testEnumProperties() {
enum Enum {
case first
case second(String)
case third(intValue: Int)
}
enum IntEnum: Int, WrappableEnum {
case first
case second = 17
}
enum StringEnum: String, WrappableEnum {
case first = "First string"
case second = "Second string"
}
struct Model {
let first = Enum.first
let second = Enum.second("Hello")
let third = Enum.third(intValue: 15)
let firstInt = IntEnum.first
let secondInt = IntEnum.second
let firstString = StringEnum.first
let secondString = StringEnum.second
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"first" : "first",
"second" : [
"second" : "Hello"
],
"third" : [
"third" : 15
],
"firstInt" : 0,
"secondInt" : 17,
"firstString" : "First string",
"secondString" : "Second string"
])
} catch {
XCTFail(error.toString())
}
}
func testDateProperty() {
let date = Date()
struct Model {
let date: Date
}
let dateFormatter = DateFormatter()
do {
let model = Model(date: date)
try verify(dictionary: wrap(model, dateFormatter: dateFormatter), againstDictionary: [
"date" : dateFormatter.string(from: date)
])
} catch {
XCTFail("\(try! wrap(Model(date: date), dateFormatter: dateFormatter) as WrappedDictionary)")
XCTFail(error.toString())
}
}
#if !os(Linux)
func testNSDateProperty() {
let date = NSDate()
struct Model {
let date: NSDate
}
let dateFormatter = DateFormatter()
do {
let model = Model(date: date)
try verify(dictionary: wrap(model, dateFormatter: dateFormatter), againstDictionary: [
"date" : dateFormatter.string(from: date as Date)
])
} catch {
XCTFail("\(try! wrap(Model(date: date), dateFormatter: dateFormatter) as WrappedDictionary)")
XCTFail(error.toString())
}
}
#endif
func testDatePropertyWithCustomizableStruct() {
let date = Date()
struct Model: WrapCustomizable {
let date: Date
}
let dateFormatter = DateFormatter()
do {
let model = Model(date: date)
try verify(dictionary: wrap(model, dateFormatter: dateFormatter), againstDictionary: [
"date" : dateFormatter.string(from: date)
])
} catch {
XCTFail(error.toString())
}
}
func testEmptyStruct() {
struct Empty {}
do {
try verify(dictionary: wrap(Empty()), againstDictionary: [:])
} catch {
XCTFail(error.toString())
}
}
func testNestedEmptyStruct() {
struct Empty {}
struct EmptyWithOptional {
let optional: String? = nil
}
struct Model {
let empty = Empty()
let emptyWithOptional = EmptyWithOptional()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"empty" : [:],
"emptyWithOptional" : [:]
])
} catch {
XCTFail(error.toString())
}
}
func testArrayProperties() {
struct Model {
let homogeneous = ["Wrap", "Tests"]
let mixed = ["Wrap", 15, 8.3] as [Any]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"homogeneous" : ["Wrap", "Tests"],
"mixed" : ["Wrap", 15, 8.3]
])
} catch {
XCTFail(error.toString())
}
}
func testDictionaryProperties() {
struct Model {
let homogeneous = [
"Key1" : "Value1",
"Key2" : "Value2"
]
let mixed: WrappedDictionary = [
"Key1" : 15,
"Key2" : 19.2,
"Key3" : "Value",
"Key4" : ["Wrap", "Tests"],
"Key5" : [
"NestedKey" : "NestedValue"
]
]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"homogeneous" : [
"Key1" : "Value1",
"Key2" : "Value2"
],
"mixed" : [
"Key1" : 15,
"Key2" : 19.2,
"Key3" : "Value",
"Key4" : ["Wrap", "Tests"],
"Key5" : [
"NestedKey" : "NestedValue"
]
]
])
} catch {
XCTFail(error.toString())
}
}
func testHomogeneousSetProperty() {
struct Model {
let set: Set<String> = ["Wrap", "Tests"]
}
do {
let dictionary: WrappedDictionary = try wrap(Model())
XCTAssertEqual(dictionary.count, 1)
guard let array = dictionary["set"] as? [String] else {
return XCTFail("Expected array for key \"set\"")
}
XCTAssertEqual(Set(array), ["Wrap", "Tests"])
} catch {
XCTFail(error.toString())
}
}
#if !os(Linux)
func testMixedNSObjectSetProperty() {
struct Model {
let set: Set<NSObject> = ["Wrap" as NSObject, 15 as NSObject, 8.3 as NSObject]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"set" : ["Wrap", 15, 8.3]
])
} catch {
XCTFail(error.toString())
}
}
#endif
func testNSURLProperty() {
struct Model {
let optionalURL = NSURL(string: "http://github.com")
let URL = NSURL(string: "http://google.com")!
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"optionalURL" : "http://github.com",
"URL" : "http://google.com"
])
} catch {
XCTFail(error.toString())
}
}
func testURLProperty() {
struct Model {
let optionalUrl = URL(string: "http://github.com")
let url = URL(string: "http://google.com")!
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"optionalUrl" : "http://github.com",
"url" : "http://google.com"
])
} catch {
XCTFail(error.toString())
}
}
func test64BitIntegerProperties() {
struct Model {
let int = Int64.max
let uint = UInt64.max
}
do {
let dictionary = try JSONSerialization.jsonObject(with: wrap(Model()), options: []) as! WrappedDictionary
try verify(dictionary: dictionary, againstDictionary: [
"int" : Int64.max,
"uint" : UInt64.max
])
} catch {
XCTFail(error.toString())
}
}
func testRootSubclass() {
class Superclass {
let string1 = "String1"
let int1 = 1
}
class Subclass: Superclass {
let string2 = "String2"
let int2 = 2
}
do {
try verify(dictionary: wrap(Subclass()), againstDictionary: [
"string1" : "String1",
"string2" : "String2",
"int1" : 1,
"int2" : 2
])
} catch {
XCTFail(error.toString())
}
}
func testRootNSObjectSubclass() {
class Model: NSObject {
let string = "String"
let double = 7.14
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "String",
"double" : 7.14
])
} catch {
XCTFail(error.toString())
}
}
func testRootDictionary() {
struct Model {
var string: String
}
let dictionary = [
"model1" : Model(string: "First"),
"model2" : Model(string: "Second")
]
do {
try verify(dictionary: wrap(dictionary), againstDictionary: [
"model1" : [
"string" : "First"
],
"model2" : [
"string" : "Second"
]
])
} catch {
XCTFail(error.toString())
}
}
func testNestedStruct() {
struct NestedModel {
let string = "Nested model"
}
struct Model {
let nested = NestedModel()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"nested" : [
"string" : "Nested model"
]
])
} catch {
XCTFail(error.toString())
}
}
func testNestedArrayOfStructs() {
struct NestedModel1 {
let string1: String
}
struct NestedModel2 {
let string2: String
}
struct Model {
let nested: [Any] = [
NestedModel1(string1: "String1"),
NestedModel2(string2: "String2"),
]
}
do {
let wrapped: WrappedDictionary = try wrap(Model())
if let nested = wrapped["nested"] as? [WrappedDictionary] {
XCTAssertEqual(nested.count, 2)
if let firstDictionary = nested.first, let secondDictionary = nested.last {
try verify(dictionary: firstDictionary, againstDictionary: [
"string1" : "String1"
])
try verify(dictionary: secondDictionary, againstDictionary: [
"string2" : "String2"
])
} else {
XCTFail("Missing dictionaries")
}
} else {
XCTFail("Unexpected type")
}
} catch {
XCTFail(error.toString())
}
}
func testNestedDictionariesOfStructs() {
struct NestedModel {
let string = "Hello"
}
struct Model {
let nested = [
"model" : NestedModel()
]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"nested" : [
"model" : [
"string" : "Hello"
]
]
])
} catch {
XCTFail(error.toString())
}
}
func testNestedSubclass() {
class Superclass {
let string1 = "String1"
}
class Subclass: Superclass {
let string2 = "String2"
}
struct Model {
let superclass = Superclass()
let subclass = Subclass()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"superclass" : [
"string1" : "String1"
],
"subclass" : [
"string1" : "String1",
"string2" : "String2"
]
])
} catch {
XCTFail(error.toString())
}
}
func testDeepNesting() {
struct ThirdModel {
let string = "Third String"
}
struct SecondModel {
let string = "Second String"
let nestedArray = [ThirdModel()]
}
struct FirstModel {
let string = "First String"
let nestedDictionary = [ "nestedDictionary" : SecondModel()]
}
do {
let wrappedDictionary :WrappedDictionary = try wrap(FirstModel())
try verify(dictionary: wrappedDictionary, againstDictionary: [
"string" : "First String",
"nestedDictionary" : [
"nestedDictionary" : [
"string" : "Second String",
"nestedArray" : [
["string" : "Third String"]
]
]
]
])
} catch {
XCTFail(error.toString())
}
}
#if !os(Linux)
func testObjectiveCObjectProperties() {
struct Model {
let string = NSString(string: "Hello")
let number = NSNumber(value: 17)
let array = NSArray(object: NSString(string: "Unwrap"))
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "Hello",
"number" : 17,
"array" : ["Unwrap"]
])
} catch {
XCTFail(error.toString())
}
}
#endif
func testWrappableKey() {
enum Key: Int, WrappableKey {
case first = 15
case second = 19
func toWrappedKey() -> String {
return String(self.rawValue)
}
}
struct Model {
let dictionary = [
Key.first : "First value",
Key.second : "Second value"
]
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"dictionary" : [
"15" : "First value",
"19" : "Second value"
]
])
} catch {
XCTFail(error.toString())
}
}
func testKeyCustomization() {
struct Model: WrapCustomizable {
let string = "Default"
let customized = "I'm customized"
let skipThis = 15
fileprivate func keyForWrapping(propertyNamed propertyName: String) -> String? {
if propertyName == "customized" {
return "totallyCustomized"
}
if propertyName == "skipThis" {
return nil
}
return propertyName
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "Default",
"totallyCustomized" : "I'm customized"
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrapping() {
struct Model: WrapCustomizable {
let string = "A string"
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
return [
"custom" : "A value"
]
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"custom" : "A value"
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrappingCallingWrapFunction() {
struct Model: WrapCustomizable {
let int = 27
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
do {
var wrapped = try Wrapper().wrap(object: self)
wrapped["custom"] = "A value"
return wrapped
} catch {
return nil
}
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"int" : 27,
"custom" : "A value"
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrappingForSingleProperty() {
struct Model: WrapCustomizable {
let string = "Hello"
let int = 16
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
if propertyName == "int" {
XCTAssertEqual((originalValue as? Int) ?? 0, self.int)
return 27
}
return nil
}
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "Hello",
"int" : 27
])
} catch {
XCTFail(error.toString())
}
}
func testCustomWrappingFailureThrows() {
struct Model: WrapCustomizable {
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
return nil
}
}
do {
_ = try wrap(Model()) as WrappedDictionary
XCTFail("Should have thrown")
} catch WrapError.wrappingFailedForObject(let object) {
XCTAssertTrue(object is Model)
} catch {
XCTFail("Invalid error type: " + error.toString())
}
}
func testCustomWrappingForSinglePropertyFailureThrows() {
struct Model: WrapCustomizable {
let string = "A string"
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
throw NSError(domain: "ERROR", code: 0, userInfo: nil)
}
}
do {
_ = try wrap(Model()) as WrappedDictionary
XCTFail("Should have thrown")
} catch WrapError.wrappingFailedForObject(let object) {
XCTAssertTrue(object is Model)
} catch {
XCTFail("Invalid error type: " + error.toString())
}
}
func testInvalidRootObjectThrows() {
do {
_ = try wrap("A string") as WrappedDictionary
} catch WrapError.invalidTopLevelObject(let object) {
XCTAssertEqual((object as? String) ?? "", "A string")
} catch {
XCTFail("Invalid error type: " + error.toString())
}
}
func testDataWrapping() {
struct Model {
let string = "A string"
let int = 42
let array = [4, 1, 9]
}
do {
let data: Data = try wrap(Model())
let object = try JSONSerialization.jsonObject(with: data, options: [])
guard let dictionary = object as? WrappedDictionary else {
return XCTFail("Invalid encoded type")
}
try verify(dictionary: dictionary, againstDictionary: [
"string" : "A string",
"int" : 42,
"array" : [4, 1, 9]
])
} catch {
XCTFail(error.toString())
}
}
func testWrappingArray() {
struct Model {
let string: String
}
do {
let models = [Model(string: "A"), Model(string: "B"), Model(string: "C")]
let wrapped: [WrappedDictionary] = try wrap(models)
XCTAssertEqual(wrapped.count, 3)
try verify(dictionary: wrapped[0], againstDictionary: ["string" : "A"])
try verify(dictionary: wrapped[1], againstDictionary: ["string" : "B"])
try verify(dictionary: wrapped[2], againstDictionary: ["string" : "C"])
} catch {
XCTFail(error.toString())
}
}
func testSnakeCasedKeyWrapping() {
struct Model: WrapCustomizable {
var wrapKeyStyle: WrapKeyStyle { return .convertToSnakeCase }
let simple = "simple name"
let camelCased = "camel cased name"
let CAPITALIZED = "capitalized name"
let _underscored = "underscored name"
let center_underscored = "center underscored name"
let double__underscored = "double underscored name"
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"simple" : "simple name",
"camel_cased" : "camel cased name",
"capitalized" : "capitalized name",
"_underscored" : "underscored name",
"center_underscored" : "center underscored name",
"double__underscored" : "double underscored name"
])
} catch {
XCTFail(error.toString())
}
}
func testContext() {
struct NestedModel: WrapCustomizable {
let string = "String"
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
XCTAssertEqual(context as! String, "Context")
return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: self)
}
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
XCTAssertEqual(context as! String, "Context")
return context
}
}
class Model: WrapCustomizable {
let string = "String"
let nestedArray = [NestedModel()]
let nestedDictionary = ["nested" : NestedModel()]
func wrap(context: Any?, dateFormatter: DateFormatter?) -> Any? {
XCTAssertEqual(context as! String, "Context")
return try? Wrapper(context: context, dateFormatter: dateFormatter).wrap(object: self)
}
func wrap(propertyNamed propertyName: String, originalValue: Any, context: Any?, dateFormatter: DateFormatter?) throws -> Any? {
XCTAssertEqual(context as! String, "Context")
return nil
}
}
do {
try verify(dictionary: wrap(Model(), context: "Context"), againstDictionary: [
"string" : "String",
"nestedArray" : [["string" : "Context"]],
"nestedDictionary" : ["nested" : ["string" : "Context"]]
])
} catch {
XCTFail(error.toString())
}
}
func testInheritance() {
class Superclass {
let string = "String"
}
class Subclass: Superclass {
let int = 22
}
do {
try verify(dictionary: wrap(Subclass()), againstDictionary: [
"string" : "String",
"int" : 22
])
} catch {
XCTFail(error.toString())
}
}
func testIgnoringClosureProperties() {
struct StringConvertible: CustomStringConvertible {
var description: String { return "(Function)" }
}
struct Model {
let closure = {}
let string = "(Function)"
let stringConvertible = StringConvertible()
}
do {
try verify(dictionary: wrap(Model()), againstDictionary: [
"string" : "(Function)",
"stringConvertible" : [:]
])
} catch {
XCTFail(error.toString())
}
}
}
// MARK: - Mocks
private protocol MockProtocol {
var constantString: String { get }
var mutableInt: Int { get set }
}
// MARK: - Utilities
private enum VerificationError: Error {
case arrayCountMismatch(Int, Int)
case dictionaryKeyMismatch([String], [String])
case cannotVerifyValue(Any)
case missingValueForKey(String)
case valueMismatchBetween(Any, Any)
}
extension VerificationError: CustomStringConvertible {
var description: String {
switch self {
case .arrayCountMismatch(let countA, let countB):
return "Array count mismatch: \(countA) vs \(countB)"
case .dictionaryKeyMismatch(let keysA, let keysB):
return "Dictionary key count mismatch: \(keysA) vs \(keysB)"
case .cannotVerifyValue(let value):
return "Cannot verify value: \(value)"
case .missingValueForKey(let key):
return "Missing expected value for key: \(key)"
case .valueMismatchBetween(let valueA, let valueB):
return "Values don't match: \(valueA) vs \(valueB)"
}
}
}
private protocol Verifiable {
static func convert(objectiveCObject: NSObject) -> Self?
var hashValue: Int { get }
}
extension Int: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Int? {
guard let number = object as? NSNumber else {
return nil
}
return number.intValue
}
}
extension Int64: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Int64? {
guard let number = object as? NSNumber else {
return nil
}
return number.int64Value
}
}
extension UInt64: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> UInt64? {
guard let number = object as? NSNumber else {
return nil
}
return number.uint64Value
}
}
extension Double: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Double? {
guard let number = object as? NSNumber else {
return nil
}
return number.doubleValue
}
}
extension String: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> String? {
guard let string = object as? NSString else {
return nil
}
#if os(Linux)
return nil
#else
return String(string)
#endif
}
}
extension Date: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Date? {
guard let date = object as? NSDate else {
return nil
}
return Date(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
}
}
extension NSNumber: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Self? {
return nil
}
}
extension NSString: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Self? {
return nil
}
}
extension NSDate: Verifiable {
fileprivate static func convert(objectiveCObject object: NSObject) -> Self? {
return nil
}
}
private func verify(dictionary: WrappedDictionary, againstDictionary expectedDictionary: WrappedDictionary) throws {
if dictionary.count != expectedDictionary.count {
throw VerificationError.dictionaryKeyMismatch(Array(dictionary.keys), Array(expectedDictionary.keys))
}
for (key, expectedValue) in expectedDictionary {
guard let actualValue = dictionary[key] else {
throw VerificationError.missingValueForKey(key)
}
if let expectedNestedDictionary = expectedValue as? WrappedDictionary {
if let actualNestedDictionary = actualValue as? WrappedDictionary {
try verify(dictionary: actualNestedDictionary, againstDictionary: expectedNestedDictionary)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
if let expectedNestedArray = expectedValue as? [Any] {
if let actualNestedArray = actualValue as? [Any] {
try verify(array: actualNestedArray, againstArray: expectedNestedArray)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
try verify(value: actualValue, againstValue: expectedValue)
}
}
private func verify(array: [Any], againstArray expectedArray: [Any]) throws {
if array.count != expectedArray.count {
throw VerificationError.arrayCountMismatch(array.count, expectedArray.count)
}
for (index, expectedValue) in expectedArray.enumerated() {
let actualValue = array[index]
if let expectedNestedDictionary = expectedValue as? WrappedDictionary {
if let actualNestedDictionary = actualValue as? WrappedDictionary {
try verify(dictionary: actualNestedDictionary, againstDictionary: expectedNestedDictionary)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
if let expectedNestedArray = expectedValue as? [Any] {
if let actualNestedArray = actualValue as? [Any] {
try verify(array: actualNestedArray, againstArray: expectedNestedArray)
continue
} else {
throw VerificationError.valueMismatchBetween(actualValue, expectedValue)
}
}
try verify(value: actualValue, againstValue: expectedValue)
}
}
private func verify(value: Any, againstValue expectedValue: Any, convertToObjectiveCObjectIfNeeded: Bool = true) throws {
guard let expectedVerifiableValue = expectedValue as? Verifiable else {
throw VerificationError.cannotVerifyValue(expectedValue)
}
guard let actualVerifiableValue = value as? Verifiable else {
throw VerificationError.cannotVerifyValue(value)
}
if actualVerifiableValue.hashValue != expectedVerifiableValue.hashValue {
if convertToObjectiveCObjectIfNeeded {
if let objectiveCObject = value as? NSObject {
let expectedValueType = type(of: expectedVerifiableValue)
guard let convertedObject = expectedValueType.convert(objectiveCObject: objectiveCObject) else {
throw VerificationError.cannotVerifyValue(value)
}
return try verify(value: convertedObject, againstValue: expectedVerifiableValue, convertToObjectiveCObjectIfNeeded: false)
}
}
throw VerificationError.valueMismatchBetween(value, expectedValue)
}
}
private extension Error {
func toString() -> String {
return "\(self)"
}
}
| 1800214289e2187dfd8c4d6c19f51f69 | 28.00922 | 140 | 0.511269 | false | false | false | false |
Irvel/Actionable-Screenshots | refs/heads/master | ActionableScreenshots/ActionableScreenshots/DetailViewController.swift | gpl-3.0 | 1 | //
// DetailViewController.swift
// ActionableScreenshots
//
// Created by Chuy Galvan on 10/21/17.
// Copyright © 2017 Jesus Galvan. All rights reserved.
//
import UIKit
import Photos
import RealmSwift
protocol UIWithCollection {
func reloadCollection()
}
class DetailViewController: UIViewController {
@IBOutlet weak var viewTextButton: UIButton!
@IBOutlet weak var imgView: UIImageView!
var screenshot: Screenshot?
var screenshotId: String!
var previousView: UIWithCollection!
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
if !screenshot!.hasText {
viewTextButton.isEnabled = false
viewTextButton.alpha = 0.45
}
let fetchOptions = PHImageRequestOptions()
fetchOptions.isSynchronous = true
self.imgView.image = screenshot?.getImage(width: imgView.superview!.frame.size.width, height: imgView.superview!.frame.size.height, contentMode: .aspectFit, fetchOptions: fetchOptions)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "showTags") {
let destinationView = segue.destination as! TagsViewController
destinationView.screenshot = screenshot
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
}
@IBAction func unwindTagsView(segueUnwind: UIStoryboardSegue) {
}
// MARK: - Button actions
@IBAction func shareButtonTapped(_ sender: Any) {
let act = UIActivityViewController(activityItems: [self.imgView.image!], applicationActivities: nil)
act.popoverPresentationController?.sourceView = self.view
self.present(act, animated: true, completion: nil)
}
@IBAction func viewTextButtonTapped(_ sender: Any) {
if screenshot!.hasText {
let alertController = UIAlertController(title: "Recognized Text", message: screenshot!.text, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { action in }
alertController.addAction(OKAction)
self.present(alertController, animated: true) { }
}
}
@IBAction func deleteButtonTapped(_ sender: Any) {
self.screenshot?.deleteImageFromDevice()
dismiss(animated: true, completion: {
let realm = try! Realm()
try! realm.write {
realm.delete(self.screenshot!)
}
self.previousView.reloadCollection()
})
}
@IBAction func backButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
| 227438728cefbe37255c4688b2015eca | 30.442308 | 192 | 0.6737 | false | false | false | false |
jangxyz/springy | refs/heads/master | springy-swift/springy_runner/main.swift | mit | 1 | #!/usr/bin/env xcrun swift -i
//
// main.swift
// springy_runner
//
// Created by 김장환 on 1/17/15.
// Copyright (c) 2015 김장환. All rights reserved.
//
import Foundation
func createTestGraph(#nodesNum:Int, #edgesNum:Int) -> Graph {
var graph = Graph()
// add 100 nodes
var edgeCandidate:[String] = []
for var i = 0; i < nodesNum; i++ {
let node = graph.newNode(["label": String(i)])
edgeCandidate.append(node.id);
}
func nodeName(node:Node) -> String {
return node.data["label"] ?? node.id
}
// add 1000 edges
for var i = 0; i < edgesNum; i++ {
// select source
//var randid:UInt32 = arc4random_uniform(edgeCandidate.count)
let rand1:Int = random() % edgeCandidate.count
var node1:Node = graph.nodeSet[edgeCandidate[rand1]]!
// println("node1: \(rand1) \(node1.description())")
// select target
var rand2:Int
do {
rand2 = random() % edgeCandidate.count
} while (rand2 == rand1)
var node2:Node = graph.nodeSet[edgeCandidate[rand2]]!
// println("node2: \(rand2) \(node2.description())")
var edge = graph.newEdge(source:node1, target:node2,
data:["label": "\(nodeName(node1)) --> \(nodeName(node2))"]
)
// hub
edgeCandidate.append(node1.id)
edgeCandidate.append(node2.id)
}
return graph
}
func importGraph(filename:String) -> Graph {
let fileContent = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: nil)
// parse JSON
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(
fileContent!.dataUsingEncoding(NSUTF8StringEncoding)!,
options: NSJSONReadingOptions.AllowFragments,
error: &parseError)
let data:JSON = JSON(parsedObject!)
//
var graph = Graph()
// add nodes
if data["nodes"] != nil {
var nodeNames = [String]()
for nodeData in data["nodes"].arrayValue {
var id = ""
if let _id1 = nodeData["id"].string {
id = _id1
} else if let _id2 = nodeData["id"].number {
id = "\(_id2)"
} else {
// let error = nodeData["id"].error
// println("error: \(error)")
}
nodeNames.append(id)
}
graph.addNodes(nodeNames)
}
// add edges
if data["edges"] != nil {
let edgeTuples = map(data["edges"].arrayValue) { (e) -> (String,String,[String:String]) in
var edgeData = [String:String]()
for (key:String,value:JSON) in e["data"] {
edgeData[key] = value.stringValue
}
return (e["source"]["id"].stringValue, e["target"]["id"].stringValue, edgeData)
}
graph.addEdges(edgeTuples)
}
return graph
}
func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String {
var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil
if NSJSONSerialization.isValidJSONObject(value) {
if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string
}
}
}
return ""
}
func exportGraph(graph:Graph,
write:(JSON) -> () = {println($0)}) {
func buildNode(node:Node) -> [String:AnyObject] {
return [
"id": node.id,
"data": node.data
]
}
var data:[String:[AnyObject]] = [
"nodes": graph.nodes.map { buildNode($0) },
"edges": graph.edges.map { (edge) in
[
"id": edge.id,
"source": buildNode(edge.source),
"target": buildNode(edge.target),
"data": edge.data
]
}
]
let json:JSON = JSON(data)
write(json)
}
func importLayout(filename:String, graph:Graph) -> ForceDirectedLayout {
let fileContent = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: nil)
// parse JSON
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(
fileContent!.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.AllowFragments, error: &parseError)
let data:JSON = JSON(parsedObject!)
let stiffness = data["stiffness"].doubleValue
let repulsion = data["repulsion"].doubleValue
let damping = data["damping"].doubleValue
let unitTime = data["unitTime"].doubleValue
let minEnergyThreshold = 0.01
var layout = ForceDirectedLayout(graph:graph,
stiffness:stiffness, repulsion:repulsion, damping:damping, energyThreshold:minEnergyThreshold, unitTime:unitTime)
func pointKey(point:Point) -> String {
return "[\(point.p.x), \(point.p.y), \(point.v.x), \(point.v.y)]"
}
// set node points
var nodePoints = [String:Point]()
var nodePointsIndexByPM = [String:Point]()
func buildPoint(_pointData:JSON) -> Point {
let pointData = _pointData.dictionaryValue
let p = pointData["p"]!.dictionaryValue
let position = Vector(x:p["x"]!.doubleValue, y:p["y"]!.doubleValue)
let v = pointData["v"]!.dictionaryValue
let velocity = Vector(x:v["x"]!.doubleValue, y:v["y"]!.doubleValue)
let mass = pointData["m"]!.doubleValue
let point = Point(p:position, m:mass)
point.v = velocity
return point
}
for (pointId:String, _pointData:JSON) in data["nodePoints"] {
let point = buildPoint(_pointData)
nodePoints[pointId] = point
nodePointsIndexByPM[pointKey(point)] = point
}
layout.nodePoints = nodePoints
// set edge springs
var edgeSprings = [String:Spring]()
for (edgeId:String, _springData:JSON) in data["edgeSprings"] {
let length = _springData["length"].doubleValue
let k = _springData["k"].doubleValue
let point1Key = pointKey(buildPoint(_springData["point1"]))
let point2Key = pointKey(buildPoint(_springData["point2"]))
let point1 = nodePointsIndexByPM[point1Key]!
let point2 = nodePointsIndexByPM[point2Key]!
edgeSprings[edgeId] = Spring(point1:point1, point2:point2, length:length, k:k)
}
layout.edgeSprings = edgeSprings
return layout
}
func exportLayout(layout:ForceDirectedLayout, write:(JSON -> ()) = {println($0)}) {
var data:[String:AnyObject] = [
"stiffness": layout.stiffness,
"repulsion": layout.repulsion,
"damping": layout.damping,
"unitTime": layout.unitTime,
"energy": layout.totalEnergy(),
"nodePoints": [String:AnyObject](),
"edgeSprings": [String:AnyObject]()
]
func buildPointData(point:Point) -> [String:AnyObject] {
return [
"p": [ "x": point.p.x, "y": point.p.y ],
"v": [ "x": point.v.x, "y": point.v.y ],
"m": point.m,
"a": [ "x": point.a.x, "y": point.a.y ]
]
}
func buildSpringData(spring:Spring) -> [String:AnyObject] {
return [
"point1": buildPointData(spring.point1),
"point2": buildPointData(spring.point2),
"length": spring.length,
"k": spring.k
]
}
func a2d<K,V>(tuples:[(K,V)]) -> [K:V] {
var dict = [K:V]()
for (key,value) in tuples {
dict[key] = value
}
return dict
}
func toDict<K,V,E>(array:[E], transform:E->(K,V)) -> [K:V] {
var dict = [K:V]()
for entity in array {
let (key,value) = transform(entity)
dict[key] = value
}
return dict
}
data["nodePoints"] = toDict(layout.eachNode) { ($0.id, buildPointData($1)) }
var edgeSprings = [String:AnyObject]()
for (i,spring) in enumerate(layout.eachSpring) {
edgeSprings[String(i)] = buildSpringData(spring)
}
data["edgeSprings"] = edgeSprings
write(JSON(data))
}
// create graph and layout
var graph:Graph
var layout:ForceDirectedLayout
// args
let args = NSProcessInfo.processInfo().arguments as NSArray
let args1 = /*"/Users/jangxyz/play/springy-swift/springy/data/20150101-123899_2_1/graph.json"*/args.count >= 2 ? args[1] as String : ""
let args2 = /*"/Users/jangxyz/play/springy-swift/springy/data/20150101-123899_2_1/layout_300.json"*/args.count >= 3 ? args[2] as String : ""
let fileManager = NSFileManager.defaultManager()
let files2 = fileManager.contentsOfDirectoryAtPath("./data/20150123-085804_10_20_400_400_0.3_0.01", error:nil)
if fileManager.fileExistsAtPath(args1) && fileManager.fileExistsAtPath(args2) {
let graphFilename = args1
let layoutFilename = args2
print("reading graph from \(graphFilename) ...")
graph = importGraph(graphFilename)
println(" done: \(graph.nodes.count), \(graph.edges.count)")
print("reading layout from \(layoutFilename) ...")
layout = importLayout(layoutFilename, graph)
println(" done.")
} else {
let nodesNum = args.count >= 2 ? args1.toInt()! : 100//10
let edgesNum = args.count >= 3 ? args2.toInt()! : 50//nodesNum * 2
//graph = createTestGraph(nodesNum:1000, edgesNum:2000)
graph = createTestGraph(nodesNum:nodesNum, edgesNum:edgesNum)
layout = ForceDirectedLayout(graph:graph,
stiffness: 400.0,
repulsion: 400,
damping: 0.5,
energyThreshold: 0.01,
unitTime: 0.01
)
}
let nodesNum = graph.nodes.count
let edgesNum = graph.edges.count
// E1 = 154285510.127098
//
// layout summary
println("---")
println("points: \(layout.eachNode.count)")
println("springs: \(layout.eachSpring.count)")
//println("Points")
//for (i,(node,point)) in enumerate(layout.eachNode) {
// println("- \(i+1): \(point)")
//}
//println("Springs")
//for (i,spring) in enumerate(layout.eachSpring) {
// println("- \(i+1): \(spring)")
//}
func writeToFile(filename:String) -> (JSON -> ()) {
return {(json:JSON) -> () in
json.rawString()!.writeToFile(filename, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
return
}
}
let startDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYYMMDD-HHmmSS"
let startDateStr = dateFormatter.stringFromDate(NSDate())
let testResultPath = "data/\(startDateStr)_\(nodesNum)_\(edgesNum)_\(layout.stiffness)_\(layout.repulsion)_\(layout.damping)_\(layout.unitTime)_swift"
var isDir:ObjCBool = true
if !fileManager.fileExistsAtPath(testResultPath, isDirectory:&isDir) {
fileManager.createDirectoryAtPath(testResultPath, withIntermediateDirectories:true, attributes: nil, error: nil)
}
// start
// onRender
var count = 0
var prevRunTime = startDate
func onRenderStart() {
//
exportGraph(graph, writeToFile("\(testResultPath)/graph.json"))
exportLayout(layout, writeToFile("\(testResultPath)/layout_\(count).json"))
}
func render() {
count += 1
func checkPrint(i:Int) -> Bool {
if (i <= 300) { return true } // DEBUG
//return false
if (i == 1) { return true }
if (i <= 100) { return true }
if (i > 30 && i <= 100 && i % 10 == 0) { return true }
if (i > 100 && i <= 1000 && i % 50 == 0) { return true }
if (i % 100 == 0) { return true }
return false
}
func checkSaveAt(i:Int) -> Bool {
if (i <= 300 && i % 10 == 0) { return true } // DEBUG
if (i < 10) { return true }
if (i == 10) { return true }
if (i == 100) { return true }
if (i % 1000 == 0) { return true }
if (i % 1000 == 300) { return true }
if (i % 1000 == 700) { return true }
return false
}
//
if checkPrint(count) {
let thisTime = NSDate()
println("- #\(count) energy: \(layout.totalEnergy()) (\(thisTime.timeIntervalSinceDate(prevRunTime)) s)")
prevRunTime = thisTime
}
if (checkSaveAt(count)) {
exportLayout(layout, writeToFile("\(testResultPath)/layout_\(count).json"))
}
}
func onRenderStop() {
// write layout
// text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
exportLayout(layout, writeToFile("\(testResultPath)/layout_\(count).json"))
// time
let end = NSDate()
println("done. took \(end.timeIntervalSinceDate(startDate)) seconds.")
}
//layout.start(render, onRenderStop:onRenderStop, onRenderStart:onRenderStart)
layout.start({}, onRenderStop:onRenderStop, onRenderStart:onRenderStart)
| 9a8d6ca0c5037fe1234278be940e861e | 31.513924 | 150 | 0.596823 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | refs/heads/dev | byuSuite/Apps/LockerRental/controller/LockerRentalMyLockersViewController.swift | apache-2.0 | 1 | //
// LockerRentalMyLockersViewController.swift
// byuSuite
//
// Created by Erik Brady on 7/19/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
protocol LockerRentalDelegate {
func loadLockers()
}
class LockerRentalMyLockersViewController: ByuViewController2, UITableViewDataSource, LockerRentalDelegate {
//MARK: Outlets
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
@IBOutlet private weak var button: UIBarButtonItem!
//MARK: Properties
private var agreements = [LockerRentalAgreement]()
private var loadedLockerCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
loadLockers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.deselectSelectedRow()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "myLockerDetail",
let vc = segue.destination as? LockerRentalMyLockersDetailViewController,
let sender = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: sender) {
vc.agreement = agreements[indexPath.row]
vc.delegate = self
} else if segue.identifier == "toBrowseLockers", let vc = segue.destination as? LockerRentalBuildingsViewController {
vc.delegate = self
}
}
//MARK: UITableViewDelegate/DataSource Methods
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if loadedLockerCount > 0 {
return "My Lockers"
}
return nil
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return loadedLockerCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(for: indexPath)
let agreement = agreements[indexPath.row]
if let building = agreement.locker?.building, let floor = agreement.locker?.floor, let number = agreement.locker?.displayedLockerNumber {
cell.textLabel?.text = "\(building) Floor \(floor) - \(number)"
}
cell.detailTextLabel?.text = "Expires on: \(agreement.expirationDateString())"
return cell
}
//MARK: IBAction Methods
@IBAction func browseAvailableLockersClicked(_ sender: Any) {
if agreements.count >= 3 {
super.displayAlert(error: nil, title: "Unable to Browse Lockers", message: "You have reached the maximum number of lockers you can rent.", alertHandler: nil)
} else {
self.performSegue(withIdentifier: "toBrowseLockers", sender: sender)
}
}
//MARK: LockerRental Delegate Methods
func loadLockers() {
//loadedLockerCount tracks the number of lockers loaded. It must be reset here because this method can be called later in the feature to reload lockers.
loadedLockerCount = 0
//Remove current rows from tableView
tableView.reloadData()
spinner.startAnimating()
LockerRentalClient.getAgreements { (agreements, error) in
if let agreements = agreements {
self.agreements = agreements
if self.agreements.count == 0 {
self.stopSpinnerIfReady()
self.tableView.tableFooterView?.isHidden = false
} else {
//Reset footer in the case that they just rented a first locker
self.tableView.tableFooterView?.isHidden = true
//Sort locker agreements by Expiration Date
self.agreements.sort()
//Load lockers for each agreement
for agreement in self.agreements {
if let lockerId = agreement.lockerId {
LockerRentalClient.getLocker(lockerId: lockerId, callback: { (locker, error) in
if let locker = locker {
agreement.locker = locker
self.loadedLockerCount += 1
self.tableView.reloadData()
self.stopSpinnerIfReady()
} else {
self.spinner.stopAnimating()
super.displayAlert(error: error)
}
})
}
}
}
} else {
super.displayAlert(error: error)
}
}
}
//MARK: Custom Methods
private func stopSpinnerIfReady() {
if agreements.count == loadedLockerCount {
spinner.stopAnimating()
button.isEnabled = true
}
}
}
| 63bc57152d04b7c1f292d8cf1ad16220 | 36.23913 | 169 | 0.578906 | false | false | false | false |
exponent/exponent | refs/heads/master | packages/expo-dev-menu/ios/DevMenuExpoSessionDelegate.swift | bsd-3-clause | 2 | // Copyright 2015-present 650 Industries. All rights reserved.
class DevMenuExpoSessionDelegate {
private static let sessionKey = "expo-dev-menu.session"
private static let userLoginEvent = "expo.dev-menu.user-login"
private static let userLogoutEvent = "expo.dev-menu.user-logout"
private let manager: DevMenuManager
init(manager: DevMenuManager) {
self.manager = manager
}
func setSessionAsync(_ session: [String: Any]?) throws {
var sessionSecret: String?
if session != nil {
guard let castedSessionSecret = session!["sessionSecret"] as? String else {
throw NSError(
domain: NSExceptionName.invalidArgumentException.rawValue,
code: 0,
userInfo: [
NSLocalizedDescriptionKey: "'sessionSecret' cannot be null."
]
)
}
sessionSecret = castedSessionSecret
}
setSesssionSecret(sessionSecret)
UserDefaults.standard.set(session, forKey: DevMenuExpoSessionDelegate.sessionKey)
}
@discardableResult
func restoreSession() -> [String: Any]? {
guard let session = UserDefaults.standard.dictionary(forKey: DevMenuExpoSessionDelegate.sessionKey) else {
return nil
}
setSesssionSecret(session["sessionSecret"] as? String)
return session
}
private func setSesssionSecret(_ sessionSecret: String?) {
let wasLoggedIn = manager.expoApiClient.isLoggedIn()
manager.expoApiClient.setSessionSecret(sessionSecret)
let isLoggedIn = manager.expoApiClient.isLoggedIn()
if !wasLoggedIn && isLoggedIn {
manager.sendEventToDelegateBridge(DevMenuExpoSessionDelegate.userLoginEvent, data: nil)
} else if wasLoggedIn && !isLoggedIn {
manager.sendEventToDelegateBridge(DevMenuExpoSessionDelegate.userLogoutEvent, data: nil)
}
}
}
| db27960c4cd0ff8c0c0d60667494defa | 31.745455 | 110 | 0.716824 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015 | refs/heads/master | 04-App Architecture/Swift 3/4-4 ResponderChain/Scenario 1/ResponderChainDemo/ResponderChainDemo/ViewController.swift | mit | 4 | //
// ViewController.swift
// ResponderChainDemo
//
// Created by Nicholas Outram on 15/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import UIKit
extension UIResponder {
func switchState(_ t : Int) -> Bool? {
guard let me = self as? UIView else {
return nil
}
for v in me.subviews {
if let sw = v as? UISwitch, v.tag == t {
return sw.isOn
}
}
return false
}
func printNextRepsonderAsString() {
var result : String = "\(type(of: self)) got a touch event."
if let nr = self.next {
result += " The next responder is " + type(of: nr).description()
} else {
result += " This class has no next responder"
}
print(result)
}
}
class ViewController: UIViewController {
@IBOutlet weak var passUpSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.printNextRepsonderAsString()
if passUpSwitch.isOn {
//Pass up the responder chain
super.touchesBegan(touches, with: event)
}
}
}
| eadf7b85245ffb908fd076a188f2ff14 | 23.967213 | 80 | 0.572554 | false | false | false | false |
ckrey/mqttswift | refs/heads/master | Sources/MqttMessage.swift | gpl-3.0 | 1 | //
// MqttMessage.swift
// mqttswift
//
// Created by Christoph Krey on 18.09.17.
//
//
import Foundation
class MqttMessage {
var topic: String!
var data: Data = Data()
var qos: MqttQoS = MqttQoS.AtMostOnce
var retain: Bool = false
var payloadFormatIndicator: UInt8? = nil
var publicationExpiryInterval : Int? = nil
var publicationExpiryTime : Date? = nil
var responseTopic: String? = nil
var correlationData: Data? = nil
var userProperties: [[String: String]]? = nil
var contentType: String? = nil
var topicAlias:Int? = nil
var subscriptionIdentifiers: [Int]? = nil
var packetIdentifier: Int? = nil
var pubrel: Bool = false
init () {
}
init(topic: String!,
data: Data!,
qos: MqttQoS!,
retain: Bool!) {
self.topic = topic
self.data = data
self.qos = qos
self.retain = retain
}
}
| 5f454e6610ec0f939c5a0ccd72301aa3 | 22.025 | 49 | 0.608035 | false | false | false | false |
wupengnash/WPWebImage | refs/heads/master | WPWebImage/Lib/WPWebImage/WPWebImage.swift | mit | 1 | //
// WPWebImage.swift
// ArtCircle
//
// Created by wupeng on 16/1/29.
//
//
import UIKit
import ImageIO
import MobileCoreServices
import AssetsLibrary
public enum CacheType {
case None, Memory, Disk
}
public typealias DownloadProgressBlock = ((receivedSize: Int64, totalSize: Int64) -> ())
public typealias CompletionHandler = ((image: UIImage?, error: NSError?, cacheType: CacheType, imageURL: NSURL?) -> ())
extension String {
func length() -> Int {
return self.characters.count
}
}
extension UIButton {
/**
渐变设置图片第二种方法
- parameter duration:
*/
func addTransition(duration:NSTimeInterval,transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) == nil && transionStyle != .None {
let transition = CATransition()
transition.type = transionStyle.rawValue
transition.duration = duration
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.layer.addAnimation(transition, forKey: transionStyle.rawValue)
}
}
func removeTransition(transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) != nil {
self.layer.removeAnimationForKey(transionStyle.rawValue)
}
}
/**
自定义的异步加载图片
- parameter urlString: url
- parameter placeholderImage: 默认图
*/
func wp_setBackgroundImageWithURL(urlString: String,
forState state:UIControlState,
autoSetImage:Bool = true,
withTransformStyle transformStyle:WPCATransionStyle = .Fade,
duration:NSTimeInterval = 1.0,
placeholderImage: UIImage? = UIColor.imageWithColor(UIColor.randomColor()),
completionHandler:((image:UIImage) ->Void)? = nil) {
guard urlString != "" else {
self.setBackgroundImage(placeholderImage, forState: state)
return
}
if self.tag != urlString.hash {
//解决reloaddata的时候imageview 闪烁问题
self.tag = urlString.hash
self.setBackgroundImage(placeholderImage, forState: state)
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
if WPCache.imageExistWithKey(urlString) {
WPCache.getDiskCacheObjectForKey(urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if self.tag == urlString.hash {
if autoSetImage {
if filePath == "" {
//内存中取出
self.removeTransition()
self.setBackgroundImage(image, forState: state)
} else {
//硬盘中取出
switch transformStyle {
case .None:
self.removeTransition()
case .Fade:
self.addTransition(duration)
default:
self.removeTransition()
}
self.setBackgroundImage(image, forState: state)
}
if completionHandler != nil {
completionHandler!(image: image)
}
} else {
if completionHandler != nil {
completionHandler!(image: image)
}
}
}
})
} else {
if urlString.length() <= 0 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.setBackgroundImage(placeholderImage, forState: state)
})
} else {
WPWebImage.downloadImage(urlString, withSuccessColsure: { (image, imageData,saveUrl) -> Void in
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let newImage = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData)
if self.tag == urlString.hash {
if autoSetImage {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
switch transformStyle {
case .Fade:
self.addTransition(duration)
self.setBackgroundImage(newImage, forState: state)
default:
self.removeTransition()
self.setBackgroundImage(newImage, forState: state)
}
})
}
WPCache.setDiskCacheObject(imageData, ForKey: urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if completionHandler != nil {
completionHandler!(image: image)
}
})
}
})
})
}
}
}
}
}
extension UIColor {
static func randomColor() -> UIColor {
return UIColor(red: (CGFloat)(arc4random() % 254 + 1)/255.0, green: (CGFloat)(arc4random() % 254 + 1)/255.0, blue: (CGFloat)(arc4random() % 254 + 1)/255.0, alpha: CGFloat.max)
}
static func imageWithColor(imageColor:UIColor) -> UIImage {
let rect = CGRect(x: CGFloat.min, y: CGFloat.min, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
let context:CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, imageColor.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
class WPCache: NSObject {
let userDefault = NSUserDefaults.standardUserDefaults()
class func setStickConversation(conversationID:String) {
WPCache.sharedInstance.userDefault.setObject(NSNumber(bool: true), forKey: "STICKY\(conversationID)")
}
class func getStickConversation(conversationID:String) -> Bool {
if let stick = WPCache.sharedInstance.userDefault.objectForKey("STICKY\(conversationID)") as? NSNumber {
return stick.boolValue
} else {
return false
}
}
class func desetStickConversation(conversationID:String) {
WPCache.sharedInstance.userDefault.setObject(NSNumber(bool: false), forKey: "STICKY\(conversationID)")
}
let defaultCache = NSCache()
static let sharedInstance = {
return WPCache()
}()
override init() {
super.init()
self.defaultMemoryCache.countLimit = 100
self.defaultMemoryCache.totalCostLimit = 80
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("terminateCleanDisk"), name: UIApplicationWillTerminateNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("cleanDisk"), name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("clearMemory"), name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
func clearMemory() {
self.defaultMemoryCache.removeAllObjects()
}
/**
清理磁盘缓存方法
- parameter expirCacheAge:
- parameter completionColsure:
*/
static func cleanDiskWithCompeletionColsure(expirCacheAge:NSInteger = WPCache.sharedInstance.maxCacheAge,completionColsure:(()->Void)? = nil) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
let diskCacheurl = NSURL(fileURLWithPath: WPCache.sharedInstance.cacheDir, isDirectory: true)
let resourceKeys = [NSURLIsDirectoryKey,NSURLContentModificationDateKey,NSURLTotalFileAllocatedSizeKey]
let fileManager = NSFileManager.defaultManager()
let fileEnumerator = fileManager.enumeratorAtURL(diskCacheurl, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil)
var fileUrls = [NSURL]()
while let fileUrl = fileEnumerator?.nextObject() as? NSURL {
fileUrls.append(fileUrl)
}
let expirationDate = NSDate(timeIntervalSinceNow: -NSTimeInterval(expirCacheAge))
var urlsToDelegate = [NSURL]()
for (_,url) in fileUrls.enumerate() {
do {
let resourceValues = try url.resourceValuesForKeys(resourceKeys)
let moditfyDate = resourceValues[NSURLContentModificationDateKey] as! NSDate
if moditfyDate.laterDate(expirationDate) .isEqualToDate(expirationDate) {
urlsToDelegate.append(url)
}
} catch _ {}
}
for (_,deleteUrl) in urlsToDelegate.enumerate() {
do {
try fileManager.removeItemAtURL(deleteUrl)
print("删除照片:\(deleteUrl.absoluteString)")
} catch _ {}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if completionColsure != nil {
completionColsure!()
}
})
}
}
func terminateCleanDisk() {
WPCache.cleanDiskWithCompeletionColsure(0, completionColsure: nil)
}
func cleanDisk() {
WPCache.cleanDiskWithCompeletionColsure()
}
/// 最大保留秒数7天
let maxCacheAge : NSInteger = 3600 * 7
let defaultMemoryCache = NSCache()
let defaultDiskCache = NSFileManager()
var diskCacheDirName = "" {
didSet {
self.cacheDir = NSTemporaryDirectory().stringByAppendingString("\(self.diskCacheDirName)/")
if !self.defaultDiskCache.fileExistsAtPath(self.diskCacheDirName) {
do {
try self.defaultDiskCache.createDirectoryAtPath(self.cacheDir, withIntermediateDirectories: true, attributes: nil)
} catch _ {}
}
}
}
var cacheDir = "" {
didSet {
}
}
static func imageExistWithKey(key:String) -> Bool {
if WPCache.sharedInstance.diskCacheDirName == "" {
WPCache.sharedInstance.diskCacheDirName = "defaultCache"
}
let filePath = WPCache.sharedInstance.cacheDir.stringByAppendingString("\(key.hashValue)")
return WPCache.sharedInstance.defaultDiskCache.fileExistsAtPath(filePath)
}
static func setDiskCacheObject(imageData:NSData , ForKey key:String ,withSuccessHandler successColsure:((image:UIImage,key:String,filePath:String) -> Void)) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
if WPCache.sharedInstance.diskCacheDirName == "" {
WPCache.sharedInstance.diskCacheDirName = "defaultCache"
}
let filePath = WPCache.sharedInstance.cacheDir.stringByAppendingString("\(key.hashValue)")
let result = WPCache.sharedInstance.defaultDiskCache.createFileAtPath(filePath, contents: imageData, attributes: nil)
// let result = imageData.writeToFile(filePath, atomically: true)
if result {
print("写入成功,\(key),\(filePath)")
let image = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData)
WPCache.sharedInstance.defaultMemoryCache.setObject(image!, forKey: key)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
successColsure(image: UIImage(data: imageData)!,key: key,filePath: filePath)
})
} else {
print("写入失败,\(key),\(filePath)")
}
}
}
static func getDiskCacheObjectForKey(key:String,withSuccessHandler successColsure:((image:UIImage,key:String,filePath:String) -> Void)) {
dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
if WPCache.sharedInstance.diskCacheDirName == "" {
WPCache.sharedInstance.diskCacheDirName = "defaultCache"
}
if WPCache.sharedInstance.defaultMemoryCache.objectForKey(key) != nil {
let image = WPCache.sharedInstance.defaultMemoryCache.objectForKey(key) as! UIImage
dispatch_async(dispatch_get_main_queue(), { () -> Void in
successColsure(image: image,key: key,filePath: "")
})
} else {
let filePath = WPCache.sharedInstance.cacheDir.stringByAppendingString("\(key.hashValue)")
let imageData = WPCache.sharedInstance.defaultDiskCache.contentsAtPath(filePath)
let image = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData!)
WPCache.sharedInstance.defaultMemoryCache.setObject(image!, forKey: key)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
successColsure(image: image!,key: key,filePath: filePath)
})
}
}
}
}
class WPWebImage: NSObject {
/**
下载图片
- parameter urlString: 图片url
- parameter colsure: 回调
*/
class func downloadImage(urlString:String,withSuccessColsure colsure:(image:UIImage,imageData:NSData,url:String) -> Void) {
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue) { (response, data, error ) -> Void in
if data != nil {
let image = WPWebImage.wp_animatedImageWithGIFData(gifData: data!)
if image != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
colsure(image: image!, imageData: data!,url: urlString)
})
}
}
}
}
/**
GIF适配
CG 框架是不会在ARC下被管理,因此此处GIF时会导致内存泄漏 20160401
证明在OC下确实如此 http://stackoverflow.com/questions/1263642/releasing-cgimage-cgimageref
Swift 下面被ARC自动管理释放 http://stackoverflow.com/questions/24900595/swift-cgpathrelease-and-arc
但是在GIF下面内存暴涨很厉害 ,GifU的解决方案:https://github.com/kaishin/Gifu/pull/55
解决方案描述:
Although the deinit block called displayLink.invalidate(), because the CADisplayLink was retaining the AnimatableImageView instance the view was never deallocated, its deinit block never executed, and .invalidate() was never called.
We can fix the retention cycle between AnimatableImageView and CADisplayLink by using another object as the target for the CADisplayLink instance, as described here.
自定义一个CADispaylink 手动管理
它自定义一个类继承自UIImageView,目前方法考虑UIImageView扩展模仿其实现方法重写
- parameter data:
- returns:
*/
class func wp_animatedImageWithGIFData(gifData data: NSData) -> UIImage! {
let options: NSDictionary = [kCGImageSourceShouldCache as String: NSNumber(bool: true), kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF]
guard let imageSource = CGImageSourceCreateWithData(data as CFDataRef, options) else {
return nil
}
let frameCount = CGImageSourceGetCount(imageSource)
var images = [UIImage]()
let duration = 0.1 * Double(frameCount)
for i in 0 ..< frameCount {
guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else {
return nil
}
images.append(UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: .Up))
}
if frameCount <= 1 {
return images.first
} else {
return UIImage.animatedImageWithImages(images, duration: duration)
}
}
}
public enum WPCATransionStyle : String {
case Fade = "kCATransitionFade"
case MoveIn = "kCATransitionMoveIn"
case Push = "kCATransitionPush"
case Reveal = "kCATransitionReveal"
case FromRight = "kCATransitionFromRight"
case FromLeft = "kCATransitionFromLeft"
case FromTop = "kCATransitionFromTop"
case FromBottom = "kCATransitionFromBottom"
case None = "None"
}
extension UIImageView {
/**
渐变设置图片第一种方法,tableview 上面有些卡顿
- parameter newImage:
- parameter duration:
*/
func transitionWithImage(newImage:UIImage,duration:NSTimeInterval) {
UIView.transitionWithView(self, duration: duration, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in
self.image = newImage
}) { (finish) -> Void in
}
}
/**
渐变设置图片第二种方法
- parameter duration:
*/
func addTransition(duration:NSTimeInterval,transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) == nil && transionStyle != .None {
let transition = CATransition()
transition.type = transionStyle.rawValue
transition.duration = duration
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self.layer.addAnimation(transition, forKey: transionStyle.rawValue)
}
}
func removeTransition(transionStyle:WPCATransionStyle = .Fade) {
if self.layer.animationForKey(transionStyle.rawValue) != nil {
self.layer.removeAnimationForKey(transionStyle.rawValue)
}
}
func wp_setImageWithAsset(urlString: String,placeholderImage: UIImage?) {
self.tag = urlString.hash
self.image = placeholderImage
if WPCache.sharedInstance.defaultCache.objectForKey(urlString) != nil {
self.image = WPCache.sharedInstance.defaultCache.objectForKey(urlString) as? UIImage
} else {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let assetLib = ALAssetsLibrary()
assetLib.assetForURL(NSURL(string: urlString), resultBlock: { (asset) -> Void in
let cgImg = asset.defaultRepresentation().fullScreenImage().takeUnretainedValue()
let fullImage = UIImage(CGImage: cgImg)
if self.tag == urlString.hash {
WPCache.sharedInstance.defaultCache.setObject(fullImage, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = fullImage
})
}
}, failureBlock: { (error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = placeholderImage
})
})
})
}
}
func wp_setLoacalOrRemoteImageWith(urlString: String,withIsNotLocalPath remotePath:String,placeholderImage: UIImage?) {
if urlString.hasPrefix("http") {
self.wp_loadImageWithUrlString(NSURL(string: urlString)!, placeholderImage: placeholderImage)
} else if urlString.hasPrefix("/var") {
self.wp_setImageWithLocalPath(urlString, withIsNotLocalPath: remotePath,placeholderImage: placeholderImage)
}
}
func wp_setPreviewImageWithLocalPath(localPath:String, withIsNotLocalPath remotePath:String) {
self.tag = localPath.hashValue
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
if let image = UIImage(contentsOfFile: localPath) {
if self.tag == localPath.hashValue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = image
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.wp_loadPreviewImageWithUrlString(NSURL(string: remotePath)!, placeholderImage: UIImage(named: "DefaultPortraitIcon"))
})
}
})
}
/**
异步加载本地图片
- parameter localPath:
- parameter remotePath:
*/
func wp_setImageWithLocalPath(localPath:String, withIsNotLocalPath remotePath:String,placeholderImage: UIImage? = nil) {
self.tag = localPath.hashValue
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
if let image = UIImage(contentsOfFile: localPath) {
if self.tag == localPath.hashValue {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = image
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.wp_loadImageWithUrlString(NSURL(string: remotePath)!, placeholderImage: UIImage(named: "DefaultPortraitIcon"))
})
}
})
}
/**
高效加圆角
- parameter urlString: url
- parameter placeholderImage: 默认图
*/
public func wp_roundImageWithURL(urlString:String,
placeholderImage: UIImage?)
{
self.wp_setImageWithURLString(urlString, autoSetImage: false, placeholderImage: placeholderImage) { [weak self] (image) -> Void in
self?.roundedImage(image)
}
}
func roundedImage(downloadImage:UIImage,withRect rect:CGRect = CGRect(x: CGFloat.min, y: CGFloat.min, width: 80, height: 80),withRadius radius:CGFloat = 10.0,completion:((roundedImage:UIImage) -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1.0)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
downloadImage.drawInRect(rect)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = roundedImage
if completion != nil {
completion!(roundedImage: roundedImage)
}
})
}
}
}
extension UIImageView {
/**
预览照片的异步加载方法
- parameter url:
- parameter placeholderImage:
- parameter progressBlock:
- parameter completionHandler:
*/
func wp_loadPreviewImageWithUrlString(url: NSURL,
placeholderImage: UIImage?,
progressBlock:DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
self.wp_loadImageWithUrlString(url, placeholderImage: placeholderImage, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
图片异步加载封装方法
- parameter url: 图片url
- parameter placeholderImage: 默认图
- parameter progressBlock: 进度回调
- parameter completionHandler: 完成时回调
*/
func wp_loadImageWithUrlString(url: NSURL,
placeholderImage: UIImage?,
progressBlock:DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) {
self.wp_setImageWithURLString(url.absoluteString, autoSetImage: true, placeholderImage: placeholderImage) { (image) -> Void in
}
}
/**
自定义的异步加载图片
- parameter urlString: url
- parameter placeholderImage: 默认图
*/
func wp_setImageWithURLString(urlString: String,
autoSetImage:Bool = true,
withTransformStyle transformStyle:WPCATransionStyle = .Fade,
duration:NSTimeInterval = 1.0,
placeholderImage: UIImage? = UIColor.imageWithColor(UIColor.randomColor()),
completionHandler:((image:UIImage) ->Void)? = nil) {
guard urlString != "" else {
self.image = placeholderImage
return
}
if self.tag != urlString.hash {
//解决reloaddata的时候imageview 闪烁问题
self.tag = urlString.hash
self.image = placeholderImage
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
if WPCache.imageExistWithKey(urlString) {
WPCache.getDiskCacheObjectForKey(urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if self.tag == urlString.hash {
if autoSetImage {
if filePath == "" {
//内存中取出
self.removeTransition()
self.image = image
} else {
//硬盘中取出
switch transformStyle {
case .None:
self.removeTransition()
self.image = image
case .Fade:
self.addTransition(duration)
self.image = image
default:
self.removeTransition()
self.image = image
}
}
if completionHandler != nil {
completionHandler!(image: image)
}
} else {
if completionHandler != nil {
completionHandler!(image: image)
}
}
}
})
} else {
if urlString.length() <= 0 {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.image = placeholderImage
})
} else {
WPWebImage.downloadImage(urlString, withSuccessColsure: { (image, imageData,saveUrl) -> Void in
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let newImage = WPWebImage.wp_animatedImageWithGIFData(gifData: imageData)
if self.tag == urlString.hash {
if autoSetImage {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
switch transformStyle {
case .Fade:
self.addTransition(duration)
self.image = newImage
default:
self.removeTransition()
self.image = newImage
}
})
}
WPCache.setDiskCacheObject(imageData, ForKey: urlString, withSuccessHandler: { (image, key, filePath) -> Void in
if completionHandler != nil {
completionHandler!(image: image)
}
})
}
})
})
}
}
}
}
} | b1e52afce3de47f622cae7e1014136a2 | 45.541195 | 237 | 0.54714 | false | false | false | false |
bettkd/Securus | refs/heads/master | Securus/LoginViewController.swift | gpl-2.0 | 1 | //
// TimelineViewController.swift
// Securus
//
// Created by Dominic Bett on 11/16/15.
// Copyright © 2015 DominicBett. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.usernameField.delegate = self
self.passwordField.delegate = self
// Do any additional setup after loading the view.
}
//Dismiss keyboard when touch outside -> resign first responder when textview is not touched
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func unwindToLogInScreen(segue:UIStoryboardSegue) {
}
@IBAction func loginAction(sender: AnyObject) {
let username = self.usernameField.text?.lowercaseString
let password = self.passwordField.text
// Validate the text fields
if username!.characters.count < 5 {
let alert = UIAlertView(title: "Invalid", message: "Username must be greater than 5 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else if password!.characters.count < 6 {
let alert = UIAlertView(title: "Invalid", message: "Password must be greater than 8 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
spinner.startAnimating()
// Send a request to login
PFUser.logInWithUsernameInBackground(username!, password: password!, block: { (user, error) -> Void in
// Stop the spinner
spinner.stopAnimating()
if ((user) != nil) {
let alert = UIAlertView(title: "Success", message: "Logged In", delegate: self, cancelButtonTitle: "OK")
alert.show()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Timeline")
self.presentViewController(viewController, animated: true, completion: nil)
})
} else {
let alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
})
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == self.usernameField!{
self.passwordField.becomeFirstResponder()
} else if textField == self.passwordField {
loginAction(self)
}
return true
}
}
| cfa3f8d5cf696453594a0a96949f2953 | 37.602041 | 153 | 0.604282 | false | false | false | false |
gali8/G8MaterialKitTextField | refs/heads/master | MKTextField/MKLabel.swift | mit | 1 | //
// MKLabel.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/29/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class MKLabel: UILabel {
@IBInspectable var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable var aniDuration: Float = 0.65
@IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable var circleGrowRatioMax: Float = 0.9 {
didSet {
mkLayer.circleGrowRatioMax = circleGrowRatioMax
}
}
@IBInspectable var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(circleLayerColor)
}
}
@IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
mkLayer.setCircleLayerColor(circleLayerColor)
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
func animateRipple(location: CGPoint? = nil) {
if let point = location {
mkLayer.didChangeTapLocation(point)
} else if rippleLocation == .TapLocation {
rippleLocation = .Center
}
mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: circleAniTimingFunction, duration: CFTimeInterval(aniDuration))
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(aniDuration))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if let firstTouch = touches.first {
let location = firstTouch.locationInView(self)
animateRipple(location)
}
}
}
| 588024032e7cfdb223ca4a55678a743f | 30.135417 | 142 | 0.632653 | false | false | false | false |
jphacks/KM_03 | refs/heads/master | iOS/LimitedSpace/LimitedSpace/Classes/Model/LimitedSpaceModel.swift | mit | 1 | //
// LimitedSpaceModel.swift
// LimitedSpace
//
// Copyright © 2015年 Ryunosuke Kirikihira. All rights reserved.
//
import Foundation
class LimitedSpaceModel :NSObject {
let itemId :Int
let title :String
let range :Int
let createDate :NSDate
var time :Int
init(title :String, range :Int, time :Int) {
self.title = title
self.range = range
self.time = time
self.createDate = NSDate()
self.itemId = 0
}
@objc required init(coder aDecoder :NSCoder) {
self.itemId = aDecoder.decodeIntegerForKey("itemId")
self.title = aDecoder.decodeObjectForKey("title") as? String ?? ""
self.range = aDecoder.decodeIntegerForKey("range")
self.createDate = aDecoder.decodeObjectForKey("createDate") as? NSDate ?? NSDate()
self.time = aDecoder.decodeIntegerForKey("time")
}
@objc func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(self.itemId, forKey: "itemId")
aCoder.encodeObject(self.title, forKey: "title")
aCoder.encodeInteger(self.range, forKey: "range")
aCoder.encodeObject(self.createDate, forKey: "createDate")
aCoder.encodeInteger(self.time, forKey: "time")
}
} | ac91a676061ea294f127a2da75bcdd2d | 29.585366 | 90 | 0.644054 | false | false | false | false |
szehnder/AERecord | refs/heads/master | AERecordExample/DetailViewController.swift | mit | 1 | //
// DetailViewController.swift
// AERecordExample
//
// Created by Marko Tadic on 11/3/14.
// Copyright (c) 2014 ae. All rights reserved.
//
import UIKit
import CoreData
import AERecord
let yellow = UIColor(red: 0.969, green: 0.984, blue: 0.745, alpha: 1)
let blue = UIColor(red: 0.918, green: 0.969, blue: 0.984, alpha: 1)
class DetailViewController: CoreDataCollectionViewController {
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// setup UISplitViewController displayMode button
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem()
navigationItem.leftItemsSupplementBackButton = true
// setup options button
let optionsButton = UIBarButtonItem(title: "Options", style: .Plain, target: self, action: "showOptions:")
self.navigationItem.rightBarButtonItem = optionsButton
// setup fetchedResultsController property
refreshFetchedResultsController()
}
// MARK: - CoreData
func showOptions(sender: AnyObject) {
let optionsAlert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
optionsAlert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
let addFewAction = UIAlertAction(title: "Add Few", style: .Default) { (action) -> Void in
// create few objects
for i in 1...5 {
Event.createWithAttributes(["timeStamp" : NSDate()])
}
AERecord.saveContextAndWait()
}
let deleteAllAction = UIAlertAction(title: "Delete All", style: .Destructive) { (action) -> Void in
// delete all objects
Event.deleteAll()
AERecord.saveContextAndWait()
}
let updateAllAction = UIAlertAction(title: "Update All", style: .Default) { (action) -> Void in
if NSProcessInfo.instancesRespondToSelector("isOperatingSystemAtLeastVersion:") {
// >= iOS 8
// batch update all objects (directly in persistent store) then refresh objects in context
Event.batchUpdateAndRefreshObjects(properties: ["timeStamp" : NSDate()])
// note that if using NSFetchedResultsController you have to call performFetch after batch updating
self.performFetch()
} else {
// < iOS 8
println("Batch updating is new in iOS 8.")
// update all objects through context
if let events = Event.all() as? [Event] {
for e in events {
e.timeStamp = NSDate()
}
AERecord.saveContextAndWait()
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
optionsAlert.addAction(addFewAction)
optionsAlert.addAction(deleteAllAction)
optionsAlert.addAction(updateAllAction)
optionsAlert.addAction(cancelAction)
presentViewController(optionsAlert, animated: true, completion: nil)
}
func refreshFetchedResultsController() {
let sortDescriptors = [NSSortDescriptor(key: "timeStamp", ascending: true)]
let request = Event.createFetchRequest(sortDescriptors: sortDescriptors)
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: AERecord.defaultContext, sectionNameKeyPath: nil, cacheName: nil)
}
// MARK: - Collection View
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as CustomCollectionViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: CustomCollectionViewCell, atIndexPath indexPath: NSIndexPath) {
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
cell.backgroundColor = event.selected ? yellow : blue
cell.textLabel.text = event.timeStamp.description
}
}
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CustomCollectionViewCell {
// update value
if let frc = fetchedResultsController {
if let event = frc.objectAtIndexPath(indexPath) as? Event {
cell.backgroundColor = yellow
// deselect previous
if let previous = Event.firstWithAttribute("selected", value: true) as? Event {
previous.selected = false
AERecord.saveContextAndWait()
}
// select current and refresh timestamp
event.selected = true
event.timeStamp = NSDate()
AERecord.saveContextAndWait()
}
}
}
}
}
| 0fd38c08399a98099ecce2cc9d95ab02 | 40.378788 | 172 | 0.623398 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop | refs/heads/master | Session 2/Signup Demo/Signup Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// Signup Demo
//
// Created by Ash Furrow on 2015-10-08.
// Copyright © 2015 Artsy. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Moya
class ViewController: UIViewController {
@IBOutlet weak var emailAddressTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var imageView: UIImageView!
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let validEmail = emailAddressTextField.rx_text.map(isEmail)
let validPassword = passwordTextField.rx_text.map(isPassword)
combineLatest(validEmail, validPassword, and)
.bindTo(submitButton.rx_enabled)
submitButton.rx_tap.map { _ -> Observable<MoyaResponse> in
return provider.request(.Image)
}.flatMap() { obs in
return obs.filterSuccessfulStatusCodes()
.mapImage()
.catchError(self.presentError)
.filter({ (thing) -> Bool in
return thing != nil
})
}
.take(1)
.bindTo(imageView.rx_image)
.addDisposableTo(disposeBag)
}
}
func isEmail(string: String) -> Bool {
return string.characters.contains("@")
}
func isPassword(string: String) -> Bool {
return string.characters.count >= 6
}
func and(lhs: Bool, rhs: Bool) -> Bool {
return lhs && rhs
}
extension UIViewController {
func presentError(error: ErrorType) -> Observable<UIImage!> {
let alertController = UIAlertController(title: "Network Error", message: (error as NSError).localizedDescription, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default) { [weak self] _ -> Void in
self?.dismissViewControllerAnimated(true, completion: nil)
})
self.presentViewController(alertController, animated: true, completion: nil)
return just(nil)
}
}
| 3418a512fd72d5f92949e74d599060ab | 26.44 | 145 | 0.647716 | false | false | false | false |
carnivalmobile/carnival-stream-examples | refs/heads/master | iOS/CarnivalSwiftStreamExamples/CarnivalSwiftStreamExamples/GraphicalCardTableViewCell.swift | apache-2.0 | 1 | //
// GraphicalCardTableViewCell.swift
// CarnivalSwiftStreamExamples
//
// Created by Sam Jarman on 14/09/15.
// Copyright (c) 2015 Carnival Mobile. All rights reserved.
//
import UIKit
class GraphicalCardTableViewCell: TextCardTableViewCell {
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var timeBackground: UIView!
override class func cellIdentifier() -> String {
return "GraphicalCardTableViewCell"
}
override func configureCell(message: CarnivalMessage) {
super.configureCell(message: message)
if message.imageURL != nil {
self.imgView.sd_setImage(with: message.imageURL, placeholderImage: UIImage(named: "placeholder_image"))
self.imgView.contentMode = UIView.ContentMode.scaleAspectFill
self.imgView.clipsToBounds = true
}
self.timeBackground.layer.cornerRadius = 4.0
}
override func setSelected(_ selected: Bool, animated: Bool) {
let backgroundColor = self.unreadLabel.backgroundColor
super.setSelected(selected, animated: animated)
self.unreadLabel.backgroundColor = backgroundColor
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let backgroundColor = self.unreadLabel.backgroundColor
super.setHighlighted(isSelected, animated: animated)
self.unreadLabel.backgroundColor = backgroundColor
}
}
| ce375b34a38499c46d0f4bc5be4a01be | 34.675 | 115 | 0.702172 | false | false | false | false |
jfosterdavis/Charles | refs/heads/develop | Charles/CustomPerkStoreCollectionViewCell.swift | apache-2.0 | 1 | //
// CustomPerkStoreCollectionViewCell.swift
// Charles
//
// Created by Jacob Foster Davis on 5/29/17.
// Copyright © 2017 Zero Mu, LLC. All rights reserved.
//
import Foundation
import UIKit
import StoreKit
class CustomPerkStoreCollectionViewCell: CustomStoreCollectionViewCell {
@IBOutlet weak var perkIconImageView: UIImageView!
@IBOutlet weak var perkColorFrame: UIView!
@IBOutlet weak var perkGotFromCharacterIndicator: UIImageView!
@IBOutlet weak var perkIconBlocker: UIView!
var perkClue: Perk? = nil
/// Adds buttons from the given phrase to the stackview
func loadAppearance(fromPerk perk: Perk) {
//empty all
for subView in stackView.subviews {
stackView.removeArrangedSubview(subView)
//remove button from heirarchy
subView.removeFromSuperview()
}
self.perkClue = perk
//create the ImageView
perkIconImageView.image = perk.icon
//perkIconImageView.backgroundColor = perk.displayColor
//color the border
perkColorFrame.layer.borderWidth = 5
perkColorFrame.layer.borderColor = perk.displayColor.cgColor
perkColorFrame.roundCorners(with: 6)
//stackView.addArrangedSubview(imageView)
roundCorners()
//infoButton.roundCorners(with: infoButton.bounds.width / 2)
perkGotFromCharacterIndicator.image = #imageLiteral(resourceName: "GroupChecked")
perkGotFromCharacterIndicator.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 0.95) //an off-white
perkGotFromCharacterIndicator.roundCorners(with: 6)
//make background the paper color
self.backgroundColor = UIColor(red: 249/255, green: 234/255, blue: 188/255, alpha: 1)
perkIconBlocker.isHidden = true
//default the shade on top unless others will change
perkGotFromCharacterIndicator.layer.zPosition = 2
perkGotFromCharacterIndicator.alpha = 0.65
characterNameLabel.textColor = .black
self.canUserHighlight = true
self.isUserInteractionEnabled = true
self.canShowInfo = true
}
func setGotPerkFromCharacterIndicator(visible: Bool) {
perkGotFromCharacterIndicator.isHidden = !visible
}
override func setStatusAffordable() {
//rotate and set text of the label
statusLabel.transform = CGAffineTransform.identity //resets to normal
statusLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 5) //rotates <45 degrees
statusLabel.text = "For Hirė"
statusShade.alpha = 0.1
statusShade.backgroundColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
setStatusVisibility(label: false, shade: true)
priceLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
priceLabel.font = UIFont(name:"GurmukhiMN", size: 15.0)
self.canUserHighlight = true
self.isUserInteractionEnabled = true
self.canShowInfo = true
}
override func setStatusUnaffordable() {
//rotate and set text of the label
statusLabel.transform = CGAffineTransform.identity //resets to normal
statusLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 5) //rotates <45 degrees
statusLabel.text = "For Hirė"
priceLabel.layer.zPosition = 1
self.setNeedsDisplay()
statusShade.alpha = 0.45
statusShade.backgroundColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
setStatusVisibility(label: false, shade: true)
priceLabel.textColor = .red
priceLabel.font = UIFont(name:"GurmukhiMN-Bold", size: 15.0)
self.canUserHighlight = true
self.isUserInteractionEnabled = true
self.canShowInfo = true
}
func setStatusRequiredCharacterNotPresent() {
//rotate and set text of the label
statusLabel.transform = CGAffineTransform.identity //resets to normal
//statusLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 5) //rotates <45 degrees
statusLabel.text = "Rėquirės Party"
perkGotFromCharacterIndicator.layer.zPosition = 1
perkGotFromCharacterIndicator.alpha = 1
perkGotFromCharacterIndicator.image = #imageLiteral(resourceName: "GroupMissing")
perkGotFromCharacterIndicator.backgroundColor = UIColor(red: 255/255, green: 94/255, blue: 94/255, alpha: 1) //a gentle red
self.setNeedsDisplay()
//put to black and white
self.backgroundColor = .white
perkIconBlocker.isHidden = true
perkColorFrame.layer.borderColor = UIColor.black.cgColor
statusShade.alpha = 0.85
statusShade.backgroundColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1)
setStatusVisibility(label: false, shade: true)
priceLabel.text = ""
priceLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
priceLabel.font = UIFont(name:"GurmukhiMN-Bold", size: 15.0)
self.canUserHighlight = true
self.isUserInteractionEnabled = true
self.canShowInfo = true
}
///sets the visual status to affordable and ready for purchase
override func setStatusUnlocked() {
setStatusVisibility(label: false, shade: false)
priceLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1)
priceLabel.font = UIFont(name:"GurmukhiMN", size: 15.0)
priceLabel.text = "Active"
self.canUserHighlight = true
self.isUserInteractionEnabled = true
self.canShowInfo = true
}
override func showInfo() {
//launch the clue if it exists
print("perk clue button pressed")
if let perk = self.perkClue, canShowInfo {
let durationString = Utilities.getEasyDurationString(from: perk.minutesUnlocked)
//create a clue based on the perk that was pressed
let perkClue = Clue(clueTitle: perk.name,
part1: nil,
part1Image: perk.icon,
part2: perk.gameDescription,
part3: String(describing: "Unlocks for \(durationString).")
)
if let storyboard = self.storyboard {
let topVC = topMostController()
let clueVC = storyboard.instantiateViewController(withIdentifier: "BasicClueViewController") as! BasicClueViewController
clueVC.clue = perkClue
clueVC.delayDismissButton = false
//set the background
clueVC.view.backgroundColor = UIColor(red: 107/255, green: 12/255, blue: 0/255, alpha: 1) //expired perks background color
clueVC.overrideTextColor = UIColor(red: 249/255, green: 234/255, blue: 188/255, alpha: 1) //paper color
clueVC.overrideGoldenRatio = true
clueVC.overrideStackViewDistribution = .fillEqually
topVC.present(clueVC, animated: true, completion: nil)
}
}
}
}
| d4eb0306b085a792818607508c8cfd92 | 38.34375 | 138 | 0.626423 | false | false | false | false |
prebid/prebid-mobile-ios | refs/heads/master | InternalTestApp/PrebidMobileDemoRendering/ViewControllers/UtilitiesViewController.swift | apache-2.0 | 1 | /* Copyright 2018-2021 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import AppTrackingTransparency
import UIKit
import Eureka
import PrebidMobile
class UtilitiesViewController: FormViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Utilities"
buildForm()
}
private func buildForm() {
form
+++ Section()
<<< makeActionRow(title: "PrebidMobile Configuration", action: { AboutViewController() }) {
$0.accessoryType = .detailDisclosureButton
}
<<< makeActionRow(title: "IAB Consent Settings", action: { IABConsentViewController() })
<<< makeActionRow(title: "Command Line Args", action: { CommandArgsViewController() })
<<< makeActionRow(title: "App Settings", action: { SettingsViewController() })
if #available(iOS 14, *) {
form.last! <<< attRequestButton
}
}
private func makeActionRow(title: String,
action: @escaping ()->UIViewController?,
extraCellSetup: ((Cell<String>)->())? = nil) -> BaseRow
{
return LabelRow() { row in
row.title = title
}
.cellSetup { cell, row in
cell.accessoryType = .disclosureIndicator
extraCellSetup?(cell)
}
.onCellSelection { [weak self] cell, row in
if let vc = action(), let navigator = self?.navigationController {
navigator.pushViewController(vc, animated: true)
}
}
}
lazy var attRequestButton = ButtonRow() {
$0.title = "Request Tracking Authorization"
}
.onCellSelection { [weak self] cell, row in
if #available(iOS 14, *) {
ATTrackingManager.requestTrackingAuthorization { [weak self] status in
var dialogMessage = UIAlertController(title: "AT Tracking",
message: "Authorization status: \(status.rawValue)",
preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
dialogMessage.addAction(ok)
DispatchQueue.main.async { [weak self] in
self?.present(dialogMessage, animated: true, completion: nil)
}
}
}
}
}
| 1b6ac2e40626e916d5d6f96347ada1d9 | 35.839506 | 106 | 0.58445 | false | false | false | false |
eigengo/reactive-architecture-cookbook-code | refs/heads/master | eas/ios/EAS/Classification/NaiveClassifier.swift | gpl-3.0 | 1 | import Foundation
class NaiveExerciseClassifier: ExerciseClassifier {
private let signalAnalysis: SignalAnalysis
init(signalAnalysis: SignalAnalysis) {
self.signalAnalysis = signalAnalysis
}
func classify(matrix: Matrix) -> String? {
let x = signalAnalysis.dft(matrix: matrix, n: 2).flatten()
let (px1, cx1) = (x[0], x[1])
let peps = Float(10)
let ceps = Float(0.5)
if abs(px1 - 86) < peps && abs(cx1 - 1.2) < ceps {
return "straight bar biceps curl"
} else if abs(px1 - 250) < peps && abs(cx1 - 1.5) < ceps {
return "chest dumbbell flyes"
}
return nil
}
}
| 313e41dd88b8aca6e82f690a2fb83ab9 | 27.25 | 66 | 0.581121 | false | false | false | false |
codepgq/AnimateDemo | refs/heads/master | Animate/Animate/controller/BaseAnimation/Size/SizeController.swift | apache-2.0 | 1 | //
// SizeController.swift
// Animate
//
// Created by Mac on 17/2/7.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class SizeController: UIViewController {
@IBOutlet weak var boundsImg: UIImageView!
@IBOutlet weak var contentsW: UIImageView!
@IBOutlet weak var contentH: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
startAnimation()
}
func startAnimation(){
//bounds
let boundsAnimate = Animate.baseAnimationWithKeyPath("bounds", fromValue: nil, toValue: NSValue(cgRect: CGRect(x: 0, y: 0, width: 50, height: 50)), duration: 0.75, repeatCount: Float.infinity, timingFunction: nil)
boundsAnimate.autoreverses = true
boundsImg.layer.add(boundsAnimate, forKey: "bounds")
//contentsRect.size.width
let widthAnimate = Animate.baseAnimationWithKeyPath("contentsRect.size.width", fromValue: nil, toValue: 0.5, duration: 0.75, repeatCount: Float.infinity, timingFunction: nil)
widthAnimate.autoreverses = true
contentsW.layer.add(widthAnimate, forKey: "contentsRect.size.width")
//contentsRect.size.height
let heightAnimate = Animate.baseAnimationWithKeyPath("contentsRect.size.height", fromValue: nil, toValue: 1.5, duration: 0.75, repeatCount: Float.infinity, timingFunction: nil)
heightAnimate.autoreverses = true
contentH.layer.add(heightAnimate, forKey: "contentsRect.size.height")
}
}
| 95d6cb13c6733fb15dc2663f90132fa1 | 38.210526 | 221 | 0.693289 | false | false | false | false |
webim/webim-client-sdk-ios | refs/heads/master | WebimClientLibrary/Webim.swift | mit | 1 | //
// Webim.swift
// WebimClientLibrary
//
// Created by Nikita Lazarev-Zubov on 02.08.17.
// Copyright © 2017 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
Main point of WebimClientLibrary.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public final class Webim {
/**
Returns new SessionBuilder object for creating WebimSession object.
- returns:
The instance of WebimSession builder.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
static public func newSessionBuilder() -> SessionBuilder {
return SessionBuilder()
}
/**
Returns new FAQBuilder object for creating FAQ object.
- returns:
The instance of FAQ builder.
- attention:
This method can't be used as is. It requires that client server to support this mechanism.
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
static public func newFAQBuilder() -> FAQBuilder {
return FAQBuilder()
}
/**
Deserializes received remote notification.
This method can be called with `userInfo` parameter of your UIApplicationDelegate method `application(_:didReceiveRemoteNotification:)`.
Remote notification dictionary must be stored inside standard APNs key "aps".
- parameter remoteNotification:
User info of received remote notification.
- returns:
Remote notification object or nil if there's no useful payload or this notification is sent not by Webim service.
- seealso:
`SessionBuilder.set(remoteNotificationsSystem:)`
`isWebim(remoteNotification:)`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
static public func parse(remoteNotification: [AnyHashable : Any], visitorId: String? = nil) -> WebimRemoteNotification? {
return InternalUtils.parse(remoteNotification: remoteNotification, visitorId: visitorId)
}
/**
If remote notifications (SessionBuilder.setRemoteNotificationSystem) are enabled for the session, then you can receive remote notifications belonging to this session.
This method can be called with `userInfo` parameter of your UIApplicationDelegate method `application(_:didReceiveRemoteNotification:)`.
Remote notification dictionary must be stored inside standard APNs key "aps".
- parameter remoteNotification:
User info of received remote notification.
- returns:
Boolean value that indicates is received remote notification is sent by Webim service.
- seealso:
`SessionBuilder.set(remoteNotificationSystem:)`
`parseRemoteNotification()`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
static public func isWebim(remoteNotification: [AnyHashable: Any]) -> Bool {
return InternalUtils.isWebim(remoteNotification: remoteNotification)
}
// MARK: -
/**
- seealso:
`SessionBuilder.setRemoteNotificationSystem()`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public enum RemoteNotificationSystem {
case apns
@available(*, unavailable, renamed: "apns")
case APNS
case fcm
case none
@available(*, unavailable, renamed: "none")
case NONE
}
}
// MARK: -
/**
`WebimSession` builder.
- seealso:
`Webim.newSessionBuilder()`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public final class SessionBuilder {
// MARK: - Properties
private var accountName: String?
private var appVersion: String?
private var deviceToken: String?
private weak var fatalErrorHandler: FatalErrorHandler?
private var localHistoryStoragingEnabled = true
private var location: String?
private var multivisitorSection = ""
private weak var notFatalErrorHandler: NotFatalErrorHandler?
private var pageTitle: String?
private var providedAuthorizationToken: String?
private weak var providedAuthorizationTokenStateListener: ProvidedAuthorizationTokenStateListener?
private var remoteNotificationSystem: Webim.RemoteNotificationSystem = .none
private var visitorDataClearingEnabled = false
private var visitorFields: ProvidedVisitorFields?
private weak var webimLogger: WebimLogger?
private var webimLoggerVerbosityLevel: WebimLoggerVerbosityLevel?
private var prechat: String?
private var onlineStatusRequestFrequencyInMillis: Int64?
// MARK: - Methods
/**
Sets company account name in Webim system.
Usually presented by full domain URL of the server (e.g "https://demo.webim.ru").
For testing purposes it is possible to use account name "demo".
- parameter accountName:
Webim account name.
- returns:
`SessionBuilder` object with account name set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(accountName: String) -> SessionBuilder {
self.accountName = accountName
return self
}
/**
Location on server.
You can use "mobile" or contact support for creating new one.
- parameter location:
Location name.
- returns:
`SessionBuilder` object with location set.
- seealso:
https://webim.ru/help/help-terms/#location
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(location: String) -> SessionBuilder {
self.location = location
return self
}
/**
Set prechat fields with extra information.
- parameter prechat:
Prechat fields in JSON format.
- returns:
`SessionBuilder` object with location set.
- attention:
This method can't be used as is. It requires that client server to support this mechanism.
- author:
Nikita Kaberov
- copyright:
2018 Webim
*/
public func set(prechat: String) -> SessionBuilder {
self.prechat = prechat
return self
}
/**
You can differentiate your app versions on server by setting this parameter. E.g. "2.9.11".
This is optional.
- parameter appVersion:
Client app version name.
- returns:
`SessionBuilder` object with app version set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(appVersion: String?) -> SessionBuilder {
self.appVersion = appVersion
return self
}
/**
A visitor can be anonymous or authorized. Without calling this method when creating a session visitor is anonymous.
In this case visitor receives a random ID, which is written in `WMKeychainWrapper`. If the data is lost (for example when application was reinstalled), the user ID is also lost, as well as the message history.
Authorizing of a visitor can be useful when there are internal mechanisms of authorization in your application and you want the message history to exist regardless of a device communication occurs from.
This method takes as a parameter a string containing the signed fields of a user in JSON format. Since the fields are necessary to be signed with a private key that can never be included into the code of a client's application, this string must be created and signed somewhere on your backend side. Read more about forming a string and a signature here: https://webim.ru/help/identification/
- important:
Can't be used simultanously with `set(providedAuthorizationTokenStateListener:providedAuthorizationToken:)`.
- parameter jsonString:
JSON-string containing the signed fields of a visitor.
- returns:
`SessionBuilder` object with visitor fields set.
- SeeAlso:
https://webim.ru/help/identification/
set(visitorFieldsJSONdata:)
- Author:
Nikita Lazarev-Zubov
- Copyright:
2017 Webim
*/
public func set(visitorFieldsJSONString: String) -> SessionBuilder {
self.visitorFields = ProvidedVisitorFields(withJSONString: visitorFieldsJSONString)
return self
}
/**
A visitor can be anonymous or authorized. Without calling this method when creating a session visitor is anonymous.
In this case visitor receives a random ID, which is written in `WMKeychainWrapper`. If the data is lost (for example when application was reinstalled), the user ID is also lost, as well as the message history.
Authorizing of a visitor can be useful when there are internal mechanisms of authorization in your application and you want the message history to exist regardless of a device communication occurs from.
This method takes as a parameter a string containing the signed fields of a user in JSON format. Since the fields are necessary to be signed with a private key that can never be included into the code of a client's application, this string must be created and signed somewhere on your backend side. Read more about forming a string and a signature here: https://webim.ru/help/identification/
- important:
Can't be used simultanously with `set(providedAuthorizationTokenStateListener:providedAuthorizationToken:)`.
- parameter jsonData:
JSON-data containing the signed fields of a visitor.
- returns:
`SessionBuilder` object with visitor fields set.
- SeeAlso:
`set(visitorFieldsJSONstring:)`
- Author:
Nikita Lazarev-Zubov
- Copyright:
2017 Webim
*/
public func set(visitorFieldsJSONData: Data) -> SessionBuilder {
self.visitorFields = ProvidedVisitorFields(withJSONObject: visitorFieldsJSONData)
return self
}
/**
When client provides custom visitor authorization mechanism, it can be realised by providing custom authorization token which is used instead of visitor fields.
- important:
Can't be used simultaneously with `set(visitorFields:)`.
- parameter providedAuthorizationTokenStateListener:
`ProvidedAuthorizationTokenStateListener` object.
- parameter providedAuthorizationToken:
Optional. Client generated provided authorization token. If it is not passed, library generates its own.
- seealso:
`ProvidedAuthorizationTokenStateListener`
- attention:
This method can't be used as is. It requires that client server to support this mechanism.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(providedAuthorizationTokenStateListener: ProvidedAuthorizationTokenStateListener?,
providedAuthorizationToken: String? = nil) -> SessionBuilder {
self.providedAuthorizationTokenStateListener = providedAuthorizationTokenStateListener
self.providedAuthorizationToken = providedAuthorizationToken
return self
}
/**
Sets the page title visible to an operator. In the web version of a chat it is a title of a web page a user opens a chat from.
By default "iOS Client".
- parameter pageTitle:
Page title that visible to an operator.
- returns:
`SessionBuilder` object with page title set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(pageTitle: String?) -> SessionBuilder {
self.pageTitle = pageTitle
return self
}
/**
Sets a fatal error handler. An error is considered fatal if after processing it the session can not be continued anymore.
- parameter fatalErrorHandler:
Fatal error handler.
- returns:
`SessionBuilder` object with fatal error handler set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(fatalErrorHandler: FatalErrorHandler?) -> SessionBuilder {
self.fatalErrorHandler = fatalErrorHandler
return self
}
public func set(notFatalErrorHandler: NotFatalErrorHandler) -> SessionBuilder {
self.notFatalErrorHandler = notFatalErrorHandler
return self
}
/**
Webim service can send remote notifications when new messages are received in chat.
By default it does not. You have to handle receiving by yourself.
To differentiate notifications from your app and from Webim service check the field "from" (see `Webim.isWebim(remoteNotification:)`).
- important:
If remote notification system is set you must set device token.
- parameter remoteNotificationSystem:
Enum that indicates which system of remote notification is used. By default – `none` (remote notifications are not to be sent).
- returns:
`SessionBuilder` object with remote notification system set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(remoteNotificationSystem: Webim.RemoteNotificationSystem) -> SessionBuilder {
self.remoteNotificationSystem = remoteNotificationSystem
return self
}
/**
Sets device token.
Example that shows how to change device token for the proper formatted one:
`let deviceToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()`
- parameter deviceToken:
Device token in hexadecimal format and without any spaces and service symbols.
- returns:
`SessionBuilder` object with device token set.
- seealso:
`setRemoteNotificationsSystem`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(deviceToken: String?) -> SessionBuilder {
self.deviceToken = deviceToken
return self
}
/**
By default a session stores a message history locally. This method allows to disable history storage.
- important:
Use only for debugging!
- parameter isLocalHistoryStoragingEnabled:
Boolean parameter that indicated if an app should enable or disable local history storing.
- returns:
`SessionBuilder` object with isLocalHistoryStoragingEnabled parameter set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(isLocalHistoryStoragingEnabled: Bool) -> SessionBuilder {
self.localHistoryStoragingEnabled = isLocalHistoryStoragingEnabled
return self
}
/**
If set to true, all the visitor data is cleared before the session starts.
- important:
Use only for debugging!
- parameter isVisitorDataClearingEnabled:
Boolean parameter that indicated if an app should clear visitor data before session starts.
- returns:
`SessionBuilder` object with isVisitorDataClearingEnabled parameter set.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(isVisitorDataClearingEnabled: Bool) -> SessionBuilder {
self.visitorDataClearingEnabled = isVisitorDataClearingEnabled
return self
}
/**
If set to true, different visitors can receive remote notifications on one device.
- parameter isMultivisitor:
Boolean parameter that indicated if an app should receive remote notifications for different visitors.
- returns:
`SessionBuilder` object with isVisitorDataClearingEnabled parameter set.
- attention:
This method can't be used as is. It requires that client server to support this mechanism.
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
public func set(multivisitorSection: String) -> SessionBuilder {
self.multivisitorSection = multivisitorSection
return self
}
/**
If is set, SDK will request online status every and fire listener.
- parameter onlineStatusRequestFrequencyInMillis:
Request location frequency to server in millis.
- returns:
`SessionBuilder` object with requestLocationFrequencyInMs parameter set.
- author:
Nikita Kaberov
- copyright:
2021 Webim
*/
public func set(onlineStatusRequestFrequencyInMillis: Int64) -> SessionBuilder {
self.onlineStatusRequestFrequencyInMillis = onlineStatusRequestFrequencyInMillis
return self
}
/**
Method to pass WebimLogger object.
- parameter webimLogger:
`WebimLogger` object.
- returns:
`SessionBuilder` object with `WebimLogger` object set.
- seealso:
`WebimLogger`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func set(webimLogger: WebimLogger?,
verbosityLevel: WebimLoggerVerbosityLevel = .warning) -> SessionBuilder {
self.webimLogger = webimLogger
webimLoggerVerbosityLevel = verbosityLevel
return self
}
/**
Builds new `WebimSession` object.
- important:
All the follow-up work with the session must be implemented from the same thread this method was called in.
Notice that a session is created as a paused. To start using it the first thing to do is to call `WebimSession.resume()`.
- returns:
New `WebimSession` object.
- throws:
`SessionBuilder.SessionBuilderError.nilAccountName` if account name wasn't set to a non-nil value.
`SessionBuilder.SessionBuilderError.nilLocation` if location wasn't set to a non-nil value.
`SessionBuilder.SessionBuilderError.invalidRemoteNotificationConfiguration` if there is a try to pass device token with `RemoteNotificationSystem` not set (or set to `.none`).
`SessionBuilder.SessionBuilderError.invalidAuthentificatorParameters` if methods `set(visitorFieldsJSONString:)` or `set(visitorFieldsJSONData:)` are called with `set(providedAuthorizationTokenStateListener:,providedAuthorizationToken:)` simultaneously.
- seealso:
`SessionBuilder.SessionBuilderError`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public func build() throws -> WebimSession {
guard let accountName = accountName else {
throw SessionBuilderError.nilAccountName
}
guard let location = location else {
throw SessionBuilderError.nilLocation
}
let remoteNotificationsEnabled = (self.remoteNotificationSystem != Webim.RemoteNotificationSystem.none)
if (deviceToken != nil)
&& !remoteNotificationsEnabled {
throw SessionBuilderError.invalidRemoteNotificationConfiguration
}
if (visitorFields != nil)
&& (providedAuthorizationTokenStateListener != nil) {
throw SessionBuilderError.invalidAuthentificatorParameters
}
if let listener = providedAuthorizationTokenStateListener, self.providedAuthorizationToken == nil {
listener.update(providedAuthorizationToken: ClientSideID.generateClientSideID())
}
if var prechat = self.prechat {
if !prechat.contains(":") {
//not json or string data
if prechat.count % 2 != 0 {
throw SessionBuilderError.invalidHex
}
var byteArray = [UInt8]()
var index = prechat.startIndex
byteArray.reserveCapacity(prechat.count/2)
for _ in 0..<prechat.count / 2 {
let nextIndex = prechat.index(index, offsetBy: 2)
if let b = UInt8(prechat[index..<nextIndex], radix: 16) {
byteArray.append(b)
} else {
throw SessionBuilderError.invalidHex
}
index = nextIndex
}
let data = Data(_: byteArray)
prechat = String(data:data, encoding: .utf8)!
print("prechat parsed: \(prechat)")
}
//prechat is json or string data
if !prechat.contains("{") {
// not json
let pairs = prechat.components(separatedBy: "\\n").map{pair in
pair.split(separator: ":").map(String.init)
}
let hasError = pairs.contains { pair in
pair.count != 2
}
if hasError {
throw SessionBuilderError.invalidHex
}
let result = pairs.map { pair in
"\"\(pair[0])\": \"\(pair[1])\""
}.joined(separator: ", ")
self.prechat = "{\(result)}"
print("json: \(self.prechat ?? "{}")")
}
}
return WebimSessionImpl.newInstanceWith(accountName: accountName,
location: location,
appVersion: appVersion,
visitorFields: visitorFields,
providedAuthorizationTokenStateListener: providedAuthorizationTokenStateListener,
providedAuthorizationToken: providedAuthorizationToken,
pageTitle: pageTitle,
fatalErrorHandler: fatalErrorHandler,
notFatalErrorHandler: notFatalErrorHandler,
deviceToken: deviceToken,
remoteNotificationSystem: remoteNotificationSystem,
isLocalHistoryStoragingEnabled: localHistoryStoragingEnabled,
isVisitorDataClearingEnabled: visitorDataClearingEnabled,
webimLogger: webimLogger,
verbosityLevel: webimLoggerVerbosityLevel,
prechat: prechat,
multivisitorSection: multivisitorSection,
onlineStatusRequestFrequencyInMillis: onlineStatusRequestFrequencyInMillis) as WebimSession
}
/**
Builds new `WebimSession` object with callback
- important:
All the follow-up work with the session must be implemented from the same thread this method was called in.
Notice that a session is created as a paused. To start using it the first thing to do is to call `WebimSession.resume()`.
- parameter onSuccess:
Clousure which will be executed when session sucessfully builded.
Returns `WebimSession` object.
- parameter onError:
Clousure which will be executed when session building failed.
Returns cause of failure as `SessionBuilder.SessionBuilderError` object.
- seealso:
`build()`
`SessionBuilder.SessionBuilderError`
- author:
Yury Vozleev
- copyright:
2020 Webim
*/
public func build(onSuccess: @escaping (WebimSession) -> (),
onError: @escaping (SessionBuilder.SessionBuilderError) -> ()) {
do {
let webimSession = try self.build()
onSuccess(webimSession)
} catch let error as SessionBuilder.SessionBuilderError {
onError(error)
} catch {
onError(.unknown)
}
}
// MARK: -
/**
Verbosity level of `WebimLogger`.
- seealso:
`SessionBuilder.set(webimLogger:verbosityLevel:)`
- author:
Nikita Lazarev-Zubov
- copyright:
2018 Webim
*/
public enum WebimLoggerVerbosityLevel {
/**
All available information will be delivered to `WebimLogger` instance with maximum verbosity level:
* session network setup parameters;
* network requests' URLs, HTTP method and parameters;
* network responses' HTTP codes, received data and errors;
* SQL queries and errors;
* full debug information and additional notes.
- author:
Nikita Lazarev-Zubov
- copyright:
2018 Webim
*/
case verbose
@available(*, unavailable, renamed: "verbose")
case VERBOSE
/**
All information which is useful when debugging will be delivered to `WebimLogger` instance with necessary verbosity level:
* session network setup parameters;
* network requests' URLs, HTTP method and parameters;
* network responses' HTTP codes, received data and errors;
* SQL queries and errors;
* moderate debug information.
- author:
Nikita Lazarev-Zubov
- copyright:
2018 Webim
*/
case debug
@available(*, unavailable, renamed: "debug")
case DEBUG
/**
Reference information and all warnings and errors will be delivered to `WebimLogger` instance:
* network requests' URLS, HTTP method and parameters;
* HTTP codes and errors descriptions of failed requests.
* SQL errors.
- author:
Nikita Lazarev-Zubov
- copyright:
2018 Webim
*/
case info
@available(*, unavailable, renamed: "info")
case INFO
/**
Errors and warnings only will be delivered to `WebimLogger` instance:
* network requests' URLs, HTTP method, parameters, HTTP code and error description.
* SQL errors.
- author:
Nikita Lazarev-Zubov
- copyright:
2018 Webim
*/
case warning
@available(*, unavailable, renamed: "warning")
case WARNING
/**
Only errors will be delivered to `WebimLogger` instance:
* network requests' URLs, HTTP method, parameters, HTTP code and error description.
- author:
Nikita Lazarev-Zubov
- copyright:
2018 Webim
*/
case error
@available(*, unavailable, renamed: "error")
case ERROR
}
/**
Error types that can be thrown by `SessionBuilder` `build()` method.
- seealso:
`SessionBuilder.build()`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
public enum SessionBuilderError: Error {
/**
Error that is thrown when trying to use standard and custom visitor fields authentication simultaneously.
- seealso:
`set(visitorFieldsJSONString:)`
`set(visitorFieldsJSONData:)`
`set(providedAuthorizationTokenStateListener:providedAuthorizationToken:)`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
case invalidAuthentificatorParameters
@available(*, unavailable, renamed: "invalidAuthentificatorParameters")
case INVALID_AUTHENTICATION_PARAMETERS
/**
Error that is thrown when trying to create session object with invalid remote notifications configuration.
- seealso:
`set(remoteNotificationSystem:)`
`set(deviceToken:)`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
case invalidRemoteNotificationConfiguration
@available(*, unavailable, renamed: "invalidRemoteNotificationConfiguration")
case INVALID_REMOTE_NOTIFICATION_CONFIGURATION
/**
Error that is thrown when trying to create session object with `nil` account name.
- seealso:
`set(accountName:)`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
case nilAccountName
@available(*, unavailable, renamed: "nilAccountName")
case NIL_ACCOUNT_NAME
/**
Error that is thrown when trying to create session object with `nil` location name.
- seealso:
`set(location:)`
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
case nilLocation
@available(*, unavailable, renamed: "nilLocation")
case NIL_LOCATION
case invalidHex
@available(*, unavailable, renamed: "invalidHex")
case INVALIDE_HEX
case unknown
@available(*, unavailable, renamed: "unknown")
case UNKNOWN
}
}
// MARK: -
/**
`FAQ` builder.
- seealso:
`Webim.newFAQBuilder()`
- attention:
This class can't be used as is. It requires that client server to support this mechanism.
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
public final class FAQBuilder {
// MARK: - Properties
private var accountName: String?
private var application: String?
private var departmentKey: String?
private var language: String?
// MARK: - Methods
/**
Sets company account name in FAQ system.
- parameter accountName:
Webim account name.
- returns:
`FAQBuilder` object with account name set.
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
public func set(accountName: String) -> FAQBuilder {
self.accountName = accountName
return self
}
public func set(application: String) -> FAQBuilder {
self.application = application
return self
}
public func set(departmentKey: String) -> FAQBuilder {
self.departmentKey = departmentKey
return self
}
public func set(language: String) -> FAQBuilder {
self.language = language
return self
}
/**
Builds new `FAQ` object.
- important:
All the follow-up work with the FAQ must be implemented from the same thread this method was called in.
Notice that a FAQ is created as a paused. To start using it the first thing to do is to call `FAQ.resume()`.
- returns:
New `FAQ` object.
- throws:
`SessionBuilder.SessionBuilderError.nilAccountName` if account name wasn't set to a non-nil value.
- seealso:
`FAQBuilder.FAQBuilderError`
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
public func build() throws -> FAQ {
guard let accountName = accountName else {
throw FAQBuilderError.nilAccountName
}
return FAQImpl.newInstanceWith(accountName: accountName,
application: application,
departmentKey: departmentKey,
language: language) as FAQ
}
/**
Error types that can be thrown by `FAQBuilder` `build()` method.
- seealso:
`FAQBuilder.build()`
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
public enum FAQBuilderError: Error {
/**
Error that is thrown when trying to create faq object with `nil` account name.
- seealso:
`set(accountName:)`
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
case nilAccountName
@available(*, unavailable, renamed: "nilAccountName")
case NIL_ACCOUNT_NAME
}
}
| 362aa4c42f1ef32f15cc7c82502db1f5 | 34.535519 | 396 | 0.639336 | false | false | false | false |
Nefuln/LNAddressBook | refs/heads/master | LNAddressBook/LNAddressBook/LNAddressBookUI/Edit/View/LNDetaiTableView.swift | mit | 1 | //
// LNDetaiTableView.swift
// LNAddressBook
//
// Created by 浪漫满屋 on 2017/8/1.
// Copyright © 2017年 com.man.www. All rights reserved.
//
import UIKit
import Contacts
class LNDetaiTableView: UITableView {
// MARK:- Public property
var contact: CNContact?
var detailPhoneBlock: ((_ phone: String) -> Void)?
var sendSmsBlock: (([[String : String]]) -> Void)?
var scrollBlock: ((_ contentOffset: CGPoint) -> Void)?
// MARK:- Public func
public func reload(with contact: CNContact) {
self.contact = contact
self.reloadData()
}
// MARK:- Override
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- Private func
private func initUI() {
tableFooterView = UIView()
separatorStyle = .none
register(LNDetailPhoneCell.self, forCellReuseIdentifier: NSStringFromClass(LNDetailPhoneCell.self))
register(LNDetailCommonCell.self, forCellReuseIdentifier: NSStringFromClass(LNDetailCommonCell.self))
dataSource = self
delegate = self
}
}
extension LNDetaiTableView: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contact?.mPhones == nil ? 1 : (self.contact?.mPhones!.count)! + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row < (self.contact?.mPhones?.count)! {
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(LNDetailPhoneCell.self), for: indexPath) as! LNDetailPhoneCell
cell.titleLabel.text = self.contact?.mPhones?[indexPath.row].keys.first
var phone = self.contact?.mPhones?[indexPath.row].values.first
if !(phone?.contains("-"))! {
phone?.insert("-", at: (phone?.index((phone?.startIndex)!, offsetBy: 3))!)
phone?.insert("-", at: (phone?.index((phone?.startIndex)!, offsetBy: 7))!)
}
cell.phoneLabel.text = phone
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(LNDetailCommonCell.self), for: indexPath) as! LNDetailCommonCell
switch indexPath.row - (self.contact?.mPhones?.count)! {
case 0:
cell.titleLabel.text = "发送信息"
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row < (self.contact?.mPhones?.count)! && (detailPhoneBlock != nil) {
detailPhoneBlock!((tableView.cellForRow(at: indexPath) as! LNDetailPhoneCell).phoneLabel.text!)
}
if indexPath.row - (self.contact?.mPhones?.count)! == 0 && sendSmsBlock != nil {
sendSmsBlock!((self.contact?.mPhones)!)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollBlock != nil {
scrollBlock!(self.contentOffset)
}
}
}
| 5196e1d13e12903f25b3b226906a0e64 | 34.540816 | 149 | 0.627046 | false | false | false | false |
Cleverlance/Pyramid | refs/heads/master | Example/Tests/Architecture Concepts/BasePresenterImplTests.swift | mit | 1 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
import XCTest
import Nimble
import Pyramid
class BasePresenterImplTests: XCTestCase {
func test_ItConformsToPresenter() {
let _: Presenter? = (nil as BasePresenterImpl<View>?)
}
func test_active_WhenInitialised_ItShouldBeFalse() {
let presenter = BasePresenterImpl<View>()
expect(presenter.isActive).to(beFalse())
}
func test_ItShouldNotKeepStrongReferenceOnView() {
let presenter = BasePresenterImpl<View>()
presenter.view = ViewDummy()
expect(presenter.view).to(beNil())
}
func test_ItShouldKeepReferenceOnView() {
let view = ViewDummy()
let presenter = BasePresenterImpl<View>()
presenter.view = view
expect(presenter.view).notTo(beNil())
}
}
private class ViewDummy: View {}
| 4f09f1fe619a6893c2ccc5b335468c27 | 23.571429 | 61 | 0.663953 | false | true | false | false |
ccrama/Slide-iOS | refs/heads/master | Slide for Reddit/SettingsBackup.swift | apache-2.0 | 1 | //
// SettingsBackup
// Slide for Reddit
//
// Created by Carlos Crane on 6/11/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import BiometricAuthentication
import LicensesViewController
import RealmSwift
import RLBAlertsPickers
import SDWebImage
import UIKit
class SettingsBackup: BubbleSettingTableViewController {
static var changed = false
var restore: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: nil)
var backup: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: nil)
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setToolbarHidden(true, animated: false)
doCells()
}
override func loadView() {
super.loadView()
}
func doCells(_ reset: Bool = true) {
self.view.backgroundColor = ColorUtil.theme.backgroundColor
// set the title
self.title = "Backup"
self.tableView.separatorStyle = .none
self.backup.textLabel?.text = "Backup"
self.backup.detailTextLabel?.text = "Backup your Slide data to iCloud"
self.backup.backgroundColor = ColorUtil.theme.foregroundColor
self.backup.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.backup.textLabel?.textColor = ColorUtil.theme.fontColor
self.backup.imageView?.image = UIImage.init(sfString: SFSymbol.squareAndArrowDownFill, overrideString: "download")?.toolbarIcon().getCopy(withColor: ColorUtil.theme.fontColor)
self.backup.imageView?.tintColor = ColorUtil.theme.fontColor
self.restore.textLabel?.text = "Restore"
self.restore.backgroundColor = ColorUtil.theme.foregroundColor
self.restore.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.restore.textLabel?.textColor = ColorUtil.theme.fontColor
self.restore.detailTextLabel?.text = "Restore your backup data from iCloud"
self.restore.imageView?.image = UIImage(sfString: SFSymbol.arrowClockwise, overrideString: "restore")?.toolbarIcon().getCopy(withColor: ColorUtil.theme.fontColor)
self.restore.imageView?.tintColor = ColorUtil.theme.fontColor
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension SettingsBackup {
func doBackup() {
let alert = UIAlertController.init(title: "Really back up your data?", message: "This will overwrite any previous backups", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in
self.backupSync()
}))
alert.addAction(UIAlertAction.init(title: "No", style: .cancel, handler: { (_) in
}))
present(alert, animated: true)
}
func doRestore() {
let alert = UIAlertController.init(title: "Really restore your data?", message: "This will overwrite all current Slide settings and you will have to restart Slide for the changes to take place", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in
self.restoreSync()
}))
alert.addAction(UIAlertAction.init(title: "No", style: .cancel, handler: { (_) in
}))
present(alert, animated: true)
}
func backupSync() {
let icloud = NSUbiquitousKeyValueStore.default
for item in icloud.dictionaryRepresentation {
icloud.removeObject(forKey: item.key)
}
for item in UserDefaults.standard.dictionaryRepresentation() {
if item.key.utf8.count < 64 {
icloud.set(item.value, forKey: item.key)
}
}
icloud.synchronize()
let alert = UIAlertController.init(title: "Your data has been synced!", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .cancel, handler: { (_) in
self.dismiss(animated: true, completion: nil)
}))
present(alert, animated: true)
}
func restoreSync() {
let icloud = NSUbiquitousKeyValueStore.default
for item in icloud.dictionaryRepresentation {
print(item)
UserDefaults.standard.set(item.value, forKey: item.key)
}
UserDefaults.standard.synchronize()
let alert = UIAlertController.init(title: "Your data has been restored!", message: "Slide will now close to apply changes", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close Slide", style: .cancel, handler: { (_) in
exit(0)
}))
present(alert, animated: true)
}
}
// MARK: - UITableView
extension SettingsBackup {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return self.backup
case 1: return self.restore
default: fatalError("Unknown row in section 0")
}
default: fatalError("Unknown section")
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
doBackup()
} else {
doRestore()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 2
default: fatalError("Unknown number of sections")
}
}
}
| 8dee9fdf890f3ce527a0894d88ad419c | 36.961039 | 226 | 0.658057 | false | false | false | false |
noppoMan/swifty-libuv | refs/heads/master | Sources/FileWriter.swift | mit | 1 | //
// FileWriter.swift
// SwiftyLibuv
//
// Created by Yuki Takei on 6/12/16.
//
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
import CLibUv
import Foundation
private class FileWriterContext {
var writeReq: UnsafeMutablePointer<uv_fs_t>? = nil
var onWrite: ((Void) throws -> Void) -> Void = {_ in }
var bytesWritten: Int64 = 0
var data: Data
var buf: uv_buf_t? = nil
let loop: Loop
let fd: Int32
let offset: Int // Not implemented yet
var length: Int? // Not implemented yet
var position: Int
var curPos: Int {
return position + Int(bytesWritten)
}
init(loop: Loop = Loop.defaultLoop, fd: Int32, data: Data, offset: Int, length: Int? = nil, position: Int, completion: @escaping ((Void) throws -> Void) -> Void){
self.loop = loop
self.fd = fd
self.data = data
self.offset = offset
self.length = length
self.position = position
self.onWrite = completion
}
}
public class FileWriter {
private var context: FileWriterContext
public init(loop: Loop = Loop.defaultLoop, fd: Int32, data: Data, offset: Int, length: Int? = nil, position: Int, completion: @escaping ((Void) throws -> Void) -> Void){
context = FileWriterContext(
loop: loop,
fd: fd,
data: data,
offset: offset,
length: length,
position: position,
completion: completion
)
}
public func start(){
if(context.data.count <= 0) {
return context.onWrite {}
}
attemptWrite(context)
}
}
private func attemptWrite(_ context: FileWriterContext){
var writeReq = UnsafeMutablePointer<uv_fs_t>.allocate(capacity: MemoryLayout<uv_fs_t>.size)
var bytes = context.data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) in
UnsafeMutablePointer(mutating: UnsafeRawPointer(bytes).assumingMemoryBound(to: Int8.self))
}
context.buf = uv_buf_init(bytes, UInt32(context.data.count))
withUnsafePointer(to: &context.buf!) {
writeReq.pointee.data = retainedVoidPointer(context)
let r = uv_fs_write(context.loop.loopPtr, writeReq, uv_file(context.fd), $0, UInt32(context.buf!.len), Int64(context.curPos)) { req in
if let req = req {
onWriteEach(req)
}
}
if r < 0 {
defer {
fs_req_cleanup(writeReq)
}
context.onWrite {
throw UVError.rawUvError(code: r)
}
return
}
}
}
private func onWriteEach(_ req: UnsafeMutablePointer<uv_fs_t>){
defer {
fs_req_cleanup(req)
}
let context: FileWriterContext = releaseVoidPointer(req.pointee.data)
if(req.pointee.result < 0) {
return context.onWrite {
throw UVError.rawUvError(code: Int32(req.pointee.result))
}
}
if(req.pointee.result == 0) {
return context.onWrite {}
}
context.bytesWritten += req.pointee.result
if Int(context.bytesWritten) >= Int(context.data.count) {
return context.onWrite {}
}
attemptWrite(context)
}
| 423d224e7569ddc6068f97e99941a889 | 24.189394 | 173 | 0.573835 | false | false | false | false |
laurentVeliscek/AudioKit | refs/heads/master | AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Filter Envelope.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Filter Envelope
//:
//: ### This is a pretty advanced example.
import XCPlayground
import AudioKit
enum SynthParameter: Int {
case Frequency, Cutoff, Gate
}
struct Synth {
static var frequency: AKOperation {
return AKOperation.parameters[SynthParameter.Frequency.rawValue]
}
static var cutoff: AKOperation {
return AKOperation.parameters[SynthParameter.Cutoff.rawValue]
}
static var gate: AKOperation {
return AKOperation.parameters[SynthParameter.Gate.rawValue]
}
}
extension AKOperationGenerator {
var frequency: Double {
get { return self.parameters[SynthParameter.Frequency.rawValue] }
set(newValue) { self.parameters[SynthParameter.Frequency.rawValue] = newValue }
}
var cutoff: Double {
get { return self.parameters[SynthParameter.Cutoff.rawValue] }
set(newValue) { self.parameters[SynthParameter.Cutoff.rawValue] = newValue }
}
var gate: Double {
get { return self.parameters[SynthParameter.Gate.rawValue] }
set(newValue) { self.parameters[SynthParameter.Gate.rawValue] = newValue }
}
}
let synth = AKOperationGenerator() { parameters in
let oscillator = AKOperation.fmOscillator(
baseFrequency: Synth.frequency,
carrierMultiplier: 3,
modulatingMultiplier: 0.7,
modulationIndex: 2,
amplitude: 0.1)
let cutoff = Synth.cutoff.gatedADSREnvelope(
gate: Synth.gate,
attack: 0.1,
decay: 0.01,
sustain: 1,
release: 0.6)
return oscillator.moogLadderFilter(cutoffFrequency: cutoff,
resonance: 0.9)
}
AudioKit.output = synth
AudioKit.start()
synth.parameters = [0, 1000, 0] // Initialize the array
synth.start()
//: Setup the user interface
let playgroundWidth = 500
class PlaygroundView: AKPlaygroundView, AKKeyboardDelegate {
override func setup() {
addTitle("Filter Envelope")
addSubview(AKPropertySlider(
property: "Cutoff Frequency",
format: "%0.1f Hz",
value: synth.cutoff, maximum: 5000,
color: AKColor.redColor()
) { frequency in
synth.cutoff = frequency
})
let keyboard = AKKeyboardView(width: playgroundWidth - 60,
height: 100)
keyboard.delegate = self
addSubview(keyboard)
}
func noteOn(note: MIDINoteNumber) {
synth.frequency = note.midiNoteToFrequency()
synth.gate = 1
}
func noteOff(note: MIDINoteNumber) {
synth.gate = 0
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
| 636a3ac0f1ec1f6e2ac86451774dd66b | 26.876289 | 87 | 0.654216 | false | false | false | false |
LYM-mg/MGDYZB | refs/heads/master | MGDYZB简单封装版/MGDYZB/Class/Home/View/HomeContentView.swift | mit | 1 | //
// HomeContentView.swift
// MGDYZB
//
// Created by ming on 16/10/25.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
//
import UIKit
protocol HomeContentViewDelegate : class {
func HomeContentViewDidScroll(_ contentView : HomeContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentCellID = "ContentCellID"
class HomeContentView: UIView {
// MARK:- 定义属性
fileprivate var childVcs : [UIViewController]
weak var parentViewController : UIViewController? /** 当前显示的父控制器 */
fileprivate var startOffsetX : CGFloat = 0
fileprivate var isForbidScrollDelegate : Bool = false
weak var delegate : HomeContentViewDelegate?
// MARK:- 懒加载属性
fileprivate lazy var collectionView : UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.scrollsToTop = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
// MARK:- 自定义构造函数
init(frame: CGRect, childVcs: [UIViewController], parentViewController : UIViewController?) {
self.childVcs = childVcs
self.parentViewController = parentViewController
super.init(frame: frame)
setUpMainView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 初始化UI
extension HomeContentView {
fileprivate func setUpMainView() {
// 1.将所有的子控制器添加父控制器中
for childVc in childVcs {
parentViewController?.addChild(childVc)
}
// 2.添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:- UICollectionViewDataSource
extension HomeContentView: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@available(iOS 6.0, *)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
@available(iOS 6.0, *)
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.创建Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) as UICollectionViewCell
// 2.给Cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVc = childVcs[(indexPath as NSIndexPath).item]
childVc.view.frame = cell.contentView.bounds
childVc.view.backgroundColor = UIColor.randomColor()
cell.contentView.addSubview(childVc.view)
return cell
}
}
// MARK:- 遵守UICollectionViewDelegate
extension HomeContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate { return }
// 1.定义获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex : Int = 0
// 2.判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count {
targetIndex = childVcs.count - 1
}
// 4.如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
} else { // 右滑
// 1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3.计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count {
sourceIndex = childVcs.count - 1
}
}
// 3.将progress/sourceIndex/targetIndex传递给titleView
delegate?.HomeContentViewDidScroll(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
// MARK:- 对外暴露的方法
extension HomeContentView {
func setCurrentIndex(_ currentIndex : Int) {
// 1.记录需要进制执行代理方法
isForbidScrollDelegate = true
// 2.滚动正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| 4d2352150ed1aed90ae4f3bc6c9b1edc | 32.227778 | 129 | 0.641364 | false | false | false | false |
Carthage/PrettyColors | refs/heads/master | Source/StyleParameter.swift | mit | 1 | /// Based on: ECMA-048 — 8.3.117
public enum StyleParameter: UInt8, Parameter {
// Reference: Terminal Support Table: https://github.com/jdhealy/PrettyColors/wiki/Terminal-Support
case Bold = 01 // bold or increased intensity
case Faint = 02 // faint, decreased intensity or second colour
case Italic = 03 // italicized
case Underlined = 04 // singly underlined
case BlinkSlow = 05 // slowly blinking (less then 150 per minute)
case Blink = 06 // rapidly blinking (150 per minute or more)
case Negative = 07 // negative image — a.k.a. Inverse
case Concealed = 08 // concealed characters
case CrossedOut = 09 // (characters still legible but marked as to be deleted)
case Font1 = 11
case Font2 = 12
case Font3 = 13
case Font4 = 14
case Font5 = 15
case Font6 = 16
case Font7 = 17
case Font8 = 18
case Font9 = 19
case Fraktur = 20 // Gothic
case UnderlinedDouble = 21 // doubly underlined
case Normal = 22 // normal colour or normal intensity (neither bold nor faint)
case Positive = 27 // positive image
case Revealed = 28 // revealed characters
case Framed = 51
case Encircled = 52
case Overlined = 53
public struct Reset {
/// Some parameters have corresponding resets,
/// but all parameters are reset by `defaultRendition`
public static let dictionary: [UInt8: UInt8] = [
03: 23, 04: 24, 05: 25, 06: 25, 11: 10,
12: 10, 13: 10, 14: 10, 15: 10, 16: 10,
17: 10, 18: 10, 19: 10, 20: 23, 51: 54,
52: 54, 53: 55
]
/// “cancels the effect of any preceding occurrence of SGR in the data stream”
public static let defaultRendition: UInt8 = 0
}
public var code: (enable: [UInt8], disable: UInt8?) {
return ( [self.rawValue], Reset.dictionary[self.rawValue] )
}
}
| 3ac6ad4fd0832dcbfa59e203cae8159c | 40.291667 | 100 | 0.601413 | false | false | false | false |
shaps80/Peek | refs/heads/master | Example/NotTwitter/Theming.swift | mit | 1 | //
// Theming.swift
// NotTwitter
//
// Created by Shaps Benkau on 10/03/2018.
// Copyright © 2018 Snippex. All rights reserved.
//
import UIKit
extension UIColor {
public static var separator: UIColor {
return UIColor(red: 189/255, green: 198/255, blue: 205/255, alpha: 1)
}
public static var background: UIColor {
return .white
}
public static var selection: UIColor {
return UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
}
}
public struct Theme {
public static func apply() {
let bar = UINavigationBar.appearance()
bar.barTintColor = .background
bar.titleTextAttributes = [
.foregroundColor: UIColor(red: 21/255, green: 23/255, blue: 26/255, alpha: 1),
.font: UIFont.systemFont(ofSize: 16, weight: .black)
]
let table = UITableView.appearance()
table.backgroundColor = .background
table.separatorColor = .separator
}
}
| defa125133d8bd150c3c30de1cc31d91 | 22.340909 | 90 | 0.588121 | false | false | false | false |
devpunk/cartesian | refs/heads/master | cartesian/Model/DrawList/MDrawListItemNode.swift | mit | 1 | import UIKit
class MDrawListItemRender
{
private static let kZoom:CGFloat = 1
private static let kMargin:CGFloat = 20
private static let kSelected:Bool = false
class func renderNode(node:DNode, context:CGContext)
{
let margin2:CGFloat = kMargin + kMargin
let originalX:CGFloat = CGFloat(node.centerX)
let originalY:CGFloat = CGFloat(node.centerY)
let widthOriginal:CGFloat = CGFloat(node.width)
let heightOriginal:CGFloat = CGFloat(node.height)
let widthOriginal_2:CGFloat = widthOriginal / 2.0
let heightOriginal_2:CGFloat = heightOriginal / 2.0
let positionedOriginalX:CGFloat = originalX - widthOriginal_2
let positionedOriginalY:CGFloat = originalY - heightOriginal_2
let positionedX:CGFloat = positionedOriginalX - kMargin
let positionedY:CGFloat = positionedOriginalY - kMargin
let widthExpanded:CGFloat = widthOriginal + margin2
let heightExpanded:CGFloat = heightOriginal + margin2
let rect:CGRect = CGRect(
x:positionedX,
y:positionedY,
width:widthExpanded,
height:heightExpanded)
node.draw(
rect:rect,
context:context,
zoom:kZoom,
selected:kSelected)
}
}
| f2ec86aaaaf093bce1ed002ea90730f7 | 34.918919 | 70 | 0.64936 | false | false | false | false |
aliceatlas/daybreak | refs/heads/master | Classes/SBBookmarks.swift | bsd-2-clause | 1 | /*
SBBookmarks.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
//typealias BookmarkItem = [String: Any]
typealias BookmarkItem = NSDictionary
class SBBookmarks: NSObject {
static let sharedBookmarks = SBBookmarks()
var items: [NSMutableDictionary] = []
override init() {
super.init()
readFromFile()
}
// MARK: Getter
func containsURL(URLString: String) -> Bool {
return indexOfURL(URLString) != NSNotFound
}
func indexOfURL(URLString: String) -> Int {
return items.firstIndex({ $0[kSBBookmarkURL] as! String == URLString }) ?? NSNotFound
}
func isEqualBookmarkItems(item1: BookmarkItem, anotherItem item2: BookmarkItem) -> Bool {
return
(item1[kSBBookmarkTitle] as! String) == (item2[kSBBookmarkTitle] as! String) &&
(item1[kSBBookmarkURL] as! String) == (item2[kSBBookmarkURL] as! String) &&
(item1[kSBBookmarkImage] as! NSData) == (item2[kSBBookmarkImage] as! NSData)
}
func itemAtIndex(index: Int) -> BookmarkItem? {
return items.get(index)
}
func containsItem(bookmarkItem: BookmarkItem) -> Int {
if let i = items.firstIndex({ self.isEqualBookmarkItems($0, anotherItem: bookmarkItem) }) {
return i
}
return NSNotFound
}
func indexOfItem(bookmarkItem: BookmarkItem) -> Int {
if let i = items.firstIndex({ $0 === bookmarkItem }) {
return i
}
return NSNotFound
}
func indexesOfItems(bookmarkItems: [BookmarkItem]) -> NSIndexSet {
let indexes = NSMutableIndexSet()
for bookmarkItem in bookmarkItems {
let index = indexOfItem(bookmarkItem)
if index != NSNotFound {
indexes.addIndex(index)
}
}
return indexes
}
// MARK: Notify
func notifyDidUpdate() {
NSNotificationCenter.defaultCenter().postNotificationName(SBBookmarksDidUpdateNotification, object: self)
}
// MARK: Actions
func readFromFile() -> Bool {
if kSBCountOfDebugBookmarks > 0 {
for index in 0..<kSBCountOfDebugBookmarks {
let title = "Title \(index)"
let URL = "http://\(index).com/"
let item = SBCreateBookmarkItem(title, URL, SBEmptyBookmarkImageData, NSDate(), nil, NSStringFromPoint(.zero))
items.append(NSMutableDictionary(dictionary: item))
}
} else {
let info = NSDictionary(contentsOfFile: SBBookmarksFilePath!)
if let bookmarkItems = (info?[kSBBookmarkItems] as? [BookmarkItem])?.ifNotEmpty {
items = bookmarkItems.map { NSMutableDictionary(dictionary: $0 as! [NSObject: AnyObject]) }
return true
}
}
return false
}
func writeToFile() -> Bool {
var r = false
if !items.isEmpty {
let path = SBBookmarksFilePath!
do {
let data = try NSPropertyListSerialization.dataWithPropertyList(
SBBookmarksWithItems(items), format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0)
r = data.writeToFile(path, atomically: true)
} catch let error as NSError {
DebugLog("%@ error = %@", __FUNCTION__, error)
}
}
return r
}
func addItem(bookmarkItem: BookmarkItem?) {
if let item = bookmarkItem {
let dict = NSMutableDictionary(dictionary: item)
let index = indexOfURL(dict[kSBBookmarkURL] as! String)
if index == NSNotFound {
items.append(dict)
} else {
items[index] = dict
}
writeToFile()
SBDispatch(notifyDidUpdate)
}
}
func replaceItem(item: BookmarkItem, atIndex index: Int) {
items[index] = NSMutableDictionary(dictionary: item)
writeToFile()
SBDispatch(notifyDidUpdate)
}
func replaceItem(oldItem: BookmarkItem, withItem newItem: BookmarkItem) {
let index = indexOfItem(oldItem)
if index != NSNotFound {
items[index] = NSMutableDictionary(dictionary: newItem)
writeToFile()
SBDispatch(notifyDidUpdate)
}
}
func addItems(inItems: [BookmarkItem], toIndex: Int) {
if !inItems.isEmpty && toIndex <= items.count {
//[items insertObjects:inItems atIndexes:[NSIndexSet indexSetWithIndex:toIndex]];
for (i, item) in enumerate(inItems) {
items.insert(NSMutableDictionary(dictionary: item as! [NSObject: AnyObject]), atIndex: i + toIndex)
}
writeToFile()
SBDispatch(notifyDidUpdate)
}
}
func moveItemsAtIndexes(indexes: NSIndexSet, toIndex: Int) {
/*
NSArray *bookmarkItems = [items objectsAtIndexes:indexes];
if ([bookmarkItems count] > 0 && toIndex <= [items count])
{
NSUInteger to = toIndex;
NSUInteger offset = 0;
NSUInteger i = 0;
for (i = [indexes lastIndex]; i != NSNotFound; i = [indexes indexLessThanIndex:i])
{
if (i < to)
offset++;
}
if (to >= offset)
{
to -= offset;
}
[bookmarkItems retain];
[items removeObjectsAtIndexes:indexes];
[items insertObjects:bookmarkItems atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(to, [indexes count])]];
[bookmarkItems release];
[self writeToFile];
[self performSelector:@selector(notifyDidUpdate) withObject:nil afterDelay:0];
}
*/
}
func removeItemsAtIndexes(indexes: NSIndexSet) {
items.removeObjectsAtIndexes(indexes)
writeToFile()
SBDispatch(notifyDidUpdate)
}
func doubleClickItemsAtIndexes(indexes: NSIndexSet) {
let selectedItems = items.objectsAtIndexes(indexes)
openItemsInSelectedDocument(selectedItems)
}
func changeLabelName(labelName: String, atIndexes indexes: NSIndexSet) {
indexes.enumerateIndexesWithOptions(.Reverse) {
(index: Int, _) in
self.items[index][kSBBookmarkLabelName] = labelName
return
}
writeToFile()
SBDispatch(notifyDidUpdate)
}
// MARK: Exec
func openItemsFromMenuItem(menuItem: NSMenuItem) {
if let representedItems = (menuItem.representedObject as! [BookmarkItem]).ifNotEmpty {
openItemsInSelectedDocument(representedItems)
}
}
func openItemsInSelectedDocument(inItems: [BookmarkItem]) {
if let selectedDocument = SBGetSelectedDocument {
selectedDocument.openAndConstructTab(bookmarkItems: inItems)
}
}
func removeItemsFromMenuItem(menuItem: NSMenuItem) {
let representedIndexes = menuItem.representedObject as! NSIndexSet
if representedIndexes.count > 0 {
removeItemsAtIndexes(representedIndexes)
}
}
func changeLabelFromMenuItem(menuItem: NSMenuItem) {
let representedIndexes = menuItem.representedObject as! NSIndexSet
let tag = menuItem.menu!.indexOfItem(menuItem)
if representedIndexes.count > 0 && tag < SBBookmarkLabelColorNames.count {
let labelName = SBBookmarkLabelColorNames[tag]
changeLabelName(labelName, atIndexes: representedIndexes)
}
}
} | b89cb53d40aeb351f6c78efc91a5edbf | 34.92 | 131 | 0.626684 | false | false | false | false |
CCRogerWang/ReactiveWeatherExample | refs/heads/master | 10-combining-operators-in-practice/final/OurPlanet/Pods/RxSwift/RxSwift/Observables/Implementations/Sample.swift | apache-2.0 | 11 | //
// Sample.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SamplerSink<O: ObserverType, SampleType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias E = SampleType
typealias Parent = SampleSequenceSink<O, SampleType>
fileprivate let _parent: Parent
var _lock: NSRecursiveLock {
return _parent._lock
}
init(parent: Parent) {
_parent = parent
}
func on(_ event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<E>) {
switch event {
case .next:
if let element = _parent._element {
_parent._element = nil
_parent.forwardOn(.next(element))
}
if _parent._atEnd {
_parent.forwardOn(.completed)
_parent.dispose()
}
case .error(let e):
_parent.forwardOn(.error(e))
_parent.dispose()
case .completed:
if let element = _parent._element {
_parent._element = nil
_parent.forwardOn(.next(element))
}
if _parent._atEnd {
_parent.forwardOn(.completed)
_parent.dispose()
}
}
}
}
class SampleSequenceSink<O: ObserverType, SampleType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias Parent = Sample<Element, SampleType>
fileprivate let _parent: Parent
let _lock = NSRecursiveLock()
// state
fileprivate var _element = nil as Element?
fileprivate var _atEnd = false
fileprivate let _sourceSubscription = SingleAssignmentDisposable()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
_sourceSubscription.setDisposable(_parent._source.subscribe(self))
let samplerSubscription = _parent._sampler.subscribe(SamplerSink(parent: self))
return Disposables.create(_sourceSubscription, samplerSubscription)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
_element = element
case .error:
forwardOn(event)
dispose()
case .completed:
_atEnd = true
_sourceSubscription.dispose()
}
}
}
class Sample<Element, SampleType> : Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _sampler: Observable<SampleType>
init(source: Observable<Element>, sampler: Observable<SampleType>) {
_source = source
_sampler = sampler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| d1b34a71deda3b920d4c8899d3e1ae19 | 25.975806 | 144 | 0.583857 | false | false | false | false |
xmartlabs/Bender | refs/heads/master | Sources/Adapters/Tensorflow/TFWeightData.swift | mit | 1 | //
// TFWeightData.swift
// Bender
//
// Created by Mathias Claassen on 5/19/17.
//
//
import Foundation
/// Internal struct used to pass weights and bias data around
struct TFWeightData {
let weights: Data?
let bias: Data?
let weightShape: Tensorflow_TensorShapeProto
let useBias: Bool
static func getWeightData(node: TFNode) -> TFWeightData? {
let varInputs = node.incomingNodes().cleanMap { ($0 as? TFNode) }.filter { $0.nodeDef.isTFVariableOrConstOp }
var weightsVar: TFNode
var biasVar: TFNode?
if varInputs.count == 1 {
weightsVar = varInputs[0]
} else if varInputs.count == 2 {
if varInputs[0].nodeDef.shape?.isBias == true {
biasVar = varInputs[0]
weightsVar = varInputs[1]
} else if varInputs[1].nodeDef.shape?.isBias == true {
biasVar = varInputs[1]
weightsVar = varInputs[0]
} else {
if varInputs[0].nodeDef.shape?.dim.count == 4 && varInputs[1].nodeDef.shape!.dim.isEmpty {
weightsVar = varInputs[0]
} else if varInputs[1].nodeDef.shape?.dim.count == 4 && varInputs[0].nodeDef.shape!.dim.isEmpty {
weightsVar = varInputs[1]
} else {
fatalError("Conv2D(Transpose) must have 1 or 2 Variable input and one of them must be a bias")
}
}
} else {
fatalError("Conv2D(Transpose) must have 1 or 2 Variable input")
}
guard let shape = weightsVar.nodeDef.shape else {
fatalError("Conv2D(Transpose) has no shape information")
}
var weights: Data?
var bias: Data?
if weightsVar.nodeDef.isTFConstOp {
weights = weightsVar.nodeDef.valueData()
} else if let weightsNode = weightsVar.incomingNodes().first as? TFNode, weightsNode.nodeDef.isTFConstOp {
weights = weightsNode.nodeDef.valueData()
}
if biasVar?.nodeDef.isTFConstOp == true {
bias = biasVar?.nodeDef.valueData()
} else if let biasNode = biasVar?.incomingNodes().first as? TFNode {
bias = biasNode.nodeDef.valueData()
}
return TFWeightData(weights: weights, bias: bias, weightShape: shape, useBias: biasVar != nil)
}
}
| fdb57e474d6e5731bd2aa61787d8cb36 | 33.955882 | 117 | 0.584771 | false | false | false | false |
rlopezdiez/RLDNavigationSwift | refs/heads/master | Sample app/Navigation prototype/Navigation setup/RLDNavigationSetup+URLs.swift | apache-2.0 | 1 | import UIKit
import RLDNavigationSwift
extension RLDNavigationSetup {
static let pathComponentToDestination = [
"menu" : "NavigationPrototype.RLDMenuViewController",
"folder" : "NavigationPrototype.RLDFolderViewController",
"connections" : "NavigationPrototype.RLDConnectionsViewController",
"chat" : "NavigationPrototype.RLDChatViewController",
"profile" : "NavigationPrototype.RLDProfileViewController",
"contact": "NavigationPrototype.RLDContactCardViewController"]
init(url:String, navigationController:UINavigationController) {
self.origin = NSStringFromClass(navigationController.topViewController!.dynamicType)
self.navigationController = navigationController
self.destination = ""
self.properties = nil
self.breadcrumbs = nil
if let urlComponents = NSURLComponents(string:url),
let path = urlComponents.path {
let pathComponents = path.componentsSeparatedByString("/")
var breadcrumbs = breadcrumbsFor(pathComponents:pathComponents)
if breadcrumbs.count > 0 {
self.destination = breadcrumbs.removeLast()
self.properties = propertiesWith(query:urlComponents.query)
self.breadcrumbs = breadcrumbs
}
}
}
private func breadcrumbsFor(pathComponents pathComponents:[String]) -> [String] {
var breadcrumbs:[String] = []
for pathComponent in pathComponents {
if let destination = self.dynamicType.pathComponentToDestination[pathComponent] {
breadcrumbs.append(destination)
} else {
return []
}
}
return breadcrumbs
}
private func propertiesWith(query query:String?) -> [String:AnyObject]? {
if let query = query {
var properties:[String:AnyObject] = [:]
var keyOrValue: NSString?, key: String?, value: String?
let controlCharacters = NSCharacterSet(charactersInString:"&?=")
let queryScanner = NSScanner(string:query)
queryScanner.charactersToBeSkipped = controlCharacters
while queryScanner.scanUpToCharactersFromSet(controlCharacters,intoString:&keyOrValue) {
value = key != nil
? String(keyOrValue!)
: nil
key = key ?? String(keyOrValue!)
if (key != nil && value != nil) {
properties[key!] = value
key = nil
value = nil
}
}
return properties;
}
return nil
}
} | f1f7a956d24b8acf482f6cd255101f99 | 38.169014 | 100 | 0.591367 | false | false | false | false |
MagicTheGathering/mtg-sdk-swift | refs/heads/master | MTGSDKSwift/Models/Constants.swift | mit | 1 | //
// Constants.swift
// MTGSDKSwift
//
// Created by Reed Carson on 4/16/18.
// Copyright © 2018 Reed Carson. All rights reserved.
//
import Foundation
struct Constants {
static let baseEndpoint = "https://api.magicthegathering.io/v1"
static let generateBoosterPath = "/booster"
static let cardsEndpoint = "/v1/cards"
static let setsEndpoint = "/v1/sets"
static let host = "api.magicthegathering.io"
static let scheme = "https"
static let defaultPageSize = "12"
static let defaultPageTotal = "1"
}
/// If logging is enabled, this function performs debug logging to the console for you with the
/// context of where it came from.
/// ## Example
/// ```
/// [MTGAPIService.swift:67:performOperation(completion:)]: MTGSDK HTTPResponse - status code: 200
/// ```
///
/// - Parameters:
/// - message: The message you'd like logged.
/// - file: The message source code file.
/// - function: The message source function.
/// - line: The message source line.
func debugPrint(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) {
guard Magic.enableLogging else {
return
}
print("[\((file as NSString).lastPathComponent):\(line):\(function)]: \(message)")
}
| 1a0c2417773573636cfd656e03ab1cd7 | 31.179487 | 108 | 0.669323 | false | false | false | false |
yasuoza/SAHistoryNavigationViewController | refs/heads/master | SAHistoryNavigationViewController/SAHistoryNavigationTransitionController.swift | mit | 1 | //
// SAHistoryNavigationTransitionController.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/05/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
class SAHistoryNavigationTransitionController: NSObject, UIViewControllerAnimatedTransitioning {
private(set) var navigationControllerOperation: UINavigationControllerOperation
private var currentTransitionContext: UIViewControllerContextTransitioning?
private var backgroundView: UIView?
private var alphaView: UIView?
private let kDefaultScale: CGFloat = 0.8
private let kDefaultDuration: NSTimeInterval = 0.3
required init(operation: UINavigationControllerOperation) {
navigationControllerOperation = operation
super.init()
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return kDefaultDuration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let toViewContoller = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let fromViewContoller = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
currentTransitionContext = transitionContext
let containerView = transitionContext.containerView()
if let fromView = fromViewContoller?.view, toView = toViewContoller?.view {
switch navigationControllerOperation {
case .Push:
pushAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .Pop:
popAnimation(transitionContext, toView: toView, fromView: fromView, containerView: containerView)
case .None:
let cancelled = transitionContext.transitionWasCancelled()
transitionContext.completeTransition(!cancelled)
}
}
}
}
//MARK: - Internal Methods
extension SAHistoryNavigationTransitionController {
func forceFinish() {
let navigationControllerOperation = self.navigationControllerOperation
if let backgroundView = backgroundView, alphaView = alphaView {
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64((kDefaultDuration + 0.1) * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue()) { [weak self] in
if let currentTransitionContext = self?.currentTransitionContext {
let toViewContoller = currentTransitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let fromViewContoller = currentTransitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
if let fromView = fromViewContoller?.view, toView = toViewContoller?.view {
switch navigationControllerOperation {
case .Push:
self?.pushAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .Pop:
self?.popAniamtionCompletion(currentTransitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
case .None:
let cancelled = currentTransitionContext.transitionWasCancelled()
currentTransitionContext.completeTransition(!cancelled)
}
self?.currentTransitionContext = nil
self?.backgroundView = nil
self?.alphaView = nil
}
}
}
}
}
}
//MARK: - Private Methods
extension SAHistoryNavigationTransitionController {
private func popAnimation(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .blackColor()
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
toView.frame = containerView.bounds
toView.transform = CGAffineTransformScale(CGAffineTransformIdentity, kDefaultScale, kDefaultScale)
containerView.addSubview(toView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .blackColor()
alphaView.alpha = 0.7
containerView.addSubview(alphaView)
self.alphaView = alphaView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: .CurveEaseOut, animations: {
toView.transform = CGAffineTransformIdentity
fromView.frame.origin.x = containerView.frame.size.width
alphaView.alpha = 0.0
}) { [weak self] finished in
if finished {
self?.popAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
}
private func popAniamtionCompletion(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled()
if cancelled {
toView.transform = CGAffineTransformIdentity
toView.removeFromSuperview()
} else {
fromView.removeFromSuperview()
}
backgroundView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
private func pushAnimation(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, containerView: UIView) {
let backgroundView = UIView(frame: containerView.bounds)
backgroundView.backgroundColor = .blackColor()
containerView.addSubview(backgroundView)
self.backgroundView = backgroundView
fromView.frame = containerView.bounds
containerView.addSubview(fromView)
let alphaView = UIView(frame: containerView.bounds)
alphaView.backgroundColor = .blackColor()
alphaView.alpha = 0.0
containerView.addSubview(alphaView)
self.alphaView = alphaView
toView.frame = containerView.bounds
toView.frame.origin.x = containerView.frame.size.width
containerView.addSubview(toView)
let kDefaultScale = self.kDefaultScale
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0.0, options: .CurveEaseOut, animations: {
fromView.transform = CGAffineTransformScale(CGAffineTransformIdentity, kDefaultScale, kDefaultScale)
toView.frame.origin.x = 0.0
alphaView.alpha = 0.7
}) { [weak self] finished in
if finished {
self?.pushAniamtionCompletion(transitionContext, toView: toView, fromView: fromView, backgroundView: backgroundView, alphaView: alphaView)
}
}
}
private func pushAniamtionCompletion(transitionContext: UIViewControllerContextTransitioning, toView: UIView, fromView: UIView, backgroundView: UIView, alphaView: UIView) {
let cancelled = transitionContext.transitionWasCancelled()
if cancelled {
toView.removeFromSuperview()
}
fromView.transform = CGAffineTransformIdentity
backgroundView.removeFromSuperview()
fromView.removeFromSuperview()
alphaView.removeFromSuperview()
transitionContext.completeTransition(!cancelled)
currentTransitionContext = nil
self.backgroundView = nil
self.alphaView = nil
}
}
| 4188ce5d0a57ab59683e7145965c0f55 | 43.871658 | 176 | 0.66333 | false | false | false | false |
EasySwift/EasySwift | refs/heads/master | Carthage/Checkouts/HanekeSwift/Haneke/DiskCache.swift | apache-2.0 | 12 | //
// DiskCache.swift
// Haneke
//
// Created by Hermes Pique on 8/10/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
open class DiskCache {
open class func basePath() -> String {
let cachesPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
let hanekePathComponent = HanekeGlobals.Domain
let basePath = (cachesPath as NSString).appendingPathComponent(hanekePathComponent)
// TODO: Do not recaculate basePath value
return basePath
}
open let path: String
open var size : UInt64 = 0
open var capacity : UInt64 = 0 {
didSet {
self.cacheQueue.async(execute: {
self.controlCapacity()
})
}
}
open lazy var cacheQueue : DispatchQueue = {
let queueName = HanekeGlobals.Domain + "." + (self.path as NSString).lastPathComponent
let cacheQueue = DispatchQueue(label: queueName, attributes: [])
return cacheQueue
}()
public init(path: String, capacity: UInt64 = UINT64_MAX) {
self.path = path
self.capacity = capacity
self.cacheQueue.async(execute: {
self.calculateSize()
self.controlCapacity()
})
}
open func setData( _ getData: @autoclosure @escaping () -> Data?, key: String) {
cacheQueue.async(execute: {
if let data = getData() {
self.setDataSync(data, key: key)
} else {
Log.error(message: "Failed to get data for key \(key)")
}
})
}
@discardableResult open func fetchData(key: String, failure fail: ((Error?) -> ())? = nil, success succeed: @escaping (Data) -> ()) {
cacheQueue.async {
let path = self.path(forKey: key)
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: Data.ReadingOptions())
DispatchQueue.main.async {
succeed(data)
}
self.updateDiskAccessDate(atPath: path)
} catch {
if let block = fail {
DispatchQueue.main.async {
block(error)
}
}
}
}
}
open func removeData(with key: String) {
cacheQueue.async(execute: {
let path = self.path(forKey: key)
self.removeFile(atPath: path)
})
}
open func removeAllData(_ completion: (() -> ())? = nil) {
let fileManager = FileManager.default
let cachePath = self.path
cacheQueue.async(execute: {
do {
let contents = try fileManager.contentsOfDirectory(atPath: cachePath)
for pathComponent in contents {
let path = (cachePath as NSString).appendingPathComponent(pathComponent)
do {
try fileManager.removeItem(atPath: path)
} catch {
Log.error(message: "Failed to remove path \(path)", error: error)
}
}
self.calculateSize()
} catch {
Log.error(message: "Failed to list directory", error: error)
}
if let completion = completion {
DispatchQueue.main.async {
completion()
}
}
})
}
open func updateAccessDate( _ getData: @autoclosure @escaping () -> Data?, key: String) {
cacheQueue.async(execute: {
let path = self.path(forKey: key)
let fileManager = FileManager.default
if (!(fileManager.fileExists(atPath: path) && self.updateDiskAccessDate(atPath: path))){
if let data = getData() {
self.setDataSync(data, key: key)
} else {
Log.error(message: "Failed to get data for key \(key)")
}
}
})
}
open func path(forKey key: String) -> String {
let escapedFilename = key.escapedFilename()
let filename = escapedFilename.characters.count < Int(NAME_MAX) ? escapedFilename : key.MD5Filename()
let keyPath = (self.path as NSString).appendingPathComponent(filename)
return keyPath
}
// MARK: Private
fileprivate func calculateSize() {
let fileManager = FileManager.default
size = 0
let cachePath = self.path
do {
let contents = try fileManager.contentsOfDirectory(atPath: cachePath)
for pathComponent in contents {
let path = (cachePath as NSString).appendingPathComponent(pathComponent)
do {
let attributes: [FileAttributeKey: Any] = try fileManager.attributesOfItem(atPath: path)
if let fileSize = attributes[FileAttributeKey.size] as? UInt64 {
size += fileSize
}
} catch {
Log.error(message: "Failed to list directory", error: error)
}
}
} catch {
Log.error(message: "Failed to list directory", error: error)
}
}
fileprivate func controlCapacity() {
if self.size <= self.capacity { return }
let fileManager = FileManager.default
let cachePath = self.path
fileManager.enumerateContentsOfDirectory(atPath: cachePath, orderedByProperty: URLResourceKey.contentModificationDateKey.rawValue, ascending: true) { (URL : URL, _, stop : inout Bool) -> Void in
self.removeFile(atPath: URL.path)
stop = self.size <= self.capacity
}
}
fileprivate func setDataSync(_ data: Data, key: String) {
let path = self.path(forKey: key)
let fileManager = FileManager.default
let previousAttributes : [FileAttributeKey: Any]? = try? fileManager.attributesOfItem(atPath: path)
do {
try data.write(to: URL(fileURLWithPath: path), options: Data.WritingOptions.atomicWrite)
} catch {
Log.error(message: "Failed to write key \(key)", error: error)
}
if let attributes = previousAttributes {
if let fileSize = attributes[FileAttributeKey.size] as? UInt64 {
substract(size: fileSize)
}
}
self.size += UInt64(data.count)
self.controlCapacity()
}
@discardableResult fileprivate func updateDiskAccessDate(atPath path: String) -> Bool {
let fileManager = FileManager.default
let now = Date()
do {
try fileManager.setAttributes([FileAttributeKey.modificationDate : now], ofItemAtPath: path)
return true
} catch {
Log.error(message: "Failed to update access date", error: error)
return false
}
}
fileprivate func removeFile(atPath path: String) {
let fileManager = FileManager.default
do {
let attributes: [FileAttributeKey: Any] = try fileManager.attributesOfItem(atPath: path)
do {
try fileManager.removeItem(atPath: path)
if let fileSize = attributes[FileAttributeKey.size] as? UInt64 {
substract(size: fileSize)
}
} catch {
Log.error(message: "Failed to remove file", error: error)
}
} catch {
if isNoSuchFileError(error) {
Log.debug(message: "File not found", error: error)
} else {
Log.error(message: "Failed to remove file", error: error)
}
}
}
fileprivate func substract(size : UInt64) {
if (self.size >= size) {
self.size -= size
} else {
Log.error(message: "Disk cache size (\(self.size)) is smaller than size to substract (\(size))")
self.size = 0
}
}
}
private func isNoSuchFileError(_ error : Error?) -> Bool {
if let error = error {
return NSCocoaErrorDomain == (error as NSError).domain && (error as NSError).code == NSFileReadNoSuchFileError
}
return false
}
| 8f3db2c6a56ad67e8b00efad32b72635 | 34.637131 | 202 | 0.550438 | false | false | false | false |
acrookston/ACRCircleView | refs/heads/master | ACRCircleView.swift | mit | 2 | //
// CircleView.swift
// License: MIT
//
// Created by Andrew Crookston <[email protected]> on 4/25/15.
//
//
import UIKit
class ACRCircleView: UIView {
// MARK: Configurable values
var strokeWidth : CGFloat = 2.0 {
didSet {
basePathLayer.lineWidth = strokeWidth
circlePathLayer.lineWidth = strokeWidth
}
}
override var tintColor : UIColor! {
didSet {
circlePathLayer.strokeColor = tintColor.CGColor
}
}
var baseColor : UIColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 1) {
didSet {
basePathLayer.strokeColor = baseColor.CGColor
}
}
var progress: CGFloat {
get {
return circlePathLayer.strokeEnd
}
set {
if (newValue > 1.0) {
circlePathLayer.strokeEnd = 1.0
} else if (newValue < 0.0) {
circlePathLayer.strokeEnd = 0.0
} else {
circlePathLayer.strokeEnd = newValue
}
}
}
// MARK: Init
private let basePathLayer = CAShapeLayer()
private let circlePathLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func startAnimating() {
var animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation!.fromValue = 0.0
animation!.toValue = 2 * M_PI
// this might be too fast
animation!.duration = 1
// HUGE_VALF is defined in math.h so import it
animation!.repeatCount = Float.infinity
circlePathLayer.addAnimation(animation, forKey: "rotation")
}
func stopAnimating() {
circlePathLayer.removeAnimationForKey("rotation")
}
// MARK: Internal
private func configure() {
basePathLayer.frame = bounds
basePathLayer.lineWidth = strokeWidth
basePathLayer.fillColor = UIColor.clearColor().CGColor
basePathLayer.strokeColor = baseColor.CGColor
basePathLayer.actions = ["strokeEnd": NSNull()]
layer.addSublayer(basePathLayer)
circlePathLayer.frame = bounds
circlePathLayer.lineWidth = strokeWidth
circlePathLayer.fillColor = UIColor.clearColor().CGColor
circlePathLayer.strokeColor = tintColor.CGColor
// make optional for animated? See: http://stackoverflow.com/questions/21688363/change-cashapelayer-without-animation
circlePathLayer.actions = ["strokeEnd": NSNull()]
// rotate the layer negative 90deg to make it start at the top. 12 o'clock, default is 3 o'clock.
circlePathLayer.transform = CATransform3DMakeRotation(-CGFloat(90.0 / 180.0 * M_PI), 0.0, 0.0, 1.0)
layer.addSublayer(circlePathLayer)
progress = 0
}
private func circleFrame() -> CGRect {
// keep the circle inside the bounds
let shorter = (bounds.width > bounds.height ? bounds.height : bounds.width) - strokeWidth
var circleFrame = CGRect(x: 0, y: 0, width: shorter, height: shorter)
circleFrame.origin.x = CGRectGetMidX(circlePathLayer.bounds) - CGRectGetMidX(circleFrame)
circleFrame.origin.y = CGRectGetMidY(circlePathLayer.bounds) - CGRectGetMidY(circleFrame)
return circleFrame
}
private func circlePath() -> UIBezierPath {
return UIBezierPath(ovalInRect: circleFrame())
}
override func layoutSubviews() {
super.layoutSubviews()
basePathLayer.frame = bounds
basePathLayer.path = circlePath().CGPath
circlePathLayer.frame = bounds
circlePathLayer.path = circlePath().CGPath
}
}
| c9b6d764452d9a7a9fdb537c341a9e7d | 29.926829 | 125 | 0.627234 | false | false | false | false |
vl4298/mah-income | refs/heads/master | Mah Income/Mah Income/Custom View/NumberButton.swift | mit | 1 |
import UIKit
class NumberButton: UIButton {
fileprivate let durationAnimation: TimeInterval = 0.2
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
override func layoutSubviews() {
super.layoutSubviews()
layoutView()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
UIView.animate(withDuration: durationAnimation, animations: {
self.backgroundColor = AppColor.NumberButton.numberButtonHightlightColor
}, completion: { _ in
})
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
UIView.animate(withDuration: durationAnimation, animations: {
self.backgroundColor = AppColor.NumberButton.numberButtonColor
}, completion: { _ in
})
}
}
extension NumberButton {
func setupView() {
let smallerSize = min(bounds.width, bounds.height)
layer.cornerRadius = smallerSize/2
backgroundColor = AppColor.NumberButton.numberButtonColor
setTitleColor(AppColor.NumberButton.numberButtonTextColor, for: .normal)
titleLabel?.font = Font.font
titleLabel?.adjustsFontSizeToFitWidth = true
}
func layoutView() {
let smallerSize = min(bounds.width, bounds.height)
layer.cornerRadius = smallerSize/2
}
}
| 98d0129766770e3b3b9ce425f14c0ce7 | 21.671642 | 78 | 0.685978 | false | false | false | false |
delba/SwiftyOAuth | refs/heads/master | Source/Token.swift | mit | 1 | //
// Token.swift
//
// Copyright (c) 2016-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
public struct Token {
/// The access token.
public var accessToken: String {
return dictionary["access_token"] as! String
}
/// The refresh token.
public var refreshToken: String? {
return dictionary["refresh_token"] as? String
}
/// The remaining lifetime on the access token.
public var expiresIn: TimeInterval? {
return dictionary["expires_in"] as? TimeInterval
}
/// A boolean value indicating whether the token is expired.
public var isExpired: Bool {
guard let expiresIn = expiresIn else {
return false
}
return Date.timeIntervalSinceReferenceDate > createdAt + expiresIn
}
/// A boolean value indicating whether the token is valid.
public var isValid: Bool {
return !isExpired
}
fileprivate var createdAt: TimeInterval {
return dictionary["created_at"] as! TimeInterval
}
/// The token type.
public var tokenType: TokenType? {
return TokenType(dictionary["token_type"])
}
/// The scopes.
public var scopes: [String]? {
return scope?.components(separatedBy: " ")
}
/// The scope.
fileprivate var scope: String? {
return dictionary["scope"] as? String
}
/// The full response dictionary.
public let dictionary: [String: Any]
public init?(dictionary: [String: Any]) {
guard dictionary["access_token"] as? String != nil else {
return nil
}
var dictionary = dictionary
if dictionary["created_at"] == nil {
dictionary["created_at"] = Date.timeIntervalSinceReferenceDate
}
self.dictionary = dictionary
}
}
| e4d7278c741a577efac9eddd4ab997df | 30.336957 | 81 | 0.67187 | false | false | false | false |
Finb/V2ex-Swift | refs/heads/master | Common/WebViewImageProtocol.swift | mit | 1 | //
// WebViewImageProtocol.swift
// V2ex-Swift
//
// Created by huangfeng on 16/10/25.
// Copyright © 2016年 Fin. All rights reserved.
//
import Kingfisher
import UIKit
private let WebviewImageProtocolHandledKey = "WebviewImageProtocolHandledKey"
class WebViewImageProtocol: URLProtocol, URLSessionDataDelegate {
var session: URLSession?
var dataTask: URLSessionDataTask?
var imageData: Data?
override class func canInit(with request: URLRequest) -> Bool {
guard let pathExtension = request.url?.pathExtension else {
return false
}
if ["jpg", "jpeg", "png", "gif"].contains(pathExtension.lowercased()) {
if let tag = self.property(forKey: WebviewImageProtocolHandledKey, in: request) as? Bool, tag == true {
return false
}
return true
}
return false
}
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override class func requestIsCacheEquivalent(_ a: URLRequest, to b: URLRequest) -> Bool {
return super.requestIsCacheEquivalent(a, to: b)
}
override func startLoading() {
let resource = ImageResource(downloadURL: self.request.url!)
let data = try? Data(contentsOf: URL(fileURLWithPath: KingfisherManager.shared.cache.cachePath(forKey: resource.cacheKey)))
if let data = data {
// 在磁盘上找到Kingfisher的缓存,则直接使用缓存
var mimeType = data.contentTypeForImageData()
mimeType.append(";charset=UTF-8")
let header = ["Content-Type": mimeType,
"Content-Length": String(data.count)]
let response = HTTPURLResponse(url: self.request.url!, statusCode: 200, httpVersion: "1.1", headerFields: header)!
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
self.client?.urlProtocol(self, didLoad: data)
self.client?.urlProtocolDidFinishLoading(self)
}
else {
// 没找到图片则下载
guard let newRequest = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else { return }
newRequest.setValue(nil, forHTTPHeaderField: "Referer")
WebViewImageProtocol.setProperty(true, forKey: WebviewImageProtocolHandledKey, in: newRequest)
self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
self.dataTask = self.session?.dataTask(with: newRequest as URLRequest)
self.dataTask?.resume()
}
}
override func stopLoading() {
self.dataTask?.cancel()
self.dataTask = nil
self.imageData = nil
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .allowed)
completionHandler(.allow)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.client?.urlProtocol(self, didLoad: data)
if self.imageData == nil {
self.imageData = data
}
else {
self.imageData!.append(data)
}
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
self.client?.urlProtocol(self, didFailWithError: error)
}
else {
self.client?.urlProtocolDidFinishLoading(self)
let resource = ImageResource(downloadURL: self.request.url!)
guard let imageData = self.imageData else { return }
// 保存图片到Kingfisher
guard let image = DefaultCacheSerializer.default.image(with: imageData, options: nil) else { return }
KingfisherManager.shared.cache.store(image, original: imageData, forKey: resource.cacheKey, toDisk: true, completionHandler: nil)
}
}
}
private extension Data {
func contentTypeForImageData() -> String {
var c: UInt8 = 0
self.copyBytes(to: &c, count: MemoryLayout<UInt8>.size * 1)
switch c {
case 0xff:
return "image/jpeg"
case 0x89:
return "image/png"
case 0x47:
return "image/gif"
default:
return ""
}
}
}
| 420edf6ed61de6c2d93531b36fb7a196 | 37.067797 | 179 | 0.638246 | false | false | false | false |
marcelmueller/MyWeight | refs/heads/master | MyWeight/Screens/AuthorizationRequest/AuthorizationRequestViewModel.swift | mit | 1 | //
// AuthorizationRequestViewModel.swift
// MyWeight
//
// Created by Diogo on 19/10/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import Foundation
public protocol AuthorizationRequestViewModelProtocol: TitleDescriptionViewModelProtocol {
var okTitle: String { get }
var cancelTitle: String { get }
var didTapOkAction: () -> Void { get }
var didTapCancelAction: () -> Void { get }
}
public struct AuthorizationRequestViewModel: AuthorizationRequestViewModelProtocol {
public let title: NSAttributedString
public let description: NSAttributedString
public let flexibleHeight: Bool
public let okTitle: String
public let cancelTitle: String
public let didTapOkAction: () -> Void
public let didTapCancelAction: () -> Void
}
extension AuthorizationRequestViewModel {
public init()
{
self.init(didTapOkAction: { _ in Log.debug("Ok") },
didTapCancelAction: { _ in Log.debug("Cancel" ) })
}
public init(didTapOkAction: @escaping () -> Void,
didTapCancelAction: @escaping () -> Void)
{
let style: StyleProvider = Style()
title = NSAttributedString(string: Localization.authorizationTitle,
font: style.title1,
color: style.textColor)
var description = NSAttributedString(string: Localization.authorizationDescription,
font: style.body,
color: style.textLightColor)
description = description.highlight(string: Localization.authorizationDescriptionHighlight1,
font: nil,
color: style.textColor)
description = description.highlight(string: Localization.authorizationDescriptionHighlight2,
font: nil,
color: style.textColor)
self.description = description
flexibleHeight = true
okTitle = Localization.authorizationOkButton
cancelTitle = Localization.authorizationCancelButton
self.didTapOkAction = didTapOkAction
self.didTapCancelAction = didTapCancelAction
}
}
| 3cb41b7067cc956fb87a7e3f54d3e317 | 30.486486 | 100 | 0.608584 | false | false | false | false |
Why51982/SLDouYu | refs/heads/master | SLDouYu/SLDouYu/Classes/Tools/Extension/UIBarButtonItem+SLExtension.swift | mit | 1 | //
// UIBarButtonItem+SLExtension.swift
// SLDouYu
//
// Created by CHEUNGYuk Hang Raymond on 2016/10/24.
// Copyright © 2016年 CHEUNGYuk Hang Raymond. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
//便利构造函数: 1.convenience开头 2.在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.zero) {
//创建UIButton
let button = UIButton()
//设置图片
button.setImage(UIImage(named: imageName), for: UIControlState.normal)
if highImageName != "" {
button.setImage(UIImage(named: highImageName), for: UIControlState.highlighted)
}
//设置尺寸
if size == CGSize.zero {
button.sizeToFit()
} else {
button.frame = CGRect(origin: CGPoint.zero, size: size)
}
//创建UIBarButtonItem
self.init(customView: button)
}
}
| b94fc3efdd2e61dbaa6350b358b9c75b | 26.705882 | 97 | 0.606157 | false | false | false | false |
jduquennoy/Log4swift | refs/heads/master | Log4swift/RotationPolicy/SizeRotationPolicy.swift | apache-2.0 | 1 | //
// SizeRotationPolicy.swift
// Log4swift
//
// Created by Jérôme Duquennoy on 20/08/2018.
// Copyright © 2018 jerome. All rights reserved.
//
import Foundation
/**
This rotation policy will request a rotation once a file gets bigger than a given threshold.
*/
class SizeRotationPolicy: FileAppenderRotationPolicy {
/// The maximum size of the file in octets before rotation is requested.
public var maxFileSize: UInt64
private var currentFileSize: UInt64 = 0
/// Creates a rotation policy with a max file size in octet.
init(maxFileSize: UInt64) {
self.maxFileSize = maxFileSize
}
func appenderDidOpenFile(atPath path: String) {
let fileManager = FileManager.default
do {
let fileAttributes = try fileManager.attributesOfItem(atPath: path)
self.currentFileSize = fileAttributes[FileAttributeKey.size] as? UInt64 ?? 0
} catch {
self.currentFileSize = 0
}
}
func appenderDidAppend(data: Data) {
self.currentFileSize += UInt64(data.count)
}
func shouldRotate() -> Bool {
return self.currentFileSize > self.maxFileSize
}
}
| 46f43b92d3caaf953d02ff8fa8b91fd8 | 26.073171 | 93 | 0.710811 | false | false | false | false |
adrianitech/magic-mapper-swift | refs/heads/master | MagicMapper/Dictionary+Value.swift | apache-2.0 | 1 | //
// Created by Adrian Mateoaea on 03/10/2016.
// Copyright © 2016 MagicMapper. All rights reserved.
//
import Foundation
extension Dictionary {
public func valueForKeyPath(_ keyPath: String) -> Any? {
var keys = keyPath.components(separatedBy: ".")
guard let key = keys.removeFirst() as? Key else {
print("Unable to use string as key on type: \(Key.self)")
return nil
}
guard var value = self[key] else { return nil }
if !keys.isEmpty {
while
let key = keys.first,
let index = Int(key),
let arr = value as? [Value],
index >= 0 && index < arr.count {
value = arr[index]
keys.remove(at: 0)
}
if let dict = value as? Dictionary {
let rejoined = keys.joined(separator: ".")
return dict.valueForKeyPath(rejoined)
}
}
return value
}
}
| 94899cc6864e4b68a44ac585580c2732 | 27.861111 | 69 | 0.492782 | false | false | false | false |
18775134221/SwiftBase | refs/heads/develop | Carthage/Checkouts/realm-cocoa/RealmSwift/Util.swift | apache-2.0 | 26 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
// MARK: Internal Helpers
internal func notFoundToNil(index: UInt) -> Int? {
if index == UInt(NSNotFound) {
return nil
}
return Int(index)
}
#if swift(>=3.0)
internal func throwRealmException(_ message: String, userInfo: [AnyHashable: Any]? = nil) {
NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatches(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
extension Object {
// Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject`
// but actually operate on `RLMObjectBase`. Do not expose cast value to user.
internal func unsafeCastToRLMObject() -> RLMObject {
return unsafeBitCast(self, to: RLMObject.self)
}
}
// MARK: CustomObjectiveCBridgeable
internal func dynamicBridgeCast<T>(fromObjectiveC x: Any) -> T {
if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type {
return BridgeableType.bridging(objCValue: x) as! T
} else {
return x as! T
}
}
internal func dynamicBridgeCast<T>(fromSwift x: T) -> Any {
if let x = x as? CustomObjectiveCBridgeable {
return x.objCValue
} else {
return x
}
}
// Used for conversion from Objective-C types to Swift types
internal protocol CustomObjectiveCBridgeable {
/* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber`
* At this point, use `as! [SwiftType]` to cast between. */
static func bridging(objCValue: Any) -> Self
var objCValue: Any { get }
}
extension Int8: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int8 {
return (objCValue as! NSNumber).int8Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int16: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int16 {
return (objCValue as! NSNumber).int16Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int32: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int32 {
return (objCValue as! NSNumber).int32Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Int64: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Int64 {
return (objCValue as! NSNumber).int64Value
}
var objCValue: Any {
return NSNumber(value: self)
}
}
extension Optional: CustomObjectiveCBridgeable {
static func bridging(objCValue: Any) -> Optional {
if objCValue is NSNull {
return nil
} else {
return .some(dynamicBridgeCast(fromObjectiveC: objCValue))
}
}
var objCValue: Any {
if let value = self {
return value
} else {
return NSNull()
}
}
}
#else
internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) {
NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatchesInString(string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
extension Object {
// Must *only* be used to call Realm Objective-C APIs that are exposed on `RLMObject`
// but actually operate on `RLMObjectBase`. Do not expose cast value to user.
internal func unsafeCastToRLMObject() -> RLMObject {
return unsafeBitCast(self, RLMObject.self)
}
}
// MARK: CustomObjectiveCBridgeable
internal func dynamicBridgeCast<T>(fromObjectiveC x: AnyObject) -> T {
if let BridgeableType = T.self as? CustomObjectiveCBridgeable.Type {
return BridgeableType.bridging(objCValue: x) as! T
} else {
return x as! T
}
}
internal func dynamicBridgeCast<T>(fromSwift x: T) -> AnyObject {
if let x = x as? CustomObjectiveCBridgeable {
return x.objCValue
} else {
return x as! AnyObject
}
}
// Used for conversion from Objective-C types to Swift types
internal protocol CustomObjectiveCBridgeable {
/* FIXME: Remove protocol once SR-2393 bridges all integer types to `NSNumber`
* At this point, use `as! [SwiftType]` to cast between. */
static func bridging(objCValue objCValue: AnyObject) -> Self
var objCValue: AnyObject { get }
}
extension Int8: CustomObjectiveCBridgeable {
static func bridging(objCValue objCValue: AnyObject) -> Int8 {
return (objCValue as! NSNumber).charValue
}
var objCValue: AnyObject {
return NSNumber(char: self)
}
}
extension Int16: CustomObjectiveCBridgeable {
static func bridging(objCValue objCValue: AnyObject) -> Int16 {
return (objCValue as! NSNumber).shortValue
}
var objCValue: AnyObject {
return NSNumber(short: self)
}
}
extension Int32: CustomObjectiveCBridgeable {
static func bridging(objCValue objCValue: AnyObject) -> Int32 {
return (objCValue as! NSNumber).intValue
}
var objCValue: AnyObject {
return NSNumber(int: self)
}
}
extension Int64: CustomObjectiveCBridgeable {
static func bridging(objCValue objCValue: AnyObject) -> Int64 {
return (objCValue as! NSNumber).longLongValue
}
var objCValue: AnyObject {
return NSNumber(longLong: self)
}
}
#endif
| 44242482de36c069008ad2022cdec6cd | 31.707763 | 111 | 0.650705 | false | false | false | false |
Feverup/braintree_ios | refs/heads/master | UITests/Helpers/BTUITest.swift | mit | 1 | import XCTest
extension XCTestCase {
func waitForElementToAppear(element: XCUIElement, timeout: NSTimeInterval = 10, file: String = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true")
expectationForPredicate(existsPredicate,
evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(timeout) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after \(timeout) seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}
func waitForElementToBeHittable(element: XCUIElement, timeout: NSTimeInterval = 10, file: String = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true && hittable == true")
expectationForPredicate(existsPredicate,
evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(timeout) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after \(timeout) seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}
}
extension XCUIElement {
func forceTapElement() {
if self.hittable {
self.tap()
} else {
let coordinate: XCUICoordinate = self.coordinateWithNormalizedOffset(CGVectorMake(0.0, 0.0))
coordinate.tap()
}
}
} | 1fa362ed610fac777ec787dffd791e67 | 38.47619 | 132 | 0.590827 | false | false | false | false |
MorganCabral/swiftrekt-ios-app-dev-challenge-2015 | refs/heads/master | app-dev-challenge/app-dev-challenge/WizardSprite.swift | mit | 1 | //
// WizardSprite.swift
// app-dev-challenge
//
// Created by Morgan Cabral on 2/8/15.
// Copyright (c) 2015 Team SwiftRekt. All rights reserved.
//
import Foundation
import SpriteKit
public class WizardSprite : SKSpriteNode {
/**
* Constructor.
*/
public init( startingPosition : CGPoint, endingPosition : CGPoint, facesRight : Bool ) {
self.startingPosition = startingPosition
self.endingPosition = endingPosition
self.facesRight = facesRight
var texture = SKTexture(imageNamed: "wizard")
var size = CGSize(width: texture.size().width, height: texture.size().height)
super.init(texture: texture, color: UIColor.whiteColor(), size: size)
// Set the position of the sprite to the specified starting position.
self.position = startingPosition
// Scale the sprite if we need to make it look to the left.
if !facesRight {
self.xScale = fabs(self.xScale) * -1
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func doInitialAnimation() {
// If we aren't already moving, indicate that we're moving now.
if( !_startedMovingToInitialPosition ) {
_startedMovingToInitialPosition = true
// Start the movement animation.
self.runAction(SKAction.moveTo(endingPosition, duration: 2.0), withKey: "wizardInitializationAnimation")
}
}
public func stopInitialAnimation() {
self.removeActionForKey("wizardInitializationAnimation")
}
var startingPosition : CGPoint
var endingPosition : CGPoint
var facesRight : Bool
private var _startedMovingToInitialPosition : Bool = false
} | 0c60a517218da1ac7b9fbea6a01f3230 | 29.035714 | 110 | 0.699584 | false | false | false | false |
twostraws/SwiftGD | refs/heads/main | Sources/SwiftGD/Geometry/Size.swift | mit | 1 | /// A structure that represents a two-dimensional size.
public struct Size {
/// The width value of the size.
public var width: Int
/// The height value of the size.
public var height: Int
/// Creates a size with specified dimensions.
///
/// - Parameters:
/// - width: The width value of the size
/// - height: The height value of the size
public init(width: Int, height: Int) {
self.width = width
self.height = height
}
}
extension Size {
/// Size whose width and height are both zero.
public static let zero = Size(width: 0, height: 0)
/// Creates a size with specified dimensions.
///
/// - Parameters:
/// - width: The width value of the size
/// - height: The height value of the size
public init(width: Int32, height: Int32) {
self.init(width: Int(width), height: Int(height))
}
}
extension Size: Comparable {
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func < (lhs: Size, rhs: Size) -> Bool {
return lhs.width < rhs.width && lhs.height < rhs.height
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: Size, rhs: Size) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
}
| 5799416afb8ba56dec5f6869f7040ee7 | 32.183333 | 79 | 0.608237 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/serialize-and-deserialize-binary-tree.swift | mit | 2 | /**
* https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
*
*
*/
// Date: Mon May 25 15:30:48 PDT 2020
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
///
/// Level-Traverse Binary Tree, fill null when no node exisit there
/// Pretty much like a heap.
/// This solution will get TLE, since there is a case, where every element has a right child only, but the tree is very high, thus,
/// The level order will generate a large string to store every empty node.
///
class Codec {
func serialize(_ root: TreeNode?) -> String {
var ret: [String] = []
var queue = [root]
while queue.isEmpty == false {
var n = queue.count
var nextLevel = false
while n > 0 {
n -= 1
let node = queue.removeFirst()
if let node = node {
if node.left != nil {
nextLevel = true
}
if node.right != nil {
nextLevel = true
}
ret.append("\(node.val)")
queue.append(node.left)
queue.append(node.right)
} else {
ret.append("null")
queue.append(nil)
queue.append(nil)
}
}
if nextLevel == false { break }
}
// while let last = ret.last, last == "null" {
// ret.removeLast()
// }
return "[" + ret.joined(separator: ",") + "]"
}
func deserialize(_ data: String) -> TreeNode? {
var tmpdata = data
tmpdata.removeFirst()
tmpdata.removeLast()
let data = tmpdata.split(separator: ",").map { String($0) }
guard let first = data.first, first != "null" else { return nil }
var queue: [TreeNode?] = [TreeNode(Int(first)!)]
for index in 1 ..< data.count {
let parentIndex = (index - 1) / 2
let node: TreeNode?
if data[index] == "null" {
node = nil
} else {
node = TreeNode(Int(data[index])!)
}
if index == parentIndex * 2 + 1 {
queue[parentIndex]?.left = node
} else {
queue[parentIndex]?.right = node
}
queue.append(node)
}
return queue.first!
}
}
///
/// Preorder- Traverse.
///
class Codec {
/// - Complexity:
/// - Time: O(n), n is the number of nodes in the tree.
/// - Space: O(n), n is the number of nodes in the tree.
///
func serialize(_ root: TreeNode?) -> String {
var ret: [String] = []
var queue = [root]
while queue.isEmpty == false {
let node = queue.removeFirst()
if let node = node {
ret.append("\(node.val)")
queue.insert(node.right, at: 0)
queue.insert(node.left, at: 0)
} else {
ret.append("null")
}
}
return ret.joined(separator: ",")
}
/// - Complexity:
/// - Time: O(n), n is the length of comma seperated Array.
/// - Space: O(log(n)), which is the height of the tree.
///
func deserialize(_ data: String) -> TreeNode? {
func build(_ data: [String], at index: inout Int) -> TreeNode? {
let content = data[index]
index += 1
if content == "null" { return nil }
let node = TreeNode(Int(content)!)
node.left = build(data, at: &index)
node.right = build(data, at: &index)
return node
}
let data = data.split(separator: ",").map { String($0) }
var index = 0
let node = build(data, at: &index)
return node
}
}
| 0932900d7163a6cc695b0e55f71113f8 | 30.648855 | 131 | 0.472021 | false | false | false | false |
mrdepth/CloudData | refs/heads/master | CloudData/CloudData/CloudOperation.swift | mit | 1 | //
// CloudOperation.swift
// CloudData
//
// Created by Artem Shimanski on 10.03.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
import CloudKit
let CloudOperationRetryLimit = 3
class CloudOperation: Operation {
var shouldRetry: Bool {
get {
return fireDate != nil
}
}
private(set) var fireDate: Date?
func finish(error: Error? = nil) {
switch error {
case CKError.networkUnavailable?,
CKError.networkFailure?,
CKError.serviceUnavailable?,
CKError.notAuthenticated?:
if _retryCounter < CloudOperationRetryLimit {
_retryCounter += 1
let retryAfter = (error as? CKError)?.retryAfterSeconds ?? 3.0
fireDate = Date(timeIntervalSinceNow: retryAfter)
print("CloudDataError: \(error!). Retry after \(retryAfter)")
}
case CKError.requestRateLimited?:
if _retryCounter < CloudOperationRetryLimit {
_retryCounter += 1
let retryAfter = (error as? CKError)?.retryAfterSeconds ?? 30
fireDate = Date(timeIntervalSinceNow: retryAfter)
print("CloudDataError: \(error!). Retry after \(retryAfter)")
}
default:
break
}
willChangeValue(forKey: "isFinished")
willChangeValue(forKey: "isExecuting")
_finished = true
_executing = false
didChangeValue(forKey: "isExecuting")
didChangeValue(forKey: "isFinished")
}
func retry(after: TimeInterval) {
fireDate = Date(timeIntervalSinceNow: after)
finish(error: nil)
}
//MARK - Operation
private var _executing: Bool = false
private var _finished: Bool = false
private var _retryCounter: Int = 0
override var isAsynchronous: Bool {
return true
}
override var isExecuting: Bool {
return _executing
}
override var isFinished: Bool {
return _finished
}
override func start() {
fireDate = nil
willChangeValue(forKey: "isExecuting")
_executing = true
_finished = false
didChangeValue(forKey: "isExecuting")
main()
}
override func main() {
finish(error: nil)
}
}
class CloudBlockOperation: CloudOperation {
let block: (CloudOperation) -> Void
init(block: @escaping (CloudOperation) -> Void) {
self.block = block
super.init()
}
override func main() {
block(self)
}
}
| bcd0f0ed20013085a7c4f1ec4038d1a2 | 19.858491 | 66 | 0.691542 | false | false | false | false |
jurre/TravisToday | refs/heads/master | Today/TravisViewController.swift | mit | 1 | //
// TodayViewController.swift
// Travis
//
// Created by Jurre Stender on 19/10/14.
// Copyright (c) 2014 jurre. All rights reserved.
//
import Cocoa
import NotificationCenter
extension Repo {
var durationLabel: String {
get {
let seconds = self.duration! % 60
let minutes = (self.duration! - seconds) / 60
return "Duration: \(minutes) min \(seconds) sec"
}
}
}
class TravisViewController: NSViewController, NCWidgetProviding, NCWidgetListViewDelegate {
// MARK: - NSViewController
@IBOutlet var listViewController: NCWidgetListViewController!
var repos: NSMutableArray = []
override var nibName: String? {
return "TravisViewController"
}
override func viewDidLoad() {
super.viewDidLoad()
// Set up the widget list view controller.
for repo in REPOS {
if let cachedRepo = RepoCache().get(repo.slug!) {
self.repos.addObject(cachedRepo)
}
}
self.listViewController.contents = self.repos
}
// MARK: - NCWidgetProviding
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
fetchRepos(completionHandler)
}
func widgetMarginInsetsForProposedMarginInsets(var defaultMarginInset: NSEdgeInsets) -> NSEdgeInsets {
// Override the left margin so that the list view is flush with the edge.
defaultMarginInset.left = 0
return defaultMarginInset
}
var widgetAllowsEditing: Bool {
// Return true to indicate that the widget supports editing of content and
// that the list view should be allowed to enter an edit mode.
return false
}
// MARK: - NCWidgetListViewDelegate
func widgetList(list: NCWidgetListViewController!, viewControllerForRow row: Int) -> NSViewController! {
// Return a new view controller subclass for displaying an item of widget
// content. The NCWidgetListViewController will set the representedObject
// of this view controller to one of the objects in its contents array.
let repo: AnyObject = repos[row]
let repoController = ListRowViewController()
repoController.repo = repo as? Repo
return repoController
}
func widgetList(list: NCWidgetListViewController!, shouldReorderRow row: Int) -> Bool {
// Return true to allow the item to be reordered in the list by the user.
return false
}
func widgetList(list: NCWidgetListViewController!, shouldRemoveRow row: Int) -> Bool {
// Return true to allow the item to be removed from the list by the user.
return false
}
// MARK: Private
private func fetchRepos(completionHandler: ((NCUpdateResult) -> Void)!) {
self.repos.removeAllObjects()
for config in REPOS {
RepoService.sharedService.find(config, completion: { (success: Bool, repo: Repo?) -> Void in
if (success) {
RepoCache().set(repo!, forKey: config.slug!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.repos.addObject(repo!)
self.listViewController.contents = self.repos
completionHandler(.NewData)
})
} else {
println("Error fetching " + config.slug!)
completionHandler(.NoData)
}
})
}
}
}
| 108d3638692e94ad39472beb4c1387ff | 27.444444 | 105 | 0.71875 | false | false | false | false |
dmrschmidt/DSWaveformImage | refs/heads/main | Sources/DSWaveformImage/WaveformImageTypes.swift | mit | 1 | import AVFoundation
#if os(macOS)
import AppKit
public typealias DSColor = NSColor
public typealias DSImage = NSImage
public enum DSScreen {
public static var scale: CGFloat { NSScreen.main?.backingScaleFactor ?? 1 }
}
#else
import UIKit
public typealias DSColor = UIColor
public typealias DSImage = UIImage
public enum DSScreen {
public static var scale: CGFloat { UIScreen.main.scale }
}
#endif
/// Renders the waveformsamples on the provided `CGContext`.
public protocol WaveformRenderer {
func render(samples: [Float], on context: CGContext, with configuration: Waveform.Configuration, lastOffset: Int)
func style(context: CGContext, with configuration: Waveform.Configuration)
}
public enum Waveform {
/** Position of the drawn waveform. */
public enum Position: Equatable {
/// **top**: Draws the waveform at the top of the image, such that only the bottom 50% are visible.
case top
/// **middle**: Draws the waveform in the middle the image, such that the entire waveform is visible.
case middle
/// **bottom**: Draws the waveform at the bottom of the image, such that only the top 50% are visible.
case bottom
/// **custom**: Draws the waveform at the specified point of the image. `x` and `y` must be within `(0...1)`!
case origin(CGPoint)
func origin() -> CGPoint {
switch self {
case .top: return CGPoint(x: 0.5, y: 0.0)
case .middle: return CGPoint(x: 0.5, y: 0.5)
case .bottom: return CGPoint(x: 0.5, y: 1.0)
case let .origin(point): return point
}
}
}
/**
Style of the waveform which is used during drawing:
- **filled**: Use solid color for the waveform.
- **gradient**: Use gradient based on color for the waveform.
- **striped**: Use striped filling based on color for the waveform.
*/
public enum Style: Equatable {
public struct StripeConfig: Equatable {
/// Color of the waveform stripes. Default is clear.
public let color: DSColor
/// Width of stripes drawn. Default is `1`
public let width: CGFloat
/// Space between stripes. Default is `5`
public let spacing: CGFloat
/// Line cap style. Default is `.round`.
public let lineCap: CGLineCap
public init(color: DSColor, width: CGFloat = 1, spacing: CGFloat = 5, lineCap: CGLineCap = .round) {
self.color = color
self.width = width
self.spacing = spacing
self.lineCap = lineCap
}
}
case filled(DSColor)
case outlined(DSColor, CGFloat)
case gradient([DSColor])
case gradientOutlined([DSColor], CGFloat)
case striped(StripeConfig)
}
/**
Defines the dampening attributes of the waveform.
*/
public struct Dampening: Equatable {
public enum Sides: Equatable {
case left
case right
case both
}
/// Determines the percentage of the resulting graph to be dampened.
///
/// Must be within `(0..<0.5)` to leave an undapmened area.
/// Default is `0.125`
public let percentage: Float
/// Determines which sides of the graph to dampen.
/// Default is `.both`
public let sides: Sides
/// Easing function to be used. Default is `pow(x, 2)`.
public let easing: (Float) -> Float
public init(percentage: Float = 0.125, sides: Sides = .both, easing: @escaping (Float) -> Float = { x in pow(x, 2) }) {
guard (0...0.5).contains(percentage) else {
preconditionFailure("dampeningPercentage must be within (0..<0.5)")
}
self.percentage = percentage
self.sides = sides
self.easing = easing
}
/// Build a new `Waveform.Dampening` with only the given parameters replaced.
public func with(percentage: Float? = nil, sides: Sides? = nil, easing: ((Float) -> Float)? = nil) -> Dampening {
.init(percentage: percentage ?? self.percentage, sides: sides ?? self.sides, easing: easing ?? self.easing)
}
public static func == (lhs: Waveform.Dampening, rhs: Waveform.Dampening) -> Bool {
// poor-man's way to make two closures Equatable w/o too much hassle
let randomEqualitySample = Float.random(in: (0..<Float.greatestFiniteMagnitude))
return lhs.percentage == rhs.percentage && lhs.sides == rhs.sides && lhs.easing(randomEqualitySample) == rhs.easing(randomEqualitySample)
}
}
/// Allows customization of the waveform output image.
public struct Configuration: Equatable {
/// Desired output size of the waveform image, works together with scale. Default is `.zero`.
public let size: CGSize
/// Background color of the waveform, defaults to `clear`.
public let backgroundColor: DSColor
/// Waveform drawing style, defaults to `.gradient`.
public let style: Style
/// *Optional* Waveform dampening, defaults to `nil`.
public let dampening: Dampening?
/// Waveform drawing position, defaults to `.middle`.
public let position: Position
/// Scale (@2x, @3x, etc.) to be applied to the image, defaults to `UIScreen.main.scale`.
public let scale: CGFloat
/**
Vertical scaling factor. Default is `0.95`, leaving a small vertical padding.
The `verticalScalingFactor` describes the maximum vertical amplitude
of the envelope being drawn in relation to its view's (image's) size.
* `0`: the waveform has no vertical amplitude and is just a line.
* `1`: the waveform uses the full available vertical space.
* `> 1`: louder waveform samples will extend out of the view boundaries and clip.
*/
public let verticalScalingFactor: CGFloat
/// Waveform antialiasing. If enabled, may reduce overall opacity. Default is `false`.
public let shouldAntialias: Bool
var shouldDampen: Bool {
dampening != nil
}
public init(size: CGSize = .zero,
backgroundColor: DSColor = DSColor.clear,
style: Style = .gradient([DSColor.black, DSColor.gray]),
dampening: Dampening? = nil,
position: Position = .middle,
scale: CGFloat = DSScreen.scale,
verticalScalingFactor: CGFloat = 0.95,
shouldAntialias: Bool = false) {
guard verticalScalingFactor > 0 else {
preconditionFailure("verticalScalingFactor must be greater 0")
}
self.backgroundColor = backgroundColor
self.style = style
self.dampening = dampening
self.position = position
self.size = size
self.scale = scale
self.verticalScalingFactor = verticalScalingFactor
self.shouldAntialias = shouldAntialias
}
/// Build a new `Waveform.Configuration` with only the given parameters replaced.
public func with(size: CGSize? = nil,
backgroundColor: DSColor? = nil,
style: Style? = nil,
dampening: Dampening? = nil,
position: Position? = nil,
scale: CGFloat? = nil,
verticalScalingFactor: CGFloat? = nil,
shouldAntialias: Bool? = nil
) -> Configuration {
Configuration(
size: size ?? self.size,
backgroundColor: backgroundColor ?? self.backgroundColor,
style: style ?? self.style,
dampening: dampening ?? self.dampening,
position: position ?? self.position,
scale: scale ?? self.scale,
verticalScalingFactor: verticalScalingFactor ?? self.verticalScalingFactor,
shouldAntialias: shouldAntialias ?? self.shouldAntialias
)
}
}
}
| ff0c00e38f537a58bdbe759668c6e55d | 37.786047 | 149 | 0.5888 | false | false | false | false |
vermont42/Conjugar | refs/heads/master | Conjugar/ReviewPrompter.swift | agpl-3.0 | 1 | //
// ReviewPrompter.swift
// Conjugar
//
// Created by Joshua Adams on 1/5/18.
// Copyright © 2018 Josh Adams. All rights reserved.
//
import StoreKit
struct ReviewPrompter: ReviewPromptable {
static let shared = ReviewPrompter()
static let promptModulo = 9
static let promptInterval: TimeInterval = 60 * 60 * 24 * 180
private let settings: Settings
private let now: Date
private let requestReview: () -> ()
private static let defaultRequestReview: () -> () = { (UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene).map { SKStoreReviewController.requestReview(in: $0) } }
init(settings: Settings = Settings(getterSetter: UserDefaultsGetterSetter()), now: Date = Date(), requestReview: @escaping () -> () = ReviewPrompter.defaultRequestReview) {
self.settings = settings
self.now = now
self.requestReview = requestReview
}
func promptableActionHappened() {
var actionCount = settings.promptActionCount
actionCount += 1
settings.promptActionCount = actionCount
let lastReviewPromptDate = settings.lastReviewPromptDate
if actionCount % ReviewPrompter.promptModulo == 0 && now.timeIntervalSince(lastReviewPromptDate) >= ReviewPrompter.promptInterval {
requestReview()
settings.lastReviewPromptDate = now
}
}
}
| 1a66849f9ae937d969cc6ae2398641e2 | 36.388889 | 226 | 0.728083 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | refs/heads/master | Foundation/TimeZone.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
internal func __NSTimeZoneIsAutoupdating(_ timezone: NSTimeZone) -> Bool {
return false
}
internal func __NSTimeZoneAutoupdating() -> NSTimeZone {
return NSTimeZone.local._nsObject
}
internal func __NSTimeZoneCurrent() -> NSTimeZone {
return NSTimeZone.system._nsObject
}
/**
`TimeZone` defines the behavior of a time zone. Time zone values represent geopolitical regions. Consequently, these values have names for these regions. Time zone values also represent a temporal offset, either plus or minus, from Greenwich Mean Time (GMT) and an abbreviation (such as PST for Pacific Standard Time).
`TimeZone` provides two static functions to get time zone values: `current` and `autoupdatingCurrent`. The `autoupdatingCurrent` time zone automatically tracks updates made by the user.
Note that time zone database entries such as “America/Los_Angeles” are IDs, not names. An example of a time zone name is “Pacific Daylight Time”. Although many `TimeZone` functions include the word “name”, they refer to IDs.
Cocoa does not provide any API to change the time zone of the computer, or of other applications.
*/
public struct TimeZone : Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSTimeZone
internal var _wrapped : NSTimeZone
internal var _autoupdating : Bool
/// The time zone currently used by the system.
public static var current : TimeZone {
return TimeZone(adoptingReference: __NSTimeZoneCurrent(), autoupdating: false)
}
/// The time zone currently used by the system, automatically updating to the user's current preference.
///
/// If this time zone is mutated, then it no longer tracks the application time zone.
///
/// The autoupdating time zone only compares equal to itself.
public static var autoupdatingCurrent : TimeZone {
return TimeZone(adoptingReference: __NSTimeZoneAutoupdating(), autoupdating: true)
}
// MARK: -
//
/// Returns a time zone initialized with a given identifier.
///
/// An example identifier is "America/Los_Angeles".
///
/// If `identifier` is an unknown identifier, then returns `nil`.
public init?(identifier: String) {
if let r = NSTimeZone(name: identifier) {
_wrapped = r
_autoupdating = false
} else {
return nil
}
}
@available(*, unavailable, renamed: "init(secondsFromGMT:)")
public init(forSecondsFromGMT seconds: Int) { fatalError() }
/// Returns a time zone initialized with a specific number of seconds from GMT.
///
/// Time zones created with this never have daylight savings and the offset is constant no matter the date. The identifier and abbreviation do NOT follow the POSIX convention (of minutes-west).
///
/// - parameter seconds: The number of seconds from GMT.
/// - returns: A time zone, or `nil` if a valid time zone could not be created from `seconds`.
public init?(secondsFromGMT seconds: Int) {
if let r = NSTimeZone(forSecondsFromGMT: seconds) as NSTimeZone? {
_wrapped = r
_autoupdating = false
} else {
return nil
}
}
/// Returns a time zone identified by a given abbreviation.
///
/// In general, you are discouraged from using abbreviations except for unique instances such as “GMT”. Time Zone abbreviations are not standardized and so a given abbreviation may have multiple meanings—for example, “EST” refers to Eastern Time in both the United States and Australia
///
/// - parameter abbreviation: The abbreviation for the time zone.
/// - returns: A time zone identified by abbreviation determined by resolving the abbreviation to a identifier using the abbreviation dictionary and then returning the time zone for that identifier. Returns `nil` if there is no match for abbreviation.
public init?(abbreviation: String) {
if let r = NSTimeZone(abbreviation: abbreviation) {
_wrapped = r
_autoupdating = false
} else {
return nil
}
}
internal init(reference: NSTimeZone) {
if __NSTimeZoneIsAutoupdating(reference) {
// we can't copy this or we lose its auto-ness (27048257)
// fortunately it's immutable
_autoupdating = true
_wrapped = reference
} else {
_autoupdating = false
_wrapped = reference.copy() as! NSTimeZone
}
}
private init(adoptingReference reference: NSTimeZone, autoupdating: Bool) {
// this path is only used for types we do not need to copy (we are adopting the ref)
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
@available(*, unavailable, renamed: "identifier")
public var name: String { fatalError() }
/// The geopolitical region identifier that identifies the time zone.
public var identifier: String {
return _wrapped.name
}
@available(*, unavailable, message: "use the identifier instead")
public var data: Data { fatalError() }
/// The current difference in seconds between the time zone and Greenwich Mean Time.
///
/// - parameter date: The date to use for the calculation. The default value is the current date.
public func secondsFromGMT(for date: Date = Date()) -> Int {
return _wrapped.secondsFromGMT(for: date)
}
/// Returns the abbreviation for the time zone at a given date.
///
/// Note that the abbreviation may be different at different dates. For example, during daylight saving time the US/Eastern time zone has an abbreviation of “EDT.” At other times, its abbreviation is “EST.”
/// - parameter date: The date to use for the calculation. The default value is the current date.
public func abbreviation(for date: Date = Date()) -> String? {
return _wrapped.abbreviation(for: date)
}
/// Returns a Boolean value that indicates whether the receiver uses daylight saving time at a given date.
///
/// - parameter date: The date to use for the calculation. The default value is the current date.
public func isDaylightSavingTime(for date: Date = Date()) -> Bool {
return _wrapped.isDaylightSavingTime(for: date)
}
/// Returns the daylight saving time offset for a given date.
///
/// - parameter date: The date to use for the calculation. The default value is the current date.
public func daylightSavingTimeOffset(for date: Date = Date()) -> TimeInterval {
return _wrapped.daylightSavingTimeOffset(for: date)
}
/// Returns the next daylight saving time transition after a given date.
///
/// - parameter date: A date.
/// - returns: The next daylight saving time transition after `date`. Depending on the time zone, this function may return a change of the time zone's offset from GMT. Returns `nil` if the time zone of the receiver does not observe daylight savings time as of `date`.
public func nextDaylightSavingTimeTransition(after date: Date) -> Date? {
return _wrapped.nextDaylightSavingTimeTransition(after: date)
}
/// Returns an array of strings listing the identifier of all the time zones known to the system.
public static var knownTimeZoneIdentifiers : [String] {
return NSTimeZone.knownTimeZoneNames
}
/// Returns the mapping of abbreviations to time zone identifiers.
public static var abbreviationDictionary : [String : String] {
get {
return NSTimeZone.abbreviationDictionary
}
set {
NSTimeZone.abbreviationDictionary = newValue
}
}
/// Returns the time zone data version.
public static var timeZoneDataVersion : String {
return NSTimeZone.timeZoneDataVersion
}
/// Returns the date of the next (after the current instant) daylight saving time transition for the time zone. Depending on the time zone, the value of this property may represent a change of the time zone's offset from GMT. Returns `nil` if the time zone does not currently observe daylight saving time.
public var nextDaylightSavingTimeTransition: Date? {
return _wrapped.nextDaylightSavingTimeTransition
}
@available(*, unavailable, renamed: "localizedName(for:locale:)")
public func localizedName(_ style: NSTimeZone.NameStyle, locale: Locale?) -> String? { fatalError() }
/// Returns the name of the receiver localized for a given locale.
public func localizedName(for style: NSTimeZone.NameStyle, locale: Locale?) -> String? {
return _wrapped.localizedName(style, locale: locale)
}
// MARK: -
public var hashValue : Int {
if _autoupdating {
return 1
} else {
return _wrapped.hash
}
}
public static func ==(lhs: TimeZone, rhs: TimeZone) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension TimeZone : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
private var _kindDescription : String {
if (self == TimeZone.current) {
return "current"
} else {
return "fixed"
}
}
public var customMirror : Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "identifier", value: identifier))
c.append((label: "kind", value: _kindDescription))
c.append((label: "abbreviation", value: abbreviation() as Any))
c.append((label: "secondsFromGMT", value: secondsFromGMT()))
c.append((label: "isDaylightSavingTime", value: isDaylightSavingTime()))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
public var description: String {
return "\(identifier) (\(_kindDescription))"
}
public var debugDescription : String {
return "\(identifier) (\(_kindDescription))"
}
}
extension TimeZone {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSTimeZone {
// _wrapped is immutable
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSTimeZone, result: inout TimeZone?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(NSTimeZone.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSTimeZone, result: inout TimeZone?) -> Bool {
result = TimeZone(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSTimeZone?) -> TimeZone {
var result: TimeZone? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
| 871ce3d00ed0ca09af43879c1d10e544 | 40.690391 | 319 | 0.656765 | false | false | false | false |
thion/bialoszewski.app | refs/heads/master | bialoszewski/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// bialoszewski
//
// Created by Kamil Nicieja on 20/07/14.
// Copyright (c) 2014 Kamil Nicieja. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let info: NSDictionary = NSBundle.mainBundle().infoDictionary
let storyboard: UIStoryboard = UIStoryboard()
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
let secret: String = info.objectForKey("Dropbox App Secret") as String
let key: String = info.objectForKey("Dropbox App Key") as String
let accountManager:DBAccountManager = DBAccountManager(appKey: key, secret: secret)
DBAccountManager.setSharedManager(accountManager)
return true
}
func application(application: UIApplication!, openURL url: NSURL!, sourceApplication source: NSString!, annotation: AnyObject!) -> Bool {
if let account: DBAccount = DBAccountManager.sharedManager().handleOpenURL(url) {
let filesystem: DBFilesystem = DBFilesystem(account: account)
DBFilesystem.setSharedFilesystem(filesystem)
return true
}
return false
}
}
| 2135acee080cb6c9ee9fc10b409430fa | 31.02439 | 141 | 0.681645 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/SpeechToText+Recognize.swift | mit | 1 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
#if os(Linux)
#else
import Foundation
import AVFoundation
private var microphoneSession: SpeechToTextSession?
extension SpeechToText {
/**
Perform speech recognition for an audio file.
- parameter audio: The audio file to transcribe.
- parameter settings: The configuration to use for this recognition request.
- parameter model: The language and sample rate of the audio. For supported models, visit
https://console.bluemix.net/docs/services/speech-to-text/input.html#models.
- parameter customizationID: The GUID of a custom language model that is to be used with the
request. The base language model of the specified custom language model must match the
model specified with the `model` parameter. By default, no custom model is used.
- parameter learningOptOut: If `true`, then this request will not be logged for training.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func recognize(
audio: URL,
settings: RecognitionSettings,
model: String? = nil,
customizationID: String? = nil,
learningOptOut: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (SpeechRecognitionResults) -> Void)
{
do {
let data = try Data(contentsOf: audio)
recognize(
audio: data,
settings: settings,
model: model,
customizationID: customizationID,
learningOptOut: learningOptOut,
failure: failure,
success: success
)
} catch {
let failureReason = "Could not load audio data from \(audio)."
let userInfo = [NSLocalizedDescriptionKey: failureReason]
let error = NSError(domain: domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
}
/**
Perform speech recognition for audio data.
- parameter audio: The audio data to transcribe.
- parameter settings: The configuration to use for this recognition request.
- parameter model: The language and sample rate of the audio. For supported models, visit
https://console.bluemix.net/docs/services/speech-to-text/input.html#models.
- parameter customizationID: The GUID of a custom language model that is to be used with the
request. The base language model of the specified custom language model must match the
model specified with the `model` parameter. By default, no custom model is used.
- parameter learningOptOut: If `true`, then this request will not be logged for training.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func recognize(
audio: Data,
settings: RecognitionSettings,
model: String? = nil,
customizationID: String? = nil,
learningOptOut: Bool? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (SpeechRecognitionResults) -> Void)
{
// extract credentials
guard case let .basicAuthentication(username, password) = credentials else {
let failureReason = "Invalid credentials format."
let userInfo = [NSLocalizedDescriptionKey: failureReason]
let error = NSError(domain: domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
// create session
let session = SpeechToTextSession(
username: username,
password: password,
model: model,
customizationID: customizationID,
learningOptOut: learningOptOut
)
// set urls
session.serviceURL = serviceURL
session.tokenURL = tokenURL
session.websocketsURL = websocketsURL
// set headers
session.defaultHeaders = defaultHeaders
// set callbacks
session.onResults = success
session.onError = failure
// execute recognition request
session.connect()
session.startRequest(settings: settings)
session.recognize(audio: audio)
session.stopRequest()
session.disconnect()
}
/**
Perform speech recognition for microphone audio. To stop the microphone, invoke
`stopRecognizeMicrophone()`.
Microphone audio is compressed to Opus format unless otherwise specified by the `compress`
parameter. With compression enabled, the `settings` should specify a `contentType` of
"audio/ogg;codecs=opus". With compression disabled, the `settings` should specify a
`contentType` of "audio/l16;rate=16000;channels=1".
This function may cause the system to automatically prompt the user for permission
to access the microphone. Use `AVAudioSession.requestRecordPermission(_:)` if you
would prefer to ask for the user's permission in advance.
- parameter settings: The configuration for this transcription request.
- parameter model: The language and sample rate of the audio. For supported models, visit
https://console.bluemix.net/docs/services/speech-to-text/input.html#models.
- parameter customizationID: The GUID of a custom language model that is to be used with the
request. The base language model of the specified custom language model must match the
model specified with the `model` parameter. By default, no custom model is used.
- parameter learningOptOut: If `true`, then this request will not be logged for training.
- parameter compress: Should microphone audio be compressed to Opus format?
(Opus compression reduces latency and bandwidth.)
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func recognizeMicrophone(
settings: RecognitionSettings,
model: String? = nil,
customizationID: String? = nil,
learningOptOut: Bool? = nil,
compress: Bool = true,
failure: ((Error) -> Void)? = nil,
success: @escaping (SpeechRecognitionResults) -> Void)
{
// make sure the AVAudioSession shared instance is properly configured
do {
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker, .mixWithOthers])
try audioSession.setActive(true)
} catch {
let failureReason = "Failed to setup the AVAudioSession sharedInstance properly."
let userInfo = [NSLocalizedDescriptionKey: failureReason]
let error = NSError(domain: self.domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
// validate settings
var settings = settings
settings.contentType = compress ? "audio/ogg;codecs=opus" : "audio/l16;rate=16000;channels=1"
// extract credentials
guard case let .basicAuthentication(username, password) = credentials else {
let failureReason = "Invalid credentials format."
let userInfo = [NSLocalizedDescriptionKey: failureReason]
let error = NSError(domain: domain, code: 0, userInfo: userInfo)
failure?(error)
return
}
// create session
let session = SpeechToTextSession(
username: username,
password: password,
model: model,
customizationID: customizationID,
learningOptOut: learningOptOut
)
// set urls
session.serviceURL = serviceURL
session.tokenURL = tokenURL
session.websocketsURL = websocketsURL
// set headers
session.defaultHeaders = defaultHeaders
// set callbacks
session.onResults = success
session.onError = failure
// start recognition request
session.connect()
session.startRequest(settings: settings)
session.startMicrophone(compress: compress)
// store session
microphoneSession = session
}
/**
Stop performing speech recognition for microphone audio.
When invoked, this function will
1. Stop recording audio from the microphone.
2. Send a stop message to stop the current recognition request.
3. Wait to receive all recognition results then disconnect from the service.
*/
public func stopRecognizeMicrophone() {
microphoneSession?.stopMicrophone()
microphoneSession?.stopRequest()
microphoneSession?.disconnect()
}
}
#endif
| d9fff53551637017fe1109342b4a151a | 39.288703 | 120 | 0.663932 | false | false | false | false |
vincentSuwenliang/Mechandising | refs/heads/master | MerchandisingSystem/LanguageManager.swift | mit | 1 | //
// LanguageManager.swift
// ccconnected
//
// Created by SuVincent on 4/2/2017.
// Copyright © 2017 hk.com.cloudpillar. All rights reserved.
//
import UIKit
class LanguageManager: NSObject {
static let sharedInstance = LanguageManager() // singleton
var availableLocales: [LanguageCode] = [.ChineseSimplified, .ChineseTraditional, .English]
var lprojBasePath: LanguageCode = .ChineseTraditional
override fileprivate init() {
super.init()
self.lprojBasePath = getSelectedLocale()
}
fileprivate func getSelectedLocale() -> LanguageCode {
let lang = Locale.preferredLanguages
let languageComponents: [String : String] = Locale.components(fromIdentifier: lang[0])
// use the system default language as language but can reset in-app
if let languageCode = languageComponents["kCFLocaleLanguageCodeKey"]{
let scriptCode = languageComponents["kCFLocaleScriptCodeKey"]
var fullLocaleCode = languageCode
if scriptCode != nil {
fullLocaleCode = "\(languageCode)-\(scriptCode!)"
}
print("lprojBasePath fsadfas",fullLocaleCode)
for availableLocale in availableLocales {
if(availableLocale.code == fullLocaleCode){
return availableLocale
}
}
}
return .ChineseTraditional
}
// pubilc function
func getCurrentBundle() -> Bundle {
if let bundle = Bundle.main.path(forResource: lprojBasePath.code, ofType: "lproj"){
return Bundle(path: bundle)!
}else{
fatalError("lproj files not found on project directory. /n Hint:Localize your strings file")
}
}
func setLocale(langCode:String){
UserDefaults.standard.set([langCode], forKey: "AppleLanguages")//replaces Locale.preferredLanguages
self.lprojBasePath = getSelectedLocale()
}
// get country name base on current setting language and country code
func getCountryName(by countryCode: String) -> String? {
let currentlocal = Locale(identifier: lprojBasePath.code)
let countryName = currentlocal.localizedString(forRegionCode: countryCode)
return countryName
}
}
| 1454cce1c5a96c48f92a90e743d1f724 | 30.783784 | 107 | 0.635204 | false | false | false | false |
kildevaeld/FASlideView | refs/heads/master | Example/Pods/Quick/Quick/Callsite.swift | mit | 2 | /**
An object encapsulating the file and line number at which
a particular example is defined.
*/
final public class Callsite: Equatable {
/**
The absolute path of the file in which an example is defined.
*/
public let file: String
/**
The line number on which an example is defined.
*/
public let line: Int
internal init(file: String, line: Int) {
self.file = file
self.line = line
}
}
/**
Returns a boolean indicating whether two Callsite objects are equal.
If two callsites are in the same file and on the same line, they must be equal.
*/
public func ==(lhs: Callsite, rhs: Callsite) -> Bool {
return lhs.file == rhs.file && lhs.line == rhs.line
}
| e55b6cc43418b57870ebd73eebeafa3b | 25.392857 | 83 | 0.638701 | false | false | false | false |
tarrgor/LctvSwift | refs/heads/master | Sources/LctvApi+Rest.swift | mit | 1 | //
// LctvApi+Rest.swift
// Pods
//
//
//
import Foundation
import Alamofire
import SwiftyJSON
extension LctvApi {
func pagingParameters(page: Int? = 0) -> [String:String] {
return [
"limit":"\(pageSize)",
"offset":"\(page ?? 0 * pageSize)"
]
}
func get(url: String, success: (JSON) -> (), failure: (String, JSON?) -> ()) {
get(url, parameters: [:], success: success, failure: failure)
}
func get(url: String, page: Int, success: (JSON) -> (), failure: (String, JSON?) -> ()) {
get(url, parameters: pagingParameters(page), success: success, failure: failure)
}
func get(url: String, parameters: [String:String], success: (JSON) -> (), failure: (String, JSON?) -> ()) {
let headers = httpHeaders()
Alamofire.request(.GET, url, parameters: parameters, headers: headers).responseJSON { response in
if let status = response.response?.statusCode {
let json = JSON(data: response.data!)
if status == 200 {
success(json)
} else {
if let message = json["detail"].string {
failure(message, json)
} else {
failure("No valid error message", json)
}
}
} else {
failure("No valid status code", nil)
}
}
}
} | 69b8ceb411668231a5fd6d356bdc7f46 | 25.916667 | 109 | 0.565453 | false | false | false | false |
jsslai/Action | refs/heads/master | Carthage/Checkouts/RxSwift/RxExample/RxExample-iOSTests/TestScheduler+MarbleTests.swift | mit | 3 | //
// TestScheduler+MarbleTests.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import RxTests
import RxCocoa
/**
There are examples like this all over the web, but I think that I've first something like this here
https://github.com/ReactiveX/RxJS/blob/master/doc/writing-marble-tests.md
These tests are called marble tests.
*/
extension TestScheduler {
/**
Transformation from this format:
---a---b------c-----
to this format
schedule onNext(1) @ 0.6s
schedule onNext(2) @ 1.4s
schedule onNext(3) @ 7.0s
....
]
You can also specify retry data in this format:
---a---b------c----#|----a--#|----b
- letters and digits mark values
- `#` marks unknown error
- `|` marks sequence completed
*/
func parseEventsAndTimes<T>(timeline: String, values: [String: T], errors: [String: Swift.Error] = [:]) -> [[Recorded<Event<T>>]] {
//print("parsing: \(timeline)")
typealias RecordedEvent = Recorded<Event<T>>
let timelines = timeline.components(separatedBy: "|")
let allExceptLast = timelines[0 ..< timelines.count - 1]
return (allExceptLast.map { $0 + "|" } + [timelines.last!])
.filter { $0.characters.count > 0 }
.map { timeline -> [Recorded<Event<T>>] in
let segments = timeline.components(separatedBy:"-")
let (time: _, events: events) = segments.reduce((time: 0, events: [RecordedEvent]())) { state, event in
let tickIncrement = event.characters.count + 1
if event.characters.count == 0 {
return (state.time + tickIncrement, state.events)
}
if event == "#" {
let errorEvent = RecordedEvent(time: state.time, event: Event<T>.error(NSError(domain: "Any error domain", code: -1, userInfo: nil)))
return (state.time + tickIncrement, state.events + [errorEvent])
}
if event == "|" {
let completed = RecordedEvent(time: state.time, event: Event<T>.completed)
return (state.time + tickIncrement, state.events + [completed])
}
guard let next = values[event] else {
guard let error = errors[event] else {
fatalError("Value with key \(event) not registered as value:\n\(values)\nor error:\n\(errors)")
}
let nextEvent = RecordedEvent(time: state.time, event: Event<T>.error(error))
return (state.time + tickIncrement, state.events + [nextEvent])
}
let nextEvent = RecordedEvent(time: state.time, event: Event<T>.next(next))
return (state.time + tickIncrement, state.events + [nextEvent])
}
//print("parsed: \(events)")
return events
}
}
/**
Creates driver for marble test.
- parameter timeline: Timeline in the form `---a---b------c--|`
- parameter values: Dictionary of values in timeline. `[a:1, b:2]`
- returns: Driver specified by timeline and values.
*/
func createDriver<T>(timeline: String, values: [String: T]) -> Driver<T> {
return createObservable(timeline: timeline, values: values, errors: [:]).asDriver(onErrorRecover: { (error) -> Driver<T> in
fatalError("This can't error out")
return Driver.never()
})
}
/**
Creates observable for marble tests.
- parameter timeline: Timeline in the form `---a---b------c--|`
- parameter values: Dictionary of values in timeline. `[a:1, b:2]`
- parameter errors: Dictionary of errors in timeline.
- returns: Observable sequence specified by timeline and values.
*/
func createObservable<T>(timeline: String, values: [String: T], errors: [String: Swift.Error] = [:]) -> Observable<T> {
let events = self.parseEventsAndTimes(timeline: timeline, values: values, errors: errors)
return createObservable(events)
}
/**
Creates observable for marble tests.
- parameter events: Recorded events to replay.
- returns: Observable sequence specified by timeline and values.
*/
func createObservable<T>(_ events: [Recorded<Event<T>>]) -> Observable<T> {
return createObservable([events])
}
/**
Creates observable for marble tests.
- parameter events: Recorded events to replay. This overloads enables modeling of retries.
`---a---b------c----#|----a--#|----b`
When next observer is subscribed, next sequence will be replayed. If all sequences have
been replayed and new observer is subscribed, `fatalError` will be raised.
- returns: Observable sequence specified by timeline and values.
*/
func createObservable<T>(_ events: [[Recorded<Event<T>>]]) -> Observable<T> {
var attemptCount = 0
print("created for \(events)")
return Observable.create { observer in
if attemptCount >= events.count {
fatalError("This is attempt # \(attemptCount + 1), but timeline only allows \(events.count).\n\(events)")
}
let scheduledEvents = events[attemptCount].map { event in
return self.scheduleRelative((), dueTime: resolution * TimeInterval(event.time)) { _ in
observer.on(event.value)
return Disposables.create()
}
}
attemptCount += 1
return Disposables.create(scheduledEvents)
}
}
/**
Enables simple construction of mock implementations from marble timelines.
- parameter Arg: Type of arguments of mocked method.
- parameter Ret: Return type of mocked method. `Observable<Ret>`
- parameter values: Dictionary of values in timeline. `[a:1, b:2]`
- parameter errors: Dictionary of errors in timeline.
- parameter timelineSelector: Method implementation. The returned string value represents timeline of
returned observable sequence. `---a---b------c----#|----a--#|----b`
- returns: Implementation of method that accepts arguments with parameter `Arg` and returns observable sequence
with parameter `Ret`.
*/
func mock<Arg, Ret>(values: [String: Ret], errors: [String: Swift.Error] = [:], timelineSelector: @escaping (Arg) -> String) -> (Arg) -> Observable<Ret> {
return { (parameters: Arg) -> Observable<Ret> in
let timeline = timelineSelector(parameters)
return self.createObservable(timeline: timeline, values: values, errors: errors)
}
}
/**
Builds testable observer for s specific observable sequence, binds it's results and sets up disposal.
- parameter source: Observable sequence to observe.
- returns: Observer that records all events for observable sequence.
*/
func record<O: ObservableConvertibleType>(source: O) -> TestableObserver<O.E> {
let observer = self.createObserver(O.E.self)
let disposable = source.asObservable().bindTo(observer)
self.scheduleAt(100000) {
disposable.dispose()
}
return observer
}
}
| 3876dc2bfd81c88f8452a898fc19c215 | 36.969849 | 158 | 0.588936 | false | true | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKitUI/controller/TKUIAutocompletionViewController.swift | apache-2.0 | 1 | //
// TKUIAutocompletionViewController.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 05.07.18.
// Copyright © 2018 SkedGo Pty Ltd. All rights reserved.
//
import UIKit
import MapKit
import RxCocoa
import RxSwift
import TripKit
public protocol TKUIAutocompletionViewControllerDelegate: AnyObject {
func autocompleter(_ controller: TKUIAutocompletionViewController, didSelect selection: TKAutocompletionSelection)
func autocompleter(_ controller: TKUIAutocompletionViewController, didSelectAccessoryFor selection: TKAutocompletionSelection)
}
/// Displays autocompletion results from search
///
/// Typically used as a `searchResultsController` being passed
/// to a `UISearchController` and assigned to that search
/// controller's `searchResultsUpdater` property.
public class TKUIAutocompletionViewController: UITableViewController {
public let providers: [TKAutocompleting]
public weak var delegate: TKUIAutocompletionViewControllerDelegate?
public var showAccessoryButtons = true
public var biasMapRect: MKMapRect = .null
private var viewModel: TKUIAutocompletionViewModel!
private let disposeBag = DisposeBag()
private let searchText = PublishSubject<(String, forced: Bool)>()
private let accessoryTapped = PublishSubject<TKUIAutocompletionViewModel.Item>()
public init(providers: [TKAutocompleting]) {
self.providers = providers
super.init(style: .plain)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
let dataSource = RxTableViewSectionedAnimatedDataSource<TKUIAutocompletionViewModel.Section>(
configureCell: { [weak self] _, tv, ip, item in
guard let self = self else {
// Shouldn't but can happen on dealloc
return UITableViewCell(style: .default, reuseIdentifier: nil)
}
guard let cell = tv.dequeueReusableCell(withIdentifier: TKUIAutocompletionResultCell.reuseIdentifier, for: ip) as? TKUIAutocompletionResultCell else {
preconditionFailure("Couldn't dequeue TKUIAutocompletionResultCell")
}
cell.configure(
with: item,
onAccessoryTapped: self.showAccessoryButtons ? { self.accessoryTapped.onNext($0) } : nil
)
return cell
},
titleForHeaderInSection: { ds, index in
return ds.sectionModels[index].title
}
)
// Reset to `nil` as we'll overwrite these
tableView.delegate = nil
tableView.dataSource = nil
tableView.register(TKUIAutocompletionResultCell.self, forCellReuseIdentifier: TKUIAutocompletionResultCell.reuseIdentifier)
viewModel = TKUIAutocompletionViewModel(
providers: providers,
searchText: searchText,
selected: tableView.rx.itemSelected.map { dataSource[$0] }.asSignal(onErrorSignalWith: .empty()),
accessorySelected: accessoryTapped.asSignal(onErrorSignalWith: .empty()),
biasMapRect: .just(biasMapRect)
)
viewModel.sections
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
viewModel.selection
.emit(onNext: { [weak self] annotation in
guard let self = self else { return }
self.delegate?.autocompleter(self, didSelect: annotation)
})
.disposed(by: disposeBag)
viewModel.accessorySelection
.emit(onNext: { [weak self] annotation in
guard let self = self else { return }
self.delegate?.autocompleter(self, didSelectAccessoryFor: annotation)
})
.disposed(by: disposeBag)
viewModel.triggerAction
.asObservable()
.flatMapLatest { [weak self] provider -> Observable<Bool> in
guard let self = self else { return .empty() }
return provider.triggerAdditional(presenter: self).asObservable()
}
.subscribe()
.disposed(by: disposeBag)
viewModel.error
.emit(onNext: { [weak self] in self?.showErrorAsAlert($0) })
.disposed(by: disposeBag)
tableView.rx.setDelegate(self)
.disposed(by: disposeBag)
}
}
extension TKUIAutocompletionViewController {
public override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > 40, !scrollView.isDecelerating {
// we are actively scrolling a fair bit => disable the keyboard
(parent as? UISearchController)?.searchBar.resignFirstResponder()
}
}
}
extension TKUIAutocompletionViewController: UISearchResultsUpdating {
public func updateSearchResults(for searchController: UISearchController) {
searchText.onNext((searchController.searchBar.text ?? "", forced: false))
}
}
| 4b14757d3ff2678f6a3ab6dd3eefb210 | 31.972222 | 158 | 0.713353 | false | false | false | false |
adamdahan/GraphKit | refs/heads/v3.x.x | Source/ActionGroup.swift | agpl-3.0 | 1 | //
// Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program located at the root of the software package
// in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>.
//
// #internal
import CoreData
@objc(ActionGroup)
internal class ActionGroup : NSManagedObject {
@NSManaged internal var name: String
@NSManaged internal var node: ManagedAction
private var context: NSManagedObjectContext?
internal var worker: NSManagedObjectContext? {
if nil == context {
let graph: Graph = Graph()
context = graph.worker
}
return context
}
/**
:name: init
:description: Initializer for the Model Object.
*/
convenience init(name: String) {
let g: Graph = Graph()
var w: NSManagedObjectContext? = g.worker
self.init(entity: NSEntityDescription.entityForName(GraphUtility.actionGroupDescriptionName, inManagedObjectContext: w!)!, insertIntoManagedObjectContext: w)
self.name = name
context = w
}
/**
:name: delete
:description: Deletes the Object Model.
*/
internal func delete() {
worker?.deleteObject(self)
}
}
| 1a35170ab7ce5754083b16cfdd813dff | 29.678571 | 159 | 0.738068 | false | false | false | false |
leotao2014/RTRefresh | refs/heads/master | RefreshComponent/RTRefreshBackStateFooter.swift | apache-2.0 | 1 | //
// RTRefreshBackStateFooter.swift
// RefreshComponent
//
// Created by leotao on 2017/1/7.
// Copyright © 2017年 leotao. All rights reserved.
//
import UIKit
class RTRefreshBackStateFooter: RTRefreshBackFooter {
var stateLabel:UILabel = {
let label = UILabel();
label.textColor = UIColor.rt_rgb(red: 90, blue: 90, green: 90);
label.font = UIFont.systemFont(ofSize: 14);
return label;
}();
override var state: RTRefreshState {
didSet {
print("子类didSet");
switch state {
case .refreshing:
self.stateLabel.text = "正在刷新...";
case .normal:
self.stateLabel.text = "上拉可以加载更多";
case .pulling:
self.stateLabel.text = "松开立即加载更多";
case .noMoreData:
self.stateLabel.text = "没有更多数据了";
default:
break;
}
}
}
override func setupSubviews() {
self.addSubview(stateLabel);
}
override func placeSubviews() {
super.placeSubviews();
let size = (self.stateLabel.text as NSString?)?.size(attributes: [NSFontAttributeName : self.stateLabel.font]);
if let size = size {
self.stateLabel.frame = CGRect(x: (self.width - size.width) * 0.5, y: (self.height - size.height) * 0.5, width: size.width, height: size.height);
}
print(self.stateLabel);
}
}
| 71a18f092193a46cd3d064ec51b00894 | 27.596154 | 157 | 0.548756 | false | false | false | false |
samodom/TestableCoreLocation | refs/heads/master | TestableCoreLocation/CLLocationManager/CLLocationManagerRequestAlwaysAuthorizationSpy.swift | mit | 1 | //
// CLLocationManagerRequestAlwaysAuthorizationSpy.swift
// TestableCoreLocation
//
// Created by Sam Odom on 3/6/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import CoreLocation
import FoundationSwagger
import TestSwagger
public extension CLLocationManager {
private static let requestAlwaysAuthorizationCalledKeyString = UUIDKeyString()
private static let requestAlwaysAuthorizationCalledKey =
ObjectAssociationKey(requestAlwaysAuthorizationCalledKeyString)
private static let requestAlwaysAuthorizationCalledReference =
SpyEvidenceReference(key: requestAlwaysAuthorizationCalledKey)
/// Spy controller for ensuring that a location manager has had `requestAlwaysAuthorization`
/// called on it.
public enum RequestAlwaysAuthorizationSpyController: SpyController {
public static let rootSpyableClass: AnyClass = CLLocationManager.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(CLLocationManager.requestAlwaysAuthorization),
spy: #selector(CLLocationManager.spy_requestAlwaysAuthorization)
)
] as Set
public static let evidence = [requestAlwaysAuthorizationCalledReference] as Set
public static let forwardsInvocations = false
}
/// Spy method that replaces the true implementation of `requestAlwaysAuthorization`
dynamic public func spy_requestAlwaysAuthorization() {
requestAlwaysAuthorizationCalled = true
}
/// Indicates whether the `requestAlwaysAuthorization` method has been called on this object.
public final var requestAlwaysAuthorizationCalled: Bool {
get {
return loadEvidence(with: CLLocationManager.requestAlwaysAuthorizationCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: CLLocationManager.requestAlwaysAuthorizationCalledReference)
}
}
}
| c2aa28f9050bd19c9ee5adc0e80b6a39 | 35.767857 | 116 | 0.73288 | false | false | false | false |
zitao0322/ShopCar | refs/heads/master | Shoping_Car/Shoping_Car/Class/ShopingCar/View/ZTChangeCountView.swift | mit | 1 | //
// ZTChangeCountView.swift
// Shoping_Car
//
// Created by venusource on 16/8/15.
// Copyright © 2016年 venusource.com. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
private let kButtonSize: CGSize = CGSizeMake(29, 29)
class ZTChangeCountView: UIView {
var count: Int!{
didSet{
goodsCountText.text = "\(count!)"
addCountButton.enabled = !(count >= allCount || count == 99)
subCountButton.enabled = !(count <= 1)
}
}
private var allCount: Int!
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(subCountButton)
addSubview(addCountButton)
addSubview(goodsCountText)
}
func setupShopingCount(selected: Int, all: Int){
allCount = all
count = selected
}
lazy var goodsCountText: UITextField = {
let textF = UITextField()
textF.textAlignment = .Center
textF.keyboardType = .NumberPad
textF.layer.borderColor = UIColor.colorWithString("#dddddd").CGColor
textF.layer.borderWidth = 0.5
textF.textColor = UIColor.colorWithString("333333")
textF.font = kFont_14
return textF
}()
lazy var subCountButton: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "product_detail_sub_normal"), forState: .Normal)
btn.setBackgroundImage(UIImage(named: "product_detail_sub_no"), forState: .Disabled)
return btn
}()
lazy var addCountButton: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "product_detail_add_normal"), forState: .Normal)
btn.setBackgroundImage(UIImage(named: "product_detail_add_no"), forState: .Disabled)
return btn
}()
override func layoutSubviews() {
super.layoutSubviews()
let btnSize = CGSizeMake(height, height)
subCountButton.ff_AlignInner(type: .TopLeft,
referView: self,
size: btnSize)
goodsCountText.ff_AlignHorizontal(type: .TopRight,
referView: subCountButton,
size: CGSizeMake(width - 2 * height, height))
addCountButton.ff_AlignHorizontal(type: .TopRight,
referView: goodsCountText,
size: btnSize)
}
} | 670175daa8b76e16c64055def80f2100 | 28.11828 | 94 | 0.571851 | false | false | false | false |
DopamineLabs/DopamineKit-iOS | refs/heads/master | BoundlessKit/Classes/Integration/HttpClients/Data/Models/BoundlessVersion.swift | mit | 1 | //
// BoundlessVersion.swift
// BoundlessKit
//
// Created by Akash Desai on 3/10/18.
//
import Foundation
internal struct BoundlessVersion {
let name: String?
let mappings: [String: [String: Any]]
internal let database: BKUserDefaults
internal var trackBatch: BKTrackBatch
internal var reportBatch: BKReportBatch
internal var refreshContainer: BKRefreshCartridgeContainer
init(_ name: String? = nil,
_ mappings: [String: [String: Any]] = [:],
database: BKUserDefaults = BKUserDefaults.standard) {
self.name = name
self.mappings = mappings
self.database = database
self.trackBatch = BKTrackBatch.initWith(database: database, forKey: "trackBatch")
self.reportBatch = BKReportBatch.initWith(database: database, forKey: "reportBatch")
self.refreshContainer = BKRefreshCartridgeContainer.initWith(database: database, forKey: "refreshContainer")
}
}
extension BoundlessVersion {
init?(data: Data, database: BKUserDefaults) {
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
defer {
unarchiver.finishDecoding()
}
guard let versionID = unarchiver.decodeObject(forKey: "versionID") as? String? else { return nil }
guard let mappings = unarchiver.decodeObject(forKey: "mappings") as? [String: [String: Any]] else { return nil }
self.init(versionID, mappings, database: database)
}
func encode() -> Data {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(name, forKey: "versionID")
archiver.encode(mappings, forKey: "mappings")
archiver.finishEncoding()
return data as Data
}
}
extension BoundlessVersion {
static func convert(from dict: [String: Any], database: BKUserDefaults) -> BoundlessVersion? {
guard let versionID = dict["versionID"] as? String else { BKLog.debug(error: "Bad parameter"); return nil }
let mappings = dict["mappings"] as? [String: [String: Any]] ?? [:]
return BoundlessVersion.init(
versionID,
mappings,
database: database
)
}
}
| a0a9372f06be1e85cd7917468d840a44 | 33.875 | 120 | 0.65233 | false | false | false | false |
cmidt-veasna/SwiftFlatbuffer | refs/heads/master | XCodeFlatbuffer/FlatbufferSwift/Sources/base.swift | apache-2.0 | 1 | //
// File.swift
// FlatbufferSwift
//
// Created by Veasna Sreng on 2/14/17.
//
//
import Foundation
// Data extension helper
extension Data {
public func get<T>(at: Int, withType: T.Type) -> T? {
let numberOfByte = at + MemoryLayout<T>.stride
if count <= numberOfByte || numberOfByte < 1 {
return nil
}
// TODO: investigate this option. Which cause memory allocation increate as it seem no deallocation has been perform
return withUnsafeBytes {
(ptr: UnsafePointer<T>) -> T in return ptr.advanced(by: (at/MemoryLayout<T>.stride)).pointee
}
}
public func getInteger<T: Integer>(at: Int) -> T {
let numberOfByte = at + MemoryLayout<T>.stride
if count <= numberOfByte || numberOfByte < 1 {
return 0
}
let copyCount = MemoryLayout<T>.stride
var bytes: [UInt8] = [UInt8](repeating: 0, count: copyCount)
copyBytes(to: &bytes, from: at ..< Data.Index(at + copyCount))
return UnsafePointer(bytes).withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
public func getFloatingPoint<T: FloatingPoint>(at: Int) -> T {
let numberOfByte = at + MemoryLayout<T>.stride
if count <= numberOfByte || numberOfByte < 1 {
return 0
}
let copyCount = MemoryLayout<T>.stride
var bytes: [UInt8] = [UInt8](repeating: 0, count: copyCount)
copyBytes(to: &bytes, from: at ..< Data.Index(at + copyCount))
return UnsafePointer(bytes).withMemoryRebound(to: T.self, capacity: 1) {
$0.pointee
}
}
public func getByte(at: Int) -> Int8 {
return getInteger(at: at)
}
public func getUnsignedByte(at: Int) -> UInt8 {
return getInteger(at: at)
}
public func getShort(at: Int) -> Int16 {
return getInteger(at: at)
}
public func getUsignedShort(at: Int) -> UInt16 {
return getInteger(at: at)
}
public func getInt(at: Int) -> Int32 {
return getInteger(at: at)
}
public func getUnsignedInt(at: Int) -> UInt32 {
return getInteger(at: at)
}
public func getLong(at: Int) -> Int64 {
return getInteger(at: at)
}
public func getUnsignedLong(at: Int) -> UInt64 {
return getInteger(at: at)
}
public func getVirtualTaleOffset(at: Int) -> Int {
return Int(getShort(at: at))
}
public func getOffset(at: Int) -> Int {
return Int(getInt(at: at))
}
public func getFloat(at: Int) -> Float {
return getFloatingPoint(at: at)
}
public func getDouble(at: Int) -> Double {
return getFloatingPoint(at: at)
}
public func getArray(at: Int, count: Int, withType: UInt8.Type) -> [UInt8]? {
var bytes: [UInt8] = [UInt8](repeating: 0, count: count)
copyBytes(to: &bytes, from: at ..< Data.Index(at + count))
return bytes
}
}
// String helper to extract Character by index of a string
extension String {
subscript (i: Int) -> Character {
return self[self.characters.index(self.startIndex, offsetBy: i)]
}
}
| da1a3dc0b8c5413cea9ce79ce333b436 | 26.956897 | 124 | 0.580019 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | SignalMessaging/Views/ImageEditor/ImageEditorPanGestureRecognizer.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
// This GR:
//
// * Tries to fail quickly to avoid conflicts with other GRs, especially pans/swipes.
// * Captures a bunch of useful "pan state" that makes using this GR much easier
// than UIPanGestureRecognizer.
public class ImageEditorPanGestureRecognizer: UIPanGestureRecognizer {
public weak var referenceView: UIView?
// Capture the location history of this gesture.
public var locationHistory = [CGPoint]()
public var locationFirst: CGPoint? {
return locationHistory.first
}
// MARK: - Touch Handling
@objc
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
updateLocationHistory(event: event)
super.touchesBegan(touches, with: event)
}
@objc
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
updateLocationHistory(event: event)
super.touchesMoved(touches, with: event)
}
@objc
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
updateLocationHistory(event: event)
super.touchesEnded(touches, with: event)
}
private func updateLocationHistory(event: UIEvent) {
guard let touches = event.allTouches,
touches.count > 0 else {
owsFailDebug("no touches.")
return
}
guard let referenceView = referenceView else {
owsFailDebug("Missing view")
return
}
// Find the centroid.
var location = CGPoint.zero
for touch in touches {
location = location.plus(touch.location(in: referenceView))
}
location = location.times(CGFloat(1) / CGFloat(touches.count))
locationHistory.append(location)
}
public override func reset() {
super.reset()
locationHistory.removeAll()
}
}
| 8bddf3dfe036bc017c2a14b922477eb4 | 27.1 | 85 | 0.645145 | false | false | false | false |
hayleyqinn/windWeather | refs/heads/master | 风生/风生/ViewController.swift | mit | 1 | //
// ViewController.swift
// 风生
//
// Created by 覃红 on 2016/10/22.
// Copyright © 2016年 hayleyqin. All rights reserved.
//
import UIKit
import JSONNeverDie
import Alamofire
import WechatKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, WechatManagerShareDelegate {
@IBOutlet weak var forecastT: UITableView!
@IBOutlet weak var cityN: UILabel!
@IBOutlet weak var aqi: UILabel!
@IBOutlet weak var tem: UILabel!
@IBOutlet weak var updateTime: UILabel!
@IBOutlet weak var aqiDes: UILabel!
@IBOutlet weak var con: UILabel!
@IBOutlet weak var conImage: UIImageView!
@IBOutlet weak var confO: UIButton!
@IBOutlet weak var conT: UILabel!
@IBOutlet weak var sportT: UILabel!
@IBOutlet weak var uvT: UILabel!
@IBOutlet weak var comT: UILabel!
@IBOutlet weak var carT: UILabel!
@IBOutlet weak var sportO: UIButton!
@IBOutlet weak var uvO: UIButton!
@IBOutlet weak var comO: UIButton!
@IBOutlet weak var carO: UIButton!
var suggestions: [String] = []
var isDisplaySug: [Bool] = []
var dateList:[String] = []
var conList:[String] = []
var temrList:[String] = []
@IBAction func shareBT(_ sender: Any) {
//exinfo is determine to return previousely app
let optionMenu = UIAlertController(title: "分享天气", message: "请选择要分享的平台", preferredStyle: .actionSheet)
let wechatAction = UIAlertAction(title: "微信好友", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
if self.suggestions.count > 0 {
WechatManager.sharedInstance.share(WXSceneSession, image: self.conImage.image, title: "\(self.cityN.text!)\(self.con.text!)", description: self.suggestions[4], url: "http://php.weather.sina.com.cn/search.php?f=1&c=1&city=\(self.cityN.text!)&dpc=1", extInfo: nil)
}
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
optionMenu.addAction(wechatAction)
optionMenu.addAction(cancelAction)
self.present(optionMenu, animated: true, completion: nil)
}
func showMessage(_ message: String) {
print(message)
}
@IBAction func carA(_ sender: Any) {
if self.suggestions.count != 0{
let sug = UITextView(frame: CGRect(x: carO.frame.origin.x - 22, y: 500, width: 70, height: 110))
sug.text = suggestions[0]
sug.isEditable = false
sug.tag = 5
sug.isSelectable = false
sug.layer.cornerRadius = 10
sug.backgroundColor = UIColor(red: 213/255, green: 239/255, blue: 236/255, alpha: 1)
if !self.isDisplaySug[4] {
//清楚非现在点击的其他已经弹出的视图
for i in 0..<5 {
if self.isDisplaySug[i] == true && i != 4{
for j in self.view.subviews{
if j.tag == i + 1 {
j.removeFromSuperview()
}
}
self.isDisplaySug[i] = false
}
}
//弹出视图
self.view.addSubview(sug)
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 0.1,y: 0.1))
UIView.animate(withDuration: 0.1, delay: 0,
options:UIViewAnimationOptions.transitionFlipFromBottom, animations:
{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 1,y: 1))
},
completion:{
(finished:Bool) -> Void in
UIView.animate(withDuration: 0.08, animations:{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform.identity)
})
})
isDisplaySug[4] = true
} else {
//remove the sug when tap the icon again
for i in self.view.subviews{
if i.tag == 5 {
i.removeFromSuperview()
}
}
isDisplaySug[4] = false
}
}
}
@IBAction func conT(_ sender: Any) {
if self.suggestions.count != 0{
let sug = UITextView(frame: CGRect(x: (carO.frame.origin.x + uvO.frame.origin.x) / 2 - 10, y: 500, width: 70, height: 110))
sug.text = suggestions[1]
sug.isEditable = false
sug.tag = 4
sug.isSelectable = false
sug.layer.cornerRadius = 10
sug.backgroundColor = UIColor(red: 213/255, green: 239/255, blue: 236/255, alpha: 1)
if !self.isDisplaySug[3] {
//清楚非现在点击的其他已经弹出的视图
for i in 0..<5 {
if self.isDisplaySug[i] == true && i != 3{
for j in self.view.subviews{
if j.tag == i + 1 {
j.removeFromSuperview()
}
}
self.isDisplaySug[i] = false
}
}
//弹出视图
self.view.addSubview(sug)
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 0.1,y: 0.1))
UIView.animate(withDuration: 0.1, delay: 0,
options:UIViewAnimationOptions.transitionFlipFromBottom, animations:
{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 1,y: 1))
},
completion:{
(finished:Bool) -> Void in
UIView.animate(withDuration: 0.08, animations:{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform.identity)
})
})
isDisplaySug[3] = true
} else {
//remove the sug when tap the icon again
for i in self.view.subviews{
if i.tag == 4 {
i.removeFromSuperview()
}
}
isDisplaySug[3] = false
}
}
}
@IBAction func uvA(_ sender: Any) {
if self.suggestions.count != 0{
let sug = UITextView(frame: CGRect(x: (self.comO.frame.origin.x + self.sportO.frame.origin.x) / 2 - 20, y: 500, width: 70, height: 110))
sug.text = suggestions[2]
sug.isEditable = false
sug.tag = 3
sug.isSelectable = false
sug.layer.cornerRadius = 10
sug.backgroundColor = UIColor(red: 213/255, green: 239/255, blue: 236/255, alpha: 1)
if !self.isDisplaySug[2] {
//清楚非现在点击的其他已经弹出的视图
for i in 0..<5 {
if self.isDisplaySug[i] == true && i != 2{
for j in self.view.subviews{
if j.tag == i + 1 {
j.removeFromSuperview()
}
}
self.isDisplaySug[i] = false
}
}
//弹出视图
self.view.addSubview(sug)
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 0.1,y: 0.1))
UIView.animate(withDuration: 0.1, delay: 0,
options:UIViewAnimationOptions.transitionFlipFromBottom, animations:
{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 1,y: 1))
},
completion:{
(finished:Bool) -> Void in
UIView.animate(withDuration: 0.08, animations:{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform.identity)
})
})
isDisplaySug[2] = true
} else {
//remove the sug when tap the icon again
for i in self.view.subviews{
if i.tag == 3 {
i.removeFromSuperview()
}
}
isDisplaySug[2] = false
}
}
}
@IBAction func comA(_ sender: Any) {
if self.suggestions.count != 0{
let sug = UITextView(frame: CGRect(x: 15, y: 500, width: 70, height: 110))
sug.text = suggestions[4]
sug.isEditable = false
sug.tag = 1
sug.isSelectable = false
sug.layer.cornerRadius = 10
sug.backgroundColor = UIColor(red: 213/255, green: 239/255, blue: 236/255, alpha: 1)
if !self.isDisplaySug[0] {
//清楚非现在点击的其他已经弹出的视图
for i in 0..<5 {
if self.isDisplaySug[i] == true && i != 0{
for j in self.view.subviews{
if j.tag == i + 1 {
j.removeFromSuperview()
}
}
self.isDisplaySug[i] = false
}
}
//弹出视图
self.view.addSubview(sug)
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 0.1,y: 0.1))
UIView.animate(withDuration: 0.1, delay: 0,
options:UIViewAnimationOptions.transitionFlipFromBottom, animations:
{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 1,y: 1))
},
completion:{
(finished:Bool) -> Void in
UIView.animate(withDuration: 0.08, animations:{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform.identity)
})
})
isDisplaySug[0] = true
} else {
//remove the sug when tap the icon again
for i in self.view.subviews{
if i.tag == 1 {
i.removeFromSuperview()
}
}
isDisplaySug[0] = false
}
}
}
@IBAction func sportA(_ sender: Any) {
if self.suggestions.count != 0{
let sug = UITextView(frame: CGRect(x: (self.uvO.frame.origin.x - self.confO.frame.origin.x) / 2 - 5, y: 500, width: 70, height: 110))
sug.text = suggestions[3]
sug.isEditable = false
sug.tag = 2
sug.isSelectable = false
sug.layer.cornerRadius = 10
sug.backgroundColor = UIColor(red: 213/255, green: 239/255, blue: 236/255, alpha: 1)
if !self.isDisplaySug[1] {
//清楚非现在点击的其他已经弹出的视图
for i in 0..<5 {
if self.isDisplaySug[i] == true && i != 1{
for j in self.view.subviews{
if j.tag == i + 1 {
j.removeFromSuperview()
}
}
self.isDisplaySug[i] = false
}
}
//弹出视图
self.view.addSubview(sug)
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 0.1,y: 0.1))
UIView.animate(withDuration: 0.1, delay: 0,
options:UIViewAnimationOptions.transitionFlipFromBottom, animations:
{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform(scaleX: 1,y: 1))
},
completion:{
(finished:Bool) -> Void in
UIView.animate(withDuration: 0.08, animations:{
()-> Void in
sug.layer.setAffineTransform(CGAffineTransform.identity)
})
})
isDisplaySug[1] = true
} else {
//remove the sug when tap the icon again
for i in self.view.subviews{
if i.tag == 2 {
i.removeFromSuperview()
}
}
isDisplaySug[1] = false
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
//调整导航栏颜色
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0/255, green: 153/255, blue: 170/255, alpha: 1)
WechatManager.appid = "wxb624f521419b82a8"
WechatManager.appSecret = "8bc62665998c981e844741513ad70e2e"
WechatManager.sharedInstance.shareDelegate = self
self.forecastT.delegate = self
self.forecastT.dataSource = self
self.isDisplaySug = [false, false, false, false, false]
//init date
initView()
confO.isSelected = false
//注册通知
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.disPlayMsg(notification:)), name: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil)
}
//初始化
func initView(){
let requestURL = "https://api.heweather.com/x3/weather"
var latestC:String
if UserDefaults.standard.object(forKey: "latestCity") as? String == nil {
latestC = "珠海"
} else {
latestC = (UserDefaults.standard.object(forKey: "latestCity") as? String)!
}
let parameters: Parameters = ["city": latestC, "key":"785b65cc83654963bd7ef0cf3864cdb5"]
Alamofire.request(requestURL, method: .get, parameters: parameters).response { response in
let jsonString = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue) as! String
let json2 = JSONND(string: jsonString)
self.updateView(json: json2)
}
}
//更新视图
func updateView(json:JSONND){
let jsonArr = json["HeWeather data service 3.0"].arrayValue
suggestions.removeAll()
if jsonArr.count != 0 {
//air condition
self.aqi.text = jsonArr[0]["aqi"]["city"]["aqi"].stringValue
self.aqiDes.text = jsonArr[0]["aqi"]["city"]["qlty"].stringValue
if Int(self.aqi.text!)! < 80 {
self.aqi.textColor = UIColor.green
self.aqiDes.textColor = UIColor.green
} else if Int(self.aqi.text!)! > 200 {
self.aqi.textColor = UIColor.red
self.aqiDes.textColor = UIColor.red
self.aqiDes.text?.append("😷")
} else if Int(self.aqi.text!)! > 80 {
self.aqi.textColor = UIColor(red: 255/255, green: 103/255, blue: 0/255, alpha: 1)
self.aqiDes.textColor = UIColor(red: 255/255, green: 103/255, blue: 0/255, alpha: 1)
}
//city
self.cityN.text = jsonArr[0]["basic"]["city"].stringValue
//record the city by this tap for next open app
UserDefaults.standard.set(self.cityN.text, forKey: "latestCity")
//update time
var ut = jsonArr[0]["basic"]["update"]["loc"].stringValue
ut = ut.substring(from: ut.index(ut.startIndex, offsetBy: 10))
self.updateTime.text = "上次更新:\(ut)"
//tem
self.tem.text = jsonArr[0]["now"]["tmp"].stringValue
if Int(self.tem.text!)! < 26 {
self.tem.textColor = UIColor.gray
} else {
self.tem.textColor = UIColor.orange
}
//suggestion
self.carT.text = jsonArr[0]["suggestion"]["cw"]["brf"].stringValue
self.suggestions.append(jsonArr[0]["suggestion"]["cw"]["txt"].stringValue)
self.comT.text = jsonArr[0]["suggestion"]["drsg"]["brf"].stringValue
self.suggestions.append(jsonArr[0]["suggestion"]["drsg"]["txt"].stringValue)
self.uvT.text = jsonArr[0]["suggestion"]["uv"]["brf"].stringValue
self.suggestions.append(jsonArr[0]["suggestion"]["uv"]["txt"].stringValue)
self.sportT.text = jsonArr[0]["suggestion"]["sport"]["brf"].stringValue
self.suggestions.append(jsonArr[0]["suggestion"]["sport"]["txt"].stringValue)
self.conT.text = jsonArr[0]["suggestion"]["comf"]["brf"].stringValue
self.suggestions.append(jsonArr[0]["suggestion"]["comf"]["txt"].stringValue)
//weather description
self.con.text = jsonArr[0]["now"]["cond"]["txt"].stringValue
switch self.con.text! {
case "多云","阴":
self.conImage.image = UIImage(named: "cloudy")
case "阵雨":
self.conImage.image = UIImage(named: "rain")
case "晴":
self.conImage.image = UIImage(named: "sunshine")
case "霾":
self.conImage.image = UIImage(named: "smog")
default:
break
}
//forecast
let forecast = jsonArr[0]["daily_forecast"].arrayValue
for i in 0..<7 {
conList.append(forecast[i]["cond"]["txt_d"].stringValue)
let fc = forecast[i]["date"].stringValue
dateList.append(fc.substring(from: fc.index(fc.startIndex, offsetBy: 5)))
temrList.append("\(forecast[i]["tmp"]["min"].stringValue)° ~ \(forecast[i]["tmp"]["max"].stringValue)°")
}
} else {
print("no such city")
}
forecastT.reloadData()
}
//响应通知
func disPlayMsg(notification:NSNotification){
let json = notification.object as! JSONND
updateView(json: json)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let date = cell.contentView.viewWithTag(1) as! UILabel
let con = cell.contentView.viewWithTag(2) as! UILabel
let temr = cell.contentView.viewWithTag(3) as! UILabel
if conList.count > 0 {
date.text = dateList[indexPath.row]
con.text = conList[indexPath.row]
temr.text = temrList[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 7
}
override func viewDidDisappear(_ animated: Bool) {
dateList.removeAll()
conList.removeAll()
temrList.removeAll()
for i in self.view.subviews{
if i.tag == 1 || i.tag == 2 || i.tag == 3 || i.tag == 4 || i.tag == 5{
i.removeFromSuperview()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 4ba40d4af2cb9d1035308a244f20d2cc | 39.856557 | 278 | 0.486157 | false | false | false | false |
Ibrahimohib/PDA | refs/heads/master | PDA/PDA/CalcViewController.swift | mit | 1 | //
// CalcViewController.swift
// PDA
//
// Created by Mohib Ibrahim on 11/13/16.
// Copyright © 2016 xula.edu. All rights reserved.
//
import UIKit
class CalcViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var sqftField: UITextField!
@IBOutlet var costsField: UITextField!
@IBOutlet var profitsField: UITextField!
@IBOutlet var typeField: UITextField!
@IBAction func calcButton(_ sender: Any) {
self.outputlabel.text = "You need to save $2,167 per month to be prepared for disaster"
}
@IBAction func reset(_ sender: Any) {
sqftField.text = ""
costsField.text = ""
profitsField.text = ""
typeField.text = ""
outputlabel.text = ""
}
@IBOutlet var outputlabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 81832893ad447c025ecbcd62c7537dd4 | 25.723077 | 106 | 0.641911 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Classes/Issues/StatusEvent/IssueStatusEventModel.swift | mit | 2 | //
// IssueStatusEventModel.swift
// Freetime
//
// Created by Ryan Nystrom on 6/7/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueStatusEventModel: ListDiffable {
let id: String
let actor: String
let commitHash: String?
let date: Date
let status: IssueStatusEvent
let pullRequest: Bool
init(id: String, actor: String, commitHash: String?, date: Date, status: IssueStatusEvent, pullRequest: Bool) {
self.id = id
self.actor = actor
self.commitHash = commitHash
self.date = date
self.status = status
self.pullRequest = pullRequest
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return id as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
// if the ids match, it should be the same object
return true
}
}
| 2018d740005947f00df5b432d1fad1be | 22.414634 | 115 | 0.654167 | false | false | false | false |
xeo-it/zipbooks-invoices-swift | refs/heads/master | zipbooks-ios/Services/APIservice.swift | mit | 1 | //
// apis.swift
// zipbooks-ios
//
// Created by Francesco Pretelli on 11/01/16.
// Copyright © 2016 Francesco Pretelli. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
class APIservice {
static let sharedInstance = APIservice() //singleton lazy initialization, apple supports it sice swift 1.2
fileprivate init() {} //This prevents others from using the default '()' initializer for this class.
static var ZIPBOOK = "https://api.zipbooks.com/v1"
let LOGIN_ENDPOINT = ZIPBOOK + "/auth/login"
let INVOICES_ENDPOINT = ZIPBOOK + "/invoices"
let CUSTOMERS_ENDPOINT = ZIPBOOK + "/customers"
let PROJECTS_ENDPOINT = ZIPBOOK + "/projects"
let EXPENSES_ENDPOINT = ZIPBOOK + "/expenses"
let TASKS_ENDPOINT = ZIPBOOK + "/tasks"
let TIME_ENTRIES_ENDPOINT = ZIPBOOK + "/time_entries"
var authHeaders = [
"Authorization": "bearer " + Utility.getToken(),
]
func login(_ email:String, password:String, callback: @escaping (_ result: Bool) -> Void ){
let body = [
"email": email,
"password": password
]
Alamofire.request(LOGIN_ENDPOINT, method: HTTPMethod.post, parameters: body, encoding: JSONEncoding(), headers: nil).responseObject{ (response: DataResponse<AuthObject>) in
guard response.result.error == nil
else {
// got an error in getting the data, need to handle it
print("error in API login -> " + String(describing: response.result.error!))
callback(false)
return
}
//handling the data
do {
let data = response.result.value! as AuthObject
if data.token == "" || data.user?.email == nil || data.user?.name == nil {
callback (false)
}
else{
try Utility.setToken(data.token)
try Utility.setUserEmail((data.user?.email)!)
try Utility.setUserName((data.user?.name)!)
callback (true)
}
}
catch {
callback (false)
}
}
}
func getInvoices(_ callback: @escaping (_ data: [Invoice]?) -> Void ){
sendRequestArray(remoteEndpoint: INVOICES_ENDPOINT, method: HTTPMethod.get){ (result:[Invoice]?) in
callback(result)
}
}
func getCustomers(_ callback: @escaping (_ data: [Customer]?) -> Void ){
sendRequestArray(remoteEndpoint: CUSTOMERS_ENDPOINT, method: HTTPMethod.get){ (result:[Customer]?) in
callback(result)
}
}
func getProjects(_ callback: @escaping (_ data: [Project]?) -> Void ){
sendRequestArray(remoteEndpoint: PROJECTS_ENDPOINT, method: HTTPMethod.get){ (result:[Project]?) in
callback(result)
}
}
func getTasks(_ callback: @escaping (_ data: [Task]?) -> Void ){
sendRequestArray(remoteEndpoint: TASKS_ENDPOINT, method: HTTPMethod.get){ (result:[Task]?) in
callback(result)
}
}
func getExpenses(_ callback: @escaping (_ data: [Expense]?) -> Void ){
sendRequestArray(remoteEndpoint: EXPENSES_ENDPOINT, method: HTTPMethod.get){ (result:[Expense]?) in
callback(result)
}
}
func getTimeEntries(_ callback: @escaping (_ data: [TimeEntry]?) -> Void ){
sendRequestArray(remoteEndpoint: TIME_ENTRIES_ENDPOINT, method: HTTPMethod.get){ (result:[TimeEntry]?) in
callback(result)
}
}
//MARK: Post Functions
func setExpense(_ expense: ExpensePost, callback: @escaping (_ data: Expense?) -> Void ){
sendRequestObject(remoteEndpoint: EXPENSES_ENDPOINT, method: HTTPMethod.post, parameters: Mapper().toJSON(expense)){ (result: Expense?) in
callback(result)
}
}
func setTimeEntry(_ expense: TimeEntryPost, callback: @escaping (_ data: TimeEntry?) -> Void ){
sendRequestObject(remoteEndpoint: TIME_ENTRIES_ENDPOINT, method: HTTPMethod.post, parameters: Mapper().toJSON(expense)){ (result: TimeEntry?) in
callback(result)
}
}
func saveNewCustomer(_ customer: CustomerPost, callback: @escaping (_ data: Customer?) -> Void ){
sendRequestObject(remoteEndpoint: CUSTOMERS_ENDPOINT, method: HTTPMethod.post, parameters: Mapper().toJSON(customer)){ (result: Customer?) in
callback(result)
}
}
func saveNewProject(_ project: ProjectPost, callback: @escaping (_ data: Project?) -> Void ){
sendRequestObject(remoteEndpoint: PROJECTS_ENDPOINT, method: HTTPMethod.post, parameters: Mapper().toJSON(project)){ (result: Project?) in
callback(result)
}
}
func saveNewTask(_ task: TaskPost, callback: @escaping (_ data: Task?) -> Void ){
sendRequestObject(remoteEndpoint: TASKS_ENDPOINT, method: HTTPMethod.post, parameters: Mapper().toJSON(task)){ (result: Task?) in
callback(result)
}
}
/*func sendPostRequest<T: Mappable>( _ endpoint:String, method:Alamofire.Method, parameters: [String : AnyObject], callback: @escaping (_ result: T?) -> Void ) {
Alamofire.request(method, endpoint, headers:authHeaders, parameters: parameters, encoding: .JSON).responseObject { (response: Response<T, NSError>) in
guard response.result.error == nil
else {
// got an error in getting the data, need to handle it
print("error in API object request -> " + String(response.result.error!))
callback(result: nil)
return
}
callback (result: response.result.value!)
}
}*/
func sendRequestObject<T: Mappable>(remoteEndpoint endpoint:String, method:HTTPMethod, parameters: [String: Any]? = nil, callback: @escaping (_ result: T?) -> Void ) {
Alamofire.request(endpoint, method: method, parameters: parameters, encoding: JSONEncoding(), headers: authHeaders).responseObject{ (response: DataResponse<T>) in
guard response.result.error == nil
else {
// got an error in getting the data, need to handle it
print("error in API object request -> " + String(describing: response.result.error!))
callback(nil)
return
}
callback (response.result.value!)
}
}
func sendRequestArray<T: Mappable>(remoteEndpoint endpoint:String, method:HTTPMethod, parameters: [String: Any]? = nil, callback: @escaping (_ result: [T]?) -> Void ) {
Alamofire.request(endpoint, method: method, parameters: parameters, encoding: JSONEncoding(), headers: authHeaders).responseArray { (response: DataResponse<[T]>) in
guard response.result.error == nil
else {
// got an error in getting the data, need to handle it
print("error in API array request for " + endpoint + "-> " + String(describing: response.result.error!))
callback(nil)
return
}
callback (response.result.value!)
}
}
func generateHeaderAfterAuth(){
authHeaders = [
"Authorization": "bearer " + Utility.getToken()
]
}
}
| ef4d0dd5b543740b3b1157a7601eee60 | 40.440217 | 180 | 0.585311 | false | false | false | false |
JK-V/Swift | refs/heads/master | ParseJSON.playground/Contents.swift | apache-2.0 | 1 | //: Playground - noun: a place where people can play
import UIKit
let blogsURL: NSURL = [#FileReference(fileReferenceLiteral: "blogs.json")#]
let data = NSData(contentsOfURL: blogsURL)!
var names = [String]()
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let blogs = json["blogs"] as? [[String: AnyObject]] {
for blog in blogs {
if let name = blog["name"] as? String {
names.append(name)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}
print(names) | 4f5b445cca4ea241d864eb9909fbd0a3 | 23.625 | 89 | 0.616949 | false | false | false | false |
smdls/C0 | refs/heads/master | C0/Other.swift | gpl-3.0 | 1 | /*
Copyright 2017 S
This file is part of C0.
C0 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.
C0 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 C0. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
struct BezierIntersection {
var t: CGFloat, isLeft: Bool, point: CGPoint
}
struct Bezier2 {
var p0 = CGPoint(), p1 = CGPoint(), p2 = CGPoint()
static func linear(_ p0: CGPoint, _ p1: CGPoint) -> Bezier2 {
return Bezier2(p0: p0, p1: p0.mid(p1), p2: p1)
}
var bounds: CGRect {
var minX = min(p0.x, p2.x), maxX = max(p0.x, p2.x)
var d = p2.x - 2*p1.x + p0.x
if d != 0 {
let t = (p0.x - p1.x)/d
if t >= 0 && t <= 1 {
let rt = 1 - t
let tx = rt*rt*p0.x + 2*rt*t*p1.x + t*t*p2.x
if tx < minX {
minX = tx
} else if tx > maxX {
maxX = tx
}
}
}
var minY = min(p0.y, p2.y), maxY = max(p0.y, p2.y)
d = p2.y - 2*p1.y + p0.y
if d != 0 {
let t = (p0.y - p1.y)/d
if t >= 0 && t <= 1 {
let rt = 1 - t
let ty = rt*rt*p0.y + 2*rt*t*p1.y + t*t*p2.y
if ty < minY {
minY = ty
} else if ty > maxY {
maxY = ty
}
}
}
return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
}
var boundingBox: CGRect {
return AABB(self).rect
}
func length(withFlatness flatness: Int = 128) -> CGFloat {
var d = 0.0.cf, oldP = p0
let nd = 1/flatness.cf
for i in 0 ..< flatness {
let newP = position(withT: (i + 1).cf*nd)
d += oldP.distance(newP)
oldP = newP
}
return d
}
func t(withLength length: CGFloat, flatness: Int = 128) -> CGFloat {
var d = 0.0.cf, oldP = p0
let nd = 1/flatness.cf
for i in 0 ..< flatness {
let t = (i + 1).cf*nd
let newP = position(withT: t)
d += oldP.distance(newP)
if d > length {
return t
}
oldP = newP
}
return 1
}
func difference(withT t: CGFloat) -> CGPoint {
return CGPoint(x: 2*(p1.x - p0.x) + 2*(p0.x - 2*p1.x + p2.x)*t, y: 2*(p1.y - p0.y) + 2*(p0.y - 2*p1.y + p2.y)*t)
}
func tangential(withT t: CGFloat) -> CGFloat {
return atan2(2*(p1.y - p0.y) + 2*(p0.y - 2*p1.y + p2.y)*t, 2*(p1.x - p0.x) + 2*(p0.x - 2*p1.x + p2.x)*t)
}
func position(withT t: CGFloat) -> CGPoint {
let rt = 1 - t
return CGPoint(x: rt*rt*p0.x + 2*t*rt*p1.x + t*t*p2.x, y: rt*rt*p0.y + 2*t*rt*p1.y + t*t*p2.y)
}
func midSplit() -> (b0: Bezier2, b1: Bezier2) {
let p0p1 = p0.mid(p1), p1p2 = p1.mid(p2)
let p = p0p1.mid(p1p2)
return (Bezier2(p0: p0, p1: p0p1, p2: p), Bezier2(p0: p, p1: p1p2, p2: p2))
}
func clip(startT t0: CGFloat, endT t1: CGFloat) -> Bezier2 {
let rt0 = 1 - t0, rt1 = 1 - t1
let t0p0p1 = CGPoint(x: rt0*p0.x + t0*p1.x, y: rt0*p0.y + t0*p1.y)
let t0p1p2 = CGPoint(x: rt0*p1.x + t0*p2.x, y: rt0*p1.y + t0*p2.y)
let np0 = CGPoint(x: rt0*t0p0p1.x + t0*t0p1p2.x, y: rt0*t0p0p1.y + t0*t0p1p2.y)
let np1 = CGPoint(x: rt1*t0p0p1.x + t1*t0p1p2.x, y: rt1*t0p0p1.y + t1*t0p1p2.y)
let t1p0p1 = CGPoint(x: rt1*p0.x + t1*p1.x, y: rt1*p0.y + t1*p1.y)
let t1p1p2 = CGPoint(x: rt1*p1.x + t1*p2.x, y: rt1*p1.y + t1*p2.y)
let np2 = CGPoint(x: rt1*t1p0p1.x + t1*t1p1p2.x, y: rt1*t1p0p1.y + t1*t1p1p2.y)
return Bezier2(p0: np0, p1: np1, p2: np2)
}
func intersects(_ other: Bezier2) -> Bool {
return intersects(other, 0, 1, 0, 1, isFlipped: false)
}
private let intersectsMinRange = 0.000001.cf
private func intersects(_ other: Bezier2, _ min0: CGFloat, _ max0: CGFloat, _ min1: CGFloat, _ max1: CGFloat, isFlipped: Bool) -> Bool {
let aabb0 = AABB(self), aabb1 = AABB(other)
if !aabb0.intersects(aabb1) {
return false
}
if max(aabb1.maxX - aabb1.minX, aabb1.maxY - aabb1.minY) < intersectsMinRange {
return true
}
let range1 = max1 - min1
let nb = other.midSplit()
if nb.b0.intersects(self, min1, min1 + 0.5*range1, min0, max0, isFlipped: !isFlipped) {
return true
} else {
return nb.b1.intersects(self, min1 + 0.5*range1, min1 + range1, min0, max0, isFlipped: !isFlipped)
}
}
func intersections(_ other: Bezier2) -> [BezierIntersection] {
var results = [BezierIntersection]()
intersections(other, &results, 0, 1, 0, 1, isFlipped: false)
return results
}
private func intersections(_ other: Bezier2, _ results: inout [BezierIntersection],
_ min0: CGFloat, _ max0: CGFloat, _ min1: CGFloat, _ max1: CGFloat, isFlipped: Bool) {
let aabb0 = AABB(self), aabb1 = AABB(other)
if !aabb0.intersects(aabb1) {
return
}
let range1 = max1 - min1
if max(aabb1.maxX - aabb1.minX, aabb1.maxY - aabb1.minY) >= intersectsMinRange {
let nb = other.midSplit()
nb.b0.intersections(self, &results, min1, min1 + range1/2, min0, max0, isFlipped: !isFlipped)
if results.count < 4 {
nb.b1.intersections(self, &results, min1 + range1/2, min1 + range1, min0, max0, isFlipped: !isFlipped)
}
return
}
let newP = CGPoint(x: (aabb1.minX + aabb1.maxX)/2, y: (aabb1.minY + aabb1.maxY)/2)
func isSolution() -> Bool {
if !results.isEmpty {
let oldP = results[results.count - 1].point
let x = newP.x - oldP.x, y = newP.y - oldP.y
if x*x + y*y < intersectsMinRange {
return false
}
}
return true
}
if !isSolution() {
return
}
let b0t: CGFloat, b1t: CGFloat, b0: Bezier2, b1:Bezier2
if !isFlipped {
b0t = (min0 + max0)/2
b1t = min1 + range1/2
b0 = self
b1 = other
} else {
b1t = (min0 + max0)/2
b0t = min1 + range1/2
b0 = other
b1 = self
}
let b0dp = b0.difference(withT: b0t), b1dp = b1.difference(withT: b1t)
let b0b1Cross = b0dp.x*b1dp.y - b0dp.y*b1dp.x
if b0b1Cross != 0 {
results.append(BezierIntersection(t: b0t, isLeft: b0b1Cross > 0, point: newP))
}
}
}
struct Bezier3 {
var p0 = CGPoint(), cp0 = CGPoint(), cp1 = CGPoint(), p1 = CGPoint()
func split(withT t: CGFloat) -> (b0: Bezier3, b1: Bezier3) {
let b0cp0 = CGPoint.linear(p0, cp0, t: t), cp0cp1 = CGPoint.linear(cp0, cp1, t: t), b1cp1 = CGPoint.linear(cp1, p1, t: t)
let b0cp1 = CGPoint.linear(b0cp0, cp0cp1, t: t), b1cp0 = CGPoint.linear(cp0cp1, b1cp1, t: t)
let p = CGPoint.linear(b0cp1, b1cp0, t: t)
return (Bezier3(p0: p0, cp0: b0cp0, cp1: b0cp1, p1: p), Bezier3(p0: p, cp0: b1cp0, cp1: b1cp1, p1: p1))
}
func y(withX x: CGFloat) -> CGFloat {
var y = 0.0.cf
let sb = split(withT: 0.5)
if !sb.b0.y(withX: x, y: &y) {
_ = sb.b1.y(withX: x, y: &y)
}
return y
}
private let yMinRange = 0.000001.cf
private func y(withX x: CGFloat, y: inout CGFloat) -> Bool {
let aabb = AABB(self)
if aabb.minX < x && aabb.maxX >= x {
if aabb.maxY - aabb.minY < yMinRange {
y = (aabb.minY + aabb.maxY)/2
return true
} else {
let sb = split(withT: 0.5)
if sb.b0.y(withX: x, y: &y) {
return true
} else {
return sb.b1.y(withX: x, y: &y)
}
}
} else {
return false
}
}
func difference(withT t: CGFloat) -> CGPoint {
let rt = 1 - t
let dx = 3*(t*t*(p1.x - cp1.x)+2*t*rt*(cp1.x - cp0.x) + rt*rt*(cp0.x - p0.x))
let dy = 3*(t*t*(p1.y - cp1.y)+2*t*rt*(cp1.y - cp0.y) + rt*rt*(cp0.y - p0.y))
return CGPoint(x: dx, y: dy)
}
}
struct AABB {
var minX = 0.0.cf, maxX = 0.0.cf, minY = 0.0.cf, maxY = 0.0.cf
init(minX: CGFloat = 0, maxX: CGFloat = 0, minY: CGFloat = 0, maxY: CGFloat = 0) {
self.minX = minX
self.minY = minY
self.maxX = maxX
self.maxY = maxY
}
init(_ rect: CGRect) {
minX = rect.minX
minY = rect.minY
maxX = rect.maxX
maxY = rect.maxY
}
init(_ b: Bezier2) {
minX = min(b.p0.x, b.p1.x, b.p2.x)
minY = min(b.p0.y, b.p1.y, b.p2.y)
maxX = max(b.p0.x, b.p1.x, b.p2.x)
maxY = max(b.p0.y, b.p1.y, b.p2.y)
}
init(_ b: Bezier3) {
minX = min(b.p0.x, b.cp0.x, b.cp1.x, b.p1.x)
minY = min(b.p0.y, b.cp0.y, b.cp1.y, b.p1.y)
maxX = max(b.p0.x, b.cp0.x, b.cp1.x, b.p1.x)
maxY = max(b.p0.y, b.cp0.y, b.cp1.y, b.p1.y)
}
var position: CGPoint {
return CGPoint(x: minX, y: minY)
}
var rect: CGRect {
return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
}
func nearestSquaredDistance(_ p: CGPoint) -> CGFloat {
if p.x < minX {
return p.y < minY ? hypot2(minX - p.x, minY - p.y) : (p.y <= maxY ? (minX - p.x).squared() : hypot2(minX - p.x, maxY - p.y))
} else if p.x <= maxX {
return p.y < minY ? (minY - p.y).squared() : (p.y <= maxY ? 0 : (minY - p.y).squared())
} else {
return p.y < minY ? hypot2(maxX - p.x, minY - p.y) : (p.y <= maxY ? (maxX - p.x).squared() : hypot2(maxX - p.x, maxY - p.y))
}
}
func intersects(_ other: AABB) -> Bool {
return minX <= other.maxX && maxX >= other.minX && minY <= other.maxY && maxY >= other.minY
}
}
final class LockTimer {
private var count = 0
private(set) var wait = false
func begin(_ endTimeLength: TimeInterval, beginHandler: () -> Void, endHandler: @escaping () -> Void) {
if wait {
count += 1
} else {
beginHandler()
wait = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + endTimeLength) {
if self.count == 0 {
endHandler()
self.wait = false
} else {
self.count -= 1
}
}
}
private(set) var inUse = false
private weak var timer: Timer?
func begin(_ interval: TimeInterval, repeats: Bool = true, tolerance: TimeInterval = TimeInterval(0), handler: @escaping (Void) -> Void) {
let time = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, repeats ? interval : 0, 0, 0) { _ in
handler()
}
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .commonModes)
self.timer = timer
inUse = true
self.timer?.tolerance = tolerance
}
func stop() {
inUse = false
timer?.invalidate()
timer = nil
}
}
final class Weak<T: AnyObject> {
weak var value : T?
init (value: T) {
self.value = value
}
}
func hypot2(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat {
return lhs*lhs + rhs*rhs
}
protocol Copying: class {
var deepCopy: Self { get }
}
protocol Interpolatable {
static func linear(_ f0: Self, _ f1: Self, t: CGFloat) -> Self
static func firstMonospline(_ f1: Self, _ f2: Self, _ f3: Self, with msx: MonosplineX) -> Self
static func monospline(_ f0: Self, _ f1: Self, _ f2: Self, _ f3: Self, with msx: MonosplineX) -> Self
static func endMonospline(_ f0: Self, _ f1: Self, _ f2: Self, with msx: MonosplineX) -> Self
}
extension Comparable {
func clip(min: Self, max: Self) -> Self {
return self < min ? min : (self > max ? max : self)
}
func isOver(old: Self, new: Self) -> Bool {
return (new >= self && old < self) || (new <= self && old > self)
}
}
extension Array {
func withRemovedLast() -> Array {
var array = self
array.removeLast()
return array
}
func withRemoved(at i: Int) -> Array {
var array = self
array.remove(at: i)
return array
}
func withAppend(_ element: Element) -> Array {
var array = self
array.append(element)
return array
}
func withInserted(_ element: Element, at i: Int) -> Array {
var array = self
array.insert(element, at: i)
return array
}
func withReplaced(_ element: Element, at i: Int) -> Array {
var array = self
array[i] = element
return array
}
}
extension String {
var localized: String {
return NSLocalizedString(self, comment: self)
}
}
extension Int {
var cf: CGFloat {
return CGFloat(self)
}
}
extension Float {
var cf: CGFloat {
return CGFloat(self)
}
static func linear(_ f0: Float, _ f1: Float, t: CGFloat) -> Float {
let tf = t.f
return f0*(1 - tf) + f1*tf
}
}
extension Double {
var f: Float {
return Float(self)
}
var cf: CGFloat {
return CGFloat(self)
}
}
struct MonosplineX {
let h0: CGFloat, h1: CGFloat, h2: CGFloat, invertH0: CGFloat, invertH1: CGFloat, invertH2: CGFloat
let invertH0H1: CGFloat, invertH1H2: CGFloat, invertH1H1: CGFloat, xx3: CGFloat, xx2: CGFloat, xx1: CGFloat
init(x1: CGFloat, x2: CGFloat, x3: CGFloat, x: CGFloat) {
h0 = 0
h1 = x2 - x1
h2 = x3 - x2
invertH0 = 0
invertH1 = 1/h1
invertH2 = 1/h2
invertH0H1 = 0
invertH1H2 = 1/(h1 + h2)
invertH1H1 = 1/(h1*h1)
xx1 = x - x1
xx2 = xx1*xx1
xx3 = xx1*xx1*xx1
}
init(x0: CGFloat, x1: CGFloat, x2: CGFloat, x3: CGFloat, x: CGFloat) {
h0 = x1 - x0
h1 = x2 - x1
h2 = x3 - x2
invertH0 = 1/h0
invertH1 = 1/h1
invertH2 = 1/h2
invertH0H1 = 1/(h0 + h1)
invertH1H2 = 1/(h1 + h2)
invertH1H1 = 1/(h1*h1)
xx1 = x - x1
xx2 = xx1*xx1
xx3 = xx1*xx1*xx1
}
init(x0: CGFloat, x1: CGFloat, x2: CGFloat, x: CGFloat) {
h0 = x1 - x0
h1 = x2 - x1
h2 = 0
invertH0 = 1/h0
invertH1 = 1/h1
invertH2 = 0
invertH0H1 = 1/(h0 + h1)
invertH1H2 = 0
invertH1H1 = 1/(h1*h1)
xx1 = x - x1
xx2 = xx1*xx1
xx3 = xx1*xx1*xx1
}
}
extension CGFloat: Interpolatable {
var f: Float {
return Float(self)
}
var d: Double {
return Double(self)
}
func interval(scale: CGFloat) -> CGFloat {
if scale == 0 {
return self
} else {
let t = floor(self / scale)*scale
return self - t > scale/2 ? t + scale : t
}
}
static func sectionIndex(value v: CGFloat, in values: [CGFloat]) -> (index: Int, interValue: CGFloat, sectionValue: CGFloat)? {
if let firstValue = values.first {
var oldV = 0.0.cf
for i in (0 ..< values.count).reversed() {
let value = values[i]
if v >= value {
return (i, v - value, oldV - value)
}
oldV = value
}
return (0, v - firstValue, oldV - firstValue)
} else {
return nil
}
}
func differenceRotation(_ other: CGFloat) -> CGFloat {
let a = self - other
return a + (a > .pi ? -2*(.pi) : (a < -.pi ? 2*(.pi) : 0))
}
static func differenceAngle(_ p0: CGPoint, p1: CGPoint, p2: CGPoint) -> CGFloat {
let pa = p1 - p0
let pb = p2 - pa
let ab = hypot(pa.x, pa.y)*hypot(pb.x, pb.y)
return ab != 0 ? (pa.x*pb.y - pa.y*pb.x > 0 ? 1 : -1)*acos((pa.x*pb.x + pa.y*pb.y)/ab) : 0
}
var clipRotation: CGFloat {
return self < -.pi ? self + 2*(.pi) : (self > .pi ? self - 2*(.pi) : self)
}
func squared() -> CGFloat {
return self*self
}
func loopValue(other: CGFloat, begin: CGFloat = 0, end: CGFloat = 1) -> CGFloat {
if other < self {
return self - other < (other - begin) + (end - self) ? self : self - (end - begin)
} else {
return other - self < (self - begin) + (end - other) ? self : self + (end - begin)
}
}
func loopValue(_ begin: CGFloat = 0, end: CGFloat = 1) -> CGFloat {
return self < begin ? self + (end - begin) : (self > end ? self - (end - begin) : self)
}
static func random(min: CGFloat, max: CGFloat) -> CGFloat {
return (max - min)*(CGFloat(arc4random_uniform(UInt32.max))/CGFloat(UInt32.max)) + min
}
static func bilinear(x: CGFloat, y: CGFloat, a: CGFloat, b: CGFloat, c: CGFloat, d: CGFloat) -> CGFloat {
return x*y*(a - b - c + d) + x*(b - a) + y*(c - a) + a
}
static func linear(_ f0: CGFloat, _ f1: CGFloat, t: CGFloat) -> CGFloat {
return f0*(1 - t) + f1*t
}
static func firstMonospline(_ f1: CGFloat, _ f2: CGFloat, _ f3: CGFloat, with msx: MonosplineX) -> CGFloat {
let s1 = (f2 - f1)*msx.invertH1, s2 = (f3 - f2)*msx.invertH2
let signS1: CGFloat = s1 > 0 ? 1 : -1, signS2: CGFloat = s2 > 0 ? 1 : -1
let yPrime1 = s1
let yPrime2 = (signS1 + signS2)*Swift.min(abs(s1), abs(s2), 0.5*abs((msx.h2*s1 + msx.h1*s2)*msx.invertH1H2))
return _monospline(f1, s1, yPrime1, yPrime2, with: msx)
}
static func monospline(_ f0: CGFloat, _ f1: CGFloat, _ f2: CGFloat, _ f3: CGFloat, with msx: MonosplineX) -> CGFloat {
let s0 = (f1 - f0)*msx.invertH0, s1 = (f2 - f1)*msx.invertH1, s2 = (f3 - f2)*msx.invertH2
let signS0: CGFloat = s0 > 0 ? 1 : -1, signS1: CGFloat = s1 > 0 ? 1 : -1, signS2: CGFloat = s2 > 0 ? 1 : -1
let yPrime1 = (signS0 + signS1)*Swift.min(abs(s0), abs(s1), 0.5*abs((msx.h1*s0 + msx.h0*s1)*msx.invertH0H1))
let yPrime2 = (signS1 + signS2)*Swift.min(abs(s1), abs(s2), 0.5*abs((msx.h2*s1 + msx.h1*s2)*msx.invertH1H2))
return _monospline(f1, s1, yPrime1, yPrime2, with: msx)
}
static func endMonospline(_ f0: CGFloat, _ f1: CGFloat, _ f2: CGFloat, with msx: MonosplineX) -> CGFloat {
let s0 = (f1 - f0)*msx.invertH0, s1 = (f2 - f1)*msx.invertH1
let signS0: CGFloat = s0 > 0 ? 1 : -1, signS1: CGFloat = s1 > 0 ? 1 : -1
let yPrime1 = (signS0 + signS1)*Swift.min(abs(s0), abs(s1), 0.5*abs((msx.h1*s0 + msx.h0*s1)*msx.invertH0H1))
let yPrime2 = s1
return _monospline(f1, s1, yPrime1, yPrime2, with: msx)
}
private static func _monospline(_ f1: CGFloat, _ s1: CGFloat, _ yPrime1: CGFloat, _ yPrime2: CGFloat, with msx: MonosplineX) -> CGFloat {
let a = (yPrime1 + yPrime2 - 2*s1)*msx.invertH1H1, b = (3*s1 - 2*yPrime1 - yPrime2)*msx.invertH1, c = yPrime1, d = f1
return a*msx.xx3 + b*msx.xx2 + c*msx.xx1 + d
}
}
extension CGPoint: Interpolatable {
func mid(_ other: CGPoint) -> CGPoint {
return CGPoint(x: (x + other.x)/2, y: (y + other.y)/2)
}
static func linear(_ f0: CGPoint, _ f1: CGPoint, t: CGFloat) -> CGPoint {
return CGPoint(x: CGFloat.linear(f0.x, f1.x, t: t), y: CGFloat.linear(f0.y, f1.y, t: t))
}
static func firstMonospline(_ f1: CGPoint, _ f2: CGPoint, _ f3: CGPoint, with msx: MonosplineX) -> CGPoint {
return CGPoint(
x: CGFloat.firstMonospline(f1.x, f2.x, f3.x, with: msx),
y: CGFloat.firstMonospline(f1.y, f2.y, f3.y, with: msx)
)
}
static func monospline(_ f0: CGPoint, _ f1: CGPoint, _ f2: CGPoint, _ f3: CGPoint, with msx: MonosplineX) -> CGPoint {
return CGPoint(
x: CGFloat.monospline(f0.x, f1.x, f2.x, f3.x, with: msx),
y: CGFloat.monospline(f0.y, f1.y, f2.y, f3.y, with: msx)
)
}
static func endMonospline(_ f0: CGPoint, _ f1: CGPoint, _ f2: CGPoint, with msx: MonosplineX) -> CGPoint {
return CGPoint(
x: CGFloat.endMonospline(f0.x, f1.x, f2.x, with: msx),
y: CGFloat.endMonospline(f0.y, f1.y, f2.y, with: msx)
)
}
static func intersection(p0: CGPoint, p1: CGPoint, q0: CGPoint, q1: CGPoint) -> Bool {
let a0 = (p0.x - p1.x)*(q0.y - p0.y) + (p0.y - p1.y)*(p0.x - q0.x), b0 = (p0.x - p1.x)*(q1.y - p0.y) + (p0.y - p1.y)*(p0.x - q1.x)
if a0*b0 < 0 {
let a1 = (q0.x - q1.x)*(p0.y - q0.y) + (q0.y - q1.y)*(q0.x - p0.x), b1 = (q0.x - q1.x)*(p1.y - q0.y) + (q0.y - q1.y)*(q0.x - p1.x)
if a1*b1 < 0 {
return true
}
}
return false
}
func tangential(_ other: CGPoint) -> CGFloat {
return atan2(other.y - y, other.x - x)
}
func crossVector(_ other: CGPoint) -> CGFloat {
return x*other.y - y*other.x
}
func distance(_ other: CGPoint) -> CGFloat {
return hypot(other.x - x, other.y - y)
}
func distanceWithLine(ap: CGPoint, bp: CGPoint) -> CGFloat {
return abs((bp - ap).crossVector(self - ap))/ap.distance(bp)
}
func distanceWithLineSegment(ap: CGPoint, bp: CGPoint) -> CGFloat {
if ap == bp {
return distance(ap)
} else {
let bav = bp - ap, pav = self - ap
let r = (bav.x*pav.x + bav.y*pav.y)/(bav.x*bav.x + bav.y*bav.y)
if r <= 0 {
return distance(ap)
} else if r > 1 {
return distance(bp)
} else {
return abs(bav.crossVector(pav))/ap.distance(bp)
}
}
}
func squaredDistance(other: CGPoint) -> CGFloat {
let nx = x - other.x, ny = y - other.y
return nx*nx + ny*ny
}
static func differenceAngle(p0: CGPoint, p1: CGPoint, p2: CGPoint) -> CGFloat {
return differenceAngle(a: p1 - p0, b: p2 - p1)
}
static func differenceAngle(a: CGPoint, b: CGPoint) -> CGFloat {
return atan2(a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y)
}
static func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
static func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
static func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x*right, y: left.y*right)
}
}
extension CGRect {
func squaredDistance(_ point: CGPoint) -> CGFloat {
return AABB(self).nearestSquaredDistance(point)
}
func unionNotEmpty(_ other: CGRect) -> CGRect {
return other.isEmpty ? self : (isEmpty ? other : union(other))
}
var circleBounds: CGRect {
let r = hypot(width, height)/2
return CGRect(x: midX - r, y: midY - r, width: r*2, height: r*2)
}
func inset(by width: CGFloat) -> CGRect {
return insetBy(dx: width, dy: width)
}
}
extension CGAffineTransform {
func flippedHorizontal(by width: CGFloat) -> CGAffineTransform {
return translatedBy(x: width, y: 0).scaledBy(x: -1, y: 1)
}
}
extension CGColor {
final func multiplyAlpha(_ a: CGFloat) -> CGColor {
return copy(alpha: a*alpha) ?? self
}
final func multiplyWhite(_ w: CGFloat) -> CGColor {
if let components = components, let colorSpace = colorSpace {
let cs = components.enumerated().map { $0.0 < components.count - 1 ? $0.1 + (1 - $0.1)*w : $0.1 }
return CGColor(colorSpace: colorSpace, components: cs) ?? self
} else {
return self
}
}
}
extension CGPath {
static func checkerboard(with size: CGSize, in frame: CGRect) -> CGPath {
let path = CGMutablePath()
let xCount = Int(frame.width/size.width) , yCount = Int(frame.height/(size.height*2))
for xi in 0 ..< xCount {
let x = frame.maxX - (xi + 1).cf*size.width
let fy = xi % 2 == 0 ? size.height : 0
for yi in 0 ..< yCount {
let y = frame.minY + yi.cf*size.height*2 + fy
path.addRect(CGRect(x: x, y: y, width: size.width, height: size.height))
}
}
return path
}
}
extension CGContext {
func addBezier(_ b: Bezier3) {
move(to: b.p0)
addCurve(to: b.p1, control1: b.cp0, control2: b.cp1)
}
func flipHorizontal(by width: CGFloat) {
translateBy(x: width, y: 0)
scaleBy(x: -1, y: 1)
}
func drawBlurWith(color fillColor: CGColor, width: CGFloat, strength: CGFloat, isLuster: Bool, path: CGPath, with di: DrawInfo) {
let nFillColor: CGColor
if fillColor.alpha < 1 {
saveGState()
setAlpha(fillColor.alpha)
nFillColor = fillColor.copy(alpha: 1) ?? fillColor
} else {
nFillColor = fillColor
}
let pathBounds = path.boundingBoxOfPath.insetBy(dx: -width, dy: -width)
let lineColor = strength == 1 ? nFillColor : nFillColor.multiplyAlpha(strength)
beginTransparencyLayer(in: boundingBoxOfClipPath.intersection(pathBounds), auxiliaryInfo: nil)
if isLuster {
setShadow(offset: CGSize(), blur: width*di.scale, color: lineColor)
} else {
let shadowY = hypot(pathBounds.size.width, pathBounds.size.height)
translateBy(x: 0, y: shadowY)
let shadowOffset = CGSize(width: shadowY*di.scale*sin(di.rotation), height: -shadowY*di.scale*cos(di.rotation))
setShadow(offset: shadowOffset, blur: width*di.scale/2, color: lineColor)
setLineWidth(width)
setLineJoin(.round)
setStrokeColor(lineColor)
addPath(path)
strokePath()
translateBy(x: 0, y: -shadowY)
}
setFillColor(nFillColor)
addPath(path)
fillPath()
endTransparencyLayer()
if fillColor.alpha < 1 {
restoreGState()
}
}
}
extension CTLine {
var typographicBounds: CGRect {
var ascent = 0.0.cf, descent = 0.0.cf, leading = 0.0.cf
let width = CTLineGetTypographicBounds(self, &ascent, &descent, &leading).cf
return CGRect(x: 0, y: descent + leading, width: width, height: ascent + descent)
}
}
extension Bundle {
var version: Int {
return Int(infoDictionary?[String(kCFBundleVersionKey)] as? String ?? "0") ?? 0
}
}
extension NSCoding {
static func with(_ data: Data) -> Self? {
return data.isEmpty ? nil : NSKeyedUnarchiver.unarchiveObject(with: data) as? Self
}
var data: Data {
return NSKeyedArchiver.archivedData(withRootObject: self)
}
}
extension NSCoder {
func decodeStruct<T: ByteCoding>(forKey key: String) -> T? {
return T(coder: self, forKey: key)
}
func encodeStruct(_ byteCoding: ByteCoding, forKey key: String) {
byteCoding.encode(in: self, forKey: key)
}
}
protocol ByteCoding {
init?(coder: NSCoder, forKey key: String)
func encode(in coder: NSCoder, forKey key: String)
init(data: Data)
var data: Data { get }
}
extension ByteCoding {
init?(coder: NSCoder, forKey key: String) {
var length = 0
if let ptr = coder.decodeBytes(forKey: key, returnedLength: &length) {
self = UnsafeRawPointer(ptr).assumingMemoryBound(to: Self.self).pointee
} else {
return nil
}
}
func encode(in coder: NSCoder, forKey key: String) {
var t = self
withUnsafePointer(to: &t) {
coder.encodeBytes(UnsafeRawPointer($0).bindMemory(to: UInt8.self, capacity: 1), length: MemoryLayout<Self>.size, forKey: key)
}
}
init(data: Data) {
self = data.withUnsafeBytes {
UnsafeRawPointer($0).assumingMemoryBound(to: Self.self).pointee
}
}
var data: Data {
var t = self
return Data(buffer: UnsafeBufferPointer(start: &t, count: 1))
}
}
extension Array: ByteCoding {
init?(coder: NSCoder, forKey key: String) {
var length = 0
if let ptr = coder.decodeBytes(forKey: key, returnedLength: &length) {
let count = length/MemoryLayout<Element>.stride
self = count == 0 ? [] : ptr.withMemoryRebound(to: Element.self, capacity: 1) {
Array(UnsafeBufferPointer<Element>(start: $0, count: count))
}
} else {
return nil
}
}
func encode(in coder: NSCoder, forKey key: String) {
withUnsafeBufferPointer { ptr in
ptr.baseAddress?.withMemoryRebound(to: UInt8.self, capacity: 1) {
coder.encodeBytes($0, length: ptr.count*MemoryLayout<Element>.stride, forKey: key)
}
}
}
}
extension NSColor {
final class func checkerboardColor(_ color: NSColor, subColor: NSColor, size s: CGFloat = 5.0) -> NSColor {
let size = NSSize(width: s*2, height: s*2)
let image = NSImage(size: size) { ctx in
let rect = CGRect(origin: CGPoint(), size: size)
ctx.setFillColor(color.cgColor)
ctx.fill(rect)
ctx.fill(CGRect(x: 0, y: s, width: s, height: s))
ctx.fill(CGRect(x: s, y: 0, width: s, height: s))
ctx.setFillColor(subColor.cgColor)
ctx.fill(CGRect(x: 0, y: 0, width: s, height: s))
ctx.fill(CGRect(x: s, y: s, width: s, height: s))
}
return NSColor(patternImage: image)
}
static func polkaDotColorWith(color: NSColor?, dotColor: NSColor, radius r: CGFloat = 1.0, distance d: CGFloat = 4.0) -> NSColor {
let tw = (2*r + d)*cos(.pi/3), th = (2*r + d)*sin(.pi/3)
let bw = (tw - 2*r)/2, bh = (th - 2*r)/2
let size = CGSize(width: floor(bw*2 + tw + r*2), height: floor(bh*2 + th + r*2))
let image = NSImage(size: size) { ctx in
if let color = color {
ctx.setFillColor(color.cgColor)
ctx.fill(CGRect(origin: CGPoint(), size: size))
}
ctx.setFillColor(dotColor.cgColor)
ctx.fillEllipse(in: CGRect(x: bw, y: bh, width: r*2, height: r*2))
ctx.fillEllipse(in: CGRect(x: bw + tw, y: bh + th, width: r*2, height: r*2))
}
return NSColor(patternImage: image)
}
}
extension NSImage {
convenience init(size: CGSize, handler: (CGContext) -> Void) {
self.init(size: size)
lockFocus()
if let ctx = NSGraphicsContext.current()?.cgContext {
handler(ctx)
}
unlockFocus()
}
final var bitmapSize: CGSize {
if let tiffRepresentation = tiffRepresentation {
if let bitmap = NSBitmapImageRep(data: tiffRepresentation) {
return CGSize(width: bitmap.pixelsWide, height: bitmap.pixelsHigh)
}
}
return CGSize()
}
final var PNGRepresentation: Data? {
if let tiffRepresentation = tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiffRepresentation) {
return bitmap.representation(using: .PNG, properties: [NSImageInterlaced: false])
} else {
return nil
}
}
static func exportAppIcon() {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.begin { [unowned panel] result in
if result == NSFileHandlingPanelOKButton, let url = panel.url {
for s in [16.0.cf, 32.0.cf, 64.0.cf, 128.0.cf, 256.0.cf, 512.0.cf, 1024.0.cf] {
try? NSImage(size: CGSize(width: s, height: s), flipped: false) { rect -> Bool in
let ctx = NSGraphicsContext.current()!.cgContext, c = s*0.5, r = s*0.43, l = s*0.008, fs = s*0.45, fillColor = NSColor(white: 1, alpha: 1), fontColor = NSColor(white: 0.4, alpha: 1)
ctx.setFillColor(fillColor.cgColor)
ctx.setStrokeColor(fontColor.cgColor)
ctx.setLineWidth(l)
ctx.addEllipse(in: CGRect(x: c - r, y: c - r, width: r*2, height: r*2))
ctx.drawPath(using: .fillStroke)
var textLine = TextLine()
textLine.string = "C\u{2080}"
textLine.font = NSFont(name: "Avenir Next Regular", size: fs) ?? NSFont.systemFont(ofSize: fs)
textLine.color = fontColor.cgColor
textLine.isHorizontalCenter = true
textLine.isCenterWithImageBounds = true
textLine.draw(in: rect, in: ctx)
return true
}.PNGRepresentation?.write(to: url.appendingPathComponent("\(String(Int(s))).png"))
}
}
}
}
}
extension NSAttributedString {
static func attributes(_ font: NSFont, color: CGColor) -> [String: Any] {
return [String(kCTFontAttributeName): font, String(kCTForegroundColorAttributeName): color]
}
}
| 25c5e05c4b8fa202512407238eae4130 | 37.056243 | 205 | 0.538898 | false | false | false | false |
tbajis/Bop | refs/heads/master | Bop/CoreDataTableViewController.swift | apache-2.0 | 1 | //
// CoreDataTableViewController.swift
// Bop
//
// Created by Thomas Manos Bajis on 5/5/17.
// Copyright © 2017 Thomas Manos Bajis. All rights reserved.
//
import UIKit
import CoreData
// MARK: - CoreDataTableViewController: UITableViewController
class CoreDataTableViewController: UITableViewController {
// MARK: Properties
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>? {
didSet {
fetchedResultsController?.delegate = self
executeSearch()
tableView.reloadData()
}
}
// MARK: Initializers
init(fetchedResultsController fc: NSFetchedResultsController<NSFetchRequestResult>, style: UITableViewStyle = .plain) {
fetchedResultsController = fc
super.init(style: style)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - CoreDataTableViewController (TODO: Implement by subclass)
extension CoreDataTableViewController {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
fatalError("MUST IMPLEMENT THIS METHOD")
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
fatalError("MUST IMPLEMENT THIS METHOD")
}
}
// MARK: - CoreDataTableViewController (Table Data Source)
extension CoreDataTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
if let fc = fetchedResultsController {
return (fc.sections?.count)!
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let fc = fetchedResultsController {
return fc.sections![section].numberOfObjects
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if let fc = fetchedResultsController {
return fc.sections![section].name
} else {
return nil
}
}
override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if let fc = fetchedResultsController {
return fc.section(forSectionIndexTitle: title, at: index)
} else {
return 0
}
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if let fc = fetchedResultsController {
return fc.sectionIndexTitles
} else {
return nil
}
}
}
// MARK: CoreDataTableViewController (Fetches)
extension CoreDataTableViewController {
func executeSearch() {
if let fc = fetchedResultsController {
do {
try fc.performFetch()
} catch let e as NSError {
print("Error while trying to perform a search: \n\(e)\n\(fetchedResultsController)")
}
}
}
}
// MARK: - CoreDataTableViewController: NSFetchedResultsControllerDelegate
extension CoreDataTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let set = IndexSet(integer: sectionIndex)
switch (type) {
case .insert:
tableView.insertSections(set, with: .fade)
case .delete:
tableView.deleteSections(set, with: .fade)
default:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch(type) {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| 27711ff4e86a884dd06f0700c66da9aa | 30.54 | 209 | 0.644684 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/public/core/ReflectionLegacy.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// How children of this value should be presented in the IDE.
public enum _MirrorDisposition {
/// As a struct.
case `struct`
/// As a class.
case `class`
/// As an enum.
case `enum`
/// As a tuple.
case tuple
/// As a miscellaneous aggregate with a fixed set of children.
case aggregate
/// As a container that is accessed by index.
case indexContainer
/// As a container that is accessed by key.
case keyContainer
/// As a container that represents membership of its values.
case membershipContainer
/// As a miscellaneous container with a variable number of children.
case container
/// An Optional which can have either zero or one children.
case optional
/// An Objective-C object imported in Swift.
case objCObject
}
/// The type returned by `_reflect(x)`; supplies an API for runtime
/// reflection on `x`.
public protocol _Mirror {
/// The instance being reflected.
var value: Any { get }
/// Identical to `type(of: value)`.
var valueType: Any.Type { get }
/// A unique identifier for `value` if it is a class instance; `nil`
/// otherwise.
var objectIdentifier: ObjectIdentifier? { get }
/// The count of `value`'s logical children.
var count: Int { get }
/// Get a name and mirror for the `i`th logical child.
subscript(i: Int) -> (String, _Mirror) { get }
/// A string description of `value`.
var summary: String { get }
/// A rich representation of `value` for an IDE, or `nil` if none is supplied.
var quickLookObject: PlaygroundQuickLook? { get }
/// How `value` should be presented in an IDE.
var disposition: _MirrorDisposition { get }
}
/// An entry point that can be called from C++ code to get the summary string
/// for an arbitrary object. The memory pointed to by "out" is initialized with
/// the summary string.
@_silgen_name("swift_getSummary")
public // COMPILER_INTRINSIC
func _getSummary<T>(_ out: UnsafeMutablePointer<String>, x: T) {
out.initialize(to: String(reflecting: x))
}
/// Produce a mirror for any value. The runtime produces a mirror that
/// structurally reflects values of any type.
@_silgen_name("swift_reflectAny")
internal func _reflect<T>(_ x: T) -> _Mirror
// -- Implementation details for the runtime's _Mirror implementation
@_silgen_name("swift_MagicMirrorData_summary")
func _swift_MagicMirrorData_summaryImpl(
_ metadata: Any.Type, _ result: UnsafeMutablePointer<String>
)
@_fixed_layout
public struct _MagicMirrorData {
let owner: Builtin.NativeObject
let ptr: Builtin.RawPointer
let metadata: Any.Type
var value: Any {
@_silgen_name("swift_MagicMirrorData_value")get
}
var valueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_valueType")get
}
public var objcValue: Any {
@_silgen_name("swift_MagicMirrorData_objcValue")get
}
public var objcValueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_objcValueType")get
}
var summary: String {
let (_, result) = _withUninitializedString {
_swift_MagicMirrorData_summaryImpl(self.metadata, $0)
}
return result
}
public func _loadValue<T>(ofType _: T.Type) -> T {
return Builtin.load(ptr) as T
}
}
@_versioned
struct _OpaqueMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String { return data.summary }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .aggregate }
}
@_silgen_name("swift_TupleMirror_count")
func _getTupleCount(_: _MagicMirrorData) -> Int
// Like the other swift_*Mirror_subscript functions declared here and
// elsewhere, this is implemented in the runtime. The Swift CC would
// normally require the String to be returned directly and the _Mirror
// indirectly. However, Clang isn't currently capable of doing that
// reliably because the size of String exceeds the normal direct-return
// ABI rules on most platforms. Therefore, we make this function generic,
// which has the disadvantage of passing the String type metadata as an
// extra argument, but does force the string to be returned indirectly.
@_silgen_name("swift_TupleMirror_subscript")
func _getTupleChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
@_versioned
internal struct _TupleMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
return _getTupleCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getTupleChild(i, data)
}
var summary: String { return "(\(count) elements)" }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .tuple }
}
@_silgen_name("swift_StructMirror_count")
func _getStructCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_StructMirror_subscript")
func _getStructChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
@_versioned
struct _StructMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
return _getStructCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getStructChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`struct` }
}
@_silgen_name("swift_EnumMirror_count")
func _getEnumCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_EnumMirror_subscript")
func _getEnumChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
@_silgen_name("swift_EnumMirror_caseName")
func _swift_EnumMirror_caseName(
_ data: _MagicMirrorData) -> UnsafePointer<CChar>
@_versioned
struct _EnumMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
return _getEnumCount(data)
}
var caseName: UnsafePointer<CChar> {
return _swift_EnumMirror_caseName(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getEnumChild(i, data)
}
var summary: String {
let maybeCaseName = String(validatingUTF8: self.caseName)
let typeName = _typeName(valueType)
if let caseName = maybeCaseName {
return typeName + "." + caseName
}
return typeName
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`enum` }
}
@_silgen_name("swift_ClassMirror_count")
func _getClassCount(_: _MagicMirrorData) -> Int
@_silgen_name("swift_ClassMirror_subscript")
func _getClassChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
#if _runtime(_ObjC)
@_silgen_name("swift_ClassMirror_quickLookObject")
public func _swift_ClassMirror_quickLookObject(_: _MagicMirrorData) -> AnyObject
@_silgen_name("_swift_stdlib_NSObject_isKindOfClass")
internal func _swift_NSObject_isImpl(_ object: AnyObject, kindOf: AnyObject) -> Bool
internal func _is(_ object: AnyObject, kindOf `class`: String) -> Bool {
return _swift_NSObject_isImpl(object, kindOf: `class` as AnyObject)
}
func _getClassPlaygroundQuickLook(_ object: AnyObject) -> PlaygroundQuickLook? {
if _is(object, kindOf: "NSNumber") {
let number: _NSNumber = unsafeBitCast(object, to: _NSNumber.self)
switch UInt8(number.objCType[0]) {
case UInt8(ascii: "d"):
return .double(number.doubleValue)
case UInt8(ascii: "f"):
return .float(number.floatValue)
case UInt8(ascii: "Q"):
return .uInt(number.unsignedLongLongValue)
default:
return .int(number.longLongValue)
}
} else if _is(object, kindOf: "NSAttributedString") {
return .attributedString(object)
} else if _is(object, kindOf: "NSImage") ||
_is(object, kindOf: "UIImage") ||
_is(object, kindOf: "NSImageView") ||
_is(object, kindOf: "UIImageView") ||
_is(object, kindOf: "CIImage") ||
_is(object, kindOf: "NSBitmapImageRep") {
return .image(object)
} else if _is(object, kindOf: "NSColor") ||
_is(object, kindOf: "UIColor") {
return .color(object)
} else if _is(object, kindOf: "NSBezierPath") ||
_is(object, kindOf: "UIBezierPath") {
return .bezierPath(object)
} else if _is(object, kindOf: "NSString") {
return .text(_forceBridgeFromObjectiveC(object, String.self))
}
return .none
}
#endif
@_versioned
struct _ClassMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue(ofType: ObjectIdentifier.self)
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? {
#if _runtime(_ObjC)
let object = _swift_ClassMirror_quickLookObject(data)
return _getClassPlaygroundQuickLook(object)
#else
return nil
#endif
}
var disposition: _MirrorDisposition { return .`class` }
}
@_versioned
struct _ClassSuperMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
// Suppress the value identifier for super mirrors.
var objectIdentifier: ObjectIdentifier? {
return nil
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(data.metadata)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`class` }
}
@_versioned
struct _MetatypeMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue(ofType: ObjectIdentifier.self)
}
var count: Int {
return 0
}
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String {
return _typeName(data._loadValue(ofType: Any.Type.self))
}
var quickLookObject: PlaygroundQuickLook? { return nil }
// Special disposition for types?
var disposition: _MirrorDisposition { return .aggregate }
}
| a87b2e9f40ffa35d5f72b5f59f9f8eca | 29.880109 | 84 | 0.685697 | false | false | false | false |
peferron/algo | refs/heads/master | EPI/Binary Trees/Compute the LCA when nodes have parent pointers/swift/main.swift | mit | 1 | public class Node {
public let left: Node?
public let right: Node?
public var parent: Node? = nil
public init(left: Node? = nil, right: Node? = nil) {
self.left = left
self.right = right
left?.parent = self
right?.parent = self
}
func depth() -> Int {
var node = self
var depth = 0
while let p = node.parent {
depth += 1
node = p
}
return depth
}
func ancestor(depth: Int) -> Node? {
var node = self
for _ in 0..<depth {
if let p = node.parent {
node = p
} else {
return nil
}
}
return node
}
public func lca(_ other: Node) -> Node? {
let selfDepth = depth()
let otherDepth = other.depth()
var selfAncestor = ancestor(depth: max(0, selfDepth - otherDepth))
var otherAncestor = other.ancestor(depth: max(0, otherDepth - selfDepth))
while let sa = selfAncestor, let oa = otherAncestor {
if sa === oa {
return sa
}
selfAncestor = sa.parent
otherAncestor = oa.parent
}
return nil
}
}
| ce006754e9f685c7bd277b45292dd8de | 22.54717 | 81 | 0.481571 | false | false | false | false |
abbeycode/Carthage | refs/heads/master | Source/CarthageKitTests/ArchiveSpec.swift | mit | 1 | //
// ArchiveSpec.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2015-01-02.
// Copyright (c) 2015 Carthage. All rights reserved.
//
import CarthageKit
import Foundation
import Nimble
import Quick
import ReactiveCocoa
class ArchiveSpec: QuickSpec {
override func spec() {
describe("unzipping") {
let archiveURL = NSBundle(forClass: self.dynamicType).URLForResource("CartfilePrivateOnly", withExtension: "zip")!
it("should unzip archive to a temporary directory") {
let result = unzipArchiveToTemporaryDirectory(archiveURL) |> single
expect(result).notTo(beNil())
expect(result?.error).to(beNil())
let directoryPath = result?.value?.path ?? NSFileManager.defaultManager().currentDirectoryPath
var isDirectory: ObjCBool = false
expect(NSFileManager.defaultManager().fileExistsAtPath(directoryPath, isDirectory: &isDirectory)).to(beTruthy())
expect(isDirectory).to(beTruthy())
let contents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(directoryPath, error: nil) ?? []
let innerFolderName = "CartfilePrivateOnly"
expect(contents.isEmpty).to(beFalsy())
expect(contents).to(contain(innerFolderName))
let innerContents = NSFileManager.defaultManager().contentsOfDirectoryAtPath(directoryPath.stringByAppendingPathComponent(innerFolderName), error: nil) ?? []
expect(innerContents.isEmpty).to(beFalsy())
expect(innerContents).to(contain("Cartfile.private"))
}
}
describe("zipping") {
let originalCurrentDirectory = NSFileManager.defaultManager().currentDirectoryPath
let temporaryURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent(NSProcessInfo.processInfo().globallyUniqueString), isDirectory: true)!
let archiveURL = temporaryURL.URLByAppendingPathComponent("archive.zip", isDirectory: false)
beforeEach {
expect(NSFileManager.defaultManager().createDirectoryAtPath(temporaryURL.path!, withIntermediateDirectories: true, attributes: nil, error: nil)).to(beTruthy())
expect(NSFileManager.defaultManager().changeCurrentDirectoryPath(temporaryURL.path!)).to(beTruthy())
return
}
afterEach {
NSFileManager.defaultManager().removeItemAtURL(temporaryURL, error: nil)
expect(NSFileManager.defaultManager().changeCurrentDirectoryPath(originalCurrentDirectory)).to(beTruthy())
return
}
it("should zip relative paths into an archive") {
let subdirPath = "subdir"
expect(NSFileManager.defaultManager().createDirectoryAtPath(subdirPath, withIntermediateDirectories: true, attributes: nil, error: nil)).to(beTruthy())
let innerFilePath = subdirPath.stringByAppendingPathComponent("inner")
expect("foobar".writeToFile(innerFilePath, atomically: true, encoding: NSUTF8StringEncoding, error: nil)).to(beTruthy())
let outerFilePath = "outer"
expect("foobar".writeToFile(outerFilePath, atomically: true, encoding: NSUTF8StringEncoding, error: nil)).to(beTruthy())
let result = zipIntoArchive(archiveURL, [ innerFilePath, outerFilePath ]) |> wait
expect(result.error).to(beNil())
let unzipResult = unzipArchiveToTemporaryDirectory(archiveURL) |> single
expect(unzipResult).notTo(beNil())
expect(unzipResult?.error).to(beNil())
let enumerationResult = NSFileManager.defaultManager().carthage_enumeratorAtURL(unzipResult?.value ?? temporaryURL, includingPropertiesForKeys: [], options: nil)
|> map { enumerator, URL in URL }
|> map { $0.lastPathComponent! }
|> collect
|> single
expect(enumerationResult).notTo(beNil())
expect(enumerationResult?.error).to(beNil())
let fileNames = enumerationResult?.value
expect(fileNames).to(contain("inner"))
expect(fileNames).to(contain(subdirPath))
expect(fileNames).to(contain(outerFilePath))
}
it("should preserve symlinks") {
let destinationPath = "symlink-destination"
expect("foobar".writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding, error: nil)).to(beTruthy())
let symlinkPath = "symlink"
expect(NSFileManager.defaultManager().createSymbolicLinkAtPath(symlinkPath, withDestinationPath: destinationPath, error: nil)).to(beTruthy())
expect(NSFileManager.defaultManager().destinationOfSymbolicLinkAtPath(symlinkPath, error: nil)).to(equal(destinationPath))
let result = zipIntoArchive(archiveURL, [ symlinkPath, destinationPath ]) |> wait
expect(result.error).to(beNil())
let unzipResult = unzipArchiveToTemporaryDirectory(archiveURL) |> single
expect(unzipResult).notTo(beNil())
expect(unzipResult?.error).to(beNil())
let unzippedSymlinkURL = (unzipResult?.value ?? temporaryURL).URLByAppendingPathComponent(symlinkPath)
expect(NSFileManager.defaultManager().fileExistsAtPath(unzippedSymlinkURL.path!)).to(beTruthy())
expect(NSFileManager.defaultManager().destinationOfSymbolicLinkAtPath(unzippedSymlinkURL.path!, error: nil)).to(equal(destinationPath))
}
}
}
}
| b505172f68ec0943449f3f28eb008b7f | 43.738739 | 169 | 0.756343 | false | false | false | false |
petrpavlik/AsyncChat | refs/heads/master | Chat/Classes/MessageCell.swift | mit | 1 | //
// MessageCell.swift
// Chat
//
// Created by Petr Pavlik on 24/10/15.
// Copyright © 2015 Petr Pavlik. All rights reserved.
//
import UIKit
import Toucan
import AsyncDisplayKit
public class MessageCell: ASCellNode {
// MARK: Layout constants
private let topVerticalPadding: CGFloat = 10.0
private let bottomVerticalPadding: CGFloat = 10.0
private let leadingHorizontalPadding: CGFloat = 8.0
private let trailingHorizontalPadding: CGFloat = 16.0
private let avatarImageSize = CGSizeMake(36, 36)
private let avatarBubbleHorizontalDistance: CGFloat = 8.0
private let bubbleTextMargin: CGFloat = 10
private let headerTextHeight: CGFloat = 20
private static let bubbleImage: UIImage = {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(18*2, 18*2), false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor)
CGContextFillEllipseInRect(context, CGRectMake(0, 0, 18*2, 18*2));
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
image = image.imageWithRenderingMode(.AlwaysTemplate)
image = image.resizableImageWithCapInsets(UIEdgeInsetsMake(18, 18, 18, 18))
return image
}()
// MARK:
public let avatarImageNode = ASNetworkImageNode()
public let bubbleNode = ASDisplayNode { () -> UIView! in
let imageView = UIImageView(image: bubbleImage)
return imageView
}
private let headerTextNode = ASTextNode()
public var headerText: String? {
didSet {
if headerText?.characters.count > 0 {
headerTextNode.hidden = false
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
paragraphStyle.lineHeightMultiple = 1.4
headerTextNode.attributedString = NSAttributedString(string: headerText!, attributes: [NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: UIColor.grayColor()])
} else {
headerTextNode.hidden = true
headerTextNode.attributedString = nil
}
}
}
var incomingMessageColorNormal = UIColor(red:0.941, green:0.941, blue:0.941, alpha: 1)
var incomingMessageColorSelected = UIColor(red:0.831, green:0.824, blue:0.827, alpha: 1)
var outgoingMessageColorNormal = UIColor(red:0.004, green:0.518, blue:1.000, alpha: 1)
var outgoingMessageColorSelected = UIColor(red:0.075, green:0.467, blue:0.976, alpha: 1)
var avatarPlaceholderColor = UIColor.grayColor()
// MARK:
var isIncomingMessage = true
// MARK:
public override init!() {
super.init()
selectionStyle = .None
addSubnode(avatarImageNode)
addSubnode(bubbleNode)
addSubnode(headerTextNode)
avatarImageNode.placeholderColor = avatarPlaceholderColor
avatarImageNode.placeholderEnabled = true
bubbleNode.tintColor = incomingMessageColorNormal
avatarImageNode.imageModificationBlock = { image in
//return Toucan(image: image).maskWithEllipse().image
return Toucan(image: image).resize(CGSize(width: 36, height: 36)).maskWithEllipse().image
}
}
override public func layoutSpecThatFits(constrainedSize: ASSizeRange) -> ASLayoutSpec! {
var rootSpec: ASLayoutSpec!
if isIncomingMessage == true {
avatarImageNode.sizeRange = ASRelativeSizeRangeMakeWithExactCGSize(CGSizeMake(36, 36))
let imageSizeLayout = ASStaticLayoutSpec(children: [avatarImageNode])
let bubbleSizeLayout = layoutSpecForBubbneNode(bubbleNode)
bubbleSizeLayout.flexShrink = true
rootSpec = ASStackLayoutSpec(direction: .Horizontal, spacing: avatarBubbleHorizontalDistance, justifyContent: .Start, alignItems: .Start, children: [imageSizeLayout, bubbleSizeLayout])
} else {
let bubbleSizeLayout = layoutSpecForBubbneNode(bubbleNode)
bubbleSizeLayout.flexShrink = true
rootSpec = ASStackLayoutSpec(direction: .Horizontal, spacing: avatarBubbleHorizontalDistance, justifyContent: .End, alignItems: .End, children: [bubbleSizeLayout])
}
if headerText?.characters.count > 0 {
//let centerSpec = ASStackLayoutSpec(direction: .Horizontal, spacing: 0, justifyContent: .Center, alignItems: .Center, children: [headerTextNode])
//centerSpec.flexGrow = true
rootSpec = ASStackLayoutSpec(direction: .Vertical, spacing: 10, justifyContent: .Start, alignItems: .Start, children: [headerTextNode, rootSpec])
}
rootSpec = ASInsetLayoutSpec(insets: UIEdgeInsetsMake(topVerticalPadding, leadingHorizontalPadding, bottomVerticalPadding, trailingHorizontalPadding), child: rootSpec)
return rootSpec
}
func layoutSpecForBubbneNode(bubbleNode: ASDisplayNode) -> ASLayoutSpec {
bubbleNode.sizeRange = ASRelativeSizeRangeMakeWithExactCGSize(CGSizeMake(76, 36))
return ASStaticLayoutSpec(children: [bubbleNode])
}
}
| e316a9cbc06b3887be0e119db7b7b3b4 | 38.107143 | 203 | 0.661735 | false | false | false | false |
zisko/swift | refs/heads/master | test/SILGen/struct_resilience.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -enable-sil-ownership -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -enable-sil-ownership -emit-silgen -enable-resilience %s | %FileCheck %s
import resilient_struct
// Resilient structs are always address-only
// CHECK-LABEL: sil hidden @$S17struct_resilience26functionWithResilientTypes_1f010resilient_A04SizeVAF_A2FXEtF : $@convention(thin) (@in Size, @noescape @callee_guaranteed (@in Size) -> @out Size) -> @out Size
// CHECK: bb0(%0 : @trivial $*Size, %1 : @trivial $*Size, %2 : @trivial $@noescape @callee_guaranteed (@in Size) -> @out Size):
func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
// Stored properties of resilient structs from outside our resilience
// domain are accessed through accessors
// CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size
var s2 = s
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[GETTER:%.*]] = function_ref @$S16resilient_struct4SizeV1wSivg : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[GETTER]]([[SIZE_BOX]])
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[OTHER_SIZE_BOX]] : $*Size
// CHECK: [[SETTER:%.*]] = function_ref @$S16resilient_struct4SizeV1wSivs : $@convention(method) (Int, @inout Size) -> ()
// CHECK: apply [[SETTER]]([[RESULT]], [[WRITE]])
s2.w = s.w
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @$S16resilient_struct4SizeV1hSivg : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
// Use materializeForSet for inout access of properties in resilient structs
// from a different resilience domain
public func inoutFunc(_ x: inout Int) {}
// CHECK-LABEL: sil hidden @$S17struct_resilience18resilientInOutTestyy0c1_A04SizeVzF : $@convention(thin) (@inout Size) -> ()
func resilientInOutTest(_ s: inout Size) {
// CHECK: function_ref @$S16resilient_struct4SizeV1wSivm
// CHECK: function_ref @$S17struct_resilience9inoutFuncyySizF
inoutFunc(&s.w)
// CHECK: return
}
// Fixed-layout structs may be trivial or loadable
// CHECK-LABEL: sil hidden @$S17struct_resilience28functionWithFixedLayoutTypes_1f010resilient_A05PointVAF_A2FXEtF : $@convention(thin) (Point, @noescape @callee_guaranteed (Point) -> Point) -> Point
// CHECK: bb0(%0 : @trivial $Point, %1 : @trivial $@noescape @callee_guaranteed (Point) -> Point):
func functionWithFixedLayoutTypes(_ p: Point, f: (Point) -> Point) -> Point {
// Stored properties of fixed layout structs are accessed directly
var p2 = p
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x
// CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x
// CHECK: assign [[RESULT]] to [[DEST]] : $*Int
p2.x = p.x
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y
_ = p.y
// CHECK: [[NEW_POINT:%.*]] = apply %1(%0)
// CHECK: return [[NEW_POINT]]
return f(p)
}
// Fixed-layout struct with resilient stored properties is still address-only
// CHECK-LABEL: sil hidden @$S17struct_resilience39functionWithFixedLayoutOfResilientTypes_1f010resilient_A09RectangleVAF_A2FXEtF : $@convention(thin) (@in Rectangle, @noescape @callee_guaranteed (@in Rectangle) -> @out Rectangle) -> @out Rectangle
// CHECK: bb0(%0 : @trivial $*Rectangle, %1 : @trivial $*Rectangle, %2 : @trivial $@noescape @callee_guaranteed (@in Rectangle) -> @out Rectangle):
func functionWithFixedLayoutOfResilientTypes(_ r: Rectangle, f: (Rectangle) -> Rectangle) -> Rectangle {
return f(r)
}
// Make sure we generate getters and setters for stored properties of
// resilient structs
public struct MySize {
// Static computed property
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV10expirationSivgZ : $@convention(method) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV10expirationSivsZ : $@convention(method) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV10expirationSivmZ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public static var expiration: Int {
get { return copyright + 70 }
set { copyright = newValue - 70 }
}
// Instance computed property
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1dSivg : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1dSivs : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1dSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public var d: Int {
get { return 0 }
set { }
}
// Instance stored property
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1wSivs : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1wSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public var w: Int
// Read-only instance stored property
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV1hSivg : $@convention(method) (@in_guaranteed MySize) -> Int
public let h: Int
// Static stored property
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV9copyrightSivgZ : $@convention(method) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV9copyrightSivsZ : $@convention(method) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @$S17struct_resilience6MySizeV9copyrightSivmZ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
public static var copyright: Int = 0
}
// CHECK-LABEL: sil @$S17struct_resilience28functionWithMyResilientTypes_1fAA0E4SizeVAE_A2EXEtF : $@convention(thin) (@in MySize, @noescape @callee_guaranteed (@in MySize) -> @out MySize) -> @out MySize
public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
// Stored properties of resilient structs from inside our resilience
// domain are accessed directly
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize
var s2 = s
// CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w
// CHECK: [[SRC:%.*]] = load [trivial] [[SRC_ADDR]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[SIZE_BOX]] : $*MySize
// CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MySize, #MySize.w
// CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int
s2.w = s.w
// CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h
// CHECK: [[RESULT:%.*]] = load [trivial] [[RESULT_ADDR]] : $*Int
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
// CHECK-LABEL: sil [transparent] [serialized] @$S17struct_resilience25publicTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
@_transparent public func publicTransparentFunction(_ s: MySize) -> Int {
// Since the body of a public transparent function might be inlined into
// other resilience domains, we have to use accessors
// CHECK: [[SELF:%.*]] = alloc_stack $MySize
// CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @$S17struct_resilience6MySizeV1wSivg
// CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK-NEXT: destroy_addr [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// CHECK-LABEL: sil [transparent] [serialized] @$S17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVF : $@convention(thin) (@in MySize) -> @owned @callee_guaranteed () -> Int
@_transparent public func publicTransparentLocalFunction(_ s: MySize) -> () -> Int {
// CHECK-LABEL: sil shared [serialized] @$S17struct_resilience30publicTransparentLocalFunctionySiycAA6MySizeVFSiycfU_ : $@convention(thin) (@guaranteed { var MySize }) -> Int
// CHECK: function_ref @$S17struct_resilience6MySizeV1wSivg : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK: return {{.*}} : $Int
return { s.w }
}
// CHECK-LABEL: sil hidden [transparent] @$S17struct_resilience27internalTransparentFunctionySiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
// CHECK: bb0([[ARG:%.*]] : @trivial $*MySize):
@_transparent func internalTransparentFunction(_ s: MySize) -> Int {
// The body of an internal transparent function will not be inlined into
// other resilience domains, so we can access storage directly
// CHECK: [[W_ADDR:%.*]] = struct_element_addr [[ARG]] : $*MySize, #MySize.w
// CHECK-NEXT: [[RESULT:%.*]] = load [trivial] [[W_ADDR]] : $*Int
// CHECK-NEXT: destroy_addr [[ARG]]
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// CHECK-LABEL: sil [serialized] [always_inline] @$S17struct_resilience26publicInlineAlwaysFunctionySiAA6MySizeVF : $@convention(thin) (@in MySize) -> Int
@inline(__always) public func publicInlineAlwaysFunction(_ s: MySize) -> Int {
// Since the body of a public transparent function might be inlined into
// other resilience domains, we have to use accessors
// CHECK: [[SELF:%.*]] = alloc_stack $MySize
// CHECK-NEXT: copy_addr %0 to [initialization] [[SELF]]
// CHECK: [[GETTER:%.*]] = function_ref @$S17struct_resilience6MySizeV1wSivg
// CHECK-NEXT: [[RESULT:%.*]] = apply [[GETTER]]([[SELF]])
// CHECK-NEXT: destroy_addr [[SELF]]
// CHECK-NEXT: dealloc_stack [[SELF]]
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: return [[RESULT]]
return s.w
}
// Make sure that @_versioned entities can be resilient
@_versioned struct VersionedResilientStruct {
@_versioned let x: Int
@_versioned let y: Int
@_versioned init(x: Int, y: Int) {
self.x = x
self.y = y
}
// Non-inlineable initializer, assigns to self -- treated as a root initializer
// CHECK-LABEL: sil @$S17struct_resilience24VersionedResilientStructV5otherA2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct }
// CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK: return
@_versioned init(other: VersionedResilientStruct) {
self = other
}
// Inlineable initializer, assigns to self -- treated as a delegating initializer
// CHECK-LABEL: sil [serialized] @$S17struct_resilience24VersionedResilientStructV6other2A2C_tcfC : $@convention(method) (@in VersionedResilientStruct, @thin VersionedResilientStruct.Type) -> @out VersionedResilientStruct
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var VersionedResilientStruct }
// CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]]
// CHECK: return
@_versioned @_inlineable init(other2: VersionedResilientStruct) {
self = other2
}
}
// CHECK-LABEL: sil [transparent] [serialized] @$S17struct_resilience27useVersionedResilientStructyAA0deF0VADF : $@convention(thin) (@in VersionedResilientStruct) -> @out VersionedResilientStruct
@_versioned
@_transparent func useVersionedResilientStruct(_ s: VersionedResilientStruct)
-> VersionedResilientStruct {
// CHECK: function_ref @$S17struct_resilience24VersionedResilientStructV1ySivg
// CHECK: function_ref @$S17struct_resilience24VersionedResilientStructV1xSivg
// CHECK: function_ref @$S17struct_resilience24VersionedResilientStructV1x1yACSi_SitcfC
return VersionedResilientStruct(x: s.y, y: s.x)
// CHECK: return
}
// CHECK-LABEL: sil [serialized] @$S17struct_resilience19inlineableInoutTestyyAA6MySizeVzF : $@convention(thin) (@inout MySize) -> ()
@_inlineable public func inlineableInoutTest(_ s: inout MySize) {
// Inlineable functions can be inlined in other resiliene domains.
//
// Make sure we use materializeForSet for an inout access of a resilient struct
// property inside an inlinable function.
// CHECK: function_ref @$S17struct_resilience6MySizeV1wSivm
inoutFunc(&s.w)
// CHECK: return
}
// Initializers for resilient structs
extension Size {
// CHECK-LABEL: sil hidden @$S16resilient_struct4SizeV0B11_resilienceE5otherA2C_tcfC : $@convention(method) (@in Size, @thin Size.Type) -> @out Size
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Size }
// CHECK-NEXT: [[SELF_UNINIT:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var Size }
// CHECK: return
init(other: Size) {
self = other
}
}
| 5a20a76060ed5f1a0b746862d9040c12 | 46.608392 | 248 | 0.680229 | false | false | false | false |
JornWu/ZhiBo_Swift | refs/heads/master | ZhiBo_Swift/Class/Home/ViewController/HotListCell.swift | mit | 1 | //
// HotListCell.swift
// ZhiBo_Swift
//
// Created by JornWu on 2017/4/23.
// Copyright © 2017年 Jorn.Wu([email protected]). All rights reserved.
//
import UIKit
import SDWebImage
import ReactiveCocoa
import ReactiveSwift
import Result
class HotListCell: UICollectionViewCell {
private var nickNameLabel: UILabel! ///昵称
private var hierarchyImgView: UIImageView! ///等级
private var categoryLabel: UILabel! ///家族
private var liveMarkImgView: UIImageView! ///直播标签
private var numberLabel: UILabel! ///观看人数
private var backgroundImgView: UIImageView! ///封面(可以用Button backgroundimage)
private var actionBtn: LinkButton! ///响应点击的按钮(可以直接使用backgroundImagView的点击手势)
var actionSignal: Signal<LinkButton, NoError> {
return actionBtn.reactive.controlEvents(.touchUpInside)
}
public func setupCell(nickName: String?, starLevel: Int?, category: String?, liveMark: UIImage?, number: Int?, backgroundImagURLString: String?, roomLink: String) {
backgroundImgView = UIImageView()
backgroundImgView.isUserInteractionEnabled = true ///使用imageView一定注意将用户交互设为true
backgroundImgView.sd_setImage(with: URL(string: backgroundImagURLString!), placeholderImage: #imageLiteral(resourceName: "no_follow_250x247"))
self.contentView.addSubview(backgroundImgView)
backgroundImgView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.size.equalToSuperview()
}
///其他控件都放到这里
let infoContainerView = UIView()
infoContainerView.backgroundColor = UIColor.clear
self.backgroundImgView.addSubview(infoContainerView)
infoContainerView.snp.makeConstraints { (make) in
make.left.right.equalToSuperview()
make.bottom.equalTo(-5)
make.height.equalTo(self.contentView).dividedBy(5)///高度等于cell的1/4
}
nickNameLabel = UILabel()
nickNameLabel.text = nickName
nickNameLabel.textColor = UIColor.white
infoContainerView.addSubview(nickNameLabel)
nickNameLabel.snp.makeConstraints { (make) in
make.left.top.right.equalToSuperview()
make.height.equalTo(infoContainerView).dividedBy(2)
}
hierarchyImgView = UIImageView()
hierarchyImgView.image = UIImage(named: "girl_star" + String(describing: starLevel!) + "_40x19")
infoContainerView.addSubview(hierarchyImgView)
hierarchyImgView.snp.makeConstraints { (make) in
make.left.bottom.equalToSuperview()
make.top.equalTo(nickNameLabel.snp.bottom)
make.width.equalTo(infoContainerView).dividedBy(5)
}
numberLabel = UILabel()
numberLabel.textAlignment = .right
numberLabel.text = String(describing: number!) + "人"
numberLabel.textColor = UIColor.white
infoContainerView.addSubview(numberLabel)
numberLabel.snp.makeConstraints { (make) in
make.left.equalTo(hierarchyImgView.snp.right)
make.top.bottom.equalTo(hierarchyImgView)
make.right.equalTo(infoContainerView)
}
categoryLabel = UILabel()
categoryLabel.text = category
categoryLabel.textColor = UIColor.white
self.backgroundImgView.addSubview(categoryLabel)
categoryLabel.snp.makeConstraints { (make) in
make.topMargin.leftMargin.equalTo(10)
make.size.equalTo(CGSize(width: 50, height: 20))
}
liveMarkImgView = UIImageView()
liveMarkImgView.image = liveMark
self.backgroundImgView.addSubview(liveMarkImgView)
liveMarkImgView.snp.makeConstraints { (make) in
make.top.equalTo(10)
make.right.equalTo(-10)
make.size.equalTo(CGSize(width: 40, height: 20))
}
actionBtn = LinkButton(type: .custom)
actionBtn.link = roomLink
self.backgroundImgView.addSubview(actionBtn)
actionBtn.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
make.size.equalToSuperview()
}
}
}
| 7f54b9eb8b39050115c3645f82dfa878 | 39.852941 | 168 | 0.666427 | false | false | false | false |
dabing1022/AlgorithmRocks | refs/heads/master | LeetCodeSwift/Playground/LeetCode.playground/Pages/026 Remove Duplicates from Sorted Array.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
/*:
# [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.
*/
import Foundation
class Solution {
class func removeDuplicates(var nums: [Int]) -> Int {
if (nums.count == 0) { return 0 }
var index = 0
for i in 1..<nums.count {
if (nums[index] != nums[i]) {
nums[++index] = nums[i]
}
}
return index + 1
}
}
class Solution2 {
class func removeDuplicateds(var nums: [Int]) -> [Int] {
if (nums.count == 0) { return [Int]() }
var index = 0
for i in 1..<nums.count {
if (nums[index] != nums[i]) {
nums[++index] = nums[i]
}
}
nums.removeRange(Range(start: index + 1, end: nums.count))
return nums
}
}
var nums = [1, 1, 3, 4, 8, 8, 100, 50, 40, 30, 30]
let elementsNotDuplicateNum = Solution.removeDuplicates(nums)
let elementsNotDuplicate = Solution2.removeDuplicateds(nums)
//: [Next](@next)
| 24815ce0f6871a16b25c8cd478b00e87 | 26.125 | 159 | 0.597103 | false | false | false | false |
SimoKutlin/tweetor | refs/heads/master | tweetor/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// tweetor
//
// Created by simo.kutlin on 03.05.17.
// Copyright © 2017 simo.kutlin All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "tweetor")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 73b855c48795666df8692d35f427e5bb | 48.333333 | 285 | 0.685702 | false | false | false | false |
Pacific3/PFoundation | refs/heads/master | PFoundation/Extensions/Dictionary.swift | mit | 1 |
extension Dictionary {
public init<Sequence: SequenceType where Sequence.Generator.Element == Value>(sequence: Sequence, @noescape keyMapper: Value -> Key?) {
self.init()
for item in sequence {
if let key = keyMapper(item) {
self[key] = item
}
}
}
public func toURLEncodedString() -> String {
var pairs = [String]()
for element in self {
if let key = encode(element.0 as! AnyObject),
let value = encode(element.1 as! AnyObject) where (!value.isEmpty && !key.isEmpty) {
pairs.append([key, value].joinWithSeparator("="))
} else {
continue
}
}
guard !pairs.isEmpty else {
return ""
}
return pairs.joinWithSeparator("&")
}
}
| 56c5da2caad75abe14bd42a72f2f47b7 | 28.4 | 139 | 0.5 | false | false | false | false |
chrisjmendez/swift-exercises | refs/heads/master | Games/FlappyBirdClone/FlappyBirdClone/GameScene.swift | mit | 1 | //
// GameScene.swift
// FlappyBirdClone
//
// Created by tommy trojan on 6/17/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var textures = [
"bird1.png", "bird2.png", "bird3.png", "bird4.png",
"bird5.png", "bird6.png", "bird7.png", "bird8.png"
]
var pipeTextures = [
"pipe1.png", "pipe2.png"
]
//Detect whether two objects are colliding
let birdGroup: UInt32 = 0x1 << 0
//The types and the ground
let enemyObjectsGroup:UInt32 = 0x1 << 1
//Opening between the two pipes represents a positive score
let openingGroup:UInt32 = 0x1 << 2
//Give objects a position
enum objectsZPositions: CGFloat{
case background = 0
case ground = 1
case pipes = 2
case bird = 3
case score = 4
case gameOver = 5
case lightbox = 6
}
//Store all the objects within here so that you can start/stop things at once
var movingGameObjects = SKNode()
var bg = SKSpriteNode()
var lightbox = SKSpriteNode()
//Objects
var bird = SKSpriteNode()
var ground = SKSpriteNode()
var pipeSpeed:NSTimeInterval = 7
var pipesSpawned:Int = 0
//Keep track if the game is over
var gameOver:Bool = false
var scoreLabelNode = SKLabelNode()
var score:Int = 0
var gameOverLabelNode = SKLabelNode()
var gameOverStatusNode = SKLabelNode()
func createBackground(){
//A. Assign the background image to a texture
var bgTexture = SKTexture(imageNamed: "background")
//B. The action that will move the background from point A to B
var moveBG = SKAction.moveByX(-bgTexture.size().width, y: 0, duration: 12)
//C. The action that will plop a new background instance at point A
var replaceBG = SKAction.moveByX(bgTexture.size().width, y: 0, duration: 0)
//D. Assign the two actions to an array
var actions = [moveBG, replaceBG]
//E. Create a sequence of the items within the array
var sequenceBG = SKAction.sequence(actions)
//F. Repeat the sequence forver
var loopBG = SKAction.repeatActionForever(sequenceBG)
//G. Create a loop so that the background doesn't go off the screen
for var i:CGFloat = 0; i < 2; i++ {
bg = SKSpriteNode(texture: bgTexture)
bg.position = CGPoint(
x: bgTexture.size().width/2 + i * bgTexture.size().width,
y: CGRectGetMidY(self.frame)
)
bg.size.height = self.frame.height
bg.zPosition = -1//objectsZPositions.background.rawValue
//Run the background loop forver
bg.runAction(loopBG)
//Keep all the objects contained within a single location
movingGameObjects.addChild(bg)
}
}
func modifyGravity(){
self.physicsWorld.contactDelegate = self
//Basic gravity is 9.8m/s but we're going to change ours
self.physicsWorld.gravity = CGVectorMake(0, -15)
}
func initProtagonist(){
//Create an animation from the bird sprites
var sprites = [SKTexture]()
for texture in self.textures{
var birdTexture = SKTexture(imageNamed: texture )
sprites.append(birdTexture)
}
let flyAnimation = SKAction.animateWithTextures(sprites, timePerFrame: 0.1)
let flyForever = SKAction.repeatActionForever(flyAnimation)
//Initialize the bird
bird = SKSpriteNode(texture: sprites[0])
bird.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
bird.zPosition = objectsZPositions.bird.rawValue
//Track the bird using a key
bird.runAction(flyForever, withKey: "birdFly")
bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height/2)
bird.physicsBody?.categoryBitMask = birdGroup
//If two objects collide, they CAN pass through
bird.physicsBody?.contactTestBitMask = openingGroup | enemyObjectsGroup
//if two objects collide, they CAN NOT pass through
bird.physicsBody?.collisionBitMask = enemyObjectsGroup
//The bird CAN NOT rotate if it collides with the object
bird.physicsBody?.allowsRotation = false
self.addChild(bird)
}
func initGround(){
var ground = SKNode()
ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.width, 1))
//Ground will be independent of gravity so it will stick
ground.physicsBody?.dynamic = false
//Position ground right at the bottom of the screen
ground.position = CGPoint(x: CGRectGetMidX(self.frame), y: 0)
//Z position
ground.zPosition = objectsZPositions.ground.rawValue
//Hit testing
ground.physicsBody?.categoryBitMask = enemyObjectsGroup
ground.physicsBody?.collisionBitMask = birdGroup
ground.physicsBody?.contactTestBitMask = birdGroup
self.addChild(ground)
}
func loadPipes(){
//A. Spawn the pipes
pipesSpawned += 2
if pipesSpawned % 10 == 0{
pipeSpeed -= 0.5
}
//B. Measure the distance of the bird and give it some margin
let margin:CGFloat = 3.5
let gap:CGFloat = bird.size.height * margin
//C. Create a random Y for the pipe positions
let randomY:CGFloat = CGFloat(arc4random_uniform(UInt32(self.frame.height * 0.7)))
//D. Create Pipe 1
var pipe1 = SKSpriteNode(texture: SKTexture(imageNamed: pipeTextures[0]) )
pipe1.position = CGPoint(
x: self.frame.width + pipe1.size.width,
y: pipe1.size.height/2 + 150 + randomY + gap/2
)
pipe1.physicsBody = SKPhysicsBody(rectangleOfSize: pipe1.size)
pipe1.physicsBody?.dynamic = false;
pipe1.physicsBody?.categoryBitMask = enemyObjectsGroup
pipe1.physicsBody?.collisionBitMask = birdGroup
pipe1.physicsBody?.contactTestBitMask = birdGroup
pipe1.zPosition = objectsZPositions.pipes.rawValue
movingGameObjects.addChild(pipe1)
//E. Describe how the pipes will move
let movePipe = SKAction.moveToX(-pipe1.size.width, duration: pipeSpeed)
let removePipe = SKAction.removeFromParent()
pipe1.runAction(SKAction.sequence([movePipe, removePipe]))
var pipe2 = SKSpriteNode(texture: SKTexture(imageNamed: pipeTextures[1]))
pipe2.position = CGPoint(
x: self.frame.width + pipe2.size.width,
y: -pipe2.size.height/2 + 150 + randomY - gap/2
)
pipe2.physicsBody = SKPhysicsBody(rectangleOfSize: pipe2.size)
pipe2.physicsBody?.dynamic = false
pipe2.physicsBody?.categoryBitMask = enemyObjectsGroup
pipe2.physicsBody?.collisionBitMask = birdGroup
pipe2.physicsBody?.contactTestBitMask = birdGroup
pipe2.zPosition = objectsZPositions.pipes.rawValue
movingGameObjects.addChild(pipe2)
pipe2.runAction(SKAction.sequence([movePipe, removePipe]))
let crossing = SKNode()
crossing.position = CGPoint(x: pipe1.position.x + pipe1.size.width/2, y: CGRectGetMidY(self.frame))
crossing.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake((1), self.frame.height))
crossing.physicsBody?.dynamic = false
crossing.physicsBody?.categoryBitMask = openingGroup
crossing.physicsBody?.contactTestBitMask = birdGroup
movingGameObjects.addChild(crossing)
crossing.runAction(SKAction.sequence([movePipe, removePipe]))
}
func initPipesTimer(){
var pipesTimer = NSTimer.scheduledTimerWithTimeInterval(2.5, target: self, selector: "loadPipes", userInfo: nil, repeats: true)
}
func initGame(){
println("initGame")
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as SKView!
skView.showsFPS = false
skView.showsNodeCount = false
skView.showsPhysics = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
func initScoreLabel(){
scoreLabelNode = SKLabelNode(fontNamed: "ChalkboardSE-Bold")
scoreLabelNode.fontSize = 50
scoreLabelNode.fontColor = SKColor.whiteColor()
scoreLabelNode.position = CGPoint(x: CGRectGetMidX(self.frame), y: self.frame.height - 50)
scoreLabelNode.text = "0"
scoreLabelNode.zPosition = objectsZPositions.score.rawValue
self.addChild(scoreLabelNode)
}
func kill(){
//Remove bird
bird.removeActionForKey("birdFly")
self.removeActionForKey("flash")
//Spin bird out of control
var radians = CGFloat(M_PI) * bird.position.y * 0.01
var duration = NSTimeInterval(bird.position.y * 0.003)
var action = SKAction.rotateByAngle(radians, duration: duration)
bird.runAction(action, completion: { () -> Void in
self.bird.speed = 0
})
//Flash the background Red
let showFire = SKAction.runBlock({ self.lightbox.color = SKColor.redColor() })
let showSky = SKAction.runBlock({ self.lightbox.color = SKColor(red: 113.0/255.0, green: 197.0/255.0, blue: 207.0/255.0, alpha: 1.0) })
let wait = SKAction.waitForDuration(0.05)
let sequence = SKAction.sequence([showFire, wait, showSky, wait])
lightbox.actionForKey("flash")
lightbox.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
lightbox.size.width = self.frame.width
lightbox.size.height = self.frame.height
lightbox.zPosition = objectsZPositions.lightbox.rawValue
lightbox.alpha = 0.6
lightbox.runAction(SKAction.repeatAction(sequence, count: 4), completion: { () -> Void in
self.lightbox.removeFromParent()
})
self.addChild(lightbox)
}
func stopGame(){
//Stop the Game
self.physicsWorld.contactDelegate = nil
movingGameObjects.speed = 0
gameOver = true
}
func addPoint(){
score += 1
scoreLabelNode.text = "\(score)"
}
func announcements(status:String){
switch(status){
case "quit":
//Accounce "Game Over"
gameOverLabelNode = SKLabelNode(fontNamed: "Copperplate-Bold")
gameOverLabelNode.fontSize = 50
gameOverLabelNode.fontColor = SKColor.whiteColor()
gameOverLabelNode.zPosition = objectsZPositions.gameOver.rawValue
gameOverLabelNode.text = "Game Over"
gameOverLabelNode.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
self.addChild(gameOverLabelNode)
//Animate
let scaleUp = SKAction.scaleTo(1.5, duration: 2)
let scale = SKAction.scaleTo(1, duration: 0.25)
let scaleSequence = SKAction.sequence([scaleUp, scale])
//Announce "Tap to Restart"
gameOverLabelNode.runAction(scaleSequence, completion: { () -> Void in
self.gameOverStatusNode = SKLabelNode(fontNamed: "Copperplate")
self.gameOverStatusNode.fontSize = 30
self.gameOverStatusNode.fontColor = SKColor.whiteColor()
self.gameOverStatusNode.zPosition = objectsZPositions.gameOver.rawValue
self.gameOverStatusNode.text = "Tap to restart"
self.gameOverStatusNode.position = CGPoint(
x: CGRectGetMidX(self.frame),
y: CGRectGetMidY(self.frame) - self.gameOverStatusNode.frame.height - 20
)
self.addChild(self.gameOverStatusNode)
//Animate
let scaleUp = SKAction.scaleTo(1.25, duration: 0.5)
let scaleBack = SKAction.scaleTo(1, duration: 0.25)
let wait = SKAction.waitForDuration(1.0)
let sequence = SKAction.sequence([wait, scaleUp, scaleBack, wait])
let repeat = SKAction.repeatActionForever(sequence)
self.gameOverStatusNode.runAction(repeat)
})
break
default:
break
}
}
/* ** ** ** ** ** ** ** ** ** ** ** **
* ** ** ** ** ** ** ** ** ** ** ** **/
override func didMoveToView(view: SKView) {
//Physics World (create a custom gravity)
modifyGravity()
//A. Add the moving objects
self.addChild(movingGameObjects)
//B. Initialize the background animation
createBackground()
//C. Create a protagonist
initProtagonist()
//D. If the bird falls, the ground will stop it from falling off the screen
initGround()
//E. Fire off the first pipe
loadPipes()
//F. Set off the pipes timer
initPipesTimer()
//G. Score label
initScoreLabel()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if gameOver == false{
bird.physicsBody?.velocity = CGVectorMake(0, 0)
bird.physicsBody?.applyImpulse(CGVectorMake(0, 60))
let rotateUp = SKAction.rotateToAngle(0.2, duration: 0)
bird.runAction(rotateUp)
}else{
initGame()
}
}
func didBeginContact(contact: SKPhysicsContact) {
//If the bird flies through the gap
if contact.bodyA.categoryBitMask == openingGroup || contact.bodyB.categoryBitMask == openingGroup{
addPoint()
} else if contact.bodyA.categoryBitMask == enemyObjectsGroup || contact.bodyB.categoryBitMask == enemyObjectsGroup{
kill()
stopGame()
announcements("quit")
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if gameOver == false{
let rotateDown = SKAction.rotateToAngle(-0.1, duration: 0)
bird.runAction(rotateDown)
}
}
override func update(currentTime: CFTimeInterval) {
}
}
| d47781decdd94c42351823de96ff184f | 38.67624 | 144 | 0.598973 | false | false | false | false |
ajaybeniwal/SwiftTransportApp | refs/heads/master | TransitFare/UIAlertAPI.swift | mit | 1 | //
// UIAlertAPI.swift
// TransitFare
//
// Created by ajaybeniwal203 on 19/2/16.
// Copyright © 2016 ajaybeniwal203. All rights reserved.
//
import UIKit
protocol ShowsAlert {}
extension UIViewController : ShowsAlert{
func showAlert(title:String = "Error", message: String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(alertController, animated: true, completion: nil)
}
func showAlertWithAction(title:String="Error" , message:String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title:"Cancel",style: .Cancel){
(action) in
}
alertController.addAction(cancelAction)
let OkAction = UIAlertAction(title: "OK", style: .Default){
(action) in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(OkAction)
presentViewController(alertController, animated: true, completion: nil)
}
func showAlertWithActionCallback(title:String="Error" , message:String,callback:(UIAlertAction) -> Void){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title:"Cancel",style: .Cancel){
(action) in
}
alertController.addAction(cancelAction)
let OkAction = UIAlertAction(title: "Ok", style: .Default, handler: callback)
alertController.addAction(OkAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
| b8a3120eb38b9690a92704fe2a954d93 | 32.431034 | 109 | 0.637958 | false | false | false | false |
EaglesoftZJ/actor-platform | refs/heads/master | actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/Cells/AATitledCell.swift | agpl-3.0 | 4 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
open class AATitledCell: AATableViewCell {
fileprivate var isAction: Bool = false
open let titleLabel: UILabel = UILabel()
open let contentLabel: UILabel = UILabel()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
titleLabel.textColor = appStyle.cellTintColor
contentView.addSubview(titleLabel)
contentView.addSubview(contentLabel)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func setContent(_ title: String, content: String, isAction: Bool) {
titleLabel.text = title
contentLabel.text = content
if isAction {
contentLabel.textColor = UIColor.lightGray
} else {
contentLabel.textColor = appStyle.cellTextColor
}
}
open override func layoutSubviews() {
super.layoutSubviews()
titleLabel.frame = CGRect(x: separatorInset.left, y: 7, width: contentView.bounds.width - separatorInset.left - 10, height: 19)
contentLabel.frame = CGRect(x: separatorInset.left, y: 27, width: contentView.bounds.width - separatorInset.left - 10, height: 22)
}
}
| 8cef07c018895090679a55e0e1cb22a8 | 32.707317 | 138 | 0.658466 | false | false | false | false |
stripysock/SwiftGen | refs/heads/master | UnitTests/TestsHelper.swift | mit | 1 | //
// SwiftGen
// Copyright (c) 2015 Olivier Halligon
// MIT Licence
//
import Foundation
import XCTest
func diff(lhs: String, _ rhs: String) -> String {
var firstDiff : Int? = nil
let nl = NSCharacterSet.newlineCharacterSet()
let lhsLines = lhs.componentsSeparatedByCharactersInSet(nl)
let rhsLines = rhs.componentsSeparatedByCharactersInSet(nl)
for (idx, pair) in zip(lhsLines, rhsLines).enumerate() {
if pair.0 != pair.1 {
firstDiff = idx
break;
}
}
if let idx = firstDiff {
let numLines = { (num: Int, line: String) -> String in "\(num)".stringByPaddingToLength(3, withString: " ", startingAtIndex: 0) + "|" + line }
let lhsNum = lhsLines.enumerate().map(numLines).joinWithSeparator("\n")
let rhsNum = rhsLines.enumerate().map(numLines).joinWithSeparator("\n")
return "Mismatch at line \(idx)>\n>>>>>> lhs\n\(lhsNum)\n======\n\(rhsNum)\n<<<<<< rhs"
}
return ""
}
func XCTDiffStrings(lhs: String, _ rhs: String) {
XCTAssertEqual(lhs, rhs, diff(lhs, rhs))
}
extension XCTestCase {
var fixturesDir : String {
return NSBundle(forClass: self.dynamicType).resourcePath!
}
func fixturePath(name: String) -> String {
guard let path = NSBundle(forClass: self.dynamicType).pathForResource(name, ofType: "") else {
fatalError("Unable to find fixture \"\(name)\"")
}
return path
}
func fixtureString(name: String, encoding: UInt = NSUTF8StringEncoding) -> String {
do {
return try NSString(contentsOfFile: fixturePath(name), encoding: encoding) as String
} catch let e {
fatalError("Unable to load fixture content: \(e)")
}
}
} | 12d40042aa06de75a5d741a520f52344 | 29.5 | 146 | 0.662211 | false | false | false | false |
pierrewehbe/MyVoice | refs/heads/master | MyVoice/VC_AudioPlayer.swift | mit | 1 | //
// VC_AudioPlayer.swift
// MyVoice
//
// Created by Pierre on 12/27/16.
// Copyright © 2016 Pierre. All rights reserved.
//
import Foundation
import UIKit
import CoreData
import AVFoundation
class VC_AudioPlayer : UIViewController , AVAudioPlayerDelegate , AVAudioRecorderDelegate {
//MARK: Buttons
@IBOutlet weak var Button_Play: UIButton!
@IBOutlet weak var Button_Pause: UIButton!
@IBOutlet weak var Button_Restart: UIButton!
@IBOutlet weak var Slider_Time: UISlider!
//MARK: Actions
@IBAction func Action_Play(_ sender: UIButton) {
audioPlayer.play()
}
@IBAction func Action_Pause(_ sender: UIButton) {
if audioPlayer.isPlaying{
audioPlayer.pause()
}else{
}
}
@IBAction func Action_Restart(_ sender: UIButton) {
if audioPlayer.isPlaying{
audioPlayer.currentTime = 0
audioPlayer.play()
}else{
audioPlayer.play()
}
}
@IBAction func Action_ChangeAudioTime(_ sender: UISlider) {
audioPlayer.stop()
audioPlayer.currentTime = TimeInterval(Slider_Time.value)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
//MARK: Variables
var audioRecorder : AVAudioRecorder?
var audioPlayer = AVAudioPlayer()
var DirectoryStack : StringStack = StringStack()
var songPlayingDir : String = ""
var songPlaying : AudioObject = AudioObject()
/*
* Not the same as before, I assume that we cannot play two song simultaneously
*/
//TODO Options
/*
* Play
* Pause
* Restart
* Create playlists
* Add to Playlists
* Play all file
* Add navigation Bar : Now playing
*/
override func viewDidLoad() {
super.viewDidLoad()
//print("LOADEDEDEDEDD")
do {
fetchAudioInformations()
songPlaying.printInfo()
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: songPlaying.directory) )
audioPlayer.prepareToPlay()
Slider_Time.maximumValue = Float(audioPlayer.duration)
var timer = Timer.scheduledTimer(timeInterval : 0.1 , target : self , selector: Selector("updateSlider") , userInfo : nil , repeats : true)
//To play in background, share it with all other applications
var audioSession = AVAudioSession.sharedInstance()
//Set its Category
do{
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
print(error.localizedDescription)
}
}catch{
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("entered segue from file")
if segue.identifier == StoR {
if let destinationVC = segue.destination as? VC_Recorder {
destinationVC.audioPlayer = self.audioPlayer
destinationVC.audioRecorder = self.audioRecorder
destinationVC.DirectoryStack = self.DirectoryStack
}
} else if segue.identifier == StoF {
if let destinationVC = segue.destination as? VC_Files {
destinationVC.audioPlayer = self.audioPlayer
destinationVC.audioRecorder = self.audioRecorder
destinationVC.DirectoryStack = self.DirectoryStack
}
}else if segue.identifier == APtoF{
if let destinationVC = segue.destination as? VC_Files {
//destinationVC.audioPlayer = self.audioPlayer
destinationVC.audioRecorder = self.audioRecorder
destinationVC.DirectoryStack = self.DirectoryStack
destinationVC.songPlayingDir = self.songPlayingDir
}
}
print(segue.identifier!)
}
func updateSlider(){
Slider_Time.value = Float(audioPlayer.currentTime)
// NSLog("Hi") // called every time this function is called
}
func fetchAudioInformations(){
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "AudioFile")
request.returnsObjectsAsFaults = false // To be able to see the data the way we saved it
print("Fetching...")
do{
let results = try context.fetch(request)
//print(results.count)
if results.count > 0 { // only if non-empty
for result in results as! [NSManagedObject]
{
if let temp = result.value(forKey: "directory") as? String{
// print("trying to fetch at " + temp)
// print("compare to : " + songPlayingDir)
if temp == songPlayingDir{
let name = result.value(forKey: "name") as? String
let duration = result.value(forKey: "duration") as? String
let dateOfCreation = result.value(forKey: "dateOfCreation") as? String
let flags = result.value(forKey: "flags") as? [TimeInterval]
songPlaying = AudioObject(n: name!, d: duration! , dof: dateOfCreation! , dir: songPlayingDir , f : flags!)
//print("Added")
}
}
}
}else{
print("No songs in the dataBase with this URL")
}
}catch let error as NSError{
print(error.localizedDescription)
}
}
}
| d785369967b327c6fd7ac38f58d5fd6d | 29.566502 | 152 | 0.543916 | false | false | false | false |
lhwsygdtc900723/firefox-ios | refs/heads/master | Client/Frontend/Browser/Browser.swift | mpl-2.0 | 2 | /* 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 WebKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
protocol BrowserHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol BrowserDelegate {
func browser(browser: Browser, didAddSnackbar bar: SnackBar)
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar)
optional func browser(browser: Browser, didCreateWebView webView: WKWebView)
optional func browser(browser: Browser, willDeleteWebView webView: WKWebView)
}
class Browser: NSObject {
var webView: WKWebView? = nil
var browserDelegate: BrowserDelegate? = nil
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
var lastRequest: NSURLRequest? = nil
var restoring: Bool = false
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
private(set) var screenshot: UIImage?
var screenshotUUID: NSUUID?
private var helperManager: HelperManager? = nil
private var configuration: WKWebViewConfiguration? = nil
init(configuration: WKWebViewConfiguration) {
self.configuration = configuration
}
class func toTab(browser: Browser) -> RemoteTab? {
if let displayURL = browser.displayURL {
let history = browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse()
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: browser.displayTitle,
history: history,
lastUsed: NSDate.now(),
icon: nil)
} else if let sessionData = browser.sessionData where !sessionData.urls.isEmpty {
let history = sessionData.urls.reverse()
return RemoteTab(clientGUID: nil,
URL: history[0],
title: browser.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
let webView = WKWebView(frame: CGRectZero, configuration: configuration!)
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGrayColor()
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
restore(webView)
self.webView = webView
browserDelegate?.browser?(self, didCreateWebView: webView)
// lastTitle is used only when showing zombie tabs after a session restore.
// Since we now have a web view, lastTitle is no longer useful.
lastTitle = nil
}
}
func restore(webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var updatedURLs = [String]()
for url in sessionData.urls {
let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString!
updatedURLs.append(updatedURL)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = updatedURLs
jsonDict["currentPage"] = currentPage
let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
lastRequest = NSURLRequest(URL: restoreURL!)
webView.loadRequest(lastRequest!)
} else if let request = lastRequest {
webView.loadRequest(request)
} else {
log.error("creating webview with no lastRequest and no session data: \(self.url)")
}
}
deinit {
if let webView = webView {
browserDelegate?.browser?(self, willDeleteWebView: webView)
}
}
var loading: Bool {
return webView?.loading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList as? [WKBackForwardListItem]
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList as? [WKBackForwardListItem]
}
var historyList: [NSURL] {
func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL }
var tabs = self.backList?.map(listToUrl) ?? [NSURL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
return displayURL?.absoluteString ?? lastTitle ?? ""
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons {
if icon.width > width {
width = icon.width!
largest = icon
}
}
return largest
}
var url: NSURL? {
return webView?.URL ?? lastRequest?.URL
}
var displayURL: NSURL? {
if let url = url {
if ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
if ErrorPageHelper.isErrorPageURL(url) {
let decodedURL = ErrorPageHelper.decodeURL(url)
if !AboutUtils.isAboutURL(decodedURL) {
return decodedURL
} else {
return nil
}
}
if !AboutUtils.isAboutURL(url) {
return url
}
}
return nil
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
webView?.goBack()
}
func goForward() {
webView?.goForward()
}
func goToBackForwardListItem(item: WKBackForwardListItem) {
webView?.goToBackForwardListItem(item)
}
func loadRequest(request: NSURLRequest) -> WKNavigation? {
if let webView = webView {
lastRequest = request
return webView.loadRequest(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
if let navigation = webView?.reloadFromOrigin() {
log.info("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
log.info("restoring webView from scratch")
restore(webView)
}
}
func addHelper(helper: BrowserHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(#name: String) -> BrowserHelper? {
return helperManager?.getHelper(name: name)
}
func hideContent(animated: Bool = false) {
webView?.userInteractionEnabled = false
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(animated: Bool = false) {
webView?.userInteractionEnabled = true
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(bar: SnackBar) {
bars.append(bar)
browserDelegate?.browser(self, didAddSnackbar: bar)
}
func removeSnackbar(bar: SnackBar) {
if let index = find(bars, bar) {
bars.removeAtIndex(index)
browserDelegate?.browser(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
func setScreenshot(screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = NSUUID()
}
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: BrowserHelper]()
private weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(helper: BrowserHelper, name: String) {
if let existingHelper = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right BrowserHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName)
}
}
func getHelper(#name: String) -> BrowserHelper? {
return helpers[name]
}
}
extension WKWebView {
func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) {
if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in
if let err = err {
println("Error injecting \(err)")
return
}
self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in
self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in })
if let err = err {
println("Error running \(err)")
return
}
callback(obj)
})
})
}
}
}
}
| 7bc8ae5ff47179a189db85ec2f961b42 | 32.737245 | 167 | 0.602042 | false | false | false | false |
phimage/CallbackURLKit | refs/heads/master | Sources/Manager.swift | mit | 1 | //
// Manager.swift
// CallbackURLKit
/*
The MIT License (MIT)
Copyright (c) 2017 Eric Marchand (phimage)
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
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/// A class to perform and receive actions.
open class Manager {
/// Singletong shared instance
public static let shared = Manager()
/// List of action/action closure
var actions: [Action: ActionHandler] = [:]
/// keep request for callback
var requests: [RequestID: Request] = [:]
open var callbackURLScheme: String?
open var callbackQueue: DispatchQueue = .main
#if APP_EXTENSIONS
/// In case of application extension, put your extensionContext here
open var extensionContext: NSExtensionContext?
open var extensionContextCompletionHandler: ((Bool) -> Swift.Void)?
#endif
/// Init
public init(callbackURLScheme: String? = nil) {
self.callbackURLScheme = callbackURLScheme
}
/// Add an action handler ie. url path and block
open subscript(action: Action) -> ActionHandler? {
get {
return actions[action]
}
set {
if newValue == nil {
actions.removeValue(forKey: action)
} else {
actions[action] = newValue
}
}
}
/// Handle url from app delegate
open func handleOpen(url: URL) -> Bool {
if url.scheme != self.callbackURLScheme || url.host != kXCUHost {
return false
}
let path = url.path
let action = String(path.dropFirst()) // remove /
let parameters = url.query?.toQueryDictionary ?? [:]
let actionParameters = Manager.action(parameters: parameters)
// is a reponse?
if action == kResponse {
if let requestID = parameters[kRequestID] /*as? RequestID*/, let request = requests[requestID] {
if let rawType = parameters[kResponseType], let responseType = ResponseType(rawValue: rawType) {
switch responseType {
case .success:
request.successCallback?(actionParameters)
case .error:
request.failureCallback?(request.client.error(code: parameters[kXCUErrorCode], message: parameters[kXCUErrorMessage]))
case .cancel:
request.cancelCallback?()
}
requests.removeValue(forKey: requestID)
}
return true
}
return false
} else if let actionHandler = actions[action] { // handle the action
let successCallback: SuccessCallback = { [weak self] returnParams in
self?.openCallback(parameters, type: .success) { comp in
if let query = returnParams?.queryString {
comp &= query
}
}
}
let failureCallback: FailureCallback = { [weak self] error in
self?.openCallback(parameters, type: .error) { comp in
comp &= error.XCUErrorQuery
}
}
let cancelCallback: CancelCallback = { [weak self] in
self?.openCallback(parameters, type: .cancel)
}
actionHandler(actionParameters, successCallback, failureCallback, cancelCallback)
return true
} else {
// unknown action, notifiy it
if let errorURLString = parameters[kXCUError], let url = URL(string: errorURLString) {
let error = NSError.error(code: .notSupportedAction, failureReason: "\(action) not supported by \(Manager.appName)")
var comp = URLComponents(url: url, resolvingAgainstBaseURL: false)!
comp &= error.XCUErrorQuery
if let newURL = comp.url {
callbackQueue.async {
self.open(url: newURL)
}
}
return true
}
}
return false
}
fileprivate func openCallback(_ parameters: [String: String], type: ResponseType, handler: ((inout URLComponents) -> Void)? = nil ) {
if let urlString = parameters[type.key], let url = URL(string: urlString),
var comp = URLComponents(url: url, resolvingAgainstBaseURL: false) {
handler?(&comp)
if let newURL = comp.url {
callbackQueue.async {
self.open(url: newURL)
}
}
}
}
/// Handle url with manager shared instance
public static func handleOpen(url: URL) -> Bool {
return self.shared.handleOpen(url: url)
}
// MARK: - perform action with temporary client
/// Perform an action on client application
/// - Parameter action: The action to perform.
/// - Parameter urlScheme: The application scheme to apply action.
/// - Parameter parameters: Optional parameters for the action.
/// - Parameter onSuccess: callback for success.
/// - Parameter onFailure: callback for failure.
/// - Parameter onCancel: callback for cancel.
///
/// Throws: CallbackURLKitError
open func perform(action: Action, urlScheme: String, parameters: Parameters = [:],
onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws {
let client = Client(urlScheme: urlScheme)
client.manager = self
try client.perform(action: action, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel)
}
public static func perform(action: Action, urlScheme: String, parameters: Parameters = [:],
onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws {
try Manager.shared.perform(action: action, urlScheme: urlScheme, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel)
}
/// Utility function to get URL schemes from Info.plist
public static var urlSchemes: [String]? {
guard let urlTypes = Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [[String: AnyObject]] else {
return nil
}
var result = [String]()
for urlType in urlTypes {
if let schemes = urlType["CFBundleURLSchemes"] as? [String] {
result += schemes
}
}
return result.isEmpty ? nil : result
}
// MARK: internal
func send(request: Request) throws {
if !request.client.appInstalled {
throw CallbackURLKitError.appWithSchemeNotInstalled(scheme: request.client.urlScheme)
}
var query: Parameters = [:]
query[kXCUSource] = Manager.appName
if let scheme = self.callbackURLScheme {
var xcuComponents = URLComponents()
xcuComponents.scheme = scheme
xcuComponents.host = kXCUHost
xcuComponents.path = "/" + kResponse
let xcuParams: Parameters = [kRequestID: request.ID]
for reponseType in request.responseTypes {
xcuComponents.queryDictionary = xcuParams + [kResponseType: reponseType.rawValue]
if let urlString = xcuComponents.url?.absoluteString {
query[reponseType.key] = urlString
}
}
if request.hasCallback {
requests[request.ID] = request
}
} else if request.hasCallback {
throw CallbackURLKitError.callbackURLSchemeNotDefined
}
let components = request.URLComponents(query)
guard let URL = components.url else {
throw CallbackURLKitError.failedToCreateRequestURL(components: components)
}
self.open(url: URL)
}
static func action(parameters: [String: String]) -> [String: String] {
let resultArray: [(String, String)] = parameters.filter { tuple in
return !(tuple.0.hasPrefix(kXCUPrefix) || protocolKeys.contains(tuple.0))
}
var result = [String: String](resultArray)
if let source = parameters[kXCUSource] {
result[kXCUSource] = source
}
return result
}
public static func open(url: Foundation.URL) {
Manager.shared.open(url: url)
}
open func open(url: Foundation.URL) {
#if APP_EXTENSIONS
if let extensionContext = extensionContext {
extensionContext.open(url, completionHandler: extensionContextCompletionHandler)
} else {
#if os(iOS) || os(tvOS)
UIApplication.shared.open(url)
#elseif os(OSX)
NSWorkspace.shared.open(url)
#endif
}
#else
#if os(iOS) || os(tvOS)
UIApplication.shared.open(url)
#elseif os(OSX)
NSWorkspace.shared.open(url)
#endif
#endif
}
static var appName: String {
if let appName = Bundle.main.localizedInfoDictionary?["CFBundleDisplayName"] as? String {
return appName
}
return Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? "CallbackURLKit"
}
}
#if os(OSX)
extension Manager {
public func registerToURLEvent() {
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(Manager.handleURLEvent(_:withReply:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
@objc public func handleURLEvent(_ event: NSAppleEventDescriptor, withReply replyEvent: NSAppleEventDescriptor) {
if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) {
_ = handleOpen(url: url)
}
}
}
#endif
| 9e7308ca4f992501c28374d08ea96eef | 36.554795 | 204 | 0.616268 | false | false | false | false |
ahoppen/swift | refs/heads/main | SwiftCompilerSources/Sources/Optimizer/PassManager/PassContext.swift | apache-2.0 | 1 | //===--- PassContext.swift - defines the PassContext type -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
import OptimizerBridging
public typealias BridgedFunctionPassCtxt =
OptimizerBridging.BridgedFunctionPassCtxt
public typealias BridgedInstructionPassCtxt =
OptimizerBridging.BridgedInstructionPassCtxt
struct PassContext {
let _bridged: BridgedPassContext
func continueWithNextSubpassRun(for inst: Instruction? = nil) -> Bool {
let bridgedInst = OptionalBridgedInstruction(obj: inst?.bridged.obj)
return PassContext_continueWithNextSubpassRun(_bridged, bridgedInst) != 0
}
//===--------------------------------------------------------------------===//
// Analysis
//===--------------------------------------------------------------------===//
var aliasAnalysis: AliasAnalysis {
let bridgedAA = PassContext_getAliasAnalysis(_bridged)
return AliasAnalysis(bridged: bridgedAA)
}
var calleeAnalysis: CalleeAnalysis {
let bridgeCA = PassContext_getCalleeAnalysis(_bridged)
return CalleeAnalysis(bridged: bridgeCA)
}
var deadEndBlocks: DeadEndBlocksAnalysis {
let bridgeDEA = PassContext_getDeadEndBlocksAnalysis(_bridged)
return DeadEndBlocksAnalysis(bridged: bridgeDEA)
}
var dominatorTree: DominatorTree {
let bridgedDT = PassContext_getDomTree(_bridged)
return DominatorTree(bridged: bridgedDT)
}
var postDominatorTree: PostDominatorTree {
let bridgedPDT = PassContext_getPostDomTree(_bridged)
return PostDominatorTree(bridged: bridgedPDT)
}
//===--------------------------------------------------------------------===//
// Interaction with AST and the SIL module
//===--------------------------------------------------------------------===//
func getContextSubstitutionMap(for type: Type) -> SubstitutionMap {
SubstitutionMap(PassContext_getContextSubstitutionMap(_bridged, type.bridged))
}
func loadFunction(name: StaticString) -> Function? {
return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer<UInt8>) in
PassContext_loadFunction(_bridged, BridgedStringRef(data: nameBuffer.baseAddress, length: nameBuffer.count)).function
}
}
//===--------------------------------------------------------------------===//
// Modify SIL
//===--------------------------------------------------------------------===//
/// Splits the basic block, which contains `inst`, before `inst` and returns the
/// new block.
///
/// `inst` and all subsequent instructions are moved to the new block, while all
/// instructions _before_ `inst` remain in the original block.
func splitBlock(at inst: Instruction) -> BasicBlock {
notifyBranchesChanged()
return PassContext_splitBlock(inst.bridged).block
}
enum EraseMode {
case onlyInstruction, includingDebugUses
}
func erase(instruction: Instruction, _ mode: EraseMode = .onlyInstruction) {
switch mode {
case .onlyInstruction:
break
case .includingDebugUses:
for result in instruction.results {
for use in result.uses {
assert(use.instruction is DebugValueInst)
PassContext_eraseInstruction(_bridged, use.instruction.bridged)
}
}
}
if instruction is FullApplySite {
notifyCallsChanged()
}
if instruction is TermInst {
notifyBranchesChanged()
}
notifyInstructionsChanged()
PassContext_eraseInstruction(_bridged, instruction.bridged)
}
func fixStackNesting(function: Function) {
PassContext_fixStackNesting(_bridged, function.bridged)
}
func modifyEffects(in function: Function, _ body: (inout FunctionEffects) -> ()) {
function._modifyEffects(body)
// TODO: do we need to notify any changes?
}
//===--------------------------------------------------------------------===//
// Private utilities
//===--------------------------------------------------------------------===//
fileprivate func notifyInstructionsChanged() {
PassContext_notifyChanges(_bridged, instructionsChanged)
}
fileprivate func notifyCallsChanged() {
PassContext_notifyChanges(_bridged, callsChanged)
}
fileprivate func notifyBranchesChanged() {
PassContext_notifyChanges(_bridged, branchesChanged)
}
}
//===----------------------------------------------------------------------===//
// Builder initialization
//===----------------------------------------------------------------------===//
extension Builder {
/// Creates a builder which inserts _before_ `insPnt`, using a custom `location`.
init(at insPnt: Instruction, location: Location, _ context: PassContext) {
self.init(insertAt: .before(insPnt), location: location, passContext: context._bridged)
}
/// Creates a builder which inserts _before_ `insPnt`, using the location of `insPnt`.
init(at insPnt: Instruction, _ context: PassContext) {
self.init(insertAt: .before(insPnt), location: insPnt.location, passContext: context._bridged)
}
/// Creates a builder which inserts _after_ `insPnt`, using the location of `insPnt`.
init(after insPnt: Instruction, _ context: PassContext) {
if let nextInst = insPnt.next {
self.init(insertAt: .before(nextInst), location: insPnt.location, passContext: context._bridged)
} else {
self.init(insertAt: .atEndOf(insPnt.block), location: insPnt.location, passContext: context._bridged)
}
}
/// Creates a builder which inserts at the end of `block`, using a custom `location`.
init(atEndOf block: BasicBlock, location: Location, _ context: PassContext) {
self.init(insertAt: .atEndOf(block), location: location, passContext: context._bridged)
}
/// Creates a builder which inserts at the begin of `block`, using the location of the first
/// instruction of `block`.
init(atBeginOf block: BasicBlock, _ context: PassContext) {
let firstInst = block.instructions.first!
self.init(insertAt: .before(firstInst), location: firstInst.location, passContext: context._bridged)
}
}
//===----------------------------------------------------------------------===//
// Modifying the SIL
//===----------------------------------------------------------------------===//
extension BasicBlock {
func addBlockArgument(type: Type, ownership: Ownership, _ context: PassContext) -> BlockArgument {
context.notifyInstructionsChanged()
return SILBasicBlock_addBlockArgument(bridged, type.bridged, ownership._bridged).blockArgument
}
func eraseArgument(at index: Int, _ context: PassContext) {
context.notifyInstructionsChanged()
SILBasicBlock_eraseArgument(bridged, index)
}
}
extension AllocRefInstBase {
func setIsStackAllocatable(_ context: PassContext) {
context.notifyInstructionsChanged()
AllocRefInstBase_setIsStackAllocatable(bridged)
}
}
extension UseList {
func replaceAll(with replacement: Value, _ context: PassContext) {
for use in self {
use.instruction.setOperand(at: use.index, to: replacement, context)
}
}
}
extension Instruction {
func setOperand(at index : Int, to value: Value, _ context: PassContext) {
if self is FullApplySite && index == ApplyOperands.calleeOperandIndex {
context.notifyCallsChanged()
}
context.notifyInstructionsChanged()
SILInstruction_setOperand(bridged, index, value.bridged)
}
}
extension RefCountingInst {
func setAtomicity(isAtomic: Bool, _ context: PassContext) {
context.notifyInstructionsChanged()
RefCountingInst_setIsAtomic(bridged, isAtomic)
}
}
| 461a9977732100e4daa676fe22c2fe26 | 34.955556 | 123 | 0.619901 | false | false | false | false |
chuhlomin/football | refs/heads/master | footballTests/GameTests.swift | mit | 1 | //
// GameTests.swift
// football
//
// Created by Konstantin Chukhlomin on 15/02/15.
// Copyright (c) 2015 Konstantin Chukhlomin. All rights reserved.
//
import XCTest
class GameTests: XCTestCase {
var game: Game?
var board: Board?
// [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
// [4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4],
// [4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4],
// [4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4],
// [5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6],
// [5, 0, 0, 0, 0, 0, x, 0, 0, 0, 0, 0, 6],
// [5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 6],
// [4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4],
// [4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4],
// [4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4],
// [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
override func setUp() {
super.setUp()
board = Board(width: 11, height: 13, goalMargin: 3)
game = Game(board: board!)
}
override func tearDown() {
super.tearDown()
}
func testShouldSwitchPlayer() {
game!.currentPlayer = game!.PLAYER_ALICE
XCTAssertEqual(game!.PLAYER_BOB, game!.switchPlayer())
XCTAssertEqual(game!.PLAYER_ALICE, game!.switchPlayer())
}
func testShouldDetermineWinner() {
XCTAssertEqual(game!.PLAYER_BOB, game!.getWinner(board!.GOAL_ALICE)!)
XCTAssertEqual(game!.PLAYER_ALICE, game!.getWinner(board!.GOAL_BOB)!)
XCTAssertNil(game!.getWinner(board!.EMPTY))
}
func testShouldDetermineIfMoveNotOver() {
XCTAssertTrue(game!.isMoveOver(0))
XCTAssertFalse(game!.isMoveOver(3))
}
func testShouldDetermineIfMoveHasCorrectLenght() {
XCTAssertFalse(game!.moveHasCorrectLenght((3, 4), pointTo: (3, 6)))
XCTAssertFalse(game!.moveHasCorrectLenght((3, 4), pointTo: (1, 3)))
XCTAssertTrue(game!.moveHasCorrectLenght((3, 4), pointTo: (3, 3)))
XCTAssertTrue(game!.moveHasCorrectLenght((3, 4), pointTo: (3, 3)))
}
func testShouldGetPossibleMovesInGeneralCase() {
game!.lastDot = (5, 6)
XCTAssertEqual(8, game!.getPossibleMoves().count)
}
func testShouldGetPossibleMovesNearTheWall() {
game!.lastDot = (1, 6)
XCTAssertEqual(3, game!.getPossibleMoves().count)
}
func testShouldGetPossibleMovesNearTheCorner() {
game!.lastDot = (2, 2)
XCTAssertEqual(7, game!.getPossibleMoves().count)
}
func testShouldGetPossibleMovesInTheCorner() {
game!.lastDot = (1, 1)
XCTAssertEqual(1, game!.getPossibleMoves().count)
}
func testShouldGetPossibleMovesNearTheGoal() {
game!.lastDot = (4, 1)
XCTAssertEqual(5, game!.getPossibleMoves().count)
}
} | bb5b30ad93d8972619f9b2956a3ddcac | 30.988372 | 77 | 0.564 | false | true | false | false |
jmgc/swift | refs/heads/master | test/Driver/Dependencies/independent-parseable-fine.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/independent-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST-DAG: "kind"{{ ?}}: "began"
// CHECK-FIRST-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-DAG: "{{(.\\/)?}}main.swift"
// CHECK-FIRST: {{^}$}}
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST: "kind"{{ ?}}: "finished"
// CHECK-FIRST: "name"{{ ?}}: "compile"
// CHECK-FIRST: "output"{{ ?}}: "Handled main.swift{{(\\r)?}}\n"
// CHECK-FIRST: {{^}$}}
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND: {{^{$}}
// CHECK-SECOND-DAG: "kind"{{ ?}}: "skipped"
// CHECK-SECOND-DAG: "name"{{ ?}}: "compile"
// CHECK-SECOND-DAG: "{{(.\\/)?}}main.swift"
// CHECK-SECOND: {{^}$}}
// RUN: touch -t 201401240006 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/independent-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST-MULTI %s
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "began"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "{{(.\\/)?}}main.swift"
// CHECK-FIRST-MULTI: {{^}$}}
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "finished"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "output"{{ ?}}: "Handled main.swift{{(\\r)?}}\n"
// CHECK-FIRST-MULTI: {{^}$}}
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "began"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "{{(.\\/)?}}other.swift"
// CHECK-FIRST-MULTI: {{^}$}}
// CHECK-FIRST-MULTI: {{^{$}}
// CHECK-FIRST-MULTI-DAG: "kind"{{ ?}}: "finished"
// CHECK-FIRST-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-FIRST-MULTI-DAG: "output"{{ ?}}: "Handled other.swift{{(\\r)?}}\n"
// CHECK-FIRST-MULTI: {{^}$}}
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-SECOND-MULTI %s
// CHECK-SECOND-MULTI: {{^{$}}
// CHECK-SECOND-MULTI-DAG: "kind"{{ ?}}: "skipped"
// CHECK-SECOND-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-SECOND-MULTI-DAG: "{{(.\\/)?}}main.swift"
// CHECK-SECOND-MULTI: {{^}$}}
// CHECK-SECOND-MULTI: {{^{$}}
// CHECK-SECOND-MULTI-DAG: "kind"{{ ?}}: "skipped"
// CHECK-SECOND-MULTI-DAG: "name"{{ ?}}: "compile"
// CHECK-SECOND-MULTI-DAG: "{{(.\\/)?}}other.swift"
// CHECK-SECOND-MULTI: {{^}$}}
// RUN: touch -t 201401240006 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST-MULTI %s
| 53b08a980d552f4e5fb9133b0aa3acd9 | 51.871795 | 337 | 0.640155 | false | false | true | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.