repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/Services/Holder/WalletState.swift
1
2215
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import MetadataKit /// An internal enum keeping track of the current state of `Wrapper & Wallet` and `MetadataState` /// /// - note: The app requires both the `Wallet` model and `MetadataState` to be available in order to function correctly. /// /// Accessing the wallet can happen using the following methods: /// 1. Create a brand new Wallet and Metadata and sync with server /// 2. Recover Account (using seed phrase, aka mnemonic) /// - Using the seed phrase we initialize the metadata which contains the necessary info to login into an account /// this makes the `MetadataState` available before having the `Wrapper`. /// 3. Login using pin (previously logged in) /// - Using the pin we have already fetched the `Wrapper`, after we decrypt using the password we store it /// and then initialize the `MetadataState` /// public enum WalletState: Equatable { public enum PartiallyLoaded: Equatable { case justMetadata(MetadataState) case justWrapper(Wrapper) } case partially(loaded: PartiallyLoaded) case loaded(wrapper: Wrapper, metadata: MetadataState) /// Returns `true` if both metadata and wallet has been initialized, otherwise `false` public var isInitialised: Bool { isMetadataInitialised && walletInitialized } public var wrapper: Wrapper? { switch self { case .partially(loaded: .justWrapper(let wrapper)): return wrapper case .partially(loaded: .justMetadata): return nil case .loaded(wrapper: let wrapper, _): return wrapper } } public var wallet: NativeWallet? { wrapper?.wallet } public var metadata: MetadataState? { switch self { case .partially(loaded: .justWrapper): return nil case .partially(loaded: .justMetadata(let metadata)): return metadata case .loaded(_, metadata: let metadata): return metadata } } public var isMetadataInitialised: Bool { metadata != nil } public var walletInitialized: Bool { wallet != nil } }
lgpl-3.0
guillermo-ag-95/App-Development-with-Swift-for-Students
2 - Introduction to UIKit/Guided Project - Apple Pie/Apple Pie/Apple Pie/ViewController.swift
1
2433
// // ViewController.swift // Apple Pie // // Created by Guillermo Alcalá Gamero on 21/12/2018. // Copyright © 2018 Guillermo Alcalá Gamero. All rights reserved. // import UIKit class ViewController: UIViewController { var listOfWords = ["buccaneer", "swift", "glorious", "incandescent", "bug", "program"] var incorrectMovesAllowed = 7 var totalWins = 0 { didSet { newRound() } } var totalLoses = 0 { didSet { newRound() } } var currentGame: Game! @IBOutlet weak var treeImageView: UIImageView! @IBOutlet weak var correctWordLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet var letterButtons: [UIButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. newRound() } @IBAction func buttonPressed(_ sender: UIButton) { sender.isEnabled = false let letterString = sender.title(for: .normal)! let letter = Character(letterString.lowercased()) currentGame.playerGuessed(letter: letter) updateGameState() } func newRound() { if !listOfWords.isEmpty { let newWord = listOfWords.removeFirst() currentGame = Game(word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: []) enableLetterButtons(true) updateUI() } else { enableLetterButtons(false) } } func updateUI() { var letters = [String]() for letter in currentGame.formattedWord { letters.append(String(letter)) } let wordWithSpacing = letters.joined(separator: " ") correctWordLabel.text = wordWithSpacing scoreLabel.text = "Wins: \(totalWins), Loses: \(totalLoses)" treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)") } func updateGameState() { if currentGame.incorrectMovesRemaining == 0 { totalLoses += 1 } else if currentGame.word == currentGame.formattedWord { totalWins += 1 } else { updateUI() } } func enableLetterButtons(_ enable: Bool) { for button in letterButtons { button.isEnabled = enable } } }
mit
seansguo/SheepChat
SheepChatTests/Messenger/MessengerViewControllerTests.swift
1
2487
// // MessengerViewControllerTests.swift // SheepChat // // Created by Sean Guo on 11/10/2016. // Copyright (c) 2016 Sean Guo. All rights reserved. // @testable import SheepChat import XCTest class MessengerViewControllerTests: XCTestCase { // MARK: - Subject under test var sut: MessengerViewController! var window: UIWindow! // MARK: - Test lifecycle override func setUp() { super.setUp() window = UIWindow() setupMessengerViewController() } override func tearDown() { window = nil super.tearDown() } // MARK: - Test setup func setupMessengerViewController() { let bundle = Bundle.main let storyboard = UIStoryboard(name: "Main", bundle: bundle) sut = storyboard.instantiateViewController(withIdentifier:"MessengerViewController") as! MessengerViewController } func loadView() { window.addSubview(sut.view) RunLoop.current.run(until: Date()) } // MARK: - Test doubles class MessengerViewControllerOutputSpy: MessengerViewControllerOutput { // MARK: - Method call expectations var fetchMessagesCalled = false var sendMessageCalled = false // MARK: - Spied methods func fetchConversationHistory(request: Messenger.FetchConversationHistory.Request) { fetchMessagesCalled = true } func sendTextMessage(request: Messenger.SendTextMessage.Request) { sendMessageCalled = true } } // MARK: - Tests func testMessengerVCShouldFetchMessagesOnLoad() { // Given let viewControllerOutputSpy = MessengerViewControllerOutputSpy() self.sut.output = viewControllerOutputSpy // When self.loadView() // Then XCTAssert(viewControllerOutputSpy.fetchMessagesCalled, "Should ask interactor to fetch conversations on load view") } func testMessengerVCShouldSendMessageWhenPressSend() { // Given let viewControllerOutputSpy = MessengerViewControllerOutputSpy() self.sut.output = viewControllerOutputSpy // When self.sut.didPressSend(UIButton(), withMessageText: "hello", senderId: "001", senderDisplayName: "Sean Guo", date: Date()) // Then XCTAssert(viewControllerOutputSpy.sendMessageCalled, "Should ask interactor to send message when press send") } }
mit
ulidev/Zilean
Package.swift
1
176
// // Created by Joan Molinas Ramon on 11/12/15. // Copyright © 2015 Joan Molinas. All rights reserved. // import PackageDescription let package = Package(name : "Zilean")
mit
iosdevzone/IDZSwiftCommonCryptoCocoaPodsTest
IDZSwiftCommonCryptoCocoaPodsTest/AppDelegate.swift
1
2269
// // AppDelegate.swift // IDZSwiftCommonCryptoCocoaPodsTest // // Created by Danny Keogan on 9/18/15. // Copyright © 2015 iOS Developer Zone. All rights reserved. // import UIKit import IDZSwiftCommonCrypto @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { print("Hello, World!".MD5) // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Series/PictorialBarSerie.swift
1
70688
// // PictorialBarSerie.swift // SwiftyEcharts // // Created by Pluto Y on 03/04/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 象形柱图 /// /// 象形柱图是可以设置各种具象图形元素(如图片、SVG PathData 等)的柱状图。往往用在信息图中。用于有至少一个类目轴或时间轴的直角坐标系上。 /// /// 示例: http://echarts.baidu.com/gallery/editor.html?c=pictorialBar-hill /// /// 布局 /// /// 象形柱图可以被想象为:它首先是个柱状图,但是柱状图的柱子并不显示。这些柱子我们称为『基准柱(reference bar)』,根据基准柱来定位和显示各种象形图形(包括图片)。 /// /// 每个象形图形根据基准柱的定位,是通过 symbolPosition、symbolOffset 来调整其于基准柱的相对位置。 /// /// 参见例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-position /// /// 可以使用 symbolSize 调整大小,从而形成各种视图效果。 /// /// 参见例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-symbolSize /// /// 象形图形类型 /// /// 每个图形可以配置成『单独』和『重复』两种类型,即通过 symbolRepeat 来设置。 /// /// - 设置为 false(默认),则一个图形来代表一个数据项。 /// - 设置为 true,则一组重复的图形来代表一个数据项。 /// /// 参见例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeat /// /// 每个象形图形可以是基本图形(如 'circle', 'rect', ...)、SVG PathData、图片,参见:symbolType。 /// /// 参见例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-graphicType /// /// 可以使用 symbolClip 对图形进行剪裁。 /// /// 参见例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-clip public final class PictorialBarSerie: Serie, Symbolized, Zable, Animatable { /// 系列中的数据内容数组。数组项通常为具体的数据项。 /// /// 通常来说,数据用一个二维数组表示。如下,每一列被称为一个『维度』。 /// /// series: [{ /// data: [ /// // 维度X 维度Y 其他维度 ... /// [ 3.4, 4.5, 15, 43], /// [ 4.2, 2.3, 20, 91], /// [ 10.8, 9.5, 30, 18], /// [ 7.2, 8.8, 18, 57] /// ] /// }] /// /// - 在 直角坐标系 (grid) 中『维度X』和『维度Y』会默认对应于 xAxis 和 yAxis。 /// - 在 极坐标系 (polar) 中『维度X』和『维度Y』会默认对应于 radiusAxis 和 angleAxis。 /// - 后面的其他维度是可选的,可以在别处被使用,例如: /// - 在 visualMap 中可以将一个或多个维度映射到颜色,大小等多个图形属性上。 /// - 在 series.symbolSize 中可以使用回调函数,基于某个维度得到 symbolSize 值。 /// - 使用 tooltip.formatter 或 series.label.normal.formatter 可以把其他维度的值展示出来。 /// /// 特别地,当只有一个轴为类目轴(axis.type 为 'category')的时候,数据可以简化用一个一维数组表示。例如: /// /// xAxis: { /// data: ['a', 'b', 'm', 'n'] /// }, /// series: [{ /// // 与 xAxis.data 一一对应。 /// data: [23, 44, 55, 19] /// // 它其实是下面这种形式的简化: /// // data: [[0, 23], [1, 44], [2, 55], [3, 19]] /// }] /// /// 『值』与 轴类型 的关系: /// /// - 当某维度对应于数值轴(axis.type 为 'value' 或者 'log')的时候:其值可以为 number(例如 12)。(也可以兼容 string 形式的 number,例如 '12') /// - 当某维度对应于类目轴(axis.type 为 'category')的时候:其值须为类目的『序数』(从 0 开始)或者类目的『字符串值』。例如: /// /// xAxis: { /// type: 'category', /// data: ['星期一', '星期二', '星期三', '星期四'] /// }, /// yAxis: { /// type: 'category', /// data: ['a', 'b', 'm', 'n', 'p', 'q'] /// }, /// series: [{ /// data: [ /// // xAxis yAxis /// [ 0, 0, 2 ], // 意思是此点位于 xAxis: '星期一', yAxis: 'a'。 /// [ '星期四', 2, 1 ], // 意思是此点位于 xAxis: '星期四', yAxis: 'm'。 /// [ 2, 'p', 2 ], // 意思是此点位于 xAxis: '星期三', yAxis: 'p'。 /// [ 3, 3, 5 ] /// ] /// }] /// /// 双类目轴的示例可以参考 Github Punchcard 示例。 /// /// - 当某维度对应于时间轴(type 为 'time')的时候,值可以为: /// - 一个时间戳,如 1484141700832,表示 UTC 时间。 /// - 或者字符串形式的时间描述: /// - ISO 8601 的子集,只包含这些形式(这几种格式,除非指明时区,否则均表示本地时间,与 moment 一致): /// - 部分年月日时间: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06'. /// - 使用 'T' 或空格分割: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123'. /// - 时区设定: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00'. /// - 其他的时间字符串,包括(均表示本地时间): '2012', '2012-3-1', '2012/3/1', '2012/03/01', '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123' /// - 或者用户自行初始化的 Date 实例: /// - 注意,用户自行初始化 Date 实例的时候,浏览器的行为有差异,不同字符串的表示也不同。 /// - 例如:在 chrome 中,new Date('2012-01-01') 表示 UTC 时间的 2012 年 1 月 1 日,而 new Date('2012-1-1') 和 new Date('2012/01/01') 表示本地时间的 2012 年 1 月 1 日。在 safari 中,不支持 new Date('2012-1-1') 这种表示方法。 /// - 所以,使用 new Date(dataString) 时,可使用第三方库解析(如 moment),或者使用 echarts.number.parseDate,或者参见 这里。 /// /// 当需要对个别数据进行个性化定义时: /// /// 数组项可用对象,其中的 value 像表示具体的数值,如: /// /// [ /// 12, /// 34, /// { /// value : 56, /// //自定义标签样式,仅对该数据项有效 /// label: {}, /// //自定义特殊 itemStyle,仅对该数据项有效 /// itemStyle:{} /// }, /// 10 /// ] /// // 或 /// [ /// [12, 33], /// [34, 313], /// { /// value: [56, 44], /// label: {}, /// itemStyle:{} /// }, /// [10, 33] /// ] /// /// 空值: /// /// 当某数据不存在时(ps:不存在不代表值为 0),可以用 '-' 或者 null 或者 undefined 或者 NaN 表示。 /// /// 例如,无数据在折线图中可表现为该点是断开的,在其它图中可表示为图形不存在。 public final class Data: Symbolized, Animatable { /// 数据项名称。 public var name: String? /// 单个数据项的数值。 public var value: Jsonable? /// 图形类型。 /// /// ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow' /// /// 也可以通过 'image://url' 设置为图片,其中 url 为图片的链接,或者 dataURI。 /// /// 可以通过 'path://' 将图标设置为任意的矢量路径。这种方式相比于使用图片的方式,不用担心因为缩放而产生锯齿或模糊,而且可以设置为任意颜色。路径图形会自适应调整为合适的大小。路径的格式参见 SVG PathData。可以从 Adobe Illustrator 等工具编辑导出。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-graphicType /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbol: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbol: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbol: ... // 只对此数据项生效 /// }] /// }] public var symbol: OneOrMore<Symbol>? /// 图形的大小。 /// /// 可以用数组分开表示宽和高,例如 [20, 10] 表示标记宽为20,高为10,也可以设置成诸如 10 这样单一的数字,表示 [10, 10]。 /// /// 可以设置成绝对值(如 10),也可以设置成百分比(如 '120%'、['55%', 23])。 /// /// 当设置为百分比时,图形的大小是基于 基准柱 的尺寸计算出来的。 /// /// 例如,当基准柱基于 x 轴(即柱子是纵向的),symbolSize 设置为 ['30%', '50%'],那么最终图形的尺寸是: /// /// - 宽度:基准柱的宽度 * 30%。 /// - 高度: /// - 如果 symbolRepeat 为 false:基准柱的高度 * 50%。 /// - 如果 symbolRepeat 为 true:基准柱的宽度 * 50%。 /// /// 基准柱基于 y 轴(即柱子是横向的)的情况类似对调可得出。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-symbolSize /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolSize: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolSize: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolSize: ... // 只对此数据项生效 /// }] /// }] public var symbolSize: FunctionOrFloatOrPair? /// 图形的定位位置。可取值: /// /// - 'start':图形边缘与柱子开始的地方内切。 /// - 'end':图形边缘与柱子结束的地方内切。 /// - 'center':图形在柱子里居中。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-position /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolPosition: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolPosition: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolPosition: ... // 只对此数据项生效 /// }] /// }] public var symbolPosition: Position? /// 图形相对于原本位置的偏移。symbolOffset 是图形定位中最后计算的一个步骤,可以对图形计算出来的位置进行微调。 /// /// 可以设置成绝对值(如 10),也可以设置成百分比(如 '120%'、['55%', 23])。 /// /// 当设置为百分比时,表示相对于自身尺寸 symbolSize 的百分比。 /// /// 例如 [0, '-50%'] 就是把图形向上移动了自身尺寸的一半的位置。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-position /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolOffset: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolOffset: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolOffset: ... // 只对此数据项生效 /// }] /// }] public var symbolOffset: Point? /// 图形的旋转角度。 /// /// 注意,symbolRotate 并不会影响图形的定位(哪怕超出基准柱的边界),而只是单纯得绕自身中心旋转。 /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolRotate: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolRotate: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolRotate: ... // 只对此数据项生效 /// }] /// }] public var symbolRotate: Float? /// 指定图形元素是否重复。值可为: /// /// - false/null/undefined:不重复,即每个数据值用一个图形元素表示。 /// - true:使图形元素重复,即每个数据值用一组重复的图形元素表示。重复的次数依据 data 计算得到。 /// - a number:使图形元素重复,即每个数据值用一组重复的图形元素表示。重复的次数是给定的定值。 /// - 'fixed':使图形元素重复,即每个数据值用一组重复的图形元素表示。重复的次数依据 symbolBoundingData 计算得到,即与 data 无关。这在此图形被用于做背景时有用。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeat /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolRepeat: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolRepeat: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolRepeat: ... // 只对此数据项生效 /// }] /// }] public var symbolRepeat: String? // ????? /// 指定图形元素重复时,绘制的顺序。这个属性在两种情况下有用处: /// /// - 当 symbolMargin 设置为负值时,重复的图形会互相覆盖,这是可以使用 symbolRepeatDirection 来指定覆盖顺序。 /// - 当 animationDelay 或 animationDelayUpdate 被使用时,symbolRepeatDirection 指定了 index 顺序。 /// /// 这个属性的值可以是:'start' 或 'end'。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeatDirection /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolRepeatDirection: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolRepeatDirection: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolRepeatDirection: ... // 只对此数据项生效 /// }] /// }] public var symbolRepeatDirection: String? // ????? /// 图形的两边间隔(『两边』是指其数值轴方向的两边)。可以是绝对数值(如 20),或者百分比值(如 '-30%'),表示相对于自身尺寸 symbolSize 的百分比。只有当 symbolRepeat 被使用时有意义。 /// /// 可以是正值,表示间隔大;也可以是负数。当 symbolRepeat 被使用时,负数时能使图形重叠。 /// /// 可以在其值结尾处加一个 "!",如 "30%!" 或 25!,表示第一个图形的开始和最后一个图形结尾留白,不紧贴边界。默认会紧贴边界。 /// /// 注意: /// /// - 当 symbolRepeat 为 true/'fixed' 的时候: 这里设置的 symbolMargin 只是个参考值,真正最后的图形间隔,是根据 symbolRepeat、symbolMargin、symbolBoundingData 综合计算得到。 /// - 当 symbolRepeat 为一个固定数值的时候: 这里设置的 symbolMargin 无效。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeatLayout /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolMargin: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolMargin: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolMargin: ... // 只对此数据项生效 /// }] /// }] public var symbolMargin: String? // ????? /// 是否剪裁图形。 /// /// - false/null/undefined:图形本身表示数值大小。 /// - true:图形被剪裁后剩余的部分表示数值大小。 /// /// symbolClip 常在这种场景下使用:同时表达『总值』和『当前数值』。在这种场景下,可以使用两个系列,一个系列是完整的图形,当做『背景』来表达总数值,另一个系列是使用 symbolClip 进行剪裁过的图形,表达当前数值。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-clip /// /// 在这个例子中: /// /// - 『背景系列』和『当前值系列』使用相同的 symbolBoundingData,使得绘制出的图形的大小是一样的。 /// - 『当前值系列』设置了比『背景系列』更高的 z,使得其覆盖在『背景系列』上。 /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolClip: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolClip: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolClip: ... // 只对此数据项生效 /// }] /// }] public var symbolClip: Bool? /// 这个属性是『指定图形界限的值』。它指定了一个 data,这个 data 映射在坐标系上的位置,是图形绘制的界限。也就是说,如果设置了 symbolBoundingData,图形的尺寸则由 symbolBoundingData 决定。 /// 当柱子是水平的,symbolBoundingData 对应到 x 轴上,当柱子是竖直的,symbolBoundingData 对应到 y 轴上。 /// /// 规则: /// /// - 没有使用 symbolRepeat 时: symbolBoundingData 缺省情况下和『参考柱』的尺寸一样。图形的尺寸由零点和 symbolBoundingData 决定。举例,当柱子是竖直的,柱子对应的 data 为 24,symbolSize 设置为 [30, '50%'],symbolBoundingData 设置为 124,那么最终图形的高度为 124 * 50% = 62。如果 symbolBoundingData 不设置,那么最终图形的高度为 24 * 50% = 12。 /// - 使用了 symbolRepeat 时: symbolBoundingData 缺省情况取当前坐标系所显示出的最值。symbolBoundingData 定义了一个 bounding,重复的图形在这个 bounding 中,依据 symbolMargin 和 symbolRepeat 和 symbolSize 进行排布。这几个变量决定了图形的间隔大小。 /// /// 在这些场景中,你可能会需要设置 symbolBoundingData: /// /// - 使用了 symbolCilp 时: 使用一个系列表达『总值』,另一个系列表达『当前值』的时候,需要两个系列画出的图形一样大。那么就把两个系列的 symbolBoundingData 设为一样大。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-clip /// /// - 使用了 symbolRepeat 时:如果需要不同柱子中的图形的间隔保持一致,那么可以把 symbolBoundingData 设为一致的数值。当然,不设置 symbolBoundingData 也是可以的,因为其缺省值就是一个定值(坐标系所显示出的最值)。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeatLayout /// /// symbolBoundingData 可以是一个数组,例如 [-40, 60],表示同时指定了正值的 symbolBoundingData 和负值的 symbolBoundingData。 /// /// 参见例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-symbolBoundingDataArray /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolBoundingData: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolBoundingData: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolBoundingData: ... // 只对此数据项生效 /// }] /// }] public var symbolBoundingData: String? // ????? /// 可以使用图片作为图形的 pattern。 /// /// var textureImg = new Image(); /// textureImg.src = 'data:image/jpeg;base64,...'; // dataURI /// // 或者 /// // textureImg.src = 'http://xxx.xxx.xxx/xx.png'; // URL /// ... /// itemStyle: { /// normal: { /// color: { /// image: textureImg, /// repeat: 'repeat' /// } /// } /// } /// /// 这时候,symbolPatternSize 指定了 pattern 的缩放尺寸。比如 symbolPatternSize 为 400 时表示图片显示为 400px * 400px 的尺寸。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-patternSize /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolPatternSize: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolPatternSize: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolPatternSize: ... // 只对此数据项生效 /// }] /// }] public var symbolPatternSize: Float? /// 指定图形元素间的覆盖关系。数值越大,越在层叠的上方。 public var z: Float? /// 是否开启 hover 在图形上的提示动画效果。 /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// hoverAnimation: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// hoverAnimation: ... // 只对此数据项生效 /// }, { /// value: 56 /// hoverAnimation: ... // 只对此数据项生效 /// }] /// }] public var hoverAnimation: Bool? /// 是否开启动画。 public var animation: Bool? /// 是否开启动画的阈值,当单个系列显示的图形数量大于这个阈值时会关闭动画。 public var animationThreshold: Float? /// 初始动画的时长,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果: /// /// animationDuration: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDuration: Time? /// 初始动画的缓动效果。不同的缓动效果可以参考 public var animationEasing: EasingFunction? /// 初始动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果。 /// /// 如下示例: /// /// animationDuration: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDelay: Time? /// 数据更新动画的时长。 /// 支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果: /// animationDurationUpdate: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDurationUpdate: Time? /// 数据更新动画的缓动效果。 public var animationEasingUpdate: EasingFunction? /// 数据更新动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果。 /// 如下示例: /// /// animationDelayUpdate: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDelayUpdate: Time? /// 单个柱条文本的样式设置。 public var label: EmphasisLabel? /// 单个柱条的样式设置。 public var itemStyle: ItemStyle? /// 本系列每个数据项中特定的 tooltip 设定。 public var tooltip: Tooltip? public init() { } } public var type: SerieType { return .pictorialBar } /// 系列名称,用于tooltip的显示,legend 的图例筛选,在 setOption 更新数据和配置项时用于指定对应的系列。 public var name: String? /// 是否启用图例 hover 时的联动高亮。 public var legendHoverLink: Bool? /// 该系列使用的坐标系,可选: /// -'cartesian2d' 使用二维的直角坐标系(也称笛卡尔坐标系),通过 xAxisIndex, yAxisIndex指定相应的坐标轴组件。 public var coordinateSystem: CoordinateSystem? /// 使用的 x 轴的 index,在单个图表实例中存在多个 x 轴的时候有用。 public var xAxisIndex: UInt8? /// 使用的 y 轴的 index,在单个图表实例中存在多个 y轴的时候有用。 public var yAxisIndex: UInt8? /// 标悬浮时在图形元素上时鼠标的样式是什么。同 CSS 的 cursor。 public var cursor: String? /// 图形上的文本标签,可用于说明图形的一些数据信息,比如值,名称等,label选项在 ECharts 2.x 中放置于itemStyle.normal下,在 ECharts 3 中为了让整个配置项结构更扁平合理,label 被拿出来跟 itemStyle 平级,并且跟 itemStyle 一样拥有 normal, emphasis 两个状态。 public var label: EmphasisLabel? /// 图形样式,有 normal 和 emphasis 两个状态。normal 是图形在默认状态下的样式;emphasis 是图形在高亮状态下的样式,比如在鼠标悬浮或者图例联动高亮时。 public var itemStyle: ItemStyle? /// 柱条的宽度,不设时自适应。支持设置成相对于类目宽度的百分比。 /// /// 在同一坐标系上,此属性会被多个 'pictorialBar' 系列共享。此属性应设置于此坐标系中最后一个 'pictorialBar' 系列上才会生效,并且是对此坐标系中所有 'pictorialBar' 系列生效。 public var barWidth: LengthValue? /// 柱条的最大宽度,不设时自适应。支持设置成相对于类目宽度的百分比。 /// /// 在同一坐标系上,此属性会被多个 'pictorialBar' 系列共享。此属性应设置于此坐标系中最后一个 'pictorialBar' 系列上才会生效,并且是对此坐标系中所有 'pictorialBar' 系列生效。 public var barMaxWidth: LengthValue? /// 柱条最小高度,可用于防止某数据项的值过小而影响交互。 public var barMinHeight: LengthValue? /// 柱间距离,可设固定值(如 20)或者百分比(如 '30%',表示柱子宽度的 30%)。 /// /// 如果想要两个系列的柱子重叠,可以设置 barGap 为 '-100%'。这在用柱子做背景的时候有用。 /// /// 在同一坐标系上,此属性会被多个 'pictorialBar' 系列共享。此属性应设置于此坐标系中最后一个 'pictorialBar' 系列上才会生效,并且是对此坐标系中所有 'pictorialBar' 系列生效。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/barGrid-barGap public var barGap: LengthValue? /// 类目间柱形距离,默认为类目间距的20%,可设固定值 /// /// 在同一坐标系上,此属性会被多个 'pictorialBar' 系列共享。此属性应设置于此坐标系中最后一个 'pictorialBar' 系列上才会生效,并且是对此坐标系中所有 'pictorialBar' 系列生效。 public var barCategoryGap: LengthValue? /// 图形类型。 /// /// ECharts 提供的标记类型包括 'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin', 'arrow' /// /// 也可以通过 'image://url' 设置为图片,其中 url 为图片的链接,或者 dataURI。 /// /// 可以通过 'path://' 将图标设置为任意的矢量路径。这种方式相比于使用图片的方式,不用担心因为缩放而产生锯齿或模糊,而且可以设置为任意颜色。路径图形会自适应调整为合适的大小。路径的格式参见 SVG PathData。可以从 Adobe Illustrator 等工具编辑导出。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-graphicType /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbol: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// 或者 /// series: [{ /// data: [{ /// value: 23 /// symbol: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbol: ... // 只对此数据项生效 /// }] /// }] public var symbol: OneOrMore<Symbol>? /// 图形的大小。 /// /// 可以用数组分开表示宽和高,例如 [20, 10] 表示标记宽为20,高为10,也可以设置成诸如 10 这样单一的数字,表示 [10, 10]。 /// /// 可以设置成绝对值(如 10),也可以设置成百分比(如 '120%'、['55%', 23])。 /// /// 当设置为百分比时,图形的大小是基于 基准柱 的尺寸计算出来的。 /// /// 例如,当基准柱基于 x 轴(即柱子是纵向的),symbolSize 设置为 ['30%', '50%'],那么最终图形的尺寸是: /// /// - 宽度:基准柱的宽度 * 30%。 /// - 高度: /// - 如果 symbolRepeat 为 false:基准柱的高度 * 50%。 /// - 如果 symbolRepeat 为 true:基准柱的宽度 * 50%。 /// /// 基准柱基于 y 轴(即柱子是横向的)的情况类似对调可得出。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-symbolSize /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolSize: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolSize: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolSize: ... // 只对此数据项生效 /// }] /// }] public var symbolSize: FunctionOrFloatOrPair? /// 图形的定位位置。可取值: /// /// - 'start':图形边缘与柱子开始的地方内切。 /// - 'end':图形边缘与柱子结束的地方内切。 /// - 'center':图形在柱子里居中。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-position /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolPosition: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolPosition: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolPosition: ... // 只对此数据项生效 /// }] /// }] public var symbolPosition: Position? /// 图形相对于原本位置的偏移。symbolOffset 是图形定位中最后计算的一个步骤,可以对图形计算出来的位置进行微调。 /// /// 可以设置成绝对值(如 10),也可以设置成百分比(如 '120%'、['55%', 23])。 /// /// 当设置为百分比时,表示相对于自身尺寸 symbolSize 的百分比。 /// /// 例如 [0, '-50%'] 就是把图形向上移动了自身尺寸的一半的位置。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-position /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolOffset: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolOffset: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolOffset: ... // 只对此数据项生效 /// }] /// }] public var symbolOffset: Point? /// 图形的旋转角度。 /// /// 注意,symbolRotate 并不会影响图形的定位(哪怕超出基准柱的边界),而只是单纯得绕自身中心旋转。 /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolRotate: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolRotate: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolRotate: ... // 只对此数据项生效 /// }] /// }] public var symbolRotate: Float? /// 指定图形元素是否重复。值可为: /// /// - false/null/undefined:不重复,即每个数据值用一个图形元素表示。 /// - true:使图形元素重复,即每个数据值用一组重复的图形元素表示。重复的次数依据 data 计算得到。 /// - a number:使图形元素重复,即每个数据值用一组重复的图形元素表示。重复的次数是给定的定值。 /// - 'fixed':使图形元素重复,即每个数据值用一组重复的图形元素表示。重复的次数依据 symbolBoundingData 计算得到,即与 data 无关。这在此图形被用于做背景时有用。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeat /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolRepeat: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolRepeat: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolRepeat: ... // 只对此数据项生效 /// }] /// }] public var symbolRepeat: String? // ????? /// 指定图形元素重复时,绘制的顺序。这个属性在两种情况下有用处: /// /// - 当 symbolMargin 设置为负值时,重复的图形会互相覆盖,这是可以使用 symbolRepeatDirection 来指定覆盖顺序。 /// - 当 animationDelay 或 animationDelayUpdate 被使用时,symbolRepeatDirection 指定了 index 顺序。 /// /// 这个属性的值可以是:'start' 或 'end'。 /// /// 例子: http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeatDirection /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolRepeatDirection: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolRepeatDirection: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolRepeatDirection: ... // 只对此数据项生效 /// }] /// }] public var symbolRepeatDirection: String? // ????? /// 图形的两边间隔(『两边』是指其数值轴方向的两边)。可以是绝对数值(如 20),或者百分比值(如 '-30%'),表示相对于自身尺寸 symbolSize 的百分比。只有当 symbolRepeat 被使用时有意义。 /// /// 可以是正值,表示间隔大;也可以是负数。当 symbolRepeat 被使用时,负数时能使图形重叠。 /// /// 可以在其值结尾处加一个 "!",如 "30%!" 或 25!,表示第一个图形的开始和最后一个图形结尾留白,不紧贴边界。默认会紧贴边界。 /// /// 注意: /// /// - 当 symbolRepeat 为 true/'fixed' 的时候: 这里设置的 symbolMargin 只是个参考值,真正最后的图形间隔,是根据 symbolRepeat、symbolMargin、symbolBoundingData 综合计算得到。 /// - 当 symbolRepeat 为一个固定数值的时候: 这里设置的 symbolMargin 无效。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeatLayout /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolMargin: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolMargin: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolMargin: ... // 只对此数据项生效 /// }] /// }] public var symbolMargin: String? // ????? /// 是否剪裁图形。 /// /// - false/null/undefined:图形本身表示数值大小。 /// - true:图形被剪裁后剩余的部分表示数值大小。 /// /// symbolClip 常在这种场景下使用:同时表达『总值』和『当前数值』。在这种场景下,可以使用两个系列,一个系列是完整的图形,当做『背景』来表达总数值,另一个系列是使用 symbolClip 进行剪裁过的图形,表达当前数值。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-clip /// /// 在这个例子中: /// /// - 『背景系列』和『当前值系列』使用相同的 symbolBoundingData,使得绘制出的图形的大小是一样的。 /// - 『当前值系列』设置了比『背景系列』更高的 z,使得其覆盖在『背景系列』上。 /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolClip: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolClip: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolClip: ... // 只对此数据项生效 /// }] /// }] public var symbolClip: Bool? /// 这个属性是『指定图形界限的值』。它指定了一个 data,这个 data 映射在坐标系上的位置,是图形绘制的界限。也就是说,如果设置了 symbolBoundingData,图形的尺寸则由 symbolBoundingData 决定。 /// 当柱子是水平的,symbolBoundingData 对应到 x 轴上,当柱子是竖直的,symbolBoundingData 对应到 y 轴上。 /// /// 规则: /// /// - 没有使用 symbolRepeat 时: symbolBoundingData 缺省情况下和『参考柱』的尺寸一样。图形的尺寸由零点和 symbolBoundingData 决定。举例,当柱子是竖直的,柱子对应的 data 为 24,symbolSize 设置为 [30, '50%'],symbolBoundingData 设置为 124,那么最终图形的高度为 124 * 50% = 62。如果 symbolBoundingData 不设置,那么最终图形的高度为 24 * 50% = 12。 /// - 使用了 symbolRepeat 时: symbolBoundingData 缺省情况取当前坐标系所显示出的最值。symbolBoundingData 定义了一个 bounding,重复的图形在这个 bounding 中,依据 symbolMargin 和 symbolRepeat 和 symbolSize 进行排布。这几个变量决定了图形的间隔大小。 /// /// 在这些场景中,你可能会需要设置 symbolBoundingData: /// /// - 使用了 symbolCilp 时: 使用一个系列表达『总值』,另一个系列表达『当前值』的时候,需要两个系列画出的图形一样大。那么就把两个系列的 symbolBoundingData 设为一样大。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-clip /// /// - 使用了 symbolRepeat 时:如果需要不同柱子中的图形的间隔保持一致,那么可以把 symbolBoundingData 设为一致的数值。当然,不设置 symbolBoundingData 也是可以的,因为其缺省值就是一个定值(坐标系所显示出的最值)。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-repeatLayout /// /// symbolBoundingData 可以是一个数组,例如 [-40, 60],表示同时指定了正值的 symbolBoundingData 和负值的 symbolBoundingData。 /// /// 参见例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-symbolBoundingDataArray /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolBoundingData: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolBoundingData: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolBoundingData: ... // 只对此数据项生效 /// }] /// }] public var symbolBoundingData: String? // ????? /// 可以使用图片作为图形的 pattern。 /// /// var textureImg = new Image(); /// textureImg.src = 'data:image/jpeg;base64,...'; // dataURI /// // 或者 /// // textureImg.src = 'http://xxx.xxx.xxx/xx.png'; // URL /// ... /// itemStyle: { /// normal: { /// color: { /// image: textureImg, /// repeat: 'repeat' /// } /// } /// } /// /// 这时候,symbolPatternSize 指定了 pattern 的缩放尺寸。比如 symbolPatternSize 为 400 时表示图片显示为 400px * 400px 的尺寸。 /// /// 例子:http://echarts.baidu.com/gallery/editor.html?c=doc-example/pictorialBar-patternSize /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// symbolPatternSize: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// symbolPatternSize: ... // 只对此数据项生效 /// }, { /// value: 56 /// symbolPatternSize: ... // 只对此数据项生效 /// }] /// }] public var symbolPatternSize: Float? /// 是否开启 hover 在图形上的提示动画效果。 /// /// 此属性可以被设置在系列的 根部,表示对此系列中所有数据都生效;也可以被设置在 data 中的 每个数据项中,表示只对此数据项生效。 /// /// 例如: /// /// series: [{ /// hoverAnimation: ... // 对 data 中所有数据项生效。 /// data: [23, 56] /// }] /// /// 或者 /// /// series: [{ /// data: [{ /// value: 23 /// hoverAnimation: ... // 只对此数据项生效 /// }, { /// value: 56 /// hoverAnimation: ... // 只对此数据项生效 /// }] /// }] public var hoverAnimation: Bool? /// 使用 dimensions 定义 data 每个维度的信息。例如: /// /// series: { /// type: 'xxx', /// // 定义了每个维度的名称。这个名称会被显示到默认的 tooltip 中。 /// dimensions: ['date', 'open', 'close', 'highest', 'lowest'] /// data: [ /// // 有了上面 dimensions 定义后,下面这五个维度的名称分别为: /// // 'date', 'open', 'close', 'highest', 'lowest' /// [12, 44, 55, 66, 2], /// [23, 6, 16, 23, 1], /// ... /// ] /// } /// series: { /// type: 'xxx', /// dimensions: [ /// null, // 如果此维度不想给出定义,则使用 null 即可 /// {type: 'ordinal'}, // 只定义此维度的类型。 /// // 'ordinal' 表示离散型,一般文本使用这种类型。 /// // 如果类型没有被定义,会自动猜测类型。 /// {name: 'good', type: 'number'}, /// 'bad' // 等同于 {name: 'bad'} /// ] /// } /// /// dimensions 数组中的每一项可以是: /// /// - string,如 'someName',等同于 {name: 'someName'} /// - Object,属性可以有: /// - name: string。 /// - type: string,支持 /// - number /// - float,即 Float64Array /// - int,即 Int32Array /// - ordinal,表示离散数据,一般指字符串。 /// - time,表示时间类型,时间类型的支持参见 data /// /// 值得一提的是,当定义了 dimensions 后,默认 tooltip 中对个维度的显示,会变为『竖排』,从而方便显示每个维度的名称。如果没有定义 dimensions,则默认 tooltip 会横排显示,且只显示数值没有维度名称可显示。 public var dimensions: [Jsonable]? /// 可以定义 data 的哪个维度被编码成什么。比如: /// /// series: { /// type: 'xxx', /// encode: { /// x: [3, 1, 5], // 表示维度 3、1、5 映射到 x 轴。 /// y: 2, // 表示维度 2 映射到 y 轴。 /// tooltip: [3, 2, 4] // 表示维度 3、2、4 会在 tooltip 中显示。 /// label: 3 // 表示 label 使用维度 3。 /// }, /// data: [ /// // 每一列称为一个『维度』。 /// // 这里分别是维度 0、1、2、3、4。 /// [12, 44, 55, 66, 2], /// [23, 6, 16, 23, 1], /// ... /// ] /// } /// /// encode 支持的属性,根据坐标系不同而不同。 对于 直角坐标系(cartesian2d),支持 x、y。 对于 极坐标系(polar),支持 radius、angle。 对于 地理坐标系(geo),支持 lng,lat。 此外,均支持 tooltip 和 label 和 itemName(用于指定 tooltip 中数据项名称)。 /// /// 当使用 dimensions 给维度定义名称后,encode 中可直接引用名称,例如: /// /// series: { /// type: 'xxx', /// dimensions: ['date', 'open', 'close', 'highest', 'lowest'], /// encode: { /// x: 'date', /// y: ['open', 'close', 'highest', 'lowest'] /// }, /// data: [ ... ] /// } public var encode: [String: Jsonable]? /// 数据,详情可以见: PictorialBarSerie.Data public var data: [Jsonable]? /// 图表标注。 public var markPoint: MarkPoint? /// 图表标线。 public var markLine: MarkLine? /// 图表标域,常用于标记图表中某个范围的数据,例如标出某段时间投放了广告。 public var markArea: MarkArea? /// 象形柱图所有图形的 zlevel 值。 /// /// zlevel用于 Canvas 分层,不同zlevel值的图形会放置在不同的 Canvas 中,Canvas 分层是一种常见的优化手段。我们可以把一些图形变化频繁(例如有动画)的组件设置成一个单独的zlevel。需要注意的是过多的 Canvas 会引起内存开销的增大,在手机端上需要谨慎使用以防崩溃。 /// /// zlevel 大的 Canvas 会放在 zlevel 小的 Canvas 的上面。 public var zlevel: Float? /// 象形柱图组件的所有图形的z值。控制图形的前后顺序。z值小的图形会被z值大的图形覆盖。 /// /// z相比zlevel优先级更低,而且不会创建新的 Canvas。 public var z: Float? /// 图形是否不响应和触发鼠标事件,默认为 false,即响应和触发鼠标事件。 public var silent: Bool? /// 是否开启动画。 public var animation: Bool? /// 是否开启动画的阈值,当单个系列显示的图形数量大于这个阈值时会关闭动画。 public var animationThreshold: Float? /// 初始动画的时长,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果: /// /// animationDuration: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDuration: Time? /// 初始动画的缓动效果。不同的缓动效果可以参考 public var animationEasing: EasingFunction? /// 初始动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的初始动画效果。 /// /// 如下示例: /// /// animationDuration: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDelay: Time? /// 数据更新动画的时长。 /// 支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果: /// animationDurationUpdate: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDurationUpdate: Time? /// 数据更新动画的缓动效果。 public var animationEasingUpdate: EasingFunction? /// 数据更新动画的延迟,支持回调函数,可以通过每个数据返回不同的 delay 时间实现更戏剧的更新动画效果。 /// 如下示例: /// /// animationDelayUpdate: function (idx) { /// // 越往后的数据延迟越大 /// return idx * 100; /// } public var animationDelayUpdate: Time? /// 本系列特定的 tooltip 设定。 public var tooltip: Tooltip? public init() { } } extension PictorialBarSerie.Data: Enumable { public enum Enums { case name(String), value(Jsonable), symbol(Symbol), symbolSize(FunctionOrFloatOrPair), symbolPosition(Position), symbolOffset(Point), symbolRotate(Float), symbolRepeat(String), symbolRepeatDirection(String), symbolMargin(String), symbolClip(Bool), symbolBoundingData(String), symbolPatternSize(Float), z(Float), hoverAnimation(Bool), animation(Bool), animationThreshold(Float), animationDuration(Time), animationEasing(EasingFunction), animationDurationUpdate(Time), animationEasingUpdate(EasingFunction), animationDelay(Time), animationDelayUpdate(Time), label(EmphasisLabel), itemStyle(ItemStyle), tooltip(Tooltip) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .name(name): self.name = name case let .value(value): self.value = value case let .symbol(symbol): self.symbol = OneOrMore(one: symbol) case let .symbolSize(symbolSize): self.symbolSize = symbolSize case let .symbolPosition(symbolPosition): self.symbolPosition = symbolPosition case let .symbolOffset(symbolOffset): self.symbolOffset = symbolOffset case let .symbolRotate(symbolRotate): self.symbolRotate = symbolRotate case let .symbolRepeat(symbolRepeat): self.symbolRepeat = symbolRepeat case let .symbolRepeatDirection(symbolRepeatDirection): self.symbolRepeatDirection = symbolRepeatDirection case let .symbolMargin(symbolMargin): self.symbolMargin = symbolMargin case let .symbolClip(symbolClip): self.symbolClip = symbolClip case let .symbolBoundingData(symbolBoundingData): self.symbolBoundingData = symbolBoundingData case let .symbolPatternSize(symbolPatternSize): self.symbolPatternSize = symbolPatternSize case let .z(z): self.z = z case let .hoverAnimation(hoverAnimation): self.hoverAnimation = hoverAnimation case let .animation(animation): self.animation = animation case let .animationThreshold(animationThreshold): self.animationThreshold = animationThreshold case let .animationDuration(animationDuration): self.animationDuration = animationDuration case let .animationEasing(animationEasing): self.animationEasing = animationEasing case let .animationDurationUpdate(animationDurationUpdate): self.animationDurationUpdate = animationDurationUpdate case let .animationEasingUpdate(animationEasingUpdate): self.animationEasingUpdate = animationEasingUpdate case let .animationDelay(animationDelay): self.animationDelay = animationDelay case let .animationDelayUpdate(animationDelayUpdate): self.animationDelayUpdate = animationDelayUpdate case let .label(label): self.label = label case let .itemStyle(itemStyle): self.itemStyle = itemStyle case let .tooltip(tooltip): self.tooltip = tooltip } } } } extension PictorialBarSerie.Data: Mappable { public func mapping(_ map: Mapper) { map["name"] = name map["value"] = value map["symbol"] = symbol map["symbolSize"] = symbolSize map["symbolPosition"] = symbolPosition map["symbolOffset"] = symbolOffset map["symbolRotate"] = symbolRotate map["symbolRepeat"] = symbolRepeat map["symbolRepeatDirection"] = symbolRepeatDirection map["symbolMargin"] = symbolMargin map["symbolClip"] = symbolClip map["symbolBoundingData"] = symbolBoundingData map["symbolPatternSize"] = symbolPatternSize map["z"] = z map["hoverAnimation"] = hoverAnimation map["animation"] = animation map["animationThreshold"] = animationThreshold map["animationDuration"] = animationDuration map["animationEasing"] = animationEasing map["animationDurationUpdate"] = animationDurationUpdate map["animationEasingUpdate"] = animationEasingUpdate map["animationDelay"] = animationDelay map["animationDelayUpdate"] = animationDelayUpdate map["label"] = label map["itemStyle"] = itemStyle map["tooltip"] = tooltip } } extension PictorialBarSerie: Enumable { public enum Enums { case name(String), legendHoverLink(Bool), coordinateSystem(CoordinateSystem), xAxisIndex(UInt8), yAxisIndex(UInt8), cursor(String), label(EmphasisLabel), itemStyle(ItemStyle), barWidth(LengthValue), barMaxWidth(LengthValue), barMinHeight(LengthValue), barGap(LengthValue), barCategoryGap(LengthValue), symbol(Symbol), symbolSize(FunctionOrFloatOrPair), symbolPosition(Position), symbolOffset(Point), symbolRotate(Float), symbolRepeat(String), symbolRepeatDirection(String), symbolMargin(String), symbolClip(Bool), symbolBoundingData(String), symbolPatternSize(Float), hoverAnimation(Bool), dimensions([Jsonable]), encode([String: Jsonable]), data([Jsonable]), markPoint(MarkPoint), markLine(MarkLine), markArea(MarkArea), zlevel(Float), z(Float), silent(Bool), animation(Bool), animationThreshold(Float), animationDuration(Time), animationEasing(EasingFunction), animationDurationUpdate(Time), animationDelayUpdate(Time), animationDelay(Time), animationEasingUpdate(EasingFunction), tooltip(Tooltip) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .name(name): self.name = name case let .legendHoverLink(legendHoverLink): self.legendHoverLink = legendHoverLink case let .coordinateSystem(coordinateSystem): self.coordinateSystem = coordinateSystem case let .xAxisIndex(xAxisIndex): self.xAxisIndex = xAxisIndex case let .yAxisIndex(yAxisIndex): self.yAxisIndex = yAxisIndex case let .cursor(cursor): self.cursor = cursor case let .label(label): self.label = label case let .itemStyle(itemStyle): self.itemStyle = itemStyle case let .barWidth(barWidth): self.barWidth = barWidth case let .barMaxWidth(barMaxWidth): self.barMaxWidth = barMaxWidth case let .barMinHeight(barMinHeight): self.barMinHeight = barMinHeight case let .barGap(barGap): self.barGap = barGap case let .barCategoryGap(barCategoryGap): self.barCategoryGap = barCategoryGap case let .symbol(symbol): self.symbol = OneOrMore(one: symbol) case let .symbolSize(symbolSize): self.symbolSize = symbolSize case let .symbolPosition(symbolPosition): self.symbolPosition = symbolPosition case let .symbolOffset(symbolOffset): self.symbolOffset = symbolOffset case let .symbolRotate(symbolRotate): self.symbolRotate = symbolRotate case let .symbolRepeat(symbolRepeat): self.symbolRepeat = symbolRepeat case let .symbolRepeatDirection(symbolRepeatDirection): self.symbolRepeatDirection = symbolRepeatDirection case let .symbolMargin(symbolMargin): self.symbolMargin = symbolMargin case let .symbolClip(symbolClip): self.symbolClip = symbolClip case let .symbolBoundingData(symbolBoundingData): self.symbolBoundingData = symbolBoundingData case let .symbolPatternSize(symbolPatternSize): self.symbolPatternSize = symbolPatternSize case let .hoverAnimation(hoverAnimation): self.hoverAnimation = hoverAnimation case let .dimensions(dimensions): self.dimensions = dimensions case let .encode(encode): self.encode = encode case let .data(data): self.data = data case let .markPoint(markPoint): self.markPoint = markPoint case let .markLine(markLine): self.markLine = markLine case let .markArea(markArea): self.markArea = markArea case let .zlevel(zlevel): self.zlevel = zlevel case let .z(z): self.z = z case let .silent(silent): self.silent = silent case let .animation(animation): self.animation = animation case let .animationThreshold(animationThreshold): self.animationThreshold = animationThreshold case let .animationDuration(animationDuration): self.animationDuration = animationDuration case let .animationEasing(animationEasing): self.animationEasing = animationEasing case let .animationDurationUpdate(animationDurationUpdate): self.animationDurationUpdate = animationDurationUpdate case let .animationDelayUpdate(animationDelayUpdate): self.animationDelayUpdate = animationDelayUpdate case let .animationDelay(animationDelay): self.animationDelay = animationDelay case let .animationEasingUpdate(animationEasingUpdate): self.animationEasingUpdate = animationEasingUpdate case let .tooltip(tooltip): self.tooltip = tooltip } } } } extension PictorialBarSerie: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["name"] = name map["legendHoverLink"] = legendHoverLink map["coordinateSystem"] = coordinateSystem map["xAxisIndex"] = xAxisIndex map["yAxisIndex"] = yAxisIndex map["cursor"] = cursor map["label"] = label map["itemStyle"] = itemStyle map["barWidth"] = barWidth map["barMaxWidth"] = barMaxWidth map["barMinHeight"] = barMinHeight map["barGap"] = barGap map["barCategoryGap"] = barCategoryGap map["symbol"] = symbol map["symbolSize"] = symbolSize map["symbolPosition"] = symbolPosition map["symbolOffset"] = symbolOffset map["symbolRotate"] = symbolRotate map["symbolRepeat"] = symbolRepeat map["symbolRepeatDirection"] = symbolRepeatDirection map["symbolMargin"] = symbolMargin map["symbolClip"] = symbolClip map["symbolBoundingData"] = symbolBoundingData map["symbolPatternSize"] = symbolPatternSize map["hoverAnimation"] = hoverAnimation map["dimensions"] = dimensions map["encode"] = encode map["data"] = data map["markPoint"] = markPoint map["markLine"] = markLine map["markArea"] = markArea map["zlevel"] = zlevel map["z"] = z map["silent"] = silent map["animation"] = animation map["animationThreshold"] = animationThreshold map["animationDuration"] = animationDuration map["animationEasing"] = animationEasing map["animationDurationUpdate"] = animationDurationUpdate map["animationDelayUpdate"] = animationDelayUpdate map["animationDelay"] = animationDelay map["animationEasingUpdate"] = animationEasingUpdate map["tooltip"] = tooltip } }
mit
FearfulFox/sacred-tiles
Sacred Tiles/CommonUIViewController.swift
1
544
// // CommonUIViewController.swift // Sacred Tiles // // Created by Fox on 3/3/15. // Copyright (c) 2015 eCrow. All rights reserved. // import UIKit; class CommonUIViewController: UIViewController { override func shouldAutorotate() -> Bool { return false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true; } }
gpl-2.0
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Graphic/ArcGraphic.swift
1
4766
// // ArcGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 12/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 圆弧类型的 `Graphic` public final class ArcGraphic: Graphic { /// 圆弧的大小和位置 public final class Shape { public var cx: Float? public var cy: Float? public var r: Float? public var r0: Float? public var startAngle: Float? public var endAngle: Float? public var clockwise: Float? public init() {} } /// MARK: Graphic public var type: GraphicType { return .arc } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 圆弧的大小和位置 public var shape: Shape? /// 圆弧的样式 public var style: CommonGraphicStyle? public init() {} } extension ArcGraphic.Shape: Enumable { public enum Enums { case cx(Float), cy(Float), r(Float), r0(Float), startAngle(Float), endAngle(Float), clockwise(Float) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .cx(cx): self.cx = cx case let .cy(cy): self.cy = cy case let .r(r): self.r = r case let .r0(r0): self.r0 = r0 case let .startAngle(startAngle): self.startAngle = startAngle case let .endAngle(endAngle): self.endAngle = endAngle case let .clockwise(clockwise): self.clockwise = clockwise } } } } extension ArcGraphic.Shape: Mappable { public func mapping(_ map: Mapper) { map["cx"] = cx map["cy"] = cy map["r"] = r map["r0"] = r0 map["startAngle"] = startAngle map["endAngle"] = endAngle map["clockwise"] = clockwise } } extension ArcGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), shape(Shape), style(CommonGraphicStyle) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .shape(shape): self.shape = shape case let .style(style): self.style = style } } } } extension ArcGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["shape"] = shape map["style"] = style } }
mit
ProcedureKit/ProcedureKit
Sources/ProcedureKit/IgnoreErrors.swift
2
838
// // ProcedureKit // // Copyright © 2016-2018 ProcedureKit. All rights reserved. // import Foundation /** Compose another `Procedure` subclass to ignore any errors that it generates. */ final public class IgnoreErrorsProcedure<T: Procedure>: ComposedProcedure<T> { /// Override to supress errors from the composed procedure override public func child(_ child: Procedure, willFinishWithError error: Error?) { assert(!child.isFinished, "child(_:willFinishWithErrors:) called with a child that has already finished") // No errors - call the super. guard let e = error else { super.child(child, willFinishWithError: error) return } // If there are errors, just log them. log.warning.message("Ignoring \(e) errors from \(child.operationName).") } }
mit
AlDrago/SwiftyJSON
Tests/PrintableTests.swift
1
3483
// PrintableTests.swift // // Copyright (c) 2014 Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import SwiftyJSON3 class PrintableTests: XCTestCase { func testNumber() { let json:JSON = 1234567890.876623 XCTAssertEqual(json.description, "1234567890.876623") XCTAssertEqual(json.debugDescription, "1234567890.876623") } func testBool() { let jsonTrue:JSON = true XCTAssertEqual(jsonTrue.description, "true") XCTAssertEqual(jsonTrue.debugDescription, "true") let jsonFalse:JSON = false XCTAssertEqual(jsonFalse.description, "false") XCTAssertEqual(jsonFalse.debugDescription, "false") } func testString() { let json:JSON = "abcd efg, HIJK;LMn" XCTAssertEqual(json.description, "abcd efg, HIJK;LMn") XCTAssertEqual(json.debugDescription, "abcd efg, HIJK;LMn") } func testNil() { let jsonNil_1:JSON = nil XCTAssertEqual(jsonNil_1.description, "null") XCTAssertEqual(jsonNil_1.debugDescription, "null") let jsonNil_2:JSON = JSON(NSNull()) XCTAssertEqual(jsonNil_2.description, "null") XCTAssertEqual(jsonNil_2.debugDescription, "null") } func testArray() { let json:JSON = [1,2,"4",5,"6"] var description = json.description.replacingOccurrences(of: "\n", with: "") description = description.replacingOccurrences(of: " ", with: "") XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(json.debugDescription.lengthOfBytes(using: String.Encoding.utf8) > 0) } func testDictionary() { let json:JSON = ["1":2,"2":"two", "3":3] var debugDescription = json.debugDescription.replacingOccurrences(of: "\n", with: "") debugDescription = debugDescription.replacingOccurrences(of: " ", with: "") XCTAssertTrue(json.description.lengthOfBytes(using: String.Encoding.utf8) > 0) XCTAssertTrue(debugDescription.range(of: "\"1\":2", options: NSString.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(debugDescription.range(of: "\"2\":\"two\"", options: NSString.CompareOptions.caseInsensitive) != nil) XCTAssertTrue(debugDescription.range(of: "\"3\":3", options: NSString.CompareOptions.caseInsensitive) != nil) } }
mit
modernistik/TimeZoneLocate
Example/TimeZoneLocate/AppDelegate.swift
1
2119
// // AppDelegate.swift // TimeZoneLocate // // Created by Anthony Persaud on 01/17/2016. // Copyright (c) 2016 Anthony Persaud. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
lorentey/swift
validation-test/compiler_crashers_fixed/27577-swift-funcdecl-setdeserializedsignature.swift
65
461
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let:{class d{var f:(}}class S<T{func a<h{func b<T where h.g=a{
apache-2.0
lorentey/swift
test/SILOptimizer/prespecialize.swift
13
1392
// RUN: %target-swift-frontend %s -Onone -Xllvm -sil-inline-generics=false -emit-sil | %FileCheck %s // REQUIRES: optimized_stdlib // Check that pre-specialization works at -Onone. // This test requires the standard library to be compiled with pre-specializations! // CHECK-LABEL: sil [noinline] @$s13prespecialize4test_4sizeySaySiGz_SitF // // function_ref specialized Collection<A where ...>.makeIterator() -> IndexingIterator<A> // CHECK: function_ref @$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyFSnySiG_Tg5 // // function_ref specialized IndexingIterator.next() -> A.Element? // CHECK: function_ref @$ss16IndexingIteratorV4next7ElementQzSgyFSnySiG_Tg5 // // Look for generic specialization <Swift.Int> of Swift.Array.subscript.getter : (Swift.Int) -> A // CHECK: function_ref @$sSayxSicigSi_Tg5 // CHECK: return @inline(never) public func test(_ a: inout [Int], size: Int) { for i in 0..<size { for j in 0..<size { a[i] = a[j] } } } // CHECK-LABEL: sil [noinline] @$s13prespecialize3runyyF // Look for generic specialization <Swift.Int> of Swift.Array.init (repeating : A, count : Swift.Int) -> Swift.Array<A> // CHECK: function_ref @$sSa9repeating5countSayxGx_SitcfCSi_Tg5 // CHECK: return @inline(never) public func run() { let size = 10000 var p = [Int](repeating: 0, count: size) for i in 0..<size { p[i] = i } test(&p, size: size) } run()
apache-2.0
phimage/XcodeProjKit
Sources/PathType.swift
1
759
// // PathType.swift // XcodeProjKit // // Created by phimage on 30/07/2017. // Copyright © 2017 phimage (Eric Marchand). All rights reserved. // import Foundation public enum PathType { case absolute(String) case relativeTo(SourceTreeFolder, String) } extension PathType { public func url(with urlForSourceTreeFolder: (SourceTreeFolder) -> URL) -> URL { switch self { case let .absolute(absolutePath): return URL(fileURLWithPath: absolutePath).standardizedFileURL case let .relativeTo(sourceTreeFolder, relativePath): let sourceTreeURL = urlForSourceTreeFolder(sourceTreeFolder) return sourceTreeURL.appendingPathComponent(relativePath).standardizedFileURL } } }
mit
vector-im/vector-ios
Riot/Modules/Room/EditHistory/EditHistoryCoordinatorType.swift
1
1060
// File created from ScreenTemplate // $ createScreen.sh Room/EditHistory EditHistory /* Copyright 2019 New Vector Ltd 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 protocol EditHistoryCoordinatorDelegate: AnyObject { func editHistoryCoordinatorDidComplete(_ coordinator: EditHistoryCoordinatorType) } /// `EditHistoryCoordinatorType` is a protocol describing a Coordinator that handle keybackup setup navigation flow. protocol EditHistoryCoordinatorType: Coordinator, Presentable { var delegate: EditHistoryCoordinatorDelegate? { get } }
apache-2.0
felipedemetrius/AppSwift3
AppSwift3/TasksViewController.swift
1
4003
// // TasksViewController.swift // AppSwift3 // // Created by Felipe Silva on 2/14/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import UIKit /// Responsible for controlling the screen that shows the user a list of task ID's class TasksViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! private var refreshControl:UIRefreshControl! /// ViewModel for this ViewController var viewModel: TasksViewModel? { didSet { observerViewModel() } } /// Controls UI components for user feedback private var isLoadingDataSource = false { didSet{ if isLoadingDataSource { activityIndicator.startAnimating() label.isHidden = true tableView.separatorStyle = UITableViewCellSeparatorStyle.none } else { refreshControl.endRefreshing() activityIndicator.stopAnimating() if viewModel?.dataSource.value == nil || viewModel?.dataSource.value?.count == 0 { label.isHidden = false tableView.separatorStyle = UITableViewCellSeparatorStyle.none } else { tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine } } tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() observerViewModel() setTableView() setPullToRefresh() } private func setTableView(){ tableView.register(UINib(nibName: "TasksTableViewCell", bundle: nil), forCellReuseIdentifier: "TasksTableViewCell") tableView.estimatedRowHeight = 66 } fileprivate func observerViewModel(){ if !isViewLoaded { return } guard let viewModel = viewModel else { return } title = viewModel.title viewModel.isLoadingDatasource.bindAndFire { [unowned self] in self.isLoadingDataSource = $0 } } @objc private func setPullToRefresh(){ refreshControl = UIRefreshControl() refreshControl.addTarget(viewModel, action: #selector(TasksViewModel.setDatasource), for: UIControlEvents.valueChanged) refreshControl.tintColor = UIColor.black tableView.addSubview(refreshControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToTaskDetail" { let vc = segue.destination as! TaskDetailViewController if let id = sender as? String { let viewModel = TaskDetailViewModel(id: id) vc.viewModel = viewModel } } } } extension TasksViewController : UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.dataSource.value?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let id = viewModel?.dataSource.value?[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell cell.label.text = id return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToTaskDetail", sender: viewModel?.dataSource.value?[indexPath.row]) } }
mit
uhnmdi/CCContinuousGlucose
CCContinuousGlucose/Classes/ContinuousGlucoseStatus.swift
1
929
// // ContinuousGlucoseStatus.swift // Pods // // Created by Kevin Tallevi on 4/18/17. // // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.cgm_status.xml import Foundation import CCToolbox public class ContinuousGlucoseStatus : NSObject { public var packetData: NSData? public var timeOffset: UInt16 = 0 public var status: ContinuousGlucoseAnnunciation! public var e2eCRC: UInt16 = 0 private let annunciationDataRange = NSRange(location:2, length: 3) init(data: NSData?) { super.init() self.packetData = data updateStatus(data: data) } public func updateStatus(data: NSData?) { data?.getBytes(&timeOffset, length: 2) let annunciationData = (data?.subdata(with: annunciationDataRange) as NSData!) self.status = ContinuousGlucoseAnnunciation(data: annunciationData) } }
mit
Sunnyyoung/Meizi-Swift
Meizi-Swift/SettingViewController.swift
1
1185
// // SettingViewController.swift // Meizi-Swift // // Created by GeekBean on 16/4/28. // Copyright © 2016年 Sunnyyoung. All rights reserved. // import UIKit import Kingfisher import PKHUD class SettingViewController: UITableViewController { @IBOutlet weak var cacheSizeLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.refreshCacheSizeLabel() } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cache = KingfisherManager.sharedManager.cache cache.clearDiskCacheWithCompletionHandler { self.refreshCacheSizeLabel() HUD.flash(.Success, delay: 1.2) } } func refreshCacheSizeLabel() -> Void { let cache = KingfisherManager.sharedManager.cache cache.calculateDiskCacheSizeWithCompletionHandler { (size) -> () in self.cacheSizeLabel.text = String(format: "%.2f MB", Float(size)/1024.0/1024.0) } } }
mit
yonat/MultiSelectSegmentedControl
Sources/MultiSelectSegmentedControl.swift
1
14929
// // MultiSelectSegmentedControl.swift // MultiSelectSegmentedControl // // Created by Yonat Sharon on 2019-08-19. // import SweeterSwift import UIKit @objc public protocol MultiSelectSegmentedControlDelegate { func multiSelect(_ multiSelectSegmentedControl: MultiSelectSegmentedControl, didChange value: Bool, at index: Int) } @IBDesignable open class MultiSelectSegmentedControl: UIControl { @objc public weak var delegate: MultiSelectSegmentedControlDelegate? // MARK: - UISegmentedControl Enhancements /// Items shown in segments. Each item can be a `String`, a `UIImage`, or an array of strings and images. @objc public var items: [Any] { get { return segments .map { $0.contents } .map { $0.count == 1 ? $0[0] : $0 } } set { removeAllSegments() for item in newValue { let arrayItem = item as? [Any] ?? [item] insertSegment(contents: arrayItem) } } } /// Indexes of selected segments (can be more than one if `allowsMultipleSelection` is `true`. @objc public var selectedSegmentIndexes: IndexSet { get { return IndexSet(segments.enumerated().filter { $1.isSelected }.map { $0.offset }) } set { for (i, segment) in segments.enumerated() { segment.isSelected = newValue.contains(i) showDividersBetweenSelectedSegments() } } } @objc public var selectedSegmentTitles: [String] { return segments.filter { $0.isSelected }.compactMap { $0.title } } /// Allow use to select multiple segments (default: `true`). @IBInspectable open dynamic var allowsMultipleSelection: Bool = true { didSet { if !allowsMultipleSelection { selectedSegmentIndex = { selectedSegmentIndex }() } } } /// Select or deselect all segments /// - Parameter selected: `true` to select (default), `false` to deselect. @objc public func selectAllSegments(_ selected: Bool = true) { selectedSegmentIndexes = selected ? IndexSet(0 ..< segments.count) : [] } /// Add segment to the control. /// - Parameter contents: An array of 1 or more strings and images /// - Parameter index: Where to insert the segment (default: at the end) /// - Parameter animated: Animate the insertion (default: false) @objc open func insertSegment(contents: [Any], at index: Int = UISegmentedControl.noSegment, animated: Bool = false) { let segment = MultiSelectSegment(contents: contents, parent: self) segment.tintColor = tintColor segment.isHidden = true perform(animated: animated) { [stackView] in if index >= 0 && index < stackView.arrangedSubviews.count { stackView.insertArrangedSubview(segment, at: index) self.removeDivider(at: index - 1) self.insertDivider(afterSegment: index - 1) self.insertDivider(afterSegment: index) } else { stackView.addArrangedSubview(segment) self.insertDivider(afterSegment: stackView.arrangedSubviews.count - 2) } segment.isHidden = false self.showDividersBetweenSelectedSegments() self.invalidateIntrinsicContentSize() } } // MARK: - Appearance /// Width of the dividers between segments and the border around the view. @IBInspectable open dynamic var borderWidth: CGFloat = 1 { didSet { stackView.spacing = borderWidth borderView.layer.borderWidth = borderWidth for divider in dividers { constrainDividerToControl(divider: divider) } constrain(stackView, at: .left, to: borderView, diff: borderWidth) constrain(stackView, at: .right, to: borderView, diff: -borderWidth) invalidateIntrinsicContentSize() } } /// Corner radius of the view. @IBInspectable open dynamic var borderRadius: CGFloat = 4 { didSet { layer.cornerRadius = borderRadius borderView.layer.cornerRadius = borderRadius } } /// Stack the segments vertically. (default: `false`) @IBInspectable open dynamic var isVertical: Bool { get { return stackView.axis == .vertical } set { removeAllDividers() stackView.axis = newValue ? .vertical : .horizontal DispatchQueue.main.async { // wait for new layout to take effect, to prevent auto layout error self.addAllDividers() } invalidateIntrinsicContentSize() } } /// Stack each segment contents vertically when it contains both text and image. (default: `false`) @IBInspectable open dynamic var isVerticalSegmentContents: Bool = false { didSet { segments.forEach { $0.updateContentsAxis() } invalidateIntrinsicContentSize() } } public dynamic var titleTextAttributes: [UIControl.State: [NSAttributedString.Key: Any]] = [:] { didSet { segments.forEach { $0.updateTitleAttributes() } invalidateIntrinsicContentSize() } } /// Configure additional properties of segments titles. For example: `multiSegment.titleConfigurationHandler = { $0.numberOfLines = 0 }` @objc open dynamic var titleConfigurationHandler: ((UILabel) -> Void)? { didSet { for segment in segments { segment.updateLabelConfiguration() } invalidateIntrinsicContentSize() } } /// Optional selected background color, if different than tintColor @IBInspectable open dynamic var selectedBackgroundColor: UIColor? { didSet { segments.forEach { $0.updateColors() } } } // MARK: - UISegmentedControl Compatibility @objc public convenience init(items: [Any]? = nil) { self.init(frame: .zero) if let items = items { self.items = items } } @objc public var selectedSegmentIndex: Int { get { return selectedSegmentIndexes.first ?? UISegmentedControl.noSegment } set { selectedSegmentIndexes = newValue >= 0 && newValue < segments.count ? [newValue] : [] } } @objc public var numberOfSegments: Int { return segments.count } /// Use different size for each segment, depending on its content size. (default: `false`) @IBInspectable public dynamic var apportionsSegmentWidthsByContent: Bool { get { return stackView.distribution != .fillEqually } set { stackView.distribution = newValue ? .fill : .fillEqually invalidateIntrinsicContentSize() } } @objc public func setImage(_ image: UIImage?, forSegmentAt index: Int) { guard index >= 0 && index < segments.count else { return } segments[index].image = image invalidateIntrinsicContentSize() } @objc public func imageForSegment(at index: Int) -> UIImage? { guard index >= 0 && index < segments.count else { return nil } return segments[index].image } @objc public func setTitle(_ title: String?, forSegmentAt index: Int) { guard index >= 0 && index < segments.count else { return } segments[index].title = title invalidateIntrinsicContentSize() } @objc public func titleForSegment(at index: Int) -> String? { guard index >= 0 && index < segments.count else { return nil } return segments[index].title } @objc public func setTitleTextAttributes(_ attributes: [NSAttributedString.Key: Any]?, for state: UIControl.State) { titleTextAttributes[state] = attributes invalidateIntrinsicContentSize() } @objc public func titleTextAttributes(for state: UIControl.State) -> [NSAttributedString.Key: Any]? { return titleTextAttributes[state] } @objc public func insertSegment(with image: UIImage, at index: Int = UISegmentedControl.noSegment, animated: Bool = false) { insertSegment(contents: [image], at: index, animated: animated) } @objc public func insertSegment(withTitle title: String, at index: Int = UISegmentedControl.noSegment, animated: Bool = false) { insertSegment(contents: [title], at: index, animated: animated) } @objc public func removeAllSegments() { removeAllDividers() stackView.removeAllArrangedSubviewsCompletely() invalidateIntrinsicContentSize() } @objc public func removeSegment(at index: Int, animated: Bool) { guard index >= 0 && index < segments.count else { return } let segment = segments[index] perform(animated: animated) { segment.isHidden = true self.removeDivider(at: index) // after removed segment self.removeDivider(at: index - 1) // before removed segment } perform(animated: animated) { self.stackView.removeArrangedSubviewCompletely(segment) self.insertDivider(afterSegment: index - 1) // before removed segment self.showDividersBetweenSelectedSegments() self.invalidateIntrinsicContentSize() } } @objc public func setEnabled(_ enabled: Bool, forSegmentAt index: Int) { guard index >= 0 && index < segments.count else { return } segments[index].isEnabled = enabled } @objc public func isEnabledForSegment(at index: Int) -> Bool { guard index >= 0 && index < segments.count else { return false } return segments[index].isEnabled } // MARK: - Overrides public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } open override var backgroundColor: UIColor? { didSet { segments.forEach { $0.updateColors() } } } open override func tintColorDidChange() { super.tintColorDidChange() let newTint = actualTintColor borderView.layer.borderColor = newTint.cgColor dividers.forEach { $0.backgroundColor = newTint } segments.forEach { $0.tintColor = tintColor } } open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() items = ["Lorem", "Ipsum", "Sit"] } open override var intrinsicContentSize: CGSize { // to pacify Interface Builder frame calculations let stackViewSize = stackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) return CGRect(origin: .zero, size: stackViewSize).insetBy(dx: -borderWidth, dy: -borderWidth).size } // MARK: - Internals public var segments: [MultiSelectSegment] { return stackView.arrangedSubviews.compactMap { $0 as? MultiSelectSegment } } let stackView = UIStackView() let borderView = UIView() var dividers: [UIView] = [] private func setup() { addConstrainedSubview(borderView, constrain: .top, .bottom, .left, .right) addConstrainedSubview(stackView, constrain: .top, .bottom) constrain(stackView, at: .left, to: borderView, diff: 1) constrain(stackView, at: .right, to: borderView, diff: -1) clipsToBounds = true stackView.distribution = .fillEqually borderWidth = { borderWidth }() borderRadius = { borderRadius }() tintColorDidChange() borderView.isUserInteractionEnabled = false addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTap))) accessibilityIdentifier = "MultiSelectSegmentedControl" } @objc open func didTap(gesture: UITapGestureRecognizer) { let location = gesture.location(in: self) guard let segment = hitTest(location, with: nil) as? MultiSelectSegment else { return } guard let index = segments.firstIndex(of: segment) else { return } perform(animated: true) { if self.allowsMultipleSelection { segment.isSelected.toggle() self.showDividersBetweenSelectedSegments() } else { if segment.isSelected { return } self.selectedSegmentIndex = index } self.sendActions(for: [.valueChanged, .primaryActionTriggered]) self.delegate?.multiSelect(self, didChange: segment.isSelected, at: index) } } // MARK: - Dividers private func showDividersBetweenSelectedSegments() { for i in 0 ..< dividers.count { let isHidden = segments[i].isSelected && segments[i + 1].isSelected dividers[i].alpha = isHidden ? 0 : 1 } } private func insertDivider(afterSegment index: Int) { guard index >= 0 && index < segments.count - 1 else { return } let segment = segments[index] let divider = UIView() divider.backgroundColor = actualTintColor dividers.insert(divider, at: index) addConstrainedSubview(divider) constrainDividerToControl(divider: divider) if isVertical { constrain(divider, at: .top, to: segment, at: .bottom) constrain(divider, at: .bottom, to: segments[index + 1], at: .top) } else { constrain(divider, at: .leading, to: segment, at: .trailing) constrain(divider, at: .trailing, to: segments[index + 1], at: .leading) } } private func removeDivider(at index: Int) { guard index >= 0 && index < dividers.count else { return } dividers[index].removeFromSuperview() dividers.remove(at: index) } private func removeAllDividers() { dividers.forEach { $0.removeFromSuperview() } dividers.removeAll() } private func addAllDividers() { guard dividers.count < segments.count else { return } for i in dividers.count ..< segments.count - 1 { insertDivider(afterSegment: i) } showDividersBetweenSelectedSegments() } private func constrainDividerToControl(divider: UIView) { if isVertical { constrain(divider, at: .left, diff: borderWidth) constrain(divider, at: .right, diff: -borderWidth) } else { constrain(divider, at: .top, diff: borderWidth) constrain(divider, at: .bottom, diff: -borderWidth) } } } extension UIView { func perform(animated: Bool, action: @escaping () -> Void) { if animated { UIView.animate(withDuration: 0.25, animations: action) } else { action() } } } extension UIControl.State: Hashable {}
mit
grogdj/toilet-paper-as-a-service
toilet-app/toilet-app/AppDelegate.swift
1
2156
// // AppDelegate.swift // toilet-app // // Created by Mauricio Salatino on 10/03/2016. // Copyright © 2016 ToiletService. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
contentful-labs/Cube
Scripts/Sync.swift
1
3911
#!/usr/bin/env cato 2.1 /* A script for syncing data between Sphere.IO and Contentful. */ let ContentfulContentTypeId = "F94etMpd2SsI2eSq4QsiG" let ContentfulSphereIOFieldId = "nJpobh9I3Yle0lnN" let ContentfulSpaceId = "jx9s8zvjjls9" let SphereIOProject = "ecomhack-demo-67" import AFNetworking import Alamofire import AppKit import Chores import ContentfulDeliveryAPI import ContentfulManagementAPI import Cube // Note: has to be added manually as a development Pod import ISO8601DateFormatter import Result func env(variable: String) -> String { return NSProcessInfo.processInfo().environment[variable] ?? "" } func key(name: String, project: String = "WatchButton") -> String { return (>["pod", "keys", "get", name, project]).stdout } NSApplicationLoad() let contentfulToken = env("CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN") let contentfulClient = CMAClient(accessToken: contentfulToken) var clientId = env("SPHERE_IO_CLIENT_ID") if clientId == "" { clientId = key("SphereIOClientId") } var clientSecret = env("SPHERE_IO_CLIENT_SECRET") if clientSecret == "" { clientSecret = key("SphereIOClientSecret") } if clientId == "" || clientSecret == "" { print("Missing commercetools credentials, please refer to the README.") exit(1) } let sphereClient = SphereIOClient(clientId: clientId, clientSecret: clientSecret, project: SphereIOProject) extension String { var floatValue: Float { return (self as NSString).floatValue } } func createEntry(space: CMASpace, type: CMAContentType, product: Product, exitAfter: Bool = false) { var fields: [NSObject : AnyObject] = [ ContentfulSphereIOFieldId: [ "en-US": product.identifier ], "name": [ "en-US": product.name ], "productDescription": [ "en-US": product.productDescription ], "price": [ "en-US": (product.price["amount"]!).floatValue ], ] space.createAssetWithTitle([ "en-US": product.name ], description: [ "en-US": product.productDescription ], fileToUpload: [ "en-US": product.imageUrl ], success: { (_, asset) in asset.processWithSuccess(nil, failure: nil) fields["productImage"] = [ "en-US": asset ] space.createEntryOfContentType(type, withFields: fields, success: { (_, entry) in print(entry) if (exitAfter) { exit(0) } }) { (_, error) in print(error) if (exitAfter) { exit(1) } } }) { (_, error) in print(error) } } func handleSpace(space: CMASpace, products: [Product]) { space.fetchEntriesMatching(["content_type": ContentfulContentTypeId], success: { (_, entries) in let importedProductIds = entries.items.map() { $0.fields[ContentfulSphereIOFieldId] as! String } space.fetchContentTypeWithIdentifier(ContentfulContentTypeId, success: { (_, type) in for (index, product) in products.enumerate() { let exitAfter = (index + 1) == products.count if importedProductIds.contains(product.identifier) { if exitAfter { exit(0) } continue } createEntry(space, type: type, product: product, exitAfter: exitAfter) } }) { (_, error) in print(error) } }) { (_, error) in print(error) } } sphereClient.fetchProductData() { (result) in if let value = result.value, results = value["results"] as? [[String:AnyObject]] { let products = results.map { (res) in Product(res) } contentfulClient.fetchSpaceWithIdentifier(ContentfulSpaceId, success: { (_, space) in handleSpace(space, products: products) }) { (_, error) in print(error) } } else { fatalError("Failed to retrieve products from commercetools.") } } NSApp.run()
mit
visenze/visearch-sdk-swift
ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Response/VaEventResponse.swift
1
1424
// // VaEventResponse.swift // ViSenzeAnalytics // // Created by Hung on 9/9/20. // Copyright © 2020 ViSenze. All rights reserved. // import UIKit public class VaEventResponse: NSObject { /// request ID public var reqid: String = "" /// the request status : OK, warning or fail public var status: String = "" public var error: VaError? = nil public init?(data: Data) { super.init() do{ let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any> self.parseJson(json) } catch { print("\(type(of: self)).\(#function)[line:\(#line)] - error: Json response might be invalid. Error during processing:") print ("\(error)\n") return nil } } public func parseJson(_ json: [String : Any]) { if let status = json["status"] as? String { self.status = status } if let errorCode = json["error"] as? [String: Any] { if let error = errorCode["message"] as? String, let code = errorCode["code"] as? Int { self.error = VaError(code: code, message: error) } } if let requestId = json["reqid"] as? String { self.reqid = requestId } } }
mit
davidcairns/DePict
DePictLib/DePictLib/DePict_Internal.swift
1
660
// // DePict_Internal.swift // DePictLib // // Created by David Cairns on 4/16/15. // Copyright (c) 2015 David Cairns. All rights reserved. // import Foundation import CoreGraphics ///: Private internal func colorToCGColor(_ color: Color) -> CGColor { let space = CGColorSpaceCreateDeviceRGB() let components: [CGFloat] = [ CGFloat(color.red), CGFloat(color.green), CGFloat(color.blue), CGFloat(1.0) ] return components.withUnsafeBufferPointer { return CGColor(colorSpace: space, components: $0.baseAddress!)! } } internal func applyPushed(_ context: CGContext, block: () -> ()) { context.saveGState() block() context.restoreGState() }
mit
RylynnLai/V2EX_sf
V2EX/RLTopicContent.swift
1
6235
// // RLTopicContent.swift // V2EX // // Created by LLZ on 16/4/29. // Copyright © 2016年 LLZ. All rights reserved. // import UIKit class RLTopicContent: UIViewController, UITableViewDelegate, UITableViewDataSource { var replyListHeight:CGFloat = 0.0 var tempCell:RLReplyCell? = nil var topicModel:Topic? lazy var replyModels:[Reply] = [Reply]() lazy var replyList:UITableView = { let list = UITableView() list.bounces = false list.scrollEnabled = false list.alpha = 0.0 list.dataSource = self list.delegate = self return list }() private lazy var footer:MJRefreshAutoNormalFooter = { let refleshFooter = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(RLTopicContent.loadRepliesData)) refleshFooter.refreshingTitleHidden = true refleshFooter.stateLabel.textColor = UIColor.lightGrayColor() refleshFooter.stateLabel.alpha = 0.4 refleshFooter.setTitle("点击或上拉显示评论列表", forState: .Idle) return refleshFooter }() @IBOutlet weak var loadingAIV: UIActivityIndicatorView! @IBOutlet weak var authorLable: UILabel! @IBOutlet weak var titleLable: UILabel! @IBOutlet weak var createdTimeLable: UILabel! @IBOutlet weak var authorBtn: UIButton! @IBOutlet weak var replieNumLable: UILabel! @IBOutlet weak var contentWbV: UIWebView! override func viewDidLoad() { super.viewDidLoad() initUI() initData() self.replyList.estimatedRowHeight = 100; } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIView.animateWithDuration(0.1, animations: { [weak self] in if let strongSelf = self { strongSelf.navigationController?.navigationBar.mj_y = 20; } }) } //MARK: -私有方法 private func initUI() { guard (topicModel != nil) else { return } //导航栏标题 self.title = topicModel!.title //帖子内容 let htmlStr = String.HTMLstringWithBody(topicModel!.content_rendered ?? "") contentWbV.loadHTMLString(htmlStr, baseURL: nil) //头像 let iconURL = NSURL.init(string: "https:\(topicModel!.member!.avatar_normal!)") authorBtn.sd_setBackgroundImageWithURL(iconURL, forState: .Normal, placeholderImage: UIImage.init(named: "blank")) //标题 titleLable.text = topicModel!.title titleLable.adjustsFontSizeToFitWidth = true//固定lable大小,内容自适应,还有个固定字体大小,lable自适应的方法sizeToFit //作者名称 authorLable.text = "\(topicModel!.member!.username!) ●" //创建时间 if topicModel!.createdTime != nil { createdTimeLable.text = "\(topicModel!.createdTime!) ●" } else { createdTimeLable.text = String.creatTimeByTimeIntervalSince1970(Double(topicModel!.created!)) } //回复个数 replieNumLable.text = "\(topicModel!.replies!)个回复" } private func initData() { /*这里规则是 *检查数据是否完整,完整就直接显示帖子内容,不重新请求;不完整就发起网络请求,并更新内存缓存保存新的数据 *用户可以手动下拉刷新话题列表刷新或下拉刷新帖子刷新,需要更新缓存数据 */ guard topicModel != nil else { return } if topicModel!.content_rendered == nil { loadingAIV.startAnimating() RLTopicsHelper.shareTopicsHelper.topicWithTopicID(topicModel!.id!, completion: {[weak self] (topic) in if let strongSelf = self { strongSelf.topicModel = topic strongSelf.initUI() } }) } } @objc private func loadRepliesData() { if let topic = topicModel { RLTopicsHelper.shareTopicsHelper.repliesWithTopicID(topic.id!, completion: { [weak self] (replies) in if let strongSelf = self { strongSelf.replyModels = replies if replies.count > 0 { strongSelf.replyList.reloadData() strongSelf.replyList.alpha = 1.0 strongSelf.replyList.mj_h = strongSelf.replyList.contentSize.height let scrollView = strongSelf.view as! UIScrollView scrollView.contentSize = CGSizeMake(strongSelf.contentWbV.frame.maxX, strongSelf.contentWbV.mj_h + 64 + strongSelf.replyList.contentSize.height) strongSelf.footer.setTitle("点击或上拉刷新评论列表", forState: .Idle) } else { strongSelf.footer.setTitle("目前还没有人发表评论", forState: .Idle) } strongSelf.footer.endRefreshing() } }) } } //MARK: - UIWebViewDelegate func webViewDidStartLoad(webView: UIWebView) { loadingAIV.startAnimating() } func webViewDidFinishLoad(webView: UIWebView) { if webView.loading { return } else { loadingAIV.stopAnimating() //根据内容改变webView的高度(有些奇怪,约束不起作用了),webView不可以滑动 webView.mj_h = webView.scrollView.contentSize.height webView.scrollView.scrollEnabled = false //本控制器的scrollView可以滑动,改变contentSize let scrollView = self.view as! UIScrollView scrollView.contentSize = CGSizeMake(webView.frame.maxX, webView.mj_h + 64)//加上导航栏高度+评论列表初始高度 replyList.frame = CGRectMake(0, webView.frame.maxY, webView.frame.maxX, 20) scrollView.addSubview(replyList) //MJRefresh(加载评论,第一次添加footer默认会拉一次数据) scrollView.mj_footer = footer } } }
mit
aunnnn/CreativeSwift
CreativeSwift/Misc/Grid.swift
1
3983
// // Grid.swift // CreativeSwift // // Created by Wirawit Rueopas on 1/21/2560 BE. // Copyright © 2560 Wirawit Rueopas. All rights reserved. // import Foundation /// An abstraction for grid. Useful for getting a frame in grid coordinate. public class Grid { public let nRows: Int public let nCols: Int public let fRows: CGFloat public let fCols: CGFloat private var cachedAllBlocks: [CGRect]? = nil public var targetRect: CGRect { didSet { cachedAllBlocks = nil blockSize = CGSize.init(width: targetRect.width/CGFloat(nRows), height: targetRect.height/CGFloat(nCols)) } } public var targetRectInset: UIEdgeInsets = .zero { didSet { cachedAllBlocks = nil blockSize = CGSize.init(width: (targetRect.width-targetRectInset.left-targetRectInset.right)/CGFloat(nRows), height: (targetRect.height-targetRectInset.top-targetRectInset.bottom)/CGFloat(nCols)) } } /// Cache of block size. Recomputed when targetRect is changed. public private(set) var blockSize: CGSize = .zero public init(rows: Int, cols: Int, targetRect: CGRect = .zero) { if rows <= 0 || cols <= 0 { fatalError("Grid cannot have less than zero rows or cols.") } self.nRows = rows self.nCols = cols self.fRows = CGFloat(rows) self.fCols = CGFloat(cols) self.targetRect = targetRect self.blockSize = CGSize.init(width: targetRect.width/CGFloat(nRows), height: targetRect.height/CGFloat(nCols)) } public func origin(row: Int, col: Int) -> CGPoint { return CGPoint.init(x: targetRect.originX + targetRectInset.left + col.asCGFloat * blockSize.width, y: targetRect.originY + targetRectInset.top + row.asCGFloat * blockSize.height) } /// Is the specified coordinate valid. E.g., is it "in" the grid. public func valid(row: Int, col: Int) -> Bool { return !(row < 0 || col < 0 || row >= nRows || col >= nCols) } /// Return a frame for single block at (row, col). public func block(row: Int, col: Int) -> CGRect { if !valid(row: row, col: col) { return .zero } return CGRect.init(origin: origin(row: row, col: col), size: blockSize) } /// Returns a frame of grid. public func frame(startRow: Int, startCol: Int, endRow: Int, endCol: Int) -> CGRect { if !valid(row: startRow, col: startCol) { return .zero } if !valid(row: endRow, col: endCol) { return .zero } if endRow < startRow || endCol < startCol { return .zero } let o = origin(row: startRow, col: startCol) let size = CGSize.init(width: blockSize.width * (endCol-startCol+1).asCGFloat, height: blockSize.height * (endRow-startRow+1).asCGFloat) return CGRect.init(origin: o, size: size) } /// Returns a frame of 'row'. public func row(_ row: Int, startCol: Int?=nil, endCol: Int?=nil) -> CGRect { let c1 = startCol ?? 0 let c2 = endCol ?? (nCols - 1) return frame(startRow: row, startCol: c1, endRow: row, endCol: c2) } /// Returns a frame of entire column. public func col(_ col: Int, startRow: Int?=nil, endRow: Int?=nil) -> CGRect { let r1 = startRow ?? 0 let r2 = endRow ?? nRows - 1 return frame(startRow: r1, startCol: col, endRow: r2, endCol: col) } /// Returns all blocks for this grid. It is cached and invalidated automatically. public func allBlocks() -> [CGRect] { if let cached = cachedAllBlocks { return cached } var res: [CGRect] = [CGRect].init(repeating: .zero, count: nRows * nCols) for i in 0..<nRows { for j in 0..<nCols { res[i*(nCols) + j] = block(row: i, col: j) } } // cache if nil cachedAllBlocks = res return res } }
mit
hughbe/ui-components
src/MenuDisabled/MenuDisabledTextField.swift
1
1016
// // MenuDisabledTextField.swift // UIComponents // // Created by Hugh Bellamy on 05/09/2015. // Copyright (c) 2015 Hugh Bellamy. All rights reserved. // @IBDesignable public class MenuDisabledTextField: UITextField { @IBInspectable public var menuEnabled: Bool = false @IBInspectable public var canPositionCaretAtStart: Bool = true @IBInspectable public var editingRectDeltaY: CGFloat = 0 public override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { return menuEnabled } public override func caretRectForPosition(position: UITextPosition) -> CGRect { if (position == beginningOfDocument && !canPositionCaretAtStart) { return super.caretRectForPosition(positionFromPosition(position, offset: 1)!) } return super.caretRectForPosition(position) } public override func editingRectForBounds(bounds: CGRect) -> CGRect { return bounds.insetBy(dx: 0, dy: editingRectDeltaY) } }
mit
ftp27/FTSegmentedControl
Example/FTSegmentedControl-Example/AppDelegate.swift
1
2194
// // AppDelegate.swift // FTSegmentedControl-Example // // Created by ftp27 on 10/12/2016. // Copyright © 2016 Aleksey Cherepanov. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
LynxTipSoftware/BTHeartrate
BTHeartRate/BluetoothManagerProtocol.swift
1
304
// // BluetoothManagerProtocol.swift // BTHeartRate // // Created on 4/18/16. // Copyright © 2016 LynxTip Software. All rights reserved. // import CoreBluetooth import Foundation import RxSwift protocol BluetoothManagerProtocol { var bluetoothState: Variable<BluetoothState> { get } }
mit
AbelSu131/ios-charts
Charts/Classes/Charts/BarChartView.swift
2
11668
// // BarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// Chart that draws bars. public class BarChartView: BarLineChartViewBase, BarChartRendererDelegate { /// flag that enables or disables the highlighting arrow private var _drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top private var _drawValueAboveBarEnabled = true /// if set to true, all values of a stack are drawn individually, and not just their sum private var _drawValuesForWholeStackEnabled = true /// if set to true, a grey area is darawn behind each bar that indicates the maximum value private var _drawBarShadowEnabled = false internal override func initialize() { super.initialize(); renderer = BarChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler); _xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self); _chartXMin = -0.5; } internal override func calcMinMax() { super.calcMinMax(); if (_data === nil) { return; } var barData = _data as! BarChartData; // increase deltax by 1 because the bars have a width of 1 _deltaX += 0.5; // extend xDelta to make space for multiple datasets (if ther are one) _deltaX *= CGFloat(_data.dataSetCount); var maxEntry = 0; for (var i = 0, count = barData.dataSetCount; i < count; i++) { var set = barData.getDataSetByIndex(i); if (maxEntry < set!.entryCount) { maxEntry = set!.entryCount; } } var groupSpace = barData.groupSpace; _deltaX += CGFloat(maxEntry) * groupSpace; _chartXMax = Double(_deltaX) - _chartXMin; } /// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart. public override func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight! { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set."); return nil; } _leftAxisTransformer.pixelToValue(&pt); if (pt.x < CGFloat(_chartXMin) || pt.x > CGFloat(_chartXMax)) { return nil; } return getHighlight(xPosition: pt.x, yPosition: pt.y); } /// Returns the correct Highlight object (including xIndex and dataSet-index) for the specified touch position. internal func getHighlight(#xPosition: CGFloat, yPosition: CGFloat) -> ChartHighlight! { if (_dataNotSet || _data === nil) { return nil; } var barData = _data as! BarChartData!; var setCount = barData.dataSetCount; var valCount = barData.xValCount; var dataSetIndex = 0; var xIndex = 0; if (!barData.isGrouped) { // only one dataset exists xIndex = Int(round(xPosition)); // check bounds if (xIndex < 0) { xIndex = 0; } else if (xIndex >= valCount) { xIndex = valCount - 1; } } else { // if this bardata is grouped into more datasets // calculate how often the group-space appears var steps = Int(xPosition / (CGFloat(setCount) + CGFloat(barData.groupSpace))); var groupSpaceSum = barData.groupSpace * CGFloat(steps); var baseNoSpace = xPosition - groupSpaceSum; dataSetIndex = Int(baseNoSpace) % setCount; xIndex = Int(baseNoSpace) / setCount; // check bounds if (xIndex < 0) { xIndex = 0; dataSetIndex = 0; } else if (xIndex >= valCount) { xIndex = valCount - 1; dataSetIndex = setCount - 1; } // check bounds if (dataSetIndex < 0) { dataSetIndex = 0; } else if (dataSetIndex >= setCount) { dataSetIndex = setCount - 1; } } var dataSet = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet!; if (!dataSet.isStacked) { return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex); } else { return getStackedHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, yValue: Double(yPosition)); } } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. internal func getStackedHighlight(#xIndex: Int, dataSetIndex: Int, yValue: Double) -> ChartHighlight! { var dataSet = _data.getDataSetByIndex(dataSetIndex); var entry = dataSet.entryForXIndex(xIndex) as! BarChartDataEntry!; if (entry !== nil) { var stackIndex = entry.getClosestIndexAbove(yValue); return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex); } else { return nil; } } /// Returns the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data. public func getBarBounds(e: BarChartDataEntry) -> CGRect! { var set = _data.getDataSetForEntry(e) as! BarChartDataSet!; if (set === nil) { return nil; } var barspace = set.barSpace; var y = CGFloat(e.value); var x = CGFloat(e.xIndex); var barWidth: CGFloat = 0.5; var spaceHalf = barspace / 2.0; var left = x - barWidth + spaceHalf; var right = x + barWidth - spaceHalf; var top = y >= 0.0 ? y : 0.0; var bottom = y <= 0.0 ? y : 0.0; var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top); getTransformer(set.axisDependency).rectValueToPixel(&bounds); return bounds; } public override var lowestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int((pt.x <= CGFloat(chartXMin)) ? 0.0 : (pt.x / div) + 1.0); } public override var highestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div)); } // MARK: Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return _drawHighlightArrowEnabled; } set { _drawHighlightArrowEnabled = newValue; setNeedsDisplay(); } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return _drawValueAboveBarEnabled; } set { _drawValueAboveBarEnabled = newValue; setNeedsDisplay(); } } /// if set to true, all values of a stack are drawn individually, and not just their sum public var drawValuesForWholeStackEnabled: Bool { get { return _drawValuesForWholeStackEnabled; } set { _drawValuesForWholeStackEnabled = newValue; setNeedsDisplay(); } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return _drawBarShadowEnabled; } set { _drawBarShadowEnabled = newValue; setNeedsDisplay(); } } /// returns true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// returns true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// returns true if all values of a stack are drawn, and not just their sum public var isDrawValuesForWholeStackEnabled: Bool { return drawValuesForWholeStackEnabled; } /// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } // MARK: - BarChartRendererDelegate public func barChartRendererData(renderer: BarChartRenderer) -> BarChartData! { return _data as! BarChartData!; } public func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return getTransformer(which); } public func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int { return maxVisibleValueCount; } public func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter! { return valueFormatter; } public func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double { return chartYMax; } public func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double { return chartYMin; } public func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double { return chartXMax; } public func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double { return chartXMin; } public func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool { return drawHighlightArrowEnabled; } public func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool { return drawValueAboveBarEnabled; } public func barChartIsDrawValuesForWholeStackEnabled(renderer: BarChartRenderer) -> Bool { return drawValuesForWholeStackEnabled; } public func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool { return drawBarShadowEnabled; } public func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted; } }
apache-2.0
drewcrawford/DCAKit
DCAKit/Foundation Additions/KVOHelp.swift
1
7179
// // KVOHelp.swift // DCAKit // // Created by Drew Crawford on 4/9/15. // Copyright (c) 2015 DrewCrawfordApps. // This file is part of DCAKit. It is subject to the license terms in the LICENSE // file found in the top level of this distribution and at // https://github.com/drewcrawford/DCAKit/blob/master/LICENSE. // No part of DCAKit, including this file, may be copied, modified, // propagated, or distributed except according to the terms contained // in the LICENSE file. import Foundation private struct ObserversMap { /** [observed : [String : [KVOHelpObserver]]]] */ private static var map = NSMapTable.weakToStrongObjectsMapTable() private static func KVOHelpsForPair(#observed: NSObject, keyPath: String) -> [KVOHelpObserver] { if let o = ObserversMap.map.objectForKey(observed) as? [String: [KVOHelpObserver]] { if o[keyPath] != nil { return o[keyPath]! } } return [] } private static func KVOHelpForTriple(#observed: NSObject, keyPath: String, referenceObject: AnyObject) -> KVOHelpObserver? { let haystack = KVOHelpsForPair(observed: observed, keyPath: keyPath) for needle in haystack { if needle.referenceObject === referenceObject { return needle } } return nil } private static func setNewHelps(#helps: [KVOHelpObserver], observed: NSObject, keyPath: String, referenceObject: AnyObject) { var newStringMap = ObserversMap.map.objectForKey(observed) as? [String: [KVOHelpObserver]] ?? [:] as [String: [KVOHelpObserver]] newStringMap[keyPath] = helps map.setObject(newStringMap, forKey: observed) } private static func setKVOHelpForTriple(#newHelp: KVOHelpObserver, observed: NSObject, keyPath: String, referenceObject: AnyObject) { removeKVOHelpForTriple(observed: observed, keyPath: keyPath, referenceObject: referenceObject) var helps = KVOHelpsForPair(observed: observed, keyPath: keyPath) helps.append(newHelp) setNewHelps(helps: helps, observed: observed, keyPath: keyPath, referenceObject: referenceObject) } /**Removes the KVOHelp for the given triple. :note: This function does remove the KVOHelp from the KVO system itself, unlike the other functions, which do not really interact with the KVO system. */ private static func removeKVOHelpForTriple(#observed: NSObject, keyPath: String, referenceObject: AnyObject) { var haystack = KVOHelpsForPair(observed: observed, keyPath: keyPath) for (i, needle) in enumerate(haystack) { if needle.referenceObject === referenceObject { observed.removeObserver(needle, forKeyPath: keyPath) haystack.removeAtIndex(i) break } } setNewHelps(helps: haystack, observed: observed, keyPath: keyPath, referenceObject: referenceObject) } } public typealias KVOHelpClosureType = (keyPath: String, observedObject: AnyObject, change: [NSObject: AnyObject], context: AnyObject?) -> () class KVOHelpObserver : NSObject { private weak var referenceObject : AnyObject? = nil private let keyPath : String private let closure: KVOHelpClosureType private let strongContext : AnyObject? init(referenceObject: AnyObject, keyPath: String, context: AnyObject?, closure: KVOHelpClosureType) { self.keyPath = keyPath self.referenceObject = referenceObject self.closure = closure self.strongContext = context } private static var danglingSelf : KVOHelpObserver? = nil override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if referenceObject == nil { //I theorize that there is some problem here where the line below //causes self to be released. //solution: create a random dangling reference to self! KVOHelpObserver.danglingSelf = self object.removeObserver(self, forKeyPath: keyPath) //eventually, we'll clean it up dispatch_after(interval: 0.01, dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), { () -> Void in KVOHelpObserver.danglingSelf = nil }) return } closure(keyPath: keyPath, observedObject: object, change: change, context: strongContext) } } public extension NSObject { /** Blocks-based KVO. :param: referenceObject a reference object, typically self. When this object gets deallocated, the observer is automatically cleaned up. :param: keyPath the key path to observe :param: options. See the documentation for KVO :param: context. An arbitrary object passed to the block. A strong pointer to the context is acquired, so choose carefully. :param: closure a closure to run to be notified about changes. You want this to be weak/unowned self. :note: Only one (observed, observer, key) triple is allowed at a time. If you try to create a new one, we will replace the existing one. */ @availability(*, deprecated=8.1,renamed="beginObservingValue") public func addObserver(#referenceObject: AnyObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: AnyObject?, closure: KVOHelpClosureType) { let kvoObserver = KVOHelpObserver(referenceObject: referenceObject, keyPath: keyPath, context: context, closure: closure) ObserversMap.setKVOHelpForTriple(newHelp: kvoObserver, observed: self, keyPath: keyPath, referenceObject: referenceObject) self.addObserver(kvoObserver, forKeyPath: keyPath, options: options, context:nil) } /** Blocks-based KVO. A variant with no referenceObject. In this case you must manually remove the observer. :param: referenceObject a reference object, typically self. When this object gets deallocated, the observer is automatically cleaned up. :param: keyPath the key path to observe :param: options. See the documentation for KVO :param: context. An arbitrary object passed to the block. A strong pointer to the context is acquired, so choose carefully. :param: closure a closure to run to be notified about changes. You want this to be weak/unowned self. :note: Only one (observed, observer, key) triple is allowed at a time. If you try to create a new one, we will replace the existing one. */ @availability(*, deprecated=8.1,renamed="beginObservingValue") public func addObserver(forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: AnyObject?, closure: KVOHelpClosureType) { self.addObserver(referenceObject: NSNull(), forKeyPath: keyPath, options: options, context: context, closure: closure) } @availability(*, deprecated=8.1) public func removeObserver(#referenceObject: AnyObject, forKeyPath keyPath: String) { let object = ObserversMap.KVOHelpForTriple(observed: self, keyPath: keyPath, referenceObject: referenceObject)! self.removeObserver(object, forKeyPath: keyPath) } }
mit
alfishe/mooshimeter-osx
mooshimeter-osx/UI/Views/LargeIndicatorView.swift
1
1030
// // LargeIndicator.swift // mooshimeter-osx // // Created by Dev on 5/24/17. // Copyright © 2017 alfishe. All rights reserved. // import Cocoa import QuartzCore @IBDesignable class LargeIndicatorView: NSView { @IBOutlet weak var lblMode: NSTextField! @IBOutlet weak var lblSign: NSTextField! @IBOutlet weak var lblValue: NSTextField! required init(coder: NSCoder) { super.init(coder: coder)! var topLevelObjects: NSArray? = nil var view: NSView? = nil let frameworkBundle = Bundle(for: classForCoder) if frameworkBundle.loadNibNamed("LargeIndicatorView", owner: self, topLevelObjects: &topLevelObjects) { view = topLevelObjects!.first(where: { $0 is NSView }) as? NSView } // Use bounds not frame or it'll be offset view?.frame = bounds // Make the view stretch with containing view view?.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] if view != nil { self.addSubview(view!) } } }
mit
Yalantis/AppearanceNavigationController
AppearanceNavigationController/RootViewController.swift
1
1501
import UIKit class RootViewController: UITableViewController, NavigationControllerAppearanceContext { private let values: [Appearance] = (0..<10).map { _ in Appearance.random() } // mark: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return values.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! // fine for sample app let appearance = values[indexPath.row] cell.contentView.backgroundColor = appearance.navigationBar.backgroundColor cell.textLabel?.textColor = appearance.navigationBar.tintColor cell.textLabel?.text = "Sample #\(indexPath.row + 1)" cell.textLabel?.backgroundColor = .clear return cell } // mark: - AppearanceNavigationControllerContext func preferredAppearance(for navigationController: UINavigationController) -> Appearance? { return Appearance.lightAppearance } // mark: - Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UITableViewCell, let target = segue.destination as? ContentViewController, let index = tableView.indexPath(for: cell)?.row { target.appearance = values[index] } } }
mit
russelhampton05/MenMew
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/MessageManager.swift
1
1596
// // MessageManager.swift // App_Prototype_Alpha_001 // // Created by russel w h on 11/5/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import Foundation import Firebase class MessageManager { //This class handles ticket statuses that the app UI can use to display and update //order information for each table. static let ref = FIRDatabase.database().reference().child("Messages") static func WriteServerMessage(id: String, message: String) { ref.child(id).child("server").setValue(message) } static func WriteUserMessage(id: String, message: String) { ref.child(id).child("user").setValue(message) } //this is ok as async static func CreateTicketAsync(id: String){ ref.child(id).child("user").setValue("nil") ref.child(id).child("server").setValue("nil") } // the messageRef should really be FIRDatabase.databae().reference().child("Messages").child(ticket.message_ID) //but this would have to be updated everytime a new ticket is attached to the user. //if that ends up being too hard you can just do it this way //FIRDatabase.databae().reference().child("Messages") // refHandle = messageRef.observe(FIRDataEventType.value, with: { (snapshot) in // let postDict = snapshot.value as! [String : AnyObject] // // only one string at a time is ever in the db and it's the latest one sent // you can choose to add those strings to an array on the controller if you want to keep track of them // ping the UInotification here // }) }
mit
octo-technology/IQKeyboardManager
Demo/Swift_Demo/ViewController/SpecialCaseViewController.swift
1
4695
// // SpecialCaseViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKit class CustomSubclassView : UIScrollView {} class SpecialCaseViewController: UIViewController, UISearchBarDelegate, UITextFieldDelegate, UITextViewDelegate { @IBOutlet private var customWorkTextField : UITextField! @IBOutlet private var textField6 : UITextField! @IBOutlet private var textField7 : UITextField! @IBOutlet private var textField8 : UITextField! @IBOutlet private var switchInteraction1 : UISwitch! @IBOutlet private var switchInteraction2 : UISwitch! @IBOutlet private var switchInteraction3 : UISwitch! @IBOutlet private var switchEnabled1 : UISwitch! @IBOutlet private var switchEnabled2 : UISwitch! @IBOutlet private var switchEnabled3 : UISwitch! override func viewDidLoad() { super.viewDidLoad() textField6.userInteractionEnabled = switchInteraction1.on textField7.userInteractionEnabled = switchInteraction2.on textField8.userInteractionEnabled = switchInteraction3.on textField6.enabled = switchEnabled1.on textField7.enabled = switchEnabled2.on textField8.enabled = switchEnabled3.on updateUI() IQKeyboardManager.sharedManager().considerToolbarPreviousNextInViewClass(CustomSubclassView) } @IBAction func showAlertClicked (barButton : UIBarButtonItem!) { let alertView : UIAlertView = UIAlertView(title: "IQKeyboardManager", message: "It doesn't affect UIAlertView (Doesn't add IQToolbar on it's textField", delegate: nil, cancelButtonTitle: "OK") alertView.alertViewStyle = UIAlertViewStyle.LoginAndPasswordInput alertView.show() } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func updateUI() { textField6.placeholder = (textField6.enabled ? "enabled" : "" ) + "," + (textField6.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField7.placeholder = (textField7.enabled ? "enabled" : "" ) + "," + (textField7.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField8.placeholder = (textField8.enabled ? "enabled" : "" ) + "," + (textField8.userInteractionEnabled ? "userInteractionEnabled" : "" ) } func switch1UserInteractionAction(sender: UISwitch) { textField6.userInteractionEnabled = sender.on updateUI() } func switch2UserInteractionAction(sender: UISwitch) { textField7.userInteractionEnabled = sender.on updateUI() } func switch3UserInteractionAction(sender: UISwitch) { textField8.userInteractionEnabled = sender.on updateUI() } func switch1Action(sender: UISwitch) { textField6.enabled = sender.on updateUI() } func switch2Action(sender: UISwitch) { textField7.enabled = sender.on updateUI() } func switch3Action(sender: UISwitch) { textField8.enabled = sender.on updateUI() } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if (textField == customWorkTextField) { if(textField.isAskingCanBecomeFirstResponder == false) { let alertView : UIAlertView = UIAlertView(title: "IQKeyboardManager", message: "Do your custom work here", delegate: nil, cancelButtonTitle: "OK") alertView.show() } return false } else { return true } } func textFieldDidBeginEditing(textField: UITextField) { switchEnabled1.enabled = false switchEnabled2.enabled = false switchEnabled3.enabled = false switchInteraction1.enabled = false switchInteraction2.enabled = false switchInteraction3.enabled = false } func textFieldDidEndEditing(textField: UITextField) { switchEnabled1.enabled = true switchEnabled2.enabled = true switchEnabled3.enabled = true switchInteraction1.enabled = true switchInteraction2.enabled = true switchInteraction3.enabled = true } override func shouldAutorotate() -> Bool { return true } }
mit
andychase/classwork
cs496/final/finalProject/ListViewController.swift
1
1213
// // FirstViewController.swift // finalProject // // Created by Andy Chase on 12/5/15. // Copyright © 2015 Andy Chase. All rights reserved. // import UIKit class ListViewController: UIViewController { var userId:String! var listType:Bool! var dataSource:ListModel! @IBOutlet var table: UITableView! @IBOutlet weak var inputField: UITextField! override func viewDidLoad() { self.dataSource = ListModel( table: table, isGlobalListType: self.restorationIdentifier == "globalList", userId: userId ) table.dataSource = self.dataSource table.delegate = self.dataSource } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.dataSource!.loadRows() } override func viewDidAppear(animated: Bool) { table.setEditing(true, animated: true) } @IBAction func addButtonPress(sender: AnyObject) { if let text = inputField.text { if text != "" { self.dataSource.addItem(text) self.dataSource.saveRows() inputField.text = "" } } } }
mit
jbruce2112/cutlines
Cutlines/AppDelegate.swift
1
4328
// // AppDelegate.swift // Cutlines // // Created by John on 1/30/17. // Copyright © 2017 Bruce32. All rights reserved. // import CloudKit import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let photoManager = PhotoManager() private var tabBarController: UITabBarController? private var navigationControllers: [UINavigationController]? private var collectionViewController: CollectionViewController? private var searchViewController: SearchViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { tabBarController = window!.rootViewController as? UITabBarController navigationControllers = tabBarController?.viewControllers as? [UINavigationController] collectionViewController = navigationControllers?.first?.viewControllers.first as? CollectionViewController searchViewController = navigationControllers?[1].viewControllers.first as? SearchViewController // Inject the manager into the initial view controllers collectionViewController?.photoManager = photoManager searchViewController?.photoManager = photoManager // Handle updating the network indicator in the status bar photoManager.cloudManager.networkStatusDelegate = self // Tell the photo manager to set everything up // required for cloud communication, syncing and storage photoManager.setup() // Listen for push events application.registerForRemoteNotifications() // Set initial theme setTheme() return true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { guard let dict = userInfo as? [String: NSObject], let notification = CKNotification(fromRemoteNotificationDictionary: dict), notification.subscriptionID == photoManager.cloudManager.subscriptionID else { completionHandler(.noData) return } photoManager.cloudManager.fetchChanges { completionHandler(UIBackgroundFetchResult.newData) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { log("Failed to register for notifications with \(error)") } 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. photoManager.cloudManager.saveSyncState() searchViewController?.saveRecent() } 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. collectionViewController?.refresh() } func setTheme() { // We're settings these properties in the AppDelegate since it already knows // about the navigation and tab controllers, and we don't currently have any // custom classes to implement their own viewWillAppear()/setTheme() behavior tabBarController?.tabBar.setTheme() for controller in navigationControllers ?? [] { controller.navigationBar.setTheme() } } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { completionHandler(quickAction(for: shortcutItem)) } private func quickAction(for shortcutItem: UIApplicationShortcutItem) -> Bool { let name = shortcutItem.type.components(separatedBy: ".").last! if name == "Search" { tabBarController?.selectedIndex = 1 return true } return false } } // MARK: NetworkStatusDelegate conformance extension AppDelegate: NetworkStatusDelegate { func statusChanged(busy: Bool) { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = busy } } }
mit
charmaex/JDTransition
JDTransition/JDAnimationScale.swift
1
1606
// // JDAnimationScale.swift // JDTransition // // Created by Jan Dammshäuser on 26.09.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import Foundation struct JDAnimationScale { static func out(inWindow window: UIView, fromVC: UIViewController, toVC: UIViewController, duration: TimeInterval, options opt: UIViewAnimationOptions?, completion: @escaping (Bool) -> Void) { window.addSubview(toVC.view) window.sendSubview(toBack: toVC.view) toVC.view.frame = fromVC.view.frame let options = opt ?? .curveEaseOut UIView.animate(withDuration: duration, delay: 0, options: options, animations: { fromVC.view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05) }) { finished in completion(finished) fromVC.view.transform = CGAffineTransform(scaleX: 1, y: 1) } } static func `in`(inWindow window: UIView, fromVC: UIViewController, toVC: UIViewController, duration: TimeInterval, options opt: UIViewAnimationOptions?, completion: @escaping (Bool) -> Void) { window.addSubview(toVC.view) toVC.view.frame = fromVC.view.frame let destCenter = fromVC.view.center let options = opt ?? .curveEaseIn toVC.view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05) UIView.animate(withDuration: duration, delay: 0, options: options, animations: { toVC.view.transform = CGAffineTransform(scaleX: 1, y: 1) toVC.view.center = destCenter }) { finished in completion(finished) } } }
mit
google/android-auto-companion-ios
Tests/AndroidAutoConnectedDeviceManagerTests/PListLoaderFake.swift
1
1032
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation @testable import AndroidAutoConnectedDeviceManager /// A fake `PListLoader` that simply returns the overlay config that is set on it. /// /// The overlay config can also be set after it has been created. struct PListLoaderFake: PListLoader { var overlay: Overlay init(overlayValues: [String: Any] = [:]) { self.overlay = Overlay(overlayValues) } func loadOverlayValues() -> Overlay { return overlay } }
apache-2.0
Xinext/RemainderCalc
src/RemainderCalc/MainViewController.swift
1
24507
// // MainViewController.swift // RemainderCalc // import UIKit import AVFoundation class MainViewController: UIViewController { // MARK: - IBOutlet @IBOutlet weak var outletMainContentsView: UIView! @IBOutlet weak var outletMainContentsBottomLayoutConstraint: NSLayoutConstraint! // タイトルエリア @IBOutlet weak var outletNavigationItem: UINavigationItem! // アプリタイトル @IBOutlet weak var outletHistoryButton: UIBarButtonItem! // 履歴ボタン @IBOutlet weak var outletPreferenceButton: UIBarButtonItem! // 設定ボタン // 表示エリア @IBOutlet weak var outletInputValueLabel: XIPaddingLabel! // 入力値テキストラベル @IBOutlet weak var outletExpressionLabel: XIPaddingLabel! // 式タイトルラベル @IBOutlet weak var outletExpressionValueLabel: XIPaddingLabel! // 式テキストラベル @IBOutlet weak var outletAnswerLabel: XIPaddingLabel! // 答えタイトルラベル @IBOutlet weak var outletAnswerValueLabel: XIPaddingLabel! // 答えテキストラベル @IBOutlet weak var outletDecimalPointTitleLabel: XIPaddingLabel! // 小数点位置タイトルラベル @IBOutlet weak var outletDecimalPointDownButton: XIPaddingButton! // 小数点Downボタン @IBOutlet weak var outletDecimalPointValueLabel: XIPaddingLabel! // 小数点位置テキスト @IBOutlet weak var outletDecimalPointUpButton: XIPaddingButton! // 小数点Upボタン // 入力エリア @IBOutlet weak var outletKey0Button: XIPaddingButton! // 0キーボタン @IBOutlet weak var outletKey00Button: XIPaddingButton! // 00キーボタン @IBOutlet weak var outletKey1Button: XIPaddingButton! // 1キーボタン @IBOutlet weak var outletKey2Button: XIPaddingButton! // 2キーボタン @IBOutlet weak var outletKey3Button: XIPaddingButton! // 3キーボタン @IBOutlet weak var outletKey4Button: XIPaddingButton! // 4キーボタン @IBOutlet weak var outletKey5Button: XIPaddingButton! // 5キーボタン @IBOutlet weak var outletKey6Button: XIPaddingButton! // 6キーボタン @IBOutlet weak var outletKey7Button: XIPaddingButton! // 7キーボタン @IBOutlet weak var outletKey8Button: XIPaddingButton! // 8キーボタン @IBOutlet weak var outletKey9Button: XIPaddingButton! // 9キーボタン @IBOutlet weak var outletKeyDotButton: XIPaddingButton! // 小数点キーボタン @IBOutlet weak var outletKeyACButton: XIPaddingButton! // AC(All Clear)キーボタン @IBOutlet weak var outletKeyBSButton: XIPaddingButton! // BS(Back space)キーボタン @IBOutlet weak var outletKeyDivideButton: XIPaddingButton! // ÷キーボタン @IBOutlet weak var outletKeyEqualButton: XIPaddingButton! // =キーボタン // MARK: - Private variable private var adMgr = AdModMgr() private var firstAppear: Bool = false var seTapButtonAudio : AVAudioPlayer! = nil // MARK: - ViewController Override override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // 表示アイテムの初期化 initEachItem() // 表示アイテムのローカライズ localizeEachItem() // SE(効果音)の初期化 initSEAudio() // 広告マネージャーの初期化 adMgr.InitManager(pvc:self, cv:outletMainContentsView, lc: outletMainContentsBottomLayoutConstraint) } /** Viewが表示される直前に呼び出されるイベントハンドラー */ override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 最初に表示される時の処理 if (firstAppear != true) { outletMainContentsView.isHidden = true // メインコンテンツの準備ができるまで非表示 } } /** Viewが表示された直後に呼び出されるイベントハンドラー */ override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 最初に表示される時の処理 if (firstAppear != true) { procStateMgr(.INIT) // メインコンテンツを初期化 outletMainContentsView.isHidden = false // メインコンテンツの準備が完了したので表示 adMgr.DispAdView(pos: AdModMgr.DISP_POSITION.BOTTOM) // 広告の表示 firstAppear = true } } /** メモリー警告 */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** initialize each item */ private func initEachItem() { // Navibar right button outletPreferenceButton.width = 0 let settingIcon = UIImage(named: "icon_preference")?.ResizeUIImage(width: 20, height: 20) outletPreferenceButton.image = settingIcon } /** localize each item */ private func localizeEachItem() { outletNavigationItem.title = NSLocalizedString("STR_MAIN_VIEW_TITLE", comment: "") outletHistoryButton.title = NSLocalizedString("STR_MAIN_HISTORY_BUTTON", comment: "") outletPreferenceButton.title = "" outletExpressionLabel.text = NSLocalizedString("STR_MAIN_EXP_LABEL", comment: "") outletAnswerLabel.text = NSLocalizedString("STR_MAIN_ANS_LABEL", comment: "") outletDecimalPointTitleLabel.text = NSLocalizedString("STR_MAIN_DECPOS_LABEL", comment: "") } /** initialize each se audio */ private func initSEAudio() { // for Tap the button let soundFilePath = Bundle.main.path(forResource: "SE_TapButton", ofType: "mp3")! let sound:URL = URL(fileURLWithPath: soundFilePath) // AVAudioPlayerのインスタンスを作成 do { seTapButtonAudio = try AVAudioPlayer(contentsOf: sound, fileTypeHint:nil) } catch { seTapButtonAudio = nil print("AVAudioPlayerインスタンス作成失敗") } // バッファに保持していつでも再生できるようにする seTapButtonAudio.prepareToPlay() } // MARK: - Action method /** [Action] 小数点位置ダウンボタン 押下 */ @IBAction func Action_DecimalPointDownButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DECPOS_DOWN) } /** [Action] 小数点位置アップボタン 押下 */ @IBAction func Action_DecimalPointUpButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DECPOS_UP) } /** [Action] 0ボタン 押下 */ @IBAction func Action_Key0Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 0 as AnyObject) } /** [Action] 00ボタン 押下 */ @IBAction func Action_Key00Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 0 as AnyObject) procStateMgr(.TAP_NUM, 0 as AnyObject) } /** [Action] 1ボタン 押下 */ @IBAction func Action_Key1Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 1 as AnyObject) } /** [Action] 2ボタン 押下 */ @IBAction func Action_Key2Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 2 as AnyObject) } /** [Action] 3ボタン 押下 */ @IBAction func Action_Key3Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 3 as AnyObject) } /** [Action] 4ボタン 押下 */ @IBAction func Action_Key4Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 4 as AnyObject) } /** [Action] 5ボタン 押下 */ @IBAction func Action_Key5Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 5 as AnyObject) } /** [Action] 6ボタン 押下 */ @IBAction func Action_Key6Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 6 as AnyObject) } /** [Action] 7ボタン 押下 */ @IBAction func Action_Key7Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 7 as AnyObject) } /** [Action] 8ボタン 押下 */ @IBAction func Action_Key8Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 8 as AnyObject) } /** [Action] 9ボタン 押下 */ @IBAction func Action_Key9Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 9 as AnyObject) } /** [Action] ACボタン 押下 */ @IBAction func Action_KeyACButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_AC) } /** [Action] 小数点ボタン 押下 */ @IBAction func Action_DotButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DP) } /** [Action] BSボタン 押下 */ @IBAction func Action_KeyBSButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_BS) } /** [Action] ÷ボタン 押下 */ @IBAction func Action_KeyDivideButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DIV) } /** [Action] =ボタン 押下 */ @IBAction func Action_KeyEqualButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_EQ) } // MARK: - State Procedure // MARK: - State Procedure (変数・定義) /** ステート定義 */ private enum PROC_STATE { case WAIT_DIVIDEND // 割られる値入力待ち 状態 (IDLE) case WAIT_DIVISOR // 割る値入力待ち 状態 case VIEW_ANSWER // 答え表示 状態 case MAXNUM // イリーガル状態チェック用 } private var procState: PROC_STATE = PROC_STATE.WAIT_DIVIDEND /** イベント定義 */ private enum PROC_EVENT { case INIT // 初期化 case TAP_DECPOS_UP // 小数点位置Upボタン押下 case TAP_DECPOS_DOWN // 小数点位置Downボタン押下 case TAP_NUM // 数字ボタン(0,00,1,2,3,4,5,6,7,8,9)押下 case TAP_DP // 小数点ボタン case TAP_AC // ACボタン押下 case TAP_BS // ←ボタン押下 case TAP_DIV // ÷ボタン押下 case TAP_EQ // =ボタン押下 case MAXNUM // イリーガルイベントチェック用 } /** あまり割算計算マネージャー */ private let remCalcMgr = RemainderCalculationManager() // MARK: - State Procedure (ステートマネージャー処理) /** Initialization of processing - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procStateMgr( _ event: PROC_EVENT, _ param: AnyObject? = nil) { // The common event processing for all state. switch event { case .INIT: // Viewの初期化 initConfigOfEachView() localizeEachItem() remCalcMgr.SetDecimalPosition(AppPreference.GetDecimalPoint()) initStateMgr() case .TAP_AC: playTapButtonSound() initStateMgr() default: // no action break; } // Event driven processing switch procState { case .WAIT_DIVIDEND: procstatemgr_Evt_WaitDividend( event, param: param ) case .WAIT_DIVISOR: procstatemgr_Evt_WaitDivisor( event, param: param ) case .VIEW_ANSWER: procstatemgr_Evt_ViewAnswer( event, param: param ) default: // Illegal state initStateMgr() break; } // State driven processing changeViewItemColorForState(state: procState) } /** [Event Driven] State: Wait dividend - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procstatemgr_Evt_WaitDividend( _ event: PROC_EVENT, param: AnyObject?) { switch event { case .INIT: // common processing event break case .TAP_DECPOS_UP: evt_TAP_DECPOS_UP() case .TAP_DECPOS_DOWN: evt_TAP_DECPOS_DOWN() case .TAP_NUM: evt_TAP_NUM(param as! Int) break case .TAP_DP: evt_TAP_DP() break case .TAP_AC: // common processing event // common processing event break case .TAP_BS: evt_TAP_BS() break case .TAP_DIV: playTapButtonSound() remCalcMgr.DecideDividend() updateTextInDisplayArea() procState = .WAIT_DIVISOR break case .TAP_EQ: // ignore break default: // Illegal event evt_ErrorHandling() procState = .WAIT_DIVIDEND break; } } /** [Event Driven] State: Wait divisor - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procstatemgr_Evt_WaitDivisor( _ event: PROC_EVENT, param: AnyObject?) { switch event { case .INIT: // common processing event break case .TAP_DECPOS_UP: evt_TAP_DECPOS_UP() case .TAP_DECPOS_DOWN: evt_TAP_DECPOS_DOWN() case .TAP_NUM: evt_TAP_NUM(param as! Int) break case .TAP_DP: evt_TAP_DP() break case .TAP_AC: // common processing event // common processing event break case .TAP_BS: evt_TAP_BS() break case .TAP_DIV: // ignore break case .TAP_EQ: playTapButtonSound() remCalcMgr.DecideDiviSor() saveDataForHistory() procState = .VIEW_ANSWER updateTextInDisplayArea() break default: // Illegal event evt_ErrorHandling() procState = .WAIT_DIVIDEND break; } } /** [Event Driven] State: View answer - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procstatemgr_Evt_ViewAnswer( _ event: PROC_EVENT, param: AnyObject?) { switch event { case .INIT: // common processing event break case .TAP_DECPOS_UP: // ignore break case .TAP_DECPOS_DOWN: // ignore break case .TAP_NUM: // ignore break case .TAP_DP: // ignore break case .TAP_AC: // common processing event // common processing event break case .TAP_BS: // ignore break case .TAP_DIV: // ignore break case .TAP_EQ: // ignore break default: // Illegal event evt_ErrorHandling() procState = .WAIT_DIVIDEND break; } } // MARK: - State Procedure (イベント共通処理) /** TAP_DECPOS_UP */ func evt_TAP_DECPOS_UP() { playTapButtonSound() remCalcMgr.UpDecimalPosition() AppPreference.SetDecimalPoint(value: remCalcMgr.P_DecimalPosition) updateTextInDisplayArea() } /** TAP_DECPOS_DOWN */ func evt_TAP_DECPOS_DOWN() { playTapButtonSound() remCalcMgr.DownDecimalPosition() AppPreference.SetDecimalPoint(value: remCalcMgr.P_DecimalPosition) updateTextInDisplayArea() } /** TAP_NUM */ func evt_TAP_NUM(_ number: Int) { playTapButtonSound() remCalcMgr.InputNumber(number) updateTextInDisplayArea() } /** TAP_BS */ func evt_TAP_BS() { playTapButtonSound() remCalcMgr.ExecuteBackSpace() updateTextInDisplayArea() } /** TAP_DP */ func evt_TAP_DP() { playTapButtonSound() remCalcMgr.InputDecimalPoint() updateTextInDisplayArea() } /** Error Handling */ func evt_ErrorHandling() { initStateMgr() updateTextInDisplayArea() } // MARK: - State Procedure (サブルーチン処理) /** Initialization state procedures */ private func initStateMgr() { remCalcMgr.InitValuesForCalc() procState = .WAIT_DIVIDEND updateTextInDisplayArea() } /** Update text in display area */ private func updateTextInDisplayArea() { outletDecimalPointValueLabel.text = remCalcMgr.P_DecPosString // 小数点位置 outletInputValueLabel.text = remCalcMgr.P_InputValuesString // 入力値 outletExpressionValueLabel.text = remCalcMgr.P_ExpressionString // 式 outletExpressionValueLabel.FontSizeToFit() outletAnswerValueLabel.text = remCalcMgr.P_AnswerString // 答え outletAnswerValueLabel.FontSizeToFit() } /** Initialize the configuration of each view */ private func initConfigOfEachView() { // 表示エリア outletInputValueLabel.text = "888888888888" // 12桁 outletInputValueLabel.FontSizeToFit() outletInputValueLabel.text = "" outletExpressionLabel.FontSizeToFit() outletAnswerLabel.FontSizeToFit() outletDecimalPointTitleLabel.FontSizeToFit() outletDecimalPointDownButton.FontSizeToFit() outletDecimalPointValueLabel.FontSizeToFit() outletDecimalPointUpButton.FontSizeToFit() // 入力エリア outletKey0Button.FontSizeToFit() outletKey00Button.FontSizeToFit() outletKey1Button.FontSizeToFit() outletKey2Button.FontSizeToFit() outletKey3Button.FontSizeToFit() outletKey4Button.FontSizeToFit() outletKey5Button.FontSizeToFit() outletKey6Button.FontSizeToFit() outletKey7Button.FontSizeToFit() outletKey8Button.FontSizeToFit() outletKey9Button.FontSizeToFit() outletKeyACButton.FontSizeToFit() outletKeyBSButton.FontSizeToFit() outletKeyDotButton.FontSizeToFit() outletKeyDivideButton.FontSizeToFit() outletKeyEqualButton.FontSizeToFit() } /** Change the color of each view item color for each state. */ private func changeViewItemColorForState(state: PROC_STATE) { switch state { case .WAIT_DIVIDEND: outletInputValueLabel.backgroundColor = UIColor.white outletExpressionValueLabel.backgroundColor = UIColor.lightGray outletAnswerValueLabel.backgroundColor = UIColor.lightGray outletDecimalPointDownButton.tintColor = UIColor.white outletDecimalPointUpButton.tintColor = UIColor.white outletKey0Button.tintColor = UIColor.white outletKey00Button.tintColor = UIColor.white outletKey1Button.tintColor = UIColor.white outletKey2Button.tintColor = UIColor.white outletKey3Button.tintColor = UIColor.white outletKey4Button.tintColor = UIColor.white outletKey5Button.tintColor = UIColor.white outletKey6Button.tintColor = UIColor.white outletKey7Button.tintColor = UIColor.white outletKey8Button.tintColor = UIColor.white outletKey9Button.tintColor = UIColor.white outletKeyDotButton.tintColor = UIColor.white outletKeyACButton.tintColor = UIColor.white outletKeyBSButton.tintColor = UIColor.white outletKeyDivideButton.tintColor = UIColor.white outletKeyEqualButton.tintColor = UIColor.lightGray case .WAIT_DIVISOR: outletInputValueLabel.backgroundColor = UIColor.white outletExpressionValueLabel.backgroundColor = UIColor.hexStr(hexStr: "A5D1F4", alpha: 1.0) outletAnswerValueLabel.backgroundColor = UIColor.lightGray outletDecimalPointDownButton.tintColor = UIColor.white outletDecimalPointUpButton.tintColor = UIColor.white outletKey0Button.tintColor = UIColor.white outletKey00Button.tintColor = UIColor.white outletKey1Button.tintColor = UIColor.white outletKey2Button.tintColor = UIColor.white outletKey3Button.tintColor = UIColor.white outletKey4Button.tintColor = UIColor.white outletKey5Button.tintColor = UIColor.white outletKey6Button.tintColor = UIColor.white outletKey7Button.tintColor = UIColor.white outletKey8Button.tintColor = UIColor.white outletKey9Button.tintColor = UIColor.white outletKeyDotButton.tintColor = UIColor.white outletKeyACButton.tintColor = UIColor.white outletKeyBSButton.tintColor = UIColor.white outletKeyDivideButton.tintColor = UIColor.lightGray outletKeyEqualButton.tintColor = UIColor.white case .VIEW_ANSWER: outletInputValueLabel.backgroundColor = UIColor.lightGray outletExpressionValueLabel.backgroundColor = UIColor.hexStr(hexStr: "A5D1F4", alpha: 1.0) outletAnswerValueLabel.backgroundColor = UIColor.hexStr(hexStr: "EAC7CD", alpha: 1.0) outletDecimalPointDownButton.tintColor = UIColor.lightGray outletDecimalPointUpButton.tintColor = UIColor.lightGray outletKey0Button.tintColor = UIColor.lightGray outletKey00Button.tintColor = UIColor.lightGray outletKey1Button.tintColor = UIColor.lightGray outletKey2Button.tintColor = UIColor.lightGray outletKey3Button.tintColor = UIColor.lightGray outletKey4Button.tintColor = UIColor.lightGray outletKey5Button.tintColor = UIColor.lightGray outletKey6Button.tintColor = UIColor.lightGray outletKey7Button.tintColor = UIColor.lightGray outletKey8Button.tintColor = UIColor.lightGray outletKey9Button.tintColor = UIColor.lightGray outletKeyDotButton.tintColor = UIColor.lightGray outletKeyACButton.tintColor = UIColor.white outletKeyBSButton.tintColor = UIColor.lightGray outletKeyDivideButton.tintColor = UIColor.lightGray outletKeyEqualButton.tintColor = UIColor.lightGray default: break } } /** 履歴用データの保存 */ private func saveDataForHistory() { ModelMgr.Save_D_History(setModel: { (data: D_History) -> Void in data.m_i_answer = remCalcMgr.P_AnswerString data.m_i_expression = remCalcMgr.P_ExpressionString data.m_i_decimal_position = Int16(remCalcMgr.P_DecimalPosition) data.m_i_divisor = remCalcMgr.P_DivisorValue data.m_i_dividend = remCalcMgr.P_DividendValue data.m_k_update_time = Date() }) ModelMgr.DeleteDataWithOffset(offset: 50) } /** Play tap the button. */ private func playTapButtonSound() { if ( AppPreference.GetButtonPushedSound() == true ) { if ( self.seTapButtonAudio != nil ) { self.seTapButtonAudio.play() } } } }
mit
yanfeng0107/ios-charts
Charts/Classes/Data/ChartData.swift
59
24664
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValueSum = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [ChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [ChartDataSet]() } public init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : count(_xVals[i]!) } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { println("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(#start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis var firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis var firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0 if (_dataSets == nil) { return } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += fabs(_dataSets[i].yValueSum) } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// returns the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// returns the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// returns the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// returns the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// returns the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Double { return _yValueSum } /// Returns the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// returns the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// Returns the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets } set { _dataSets = newValue } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations. /// /// :param: dataSets the DataSet array to search /// :param: type /// :param: ignorecase if true, the search is not case-sensitive /// :returns: internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// returns the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// Returns the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// :param: highlight /// :returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { if highlight.dataSetIndex >= dataSets.count { return nil } else { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } } /// Returns the DataSet object with the given label. /// sensitive or not. /// IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations. /// /// :param: label /// :param: ignorecase public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { var index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount _yValueSum += d.yValueSum if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } var d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount _yValueSum -= d.yValueSum calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { var val = e.value var set = _dataSets[dataSetIndex] if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 _yValueSum += val handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) set.addEntry(e) } else { println("ChartData.addEntry() - dataSetIndex our of range.") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset var removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex) if (removed) { var val = entry.value _yValCount -= 1 _yValueSum -= val calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. Returns true if an entry was removed, false if no Entry /// was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } var entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// Returns the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { var set = _dataSets[i] for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set } } } return nil } /// Returns the index of the provided DataSet inside the DataSets array of /// this data object. Returns -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// Returns all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { var clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. Returns true if so, false if not. public func contains(#entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true } } return false } /// Checks if this data object contains the specified DataSet. Returns true if so, false if not. public func contains(#dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true } } return false } /// MARK: - ObjC compatibility /// returns the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
apache-2.0
MonkeyRing/DragBackNavigationController
DragNavigationController/DragNavigationController/ViewController.swift
1
298
// // ViewController.swift // DragNavigationController // // Created by FundSmart IOS on 16/5/21. // Copyright © 2016年 黄海龙. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
mit
ignacio-chiazzo/ARKit
ARKitProject/UI Elements/HitTestVisualization.swift
1
4017
import Foundation import ARKit class HitTestVisualization { var minHitDistance: CGFloat = 0.01 var maxHitDistance: CGFloat = 4.5 var xAxisSamples = 6 var yAxisSamples = 6 var fieldOfViewWidth: CGFloat = 0.8 var fieldOfViewHeight: CGFloat = 0.8 let hitTestPointParentNode = SCNNode() var hitTestPoints = [SCNNode]() var hitTestFeaturePoints = [SCNNode]() let sceneView: ARSCNView let overlayView = LineOverlayView() init(sceneView: ARSCNView) { self.sceneView = sceneView overlayView.backgroundColor = UIColor.clear overlayView.frame = sceneView.frame sceneView.addSubview(overlayView) } deinit { hitTestPointParentNode.removeFromParentNode() overlayView.removeFromSuperview() } func setupHitTestResultPoints() { if hitTestPointParentNode.parent == nil { self.sceneView.scene.rootNode.addChildNode(hitTestPointParentNode) } while hitTestPoints.count < xAxisSamples * yAxisSamples { hitTestPoints.append(createCrossNode(size: 0.01, color: UIColor.blue, horizontal:false)) hitTestFeaturePoints.append(createCrossNode(size: 0.01, color: UIColor.yellow, horizontal:true)) } } func render() { // Remove any old nodes, hitTestPointParentNode.childNodes.forEach { $0.removeFromParentNode() $0.geometry = nil } // Ensure there are enough nodes that can be rendered. setupHitTestResultPoints() let xAxisOffset: CGFloat = (1 - fieldOfViewWidth) / 2 let yAxisOffset: CGFloat = (1 - fieldOfViewHeight) / 2 let stepX = fieldOfViewWidth / CGFloat(xAxisSamples - 1) let stepY = fieldOfViewHeight / CGFloat(yAxisSamples - 1) var screenSpaceX: CGFloat = xAxisOffset var screenSpaceY: CGFloat = yAxisOffset guard let currentFrame = sceneView.session.currentFrame else { return } for x in 0 ..< xAxisSamples { screenSpaceX = xAxisOffset + (CGFloat(x) * stepX) for y in 0 ..< yAxisSamples { screenSpaceY = yAxisOffset + (CGFloat(y) * stepY) let hitTestPoint = hitTestPoints[(x * yAxisSamples) + y] let hitTestResults = currentFrame.hitTest(CGPoint(x: screenSpaceX, y: screenSpaceY), types: .featurePoint) if hitTestResults.isEmpty { hitTestPoint.isHidden = true continue } hitTestPoint.isHidden = false let result = hitTestResults[0] // Place a blue cross, oriented parallel to the screen at the place of the hit. let hitTestPointPosition = SCNVector3.positionFromTransform(result.worldTransform) hitTestPoint.position = hitTestPointPosition hitTestPointParentNode.addChildNode(hitTestPoint) // Subtract the result's local position from the world position // to get the position of the feature which the ray hit. let localPointPosition = SCNVector3.positionFromTransform(result.localTransform) let featurePosition = hitTestPointPosition - localPointPosition let hitTestFeaturePoint = hitTestFeaturePoints[(x * yAxisSamples) + y] hitTestFeaturePoint.position = featurePosition hitTestPointParentNode.addChildNode(hitTestFeaturePoint) // Create a 2D line between the feature point and the hit test result to be drawn on the overlay view. overlayView.addLine(start: screenPoint(for: hitTestPointPosition), end: screenPoint(for: featurePosition)) } } // Draw the 2D lines DispatchQueue.main.async { self.overlayView.setNeedsDisplay() } } private func screenPoint(for point: SCNVector3) -> CGPoint { let projectedPoint = sceneView.projectPoint(point) return CGPoint(x: CGFloat(projectedPoint.x), y: CGFloat(projectedPoint.y)) } } class LineOverlayView: UIView { struct Line { var start: CGPoint var end: CGPoint } var lines = [Line]() func addLine(start: CGPoint, end: CGPoint) { lines.append(Line(start: start, end: end)) } override func draw(_ rect: CGRect) { super.draw(rect) for line in lines { let path = UIBezierPath() path.move(to: line.start) path.addLine(to: line.end) path.close() UIColor.red.set() path.stroke() path.fill() } lines.removeAll() } }
mit
IsaoTakahashi/iOS-KaraokeSearch
KaraokeSearch/PodSong.swift
1
498
// // PodSong.swift // KaraokeSearch // // Created by 高橋 勲 on 2015/05/21. // Copyright (c) 2015年 高橋 勲. All rights reserved. // import Foundation class PodSong: NSObject { var songId: Int, artistName: String, songTitle: String, albumTitle: String init(songId: Int, artistName: String, songTitle: String, albumTitle: String) { self.songId = songId self.artistName = artistName self.songTitle = songTitle self.albumTitle = albumTitle } }
mit
jarocht/iOS-AlarmDJ
AlarmDJ/AlarmDJ/AppDelegate.swift
1
2184
// // AppDelegate.swift // AlarmDJ // // Created by X Code User on 7/22/15. // Copyright (c) 2015 Tim Jaroch, Morgan Heyboer, Andreas Plüss (TEAM E). All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
alessiobrozzi/firefox-ios
Client/Frontend/Browser/ThirdPartySearchAlerts.swift
9
2900
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class ThirdPartySearchAlerts: UIAlertController { /** Allows the keyboard to pop back up after an alertview. **/ override var canBecomeFirstResponder: Bool { return false } /** Builds the Alert view that asks if the users wants to add a third party search engine. - parameter okayCallback: Okay option handler. - returns: UIAlertController for asking the user to add a search engine **/ static func addThirdPartySearchEngine(_ okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController { let alert = ThirdPartySearchAlerts( title: Strings.ThirdPartySearchAddTitle, message: Strings.ThirdPartySearchAddMessage, preferredStyle: UIAlertControllerStyle.alert ) let noOption = UIAlertAction( title: Strings.ThirdPartySearchCancelButton, style: UIAlertActionStyle.cancel, handler: nil ) let okayOption = UIAlertAction( title: Strings.ThirdPartySearchOkayButton, style: UIAlertActionStyle.default, handler: okayCallback ) alert.addAction(okayOption) alert.addAction(noOption) return alert } /** Builds the Alert view that shows the user an error in case a search engine could not be added. - returns: UIAlertController with an error dialog **/ static func failedToAddThirdPartySearch() -> UIAlertController { return searchAlertWithOK(title: Strings.ThirdPartySearchFailedTitle, message: Strings.ThirdPartySearchFailedMessage) } static func incorrectCustomEngineForm() -> UIAlertController { return searchAlertWithOK(title: Strings.CustomEngineFormErrorTitle, message: Strings.CustomEngineFormErrorMessage) } static func duplicateCustomEngine() -> UIAlertController { return searchAlertWithOK(title: Strings.CustomEngineDuplicateErrorTitle, message: Strings.CustomEngineDuplicateErrorMessage) } private static func searchAlertWithOK(title: String, message: String) -> UIAlertController { let alert = ThirdPartySearchAlerts( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) let okayOption = UIAlertAction( title: Strings.ThirdPartySearchOkayButton, style: UIAlertActionStyle.default, handler: nil ) alert.addAction(okayOption) return alert } }
mpl-2.0
furuya02/ProvisioningProfileExplorer
ProvisioningProfileExplorer/Certificate.swift
1
455
// // ertificate.swift // ProvisioningProfileExplorer // // Created by hirauchi.shinichi on 2016/04/16. // Copyright © 2016年 SAPPOROWORKS. All rights reserved. // import Cocoa class Certificate: NSObject { var summary: String = "" var expires: NSDate? = nil var lastDays = 0 init(summary:String,expires:NSDate?,lastDays:Int){ self.summary = summary self.expires = expires self.lastDays = lastDays } }
mit
benlangmuir/swift
test/SourceKit/Indexing/index_enum_case.swift
5
713
// RUN: %sourcekitd-test -req=index %s -- -Xfrontend -serialize-diagnostics-path -Xfrontend %t.dia %s -Xfrontend -disable-implicit-concurrency-module-import -Xfrontend -disable-implicit-string-processing-module-import | %sed_clean > %t.response // RUN: %diff -u %s.response %t.response public enum E { case one, two(a: String), three var text: String { switch self { case .one: return "one" case .two(let a): return a case .three: return "three" } } } let e: E = .two(a:"String") func brokenEnums() { switch NonExistent.A { case .A: return "one" } switch E.one { case .tenthousand: return "one" } }
apache-2.0
bitjammer/swift
test/Interpreter/SDK/Inputs/multi-file-imported-enum/main.swift
71
202
import Foundation class B { func f() -> Bool { let now = NSDate() let later = NSDate.distantFuture as NSDate return now.compare(later as Date) != .orderedDescending } } print(B().f())
apache-2.0
xiaoxinghu/swift-org
Sources/Paragraph.swift
1
1061
// // Paragraph.swift // SwiftOrg // // Created by Xiaoxing Hu on 21/09/16. // Copyright © 2016 Xiaoxing Hu. All rights reserved. // import Foundation public struct Paragraph: Node { public var lines: [String] public var text: String { return lines.joined(separator: " ") } public var parsed: [InlineToken] { return InlineLexer(text: text).tokenize() } public var description: String { return "Paragraph(text: \(text))" } } extension OrgParser { func parseParagraph(_ startWith: String? = nil) throws -> Paragraph? { var paragraph: Paragraph? = nil if let firstLine = startWith { paragraph = Paragraph(lines: [firstLine]) } while let (_, token) = tokens.peek() { if case .line(let t) = token { paragraph = paragraph ?? Paragraph(lines: []) paragraph?.lines.append(t) _ = tokens.dequeue() } else { break } } return paragraph } }
mit
dymx101/BallDown
BallDown/Board/BoardStick.swift
1
3147
// // BoardStick.swift // BallDown // // Copyright © 2015 ones. All rights reserved. // import Foundation import SpriteKit class BoardSticks: BoardAbstract { let boardRadius = Boards.radius let stickWidth = 20 let stickHeight = 25 let stickColor = SKColor(hue: CGFloat(0) / 360.0, saturation: 0.15, brightness: 0.9, alpha: 1) let stickStrokeColor = SKColor(hue: CGFloat(0) / 360.0, saturation: 0.15, brightness: 0.7, alpha: 1) var boardCollideMask: UInt32! var stickCollideMask: UInt32! override func newNode(boardTemplate: BoardTemplate, boardSize: CGSize) -> SKNode { boardCollideMask = boardTemplate.collideMaskFirst stickCollideMask = boardTemplate.collideMaskSecond let board = SKShapeNode(rectOfSize: boardSize, cornerRadius: boardRadius) board.name = "BoardStick.board" board.physicsBody = SKPhysicsBody(rectangleOfSize: board.frame.size) board.physicsBody!.categoryBitMask = boardCollideMask board.physicsBody!.dynamic = false board.position.x = board.frame.width / 2 board.fillColor = Boards.normalBoardColor board.strokeColor = Boards.normalBoardStrokeColor board.bind = self let boardAvaliableWidth = board.frame.width - boardRadius * 2 let sticks = makeSticks(boardAvaliableWidth) sticks.name = "BoardStick.sticks" sticks.userData = NSMutableDictionary() sticks.userData!.setValue(self, forKey: Boards.DATA_BOARD_NAME) sticks.position.x = -sticks.frame.width / 2 sticks.position.y = board.frame.height / 2 sticks.fillColor = stickColor sticks.strokeColor = stickStrokeColor sticks.bind = self board.addChild(sticks) return board } override func onBeginContact(board: SKNode, ball: Ball, contact: SKPhysicsContact, game: GameDelegate) { if board.physicsBody!.categoryBitMask == self.stickCollideMask { game.stopGame() } } override func playCollideSound(fromFloor: Int, toFloor: Int) { } private func makeSticks(boardAvaliableWidth: CGFloat)-> SKShapeNode { let stickCount = Int(floor(boardAvaliableWidth / CGFloat(stickWidth))) var drawX = CGFloat(0) let sticksPath = CGPathCreateMutable() CGPathMoveToPoint(sticksPath, nil, drawX, CGFloat(0)) for _ in 0 ..< stickCount { drawX += CGFloat(stickWidth / 2) CGPathAddLineToPoint(sticksPath, nil, drawX, CGFloat(stickHeight)) drawX += CGFloat(stickWidth / 2) CGPathAddLineToPoint(sticksPath, nil, drawX, CGFloat(0)) } CGPathCloseSubpath(sticksPath) let sticks = SKShapeNode(path: sticksPath) sticks.physicsBody = SKPhysicsBody(rectangleOfSize: sticks.frame.size, center: CGPoint(x: sticks.frame.width / 2, y: sticks.frame.height / 2)) sticks.physicsBody!.categoryBitMask = stickCollideMask sticks.physicsBody!.dynamic = false return sticks } }
mit
PokeMapCommunity/PokeMap-iOS
Pods/Permission/Source/PermissionTypes/Contacts.swift
1
1958
// // Contacts.swift // // Copyright (c) 2015-2016 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 Contacts // MARK: - Contacts internal extension Permission { var statusContacts: PermissionStatus { if #available(iOS 9.0, *) { let status = CNContactStore.authorizationStatusForEntityType(.Contacts) switch status { case .Authorized: return .Authorized case .Restricted, .Denied: return .Denied case .NotDetermined: return .NotDetermined } } else { fatalError() } } func requestContacts(callback: Callback) { if #available(iOS 9.0, *) { CNContactStore().requestAccessForEntityType(.Contacts) { _,_ in callback(self.statusContacts) } } else { fatalError() } } }
mit
kickstarter/Kickstarter-Prelude
Prelude/NumericType.swift
1
995
import CoreGraphics /// A `NumericType` instance is something that acts numeric-like, i.e. can be added, subtracted /// and multiplied with other numeric types. public protocol NumericType { static func + (lhs: Self, rhs: Self) -> Self static func - (lhs: Self, rhs: Self) -> Self static func * (lhs: Self, rhs: Self) -> Self func negate() -> Self static func zero() -> Self static func one() -> Self init(_ v: Int) } extension NumericType { public func negate() -> Self { return Self.zero() - self } } extension NumericType where Self: Comparable { public func abs() -> Self { if self < Self.zero() { return self.negate() } return self } } extension CGFloat: NumericType { public static func zero() -> CGFloat { return 0.0 } public static func one() -> CGFloat { return 1.0 } } extension Double: NumericType { public static func zero() -> Double { return 0.0 } public static func one() -> Double { return 1.0 } }
apache-2.0
charvoa/TimberiOS
TimberiOS/Classes/String+Custom.swift
1
419
// // String+Custom.swift // TimberiOS // // Created by Nicolas on 28/09/2017. // import Foundation extension String { func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } func toBase64() -> String { return Data(self.utf8).base64EncodedString() } }
mit
ibhupi/cksapp
ios-app/cksapp/AppDelegate.swift
1
3163
// // AppDelegate.swift // cksapp // // Created by Bhupendra Singh on 7/2/16. // Copyright © 2016 Bhupendra Singh. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. if let userID = NSUserDefaults.standardUserDefaults().stringForKey("currentUserID") { CurrentUser.id = userID CurrentUserSchduele.userID = CurrentUser.id GameService.sharedInstance.AllGames({ (items) in GameService.sharedInstance.fetchCurrentUserSchedule() }) } else { APIService.UserFromAPI({ (items) in if let item = items?.first { CurrentUser.id = item.id NSUserDefaults.standardUserDefaults().setObject(CurrentUser.id, forKey: "currentUserID") NSUserDefaults.standardUserDefaults().synchronize() CurrentUserSchduele.userID = CurrentUser.id GameService.sharedInstance.AllGames({ (items) in GameService.sharedInstance.fetchCurrentUserSchedule() }) } }) } let _ = LocationServices.sharedInstance return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
OscarSwanros/swift
tools/SwiftSyntax/SyntaxCollection.swift
5
4631
//===-------------- SyntaxCollection.swift - Syntax Collection ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation /// Represents a collection of Syntax nodes of a specific type. SyntaxCollection /// behaves as a regular Swift collection, and has accessors that return new /// versions of the collection with different children. public class SyntaxCollection<SyntaxElement: Syntax>: Syntax { /// Creates a new SyntaxCollection by replacing the underlying layout with /// a different set of raw syntax nodes. /// /// - Parameter layout: The new list of raw syntax nodes underlying this /// collection. /// - Returns: A new SyntaxCollection with the new layout underlying it. internal func replacingLayout( _ layout: [RawSyntax]) -> SyntaxCollection<SyntaxElement> { let newRaw = data.raw.replacingLayout(layout) let (newRoot, newData) = data.replacingSelf(newRaw) return SyntaxCollection<SyntaxElement>(root: newRoot, data: newData) } /// Creates a new SyntaxCollection by appending the provided syntax element /// to the children. /// /// - Parameter syntax: The element to append. /// - Returns: A new SyntaxCollection with that element appended to the end. public func appending( _ syntax: SyntaxElement) -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.append(syntax.raw) return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by prepending the provided syntax element /// to the children. /// /// - Parameter syntax: The element to prepend. /// - Returns: A new SyntaxCollection with that element prepended to the /// beginning. public func prepending( _ syntax: SyntaxElement) -> SyntaxCollection<SyntaxElement> { return inserting(syntax, at: 0) } /// Creates a new SyntaxCollection by inserting the provided syntax element /// at the provided index in the children. /// /// - Parameters: /// - syntax: The element to insert. /// - index: The index at which to insert the element in the collection. /// /// - Returns: A new SyntaxCollection with that element appended to the end. public func inserting(_ syntax: SyntaxElement, at index: Int) -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout /// Make sure the index is a valid insertion index (0 to 1 past the end) precondition((newLayout.startIndex...newLayout.endIndex).contains(index), "inserting node at invalid index \(index)") newLayout.insert(syntax.raw, at: index) return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by removing the syntax element at the /// provided index. /// /// - Parameter index: The index of the element to remove from the collection. /// - Returns: A new SyntaxCollection with the element at the provided index /// removed. public func removing(childAt index: Int) -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.remove(at: index) return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by removing the first element. /// /// - Returns: A new SyntaxCollection with the first element removed. public func removingFirst() -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.removeFirst() return replacingLayout(newLayout) } /// Creates a new SyntaxCollection by removing the last element. /// /// - Returns: A new SyntaxCollection with the last element removed. public func removingLast() -> SyntaxCollection<SyntaxElement> { var newLayout = data.raw.layout newLayout.removeLast() return replacingLayout(newLayout) } } /// Conformance for SyntaxCollection to the Collection protocol. extension SyntaxCollection: Collection { public var startIndex: Int { return data.childCaches.startIndex } public var endIndex: Int { return data.childCaches.endIndex } public func index(after i: Int) -> Int { return data.childCaches.index(after: i) } public subscript(_ index: Int) -> SyntaxElement { return child(at: index)! as! SyntaxElement } }
apache-2.0
natecook1000/swift-compiler-crashes
crashes-duplicates/09748-swift-parser-skipsingle.swift
11
278
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing for in { let a { func g { class d { class case , let { { { { { { { { { { ( ( { { { { { { { { { { ( { { { a {
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/10475-swift-sourcemanager-getmessage.swift
11
250
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing deinit { class a { enum A { var d = { { extension NSData { func a { class case ,
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/27324-swift-constraints-constraintsystem-finalize.swift
4
221
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<T where k:A{class A{var _=(let a{var _={A{
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/15347-swift-sourcemanager-getmessage.swift
11
203
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { case ( { { } class case ,
mit
supermarin/Swifternalization
SwifternalizationTests/ExpressionTests.swift
1
1266
// // ExpressionTests.swift // Swifternalization // // Created by Tomasz Szulc on 27/06/15. // Copyright (c) 2015 Tomasz Szulc. All rights reserved. // import UIKit import XCTest import Swifternalization class ExpressionTests: XCTestCase { func testThatInequalityExpressionShouldBeCreated() { XCTAssertTrue(Expression.expressionFromString("abc{ie:%d=2}") != nil, "Expression should be created") } func testThatInequalityExtendedExpressionShouldBeCreated() { XCTAssertTrue(Expression.expressionFromString("abc{iex:4<%d<=5}") != nil, "Expression should be created") } func testThatRegexExpressionShouldBeCreated() { XCTAssertTrue(Expression.expressionFromString("abc{exp:.*}") != nil, "Expression should be created") } func testThatExpressionCannotBeCreated() { XCTAssertTrue(Expression.expressionFromString("abc") == nil, "There is no expression here") } func testThatExpressionCannotBeFound() { XCTAssertFalse(Expression.parseExpressionPattern("{abc}") == nil, "Expression should not be found") } func testThatExpressionCanBeFound() { XCTAssertTrue(Expression.parseExpressionPattern("{ie:%d>2}") != nil, "Expression should be found") } }
mit
jwfriese/FrequentFlyer
FrequentFlyer/HTTP/EventSourceCreator.swift
1
192
import EventSource class EventSourceCreator { func create(withURL url: String, headers: [String : String]) -> EventSource { return EventSource(url: url, headers: headers) } }
apache-2.0
gkye/TheMovieDatabaseSwiftWrapper
Tests/TMDBSwiftTests/Mock Models/MockCrewMember.swift
1
709
@testable import TMDBSwift extension CrewMember { static let mock = CrewMember(id: 491, adult: false, creditID: "52fe420dc3a36847f800046d", department: "Sound", gender: Gender(rawValue: 2), job: "Original Music Composer", knownForDepartment: "Sound", name: "John Williams", originalName: "John Williams", popularity: 1.949, profilePath: "/KFyMqUWeiBdP9tJcZyGWOqnrgK.jpg") }
mit
boolkybear/SWCraftMU-BowlingKata-160527
SWCraftMu-KataBowling-160527/SWCraftMu-KataBowling-160527Tests/SWCraftMu-KataBowling-160527-strikes.swift
1
2050
// // SWCraftMu-KataBowling-160527-strikes.swift // SWCraftMu-KataBowling-160527 // // Created by Jose on 29/5/16. // Copyright © 2016 ByBDesigns. All rights reserved. // import XCTest @testable import SWCraftMu_KataBowling_160527 class SWCraftMu_KataBowling_160527_strikes: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // func testExample() { // // This is an example of a functional test case. // // Use XCTAssert and related functions to verify your tests produce the correct results. // } // // func testPerformanceExample() { // // This is an example of a performance test case. // self.measureBlock { // // Put the code you want to measure the time of here. // } // } func testAllStrikes() { let counter = BowlingCounter("XXXXXXXXXXXX") XCTAssert(counter.score == 30*10) } func testOnlyFirstStrike() { let counter = BowlingCounter("X------------------") XCTAssert(counter.score == 10) } func testRandomStrikesAndRolls() { let counter = BowlingCounter("X12X34X54X32X1-") XCTAssert(counter.score == 10 + 1 + 2 + 1 + 2 + 10 + 3 + 4 + 3 + 4 + 10 + 5 + 4 + 5 + 4 + 10 + 3 + 2 + 3 + 2 + 10 + 1 + 1) } func testEndsWithStrikeAndRoll() { let counter = BowlingCounter("XXXXXXXXXX12") XCTAssert(counter.score == (10 + 10 + 10) * 8 + (10 + 10 + 1) + (10 + 1 + 2)) } func testEndsWithStrikes() { let counter = BowlingCounter("------------------XXX") XCTAssert(counter.score == 30) } func testEndsWithStrikeAndSpare() { let counter = BowlingCounter("------------------X-/") XCTAssert(counter.score == 20) } }
mit
SweetzpotAS/TCXZpot-Swift
TCXZpot-Swift/AbstractSource.swift
1
766
// // AbstractSource.swift // TCXZpot // // Created by Tomás Ruiz López on 19/5/17. // Copyright 2017 SweetZpot AS // 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 public protocol AbstractSource { var tcxType : String { get } }
apache-2.0
johnlui/Swift-MMP
Frameworks/Pitaya/Source/Pitaya.swift
1
7349
// The MIT License (MIT) // Copyright (c) 2015 JohnLui <wenhanlv@gmail.com> https://github.com/johnlui // 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. // // Pitaya.swift // Pitaya // // Created by JohnLui on 15/5/14. // import Foundation /// make your code looks tidier public typealias Pita = Pitaya open class Pitaya { /// if set to true, Pitaya will log all information in a NSURLSession lifecycle open static var DEBUG = false var pitayaManager: PitayaManager! /** the only init method to fire a HTTP / HTTPS request - parameter method: the HTTP method you want - parameter url: the url you want - parameter timeout: time out setting - returns: a Pitaya object */ open static func build(HTTPMethod method: HTTPMethod, url: String) -> Pitaya { let p = Pitaya() p.pitayaManager = PitayaManager.build(method, url: url) return p } open static func build(HTTPMethod method: HTTPMethod, url: String, timeout: Double, execution: Execution = .async) -> Pitaya { let p = Pitaya() p.pitayaManager = PitayaManager.build(method, url: url, timeout: timeout, execution: execution) return p } /** add params to self (Pitaya object) - parameter params: what params you want to add in the request. Pitaya will do things right whether methed is GET or POST. - returns: self (Pitaya object) */ open func addParams(_ params: [String: Any]) -> Pitaya { self.pitayaManager.addParams(params) return self } /** add files to self (Pitaya object), POST only - parameter params: add some files to request - returns: self (Pitaya object) */ open func addFiles(_ files: [File]) -> Pitaya { self.pitayaManager.addFiles(files) return self } /** add a SSL pinning to check whether undering the Man-in-the-middle attack - parameter data: data of certification file, .cer format - parameter SSLValidateErrorCallBack: error callback closure - returns: self (Pitaya object) */ open func addSSLPinning(LocalCertData data: Data, SSLValidateErrorCallBack: (()->Void)? = nil) -> Pitaya { self.pitayaManager.addSSLPinning(LocalCertData: [data], SSLValidateErrorCallBack: SSLValidateErrorCallBack) return self } /** add a SSL pinning to check whether undering the Man-in-the-middle attack - parameter LocalCertDataArray: data array of certification file, .cer format - parameter SSLValidateErrorCallBack: error callback closure - returns: self (Pitaya object) */ open func addSSLPinning(LocalCertDataArray dataArray: [Data], SSLValidateErrorCallBack: (()->Void)? = nil) -> Pitaya { self.pitayaManager.addSSLPinning(LocalCertData: dataArray, SSLValidateErrorCallBack: SSLValidateErrorCallBack) return self } /** set a custom HTTP header - parameter key: HTTP header key - parameter value: HTTP header value - returns: self (Pitaya object) */ open func setHTTPHeader(Name key: String, Value value: String) -> Pitaya { self.pitayaManager.setHTTPHeader(Name: key, Value: value) return self } /** set HTTP body to what you want. This method will discard any other HTTP body you have built. - parameter string: HTTP body string you want - parameter isJSON: is JSON or not: will set "Content-Type" of HTTP request to "application/json" or "text/plain;charset=UTF-8" - returns: self (Pitaya object) */ open func setHTTPBodyRaw(_ string: String, isJSON: Bool = false) -> Pitaya { self.pitayaManager.sethttpBodyRaw(string, isJSON: isJSON) return self } /** set username and password of HTTP Basic Auth to the HTTP request header - parameter username: username - parameter password: password - returns: self (Pitaya object) */ open func setBasicAuth(_ username: String, password: String) -> Pitaya { self.pitayaManager.setBasicAuth((username, password)) return self } /** add error callback to self (Pitaya object). this will called only when network error, if we can receive any data from server, responseData() will be fired. - parameter errorCallback: errorCallback Closure - returns: self (Pitaya object) */ open func onNetworkError(_ errorCallback: @escaping ((_ error: NSError) -> Void)) -> Pitaya { self.pitayaManager.addErrorCallback(errorCallback) return self } /** async response the http body in NSData type - parameter callback: callback Closure - parameter response: void */ open func responseData(_ callback: ((_ data: Data?, _ response: HTTPURLResponse?) -> Void)?) { self.pitayaManager?.fire(callback) } /** async response the http body in String type - parameter callback: callback Closure - parameter response: void */ open func responseString(_ callback: ((_ string: String?, _ response: HTTPURLResponse?) -> Void)?) { self.responseData { (data, response) -> Void in var string = "" if let d = data, let s = NSString(data: d, encoding: String.Encoding.utf8.rawValue) as String? { string = s } callback?(string, response) } } /** async response the http body in JSON type use JSONNeverDie(https://github.com/johnlui/JSONNeverDie). - parameter callback: callback Closure - parameter response: void */ open func responseJSON(_ callback: ((_ json: JSONND, _ response: HTTPURLResponse?) -> Void)?) { self.responseString { (string, response) in var json = JSONND() if let s = string { json = JSONND(string: s) } callback?(json, response) } } /** cancel the request. - parameter callback: callback Closure */ open func cancel(_ callback: (() -> Void)?) { self.pitayaManager.cancelCallback = callback self.pitayaManager.task.cancel() } }
mit
ReSwift/ReSwift-Todo-Example
ReSwift-Todo/PatchingResponder.swift
1
901
// // PatchingResponder.swift // ReSwift-Todo // // Created by Christian Tietze on 15/09/16. // Copyright © 2016 ReSwift. All rights reserved. // import Cocoa protocol PatchingResponderType: class { var referenceResponder: NSResponder! { get } func patchIntoResponderChain() } extension PatchingResponderType where Self : NSResponder { func patchIntoResponderChain() { let oldResponder = referenceResponder.nextResponder referenceResponder.nextResponder = self self.nextResponder = oldResponder } } /// `NSResponder` that upon `awakeFromNib()` puts itself into the /// responder chain right before `referenceResponder`. class PatchingResponder: NSResponder, PatchingResponderType { @IBOutlet var referenceResponder: NSResponder! override func awakeFromNib() { super.awakeFromNib() self.patchIntoResponderChain() } }
mit
rushabh55/NaviTag-iOS
iOS/SwiftExample/AppDelegate.swift
1
5242
import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate{ var window: UIWindow? var userName = String() var lat : Double = Double() var long : Double = Double() var locationManager: CLLocationManager! var myLong: Double = 0.0 var myLat: Double = 0.0 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true) locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() println("start \(__FUNCTION__)") println("end \(__FUNCTION__)") return true } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { locationManager.stopUpdatingLocation() if ((error) != nil) { print(error) } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var str: String switch(status){ case .NotDetermined: str = "NotDetermined" case .Restricted: str = "Restricted" case .Denied: str = "Denied" case .Authorized: str = "Authorized" case .AuthorizedWhenInUse: str = "AuthorizedWhenInUse" } //println("locationManager auth status changed, \(str)") if( status == .Authorized || status == .AuthorizedWhenInUse ) { locationManager.startUpdatingLocation() println("startUpdatingLocation") } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { println("found \(locations.count) placemarks.") if( locations.count > 0 ){ let location = locations[0] as CLLocation; //locationManager.stopUpdatingLocation() //self.L1 = location myLong = location.coordinate.latitude myLat = location.coordinate.longitude println("location updated, lat:\(location.coordinate.latitude), lon:\(location.coordinate.longitude), stop updating.") } } func update() { if self.userName != "" { let url: NSURL = NSURL(string: "http://rushg.me/TreasureHunt/User.php?q=editUser&username=" + self.userName + "&location=" + myLat.description + "," + myLong.description)! // debugPrint(url) let request = NSURLRequest(URL: url) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in // debugPrint(NSString(data: data, encoding: NSUTF8StringEncoding)) } } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. println("start \(__FUNCTION__)") println("end \(__FUNCTION__)") } 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. println("start \(__FUNCTION__)") println("end \(__FUNCTION__)") } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. println("start \(__FUNCTION__)") println("end \(__FUNCTION__)") } 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. println("start \(__FUNCTION__)") println("end \(__FUNCTION__)") } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. println("start \(__FUNCTION__)") println("end \(__FUNCTION__)") } }
apache-2.0
SwiftKit/Torch
Source/Predicate/AggregatePredicate.swift
1
781
// // AggregatePredicate.swift // Torch // // Created by Tadeáš Kříž on 24/07/16. // Copyright © 2016 Brightify. All rights reserved. // import Foundation func joinKeyPaths(path1: String, _ path2: String) -> String { return "\(path1).\(path2)" } public enum AggregatePredicateType: String { case Any case All case None } public struct AggregatePredicate<PARENT: TorchEntity>: PredicateConvertible { public typealias ParentType = PARENT public let type: AggregatePredicateType public let keyPath: String public let operatorString: String public let value: NSObject public func toPredicate() -> NSPredicate { return NSPredicate(format: "\(type.rawValue.uppercaseString) %K \(operatorString) %@", keyPath, value) } }
mit
dymx101/NiuBiBookCity
BookMountain/Model/BCTDataManager.swift
1
2283
// // BCTDataManager.swift // BookMountain // // Created by 冯璇 on 2017/6/15. // Copyright © 2017年 Yiming Dong. All rights reserved. // import UIKit class BCTDataManager: NSObject { static let shared = BCTDataManager() var bookCategory:[BCTBookCategoryModel] = [] // var dicBooksCategoryAry:[String:Any] = [:] var bookList : [BCTBookModel] = [] var categoryBookList : [BCTBookModel] = [] var historyKeyWord : String = "" var pageIndex = 0 var categoryPageIndex = 0 func resetSearch(strKey:String) { if(strKey != historyKeyWord) { pageIndex = 0 bookList = [] } } func resetCategory(index:Int) { if(index == 0) { categoryPageIndex = 0 categoryBookList = [] } } override init() { super.init() self.loadData() } // Converted with Swiftify v1.0.6355 - https://objectivec2swift.com/ func loadData() { let bookCityConfig = BCTBookCityConfig.shared let count: Int = bookCityConfig.bookCategory.count for i in 0..<count { // NSLog (@"Key: %@ for value: %@", key, value); let dicItem: [String: Any] = bookCityConfig.bookCategory[i] as! [String: Any] let bookcategorymodel = BCTBookCategoryModel() bookcategorymodel.curIndex = 1 bookcategorymodel.name = dicItem[CATEGORYNAME] as! String // bookcategorymodel.strUrl = dicItem[URL] as! String bookcategorymodel.categoryDescription = dicItem[DESCRIPTION] as! String // bookcategorymodel.bgColor = UIColorFromNSString(dicItem["bgColor"]) bookcategorymodel.aryUrl = dicItem[URLARY] as! [String] bookCategory.append(bookcategorymodel) } } // Converted with Swiftify v1.0.6355 - https://objectivec2swift.com/ // func getBookArybyCategoryname(strCategoryname: String) -> [Any] { // var retArray: [Any] = dicBooksCategoryAry[strCategoryname] // if retArray == nil { // retArray = [Any]() // dicBooksCategoryAry[strCategoryname] = retArray // } // return retArray // } }
gpl-3.0
KaushalElsewhere/AllHandsOn
TryMadhu/TryMadhu/Setting.swift
1
202
// // Setting.swift // TryMadhu // // Created by Kaushal Elsewhere on 15/05/2017. // Copyright © 2017 Elsewhere. All rights reserved. // import Foundation struct Setting { var name: String }
mit
MenloHacks/ios-app
Menlo Hacks/Pods/PushNotifications/Sources/PersistenceService.swift
1
2873
import Foundation struct PersistenceService: InterestPersistable, UserPersistable { let service: UserDefaults private let prefix = Constants.PersistanceService.prefix func persist(interest: String) -> Bool { guard !self.interestExists(interest: interest) else { return false } service.set(interest, forKey: self.prefixInterest(interest)) return true } func persist(interests: [String]) -> Bool { guard let persistedInterests = self.getSubscriptions(), persistedInterests.sorted().elementsEqual(interests.sorted()) else { self.removeAllSubscriptions() for interest in interests { _ = self.persist(interest: interest) } return true } return false } func setUserId(userId: String) -> Bool { guard !self.userIdExists(userId: userId) else { return false } service.set(userId, forKey: Constants.PersistanceService.userId) return true } func getUserId() -> String? { return service.object(forKey: Constants.PersistanceService.userId) as? String } func removeUserId() { service.removeObject(forKey: Constants.PersistanceService.userId) } func remove(interest: String) -> Bool { guard self.interestExists(interest: interest) else { return false } service.removeObject(forKey: self.prefixInterest(interest)) return true } func removeAllSubscriptions() { self.removeFromPersistanceStore(prefix: prefix) } func removeAll() { self.removeFromPersistanceStore(prefix: "com.pusher.sdk") } func getSubscriptions() -> [String]? { return service.dictionaryRepresentation().filter { $0.key.hasPrefix(prefix) }.map { String(describing: ($0.value)) } } func persistServerConfirmedInterestsHash(_ hash: String) { service.set(hash, forKey: Constants.PersistanceService.hashKey) } func getServerConfirmedInterestsHash() -> String { return service.value(forKey: Constants.PersistanceService.hashKey) as? String ?? "" } private func interestExists(interest: String) -> Bool { return service.object(forKey: self.prefixInterest(interest)) != nil } private func userIdExists(userId: String) -> Bool { return service.object(forKey: Constants.PersistanceService.userId) != nil } private func prefixInterest(_ interest: String) -> String { return "\(prefix):\(interest)" } private func removeFromPersistanceStore(prefix: String) { for element in service.dictionaryRepresentation() { if element.key.hasPrefix(prefix) { service.removeObject(forKey: element.key) } } } }
mit
nickynick/Visuals
Visuals/Container.swift
1
1060
// // Container.swift // Visuals // // Created by Nick Tymchenko on 05/07/14. // Copyright (c) 2014 Nick Tymchenko. All rights reserved. // import Foundation struct Container: ItemToken { let relations: Relation[] var firstItem: Item { return self.relations[0].lhs } var lastItem: Item { return self.relations[self.relations.count - 1].rhs } subscript(view: View) -> Container { return self[Item(view: view)] } subscript(item: Item) -> Container { get { let relation = Relation(lhs: self.lastItem, rhs: item, space: Space(value: 0)) return Container(relations: self.relations + [relation]) } } func append(space: Space) -> SpaceToken { return SpaceFromContainer(container: self, space: space) } func append(space: Space, itemToken: ItemToken) -> ItemToken { let relation = Relation(lhs: self.lastItem, rhs: itemToken.firstItem, space: space) return Container(relations: self.relations + [relation] + itemToken.relations) } }
mit
SD10/SwifterSwift
Tests/SwifterSwiftTests/DateExtensionsTests.swift
2
20139
// // DateExtensionsTests.swift // SwifterSwift // // Created by Omar Albeik on 8/27/16. // Copyright © 2016 Omar Albeik. All rights reserved. // import XCTest @testable import SwifterSwift class DateExtensionsTests: XCTestCase { override func setUp() { super.setUp() NSTimeZone.default = TimeZone(abbreviation: "UTC")! } func testCalendar() { switch Calendar.current.identifier { case .buddhist: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .buddhist).identifier) case .chinese: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .chinese).identifier) case .coptic: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .coptic).identifier) case .ethiopicAmeteAlem: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .ethiopicAmeteAlem).identifier) case .ethiopicAmeteMihret: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .ethiopicAmeteMihret).identifier) case .gregorian: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .gregorian).identifier) case .hebrew: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .hebrew).identifier) case .indian: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .indian).identifier) case .islamic: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamic).identifier) case .islamicCivil: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamicCivil).identifier) case .islamicTabular: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamicTabular).identifier) case .islamicUmmAlQura: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .islamicUmmAlQura).identifier) case .iso8601: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .iso8601).identifier) case .japanese: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .japanese).identifier) case .persian: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .persian).identifier) case .republicOfChina: XCTAssertEqual(Date().calendar.identifier, Calendar(identifier: .republicOfChina).identifier) } } func testEra() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.era, 1) } func testYear() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.year, 1970) date.year = 2000 XCTAssertEqual(date.year, 2000) } func testQuarter() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.quarter, 0) } func testMonth() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.month, 1) date.month = 2 XCTAssertEqual(date.month, 2) date.month = 14 XCTAssertEqual(date.month, 2) } func testWeekOfYear() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.weekOfYear, 1) let dateAfter10Days = Calendar.current.date(byAdding: .day, value: 7, to: date)! XCTAssertEqual(dateAfter10Days.weekOfYear, 2) } func testWeekOfMonth() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.weekOfMonth, 1) let dateAfter7Days = Calendar.current.date(byAdding: .day, value: 7, to: date)! XCTAssertEqual(dateAfter7Days.weekOfMonth, 2) } func testWeekday() { var date = Date(timeIntervalSince1970: 0) date.weekday = 1 XCTAssertEqual(date.weekday, 1) date.weekday = -1 XCTAssertEqual(date.weekday, 1) date.weekday = 10 XCTAssertEqual(date.weekday, 1) date.weekday = 7 XCTAssertEqual(date.weekday, 7) } func testDay() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.day, 1) date.day = -3 XCTAssertEqual(date.day, 1) date.day = 45 XCTAssertEqual(date.day, 1) date.day = 4 XCTAssertEqual(date.day, 4) } func testHour() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.hour, 0) date.hour = -3 XCTAssertEqual(date.hour, 0) date.hour = 25 XCTAssertEqual(date.hour, 0) date.hour = 4 XCTAssertEqual(date.hour, 4) } func testMinute() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.minute, 0) date.minute = -3 XCTAssertEqual(date.minute, 0) date.minute = 71 XCTAssertEqual(date.minute, 0) date.minute = 4 XCTAssertEqual(date.minute, 4) } func testSecond() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.second, 0) date.second = -3 XCTAssertEqual(date.second, 0) date.second = 71 XCTAssertEqual(date.second, 0) date.second = 12 XCTAssertEqual(date.second, 12) } func testNanosecond() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.nanosecond, 0) date.nanosecond = -3 XCTAssertEqual(date.nanosecond, 0) date.nanosecond = 10000 XCTAssert(date.nanosecond >= 1000) XCTAssert(date.nanosecond <= 100000) } func testMillisecond() { var date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.millisecond, 0) date.millisecond = -3 XCTAssertEqual(date.millisecond, 0) date.millisecond = 10 XCTAssert(date.millisecond >= 9) XCTAssert(date.millisecond <= 11) } func testIsInFuture() { let oldDate = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z let futureDate = Date(timeIntervalSinceNow: 512) XCTAssert(futureDate.isInFuture) XCTAssertFalse(oldDate.isInFuture) } func testIsInPast() { let oldDate = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z let futureDate = Date(timeIntervalSinceNow: 512) XCTAssert(oldDate.isInPast) XCTAssertFalse(futureDate.isInPast) } func testIsInToday() { XCTAssert(Date().isInToday) let tomorrow = Date().adding(.day, value: 1) XCTAssertFalse(tomorrow.isInToday) let yesterday = Date().adding(.day, value: -1) XCTAssertFalse(yesterday.isInToday) } func testIsInYesterday() { XCTAssertFalse(Date().isInYesterday) let tomorrow = Date().adding(.day, value: 1) XCTAssertFalse(tomorrow.isInYesterday) let yesterday = Date().adding(.day, value: -1) XCTAssert(yesterday.isInYesterday) } func testIsInTomorrow() { XCTAssertFalse(Date().isInTomorrow) let tomorrow = Date().adding(.day, value: 1) XCTAssert(tomorrow.isInTomorrow) let yesterday = Date().adding(.day, value: -1) XCTAssertFalse(yesterday.isInTomorrow) } func testIsInWeekend() { let date = Date() XCTAssertEqual(date.isInWeekend, Calendar.current.isDateInWeekend(date)) } func testIsInWeekday() { let date = Date() XCTAssertEqual(date.isInWeekday, !Calendar.current.isDateInWeekend(date)) } func testIso8601String() { let date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z XCTAssertEqual(date.iso8601String, "1970-01-01T00:08:32.000Z") } func testNearestFiveMinutes() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.nearestFiveMinutes, date) let date2 = date.adding(.minute, value: 4) // adding 4 minutes XCTAssertNotEqual(date2.nearestFiveMinutes, date) XCTAssertEqual(date2.nearestFiveMinutes, date.adding(.minute, value: 5)) let date3 = date.adding(.minute, value: 7) // adding 7 minutes XCTAssertEqual(date3.nearestFiveMinutes, date.adding(.minute, value: 5)) let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes XCTAssertEqual(date4.nearestFiveMinutes, date.adding(.hour, value: 1)) } func testNearestTenMinutes() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.nearestTenMinutes, date) let date2 = date.adding(.minute, value: 4) // adding 4 minutes XCTAssertEqual(date2.nearestTenMinutes, date) let date3 = date.adding(.minute, value: 7) // adding 7 minutes XCTAssertEqual(date3.nearestTenMinutes, date.adding(.minute, value: 10)) let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes XCTAssertEqual(date4.nearestTenMinutes, date.adding(.hour, value: 1)) } func testNearestQuarterHour() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.nearestQuarterHour, date) let date2 = date.adding(.minute, value: 4) // adding 4 minutes XCTAssertEqual(date2.nearestQuarterHour, date) let date3 = date.adding(.minute, value: 12) // adding 12 minutes XCTAssertEqual(date3.nearestQuarterHour, date.adding(.minute, value: 15)) let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes XCTAssertEqual(date4.nearestQuarterHour, date.adding(.hour, value: 1)) } func testNearestHalfHour() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.nearestHalfHour, date) let date2 = date.adding(.minute, value: 4) // adding 4 minutes XCTAssertEqual(date2.nearestHalfHour, date) let date3 = date.adding(.minute, value: 19) // adding 19 minutes XCTAssertEqual(date3.nearestHalfHour, date.adding(.minute, value: 30)) let date4 = date.adding(.hour, value: 1).adding(.minute, value: 2) // adding 1 hour and 2 minutes XCTAssertEqual(date4.nearestHalfHour, date.adding(.hour, value: 1)) } func testNearestHour() { let date = Date(timeIntervalSince1970: 0) XCTAssertEqual(date.nearestHour, date) let date2 = date.adding(.minute, value: 4) // adding 4 minutes XCTAssertEqual(date2.nearestHour, date) let date3 = date.adding(.minute, value: 34) // adding 34 minutes XCTAssertEqual(date3.nearestHour, date.adding(.hour, value: 1)) } func testTimezone() { XCTAssertEqual(Date().timeZone, Calendar.current.timeZone) } func testUnixTimestamp() { let date = Date() XCTAssertEqual(date.unixTimestamp, date.timeIntervalSince1970) let date2 = Date(timeIntervalSince1970: 100) XCTAssertEqual(date2.unixTimestamp, 100) } func testAdding() { let date = Date(timeIntervalSince1970: 3610) // Jan 1, 1970, 3:00:10 AM let date1 = date.adding(.second, value: 10) XCTAssertEqual(date1.second, date.second + 10) XCTAssertEqual(date1.adding(.second, value: -10), date) let date2 = date.adding(.minute, value: 10) XCTAssertEqual(date2.minute, date.minute + 10) XCTAssertEqual(date2.adding(.minute, value: -10), date) let date3 = date.adding(.hour, value: 2) XCTAssertEqual(date3.hour, date.hour + 2) XCTAssertEqual(date3.adding(.hour, value: -2), date) let date4 = date.adding(.day, value: 2) XCTAssertEqual(date4.day, date.day + 2) XCTAssertEqual(date4.adding(.day, value: -2), date) let date5 = date.adding(.weekOfYear, value: 1) XCTAssertEqual(date5.day, date.day + 7) XCTAssertEqual(date5.adding(.weekOfYear, value: -1), date) let date6 = date.adding(.weekOfMonth, value: 1) XCTAssertEqual(date6.day, date.day + 7) XCTAssertEqual(date6.adding(.weekOfMonth, value: -1), date) let date7 = date.adding(.month, value: 2) XCTAssertEqual(date7.month, date.month + 2) XCTAssertEqual(date7.adding(.month, value: -2), date) let date8 = date.adding(.year, value: 4) XCTAssertEqual(date8.year, date.year + 4) XCTAssertEqual(date8.adding(.year, value: -4), date) XCTAssertEqual(date.adding(.calendar, value: 10), date) } func testAdd() { var date = Date(timeIntervalSince1970: 0) date.second = 10 date.add(.second, value: -1) XCTAssertEqual(date.second, 9) date.add(.second, value: 1) XCTAssertEqual(date.second, 10) date.minute = 10 date.add(.minute, value: -1) XCTAssertEqual(date.minute, 9) date.add(.minute, value: 1) XCTAssertEqual(date.minute, 10) date.hour = 10 date.add(.hour, value: -1) XCTAssertEqual(date.hour, 9) date.add(.hour, value: 1) XCTAssertEqual(date.hour, 10) date.day = 10 date.add(.day, value: -1) XCTAssertEqual(date.day, 9) date.add(.day, value: 1) XCTAssertEqual(date.day, 10) date.month = 10 date.add(.month, value: -1) XCTAssertEqual(date.month, 9) date.add(.month, value: 1) XCTAssertEqual(date.month, 10) date = Date() date.add(.year, value: -1) XCTAssertEqual(date.year, 2016) date.add(.year, value: 1) XCTAssertEqual(date.year, 2017) } func testChanging() { let date = Date(timeIntervalSince1970: 0) XCTAssertNil(date.changing(.second, value: -10)) XCTAssertNil(date.changing(.second, value: 70)) XCTAssertNotNil(date.changing(.second, value: 20)) XCTAssertEqual(date.changing(.second, value: 20)!.second, 20) XCTAssertNil(date.changing(.minute, value: -10)) XCTAssertNil(date.changing(.minute, value: 70)) XCTAssertNotNil(date.changing(.minute, value: 20)) XCTAssertEqual(date.changing(.minute, value: 20)!.minute, 20) XCTAssertNil(date.changing(.hour, value: -2)) XCTAssertNil(date.changing(.hour, value: 25)) XCTAssertNotNil(date.changing(.hour, value: 6)) XCTAssertEqual(date.changing(.hour, value: 6)!.hour, 6) XCTAssertNil(date.changing(.day, value: -2)) XCTAssertNil(date.changing(.day, value: 35)) XCTAssertNotNil(date.changing(.day, value: 6)) XCTAssertEqual(date.changing(.day, value: 6)!.day, 6) XCTAssertNil(date.changing(.month, value: -2)) XCTAssertNil(date.changing(.month, value: 13)) XCTAssertNotNil(date.changing(.month, value: 6)) XCTAssertEqual(date.changing(.month, value: 6)!.month, 6) XCTAssertNotNil(date.changing(.year, value: 2015)) XCTAssertEqual(date.changing(.year, value: 2015)!.year, 2015) } func testBeginning() { let date = Date() XCTAssertNotNil(date.beginning(of: .second)) XCTAssertEqual(date.beginning(of: .second)!.nanosecond, 0) XCTAssertNotNil(date.beginning(of: .minute)) XCTAssertEqual(date.beginning(of: .minute)!.second, 0) XCTAssertNotNil(date.beginning(of: .hour)) XCTAssertEqual(date.beginning(of: .hour)!.minute, 0) XCTAssertNotNil(date.beginning(of: .day)) XCTAssertEqual(date.beginning(of: .day)!.hour, 0) XCTAssert(date.beginning(of: .day)!.isInToday) let beginningOfWeek = Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: date)) XCTAssertNotNil(date.beginning(of: .weekOfMonth)) XCTAssertNotNil(beginningOfWeek) XCTAssertEqual(date.beginning(of: .weekOfMonth)!.day, beginningOfWeek!.day) let beginningOfMonth = Date(year: 2016, month: 8, day: 1, hour: 5) XCTAssertNotNil(date.beginning(of: .month)) XCTAssertNotNil(beginningOfMonth) XCTAssertEqual(date.beginning(of: .month)!.day, beginningOfMonth!.day) let beginningOfYear = Date(year: 2016, month: 1, day: 1, hour: 5) XCTAssertNotNil(date.beginning(of: .year)) XCTAssertNotNil(beginningOfYear) XCTAssertEqual(date.beginning(of: .year)!.day, beginningOfYear!.day) XCTAssertNil(date.beginning(of: .quarter)) } func testEnd() { let date = Date(timeIntervalSince1970: 512) // January 1, 1970 at 2:08:32 AM GMT+2 XCTAssertEqual(date.end(of: .second)!.second , 32) XCTAssertEqual(date.end(of: .hour)!.minute, 59) XCTAssertEqual(date.end(of: .minute)!.second, 59) XCTAssertEqual(date.end(of: .day)!.hour, 23) XCTAssertEqual(date.end(of: .day)!.minute, 59) XCTAssertEqual(date.end(of: .day)!.second, 59) var endOfWeek = date.beginning(of: .weekOfYear) endOfWeek!.add(.day, value: 7) endOfWeek!.add(.second, value: -1) XCTAssertEqual(date.end(of: .weekOfYear), endOfWeek) XCTAssertEqual(date.end(of: .month)!.day, 31) XCTAssertEqual(date.end(of: .month)!.hour, 23) XCTAssertEqual(date.end(of: .month)!.minute, 59) XCTAssertEqual(date.end(of: .month)!.second, 59) XCTAssertEqual(date.end(of: .year)!.month, 12) XCTAssertEqual(date.end(of: .year)!.day, 31) XCTAssertEqual(date.end(of: .year)!.hour, 23) XCTAssertEqual(date.end(of: .year)!.minute, 59) XCTAssertEqual(date.end(of: .year)!.second, 59) XCTAssertNil(date.end(of: .quarter)) } func testDateString() { let date = Date(timeIntervalSince1970: 512) let formatter = DateFormatter() formatter.timeStyle = .none formatter.dateStyle = .short XCTAssertEqual(date.dateString(ofStyle: .short), formatter.string(from: date)) formatter.dateStyle = .medium XCTAssertEqual(date.dateString(ofStyle: .medium), formatter.string(from: date)) formatter.dateStyle = .long XCTAssertEqual(date.dateString(ofStyle: .long), formatter.string(from: date)) formatter.dateStyle = .full XCTAssertEqual(date.dateString(ofStyle: .full), formatter.string(from: date)) } func testDateTimeString() { let date = Date(timeIntervalSince1970: 512) let formatter = DateFormatter() formatter.timeStyle = .short formatter.dateStyle = .short XCTAssertEqual(date.dateTimeString(ofStyle: .short), formatter.string(from: date)) formatter.timeStyle = .medium formatter.dateStyle = .medium XCTAssertEqual(date.dateTimeString(ofStyle: .medium), formatter.string(from: date)) formatter.timeStyle = .long formatter.dateStyle = .long XCTAssertEqual(date.dateTimeString(ofStyle: .long), formatter.string(from: date)) formatter.timeStyle = .full formatter.dateStyle = .full XCTAssertEqual(date.dateTimeString(ofStyle: .full), formatter.string(from: date)) } func testIsInCurrent() { let date = Date() let oldDate = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z XCTAssert(date.isInCurrent(.second)) XCTAssertFalse(oldDate.isInCurrent(.second)) XCTAssert(date.isInCurrent(.minute)) XCTAssertFalse(oldDate.isInCurrent(.minute)) XCTAssert(date.isInCurrent(.hour)) XCTAssertFalse(oldDate.isInCurrent(.hour)) XCTAssert(date.isInCurrent(.day)) XCTAssertFalse(oldDate.isInCurrent(.day)) XCTAssert(date.isInCurrent(.weekOfMonth)) XCTAssertFalse(oldDate.isInCurrent(.weekOfMonth)) XCTAssert(date.isInCurrent(.month)) XCTAssertFalse(oldDate.isInCurrent(.month)) XCTAssert(date.isInCurrent(.year)) XCTAssertFalse(oldDate.isInCurrent(.year)) XCTAssert(date.isInCurrent(.era)) } func testTimeString() { let date = Date(timeIntervalSince1970: 512) let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short XCTAssertEqual(date.timeString(ofStyle: .short), formatter.string(from: date)) formatter.timeStyle = .medium XCTAssertEqual(date.timeString(ofStyle: .medium), formatter.string(from: date)) formatter.timeStyle = .long XCTAssertEqual(date.timeString(ofStyle: .long), formatter.string(from: date)) formatter.timeStyle = .full XCTAssertEqual(date.timeString(ofStyle: .full), formatter.string(from: date)) } func testDayName() { let date = Date(timeIntervalSince1970: 1486121165) XCTAssertEqual(date.dayName(ofStyle: .full), "Friday") XCTAssertEqual(date.dayName(ofStyle: .threeLetters), "Fri") XCTAssertEqual(date.dayName(ofStyle: .oneLetter), "F") } func testMonthName() { let date = Date(timeIntervalSince1970: 1486121165) XCTAssertEqual(date.monthName(ofStyle: .full), "February") XCTAssertEqual(date.monthName(ofStyle: .threeLetters), "Feb") XCTAssertEqual(date.monthName(ofStyle: .oneLetter), "F") } func testNewDateFromComponenets() { let date = Date(calendar: Date().calendar, timeZone: Date().timeZone, era: Date().era, year: Date().year, month: Date().month, day: Date().day, hour: Date().hour, minute: Date().minute, second: Date().second, nanosecond: Date().nanosecond) XCTAssertNotNil(date) let date1 = Date(timeIntervalSince1970: date!.timeIntervalSince1970) XCTAssertEqual(date!.timeIntervalSince1970, date1.timeIntervalSince1970) let date2 = Date(calendar: nil, timeZone: Date().timeZone, era: Date().era, year: nil, month: nil, day: Date().day, hour: Date().hour, minute: Date().minute, second: Date().second, nanosecond: Date().nanosecond) XCTAssertNil(date2) } func testNewDateFromIso8601String() { let date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z let dateFromIso8601 = Date(iso8601String: "1970-01-01T00:08:32.000Z") XCTAssertEqual(date, dateFromIso8601) XCTAssertNil(Date(iso8601String: "hello")) } func testNewDateFromUnixTimestamp() { let date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z let dateFromUnixTimestamp = Date(unixTimestamp: 512) XCTAssertEqual(date, dateFromUnixTimestamp) } }
mit
Swift3Home/Swift3_Object-oriented
013-加载百度/013-加载百度/ViewController.swift
1
1531
// // ViewController.swift // 013-加载百度 // // Created by lichuanjun on 2017/6/4. // Copyright © 2017年 lichuanjun. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // URL 的构造函数可以返回nil // 构造函数就是实例化对象的 // init?(string: String) -> 构造函数可以返回 nil let url = URL(string: "http://www.baidu.com") // 发起网络请求 // - 和 OC 的区别:Swift-闭包的所有参数,需要自己写; // OC-是直接带入 // - 优点:如果不关心的值,可以直接`_`忽略 URLSession.shared.dataTask(with: url!) { (data, _, error) in // if(error != nil) { // print("网络请求失败") // return // } guard let data = data else { print("网络请求失败 \(String(describing: error))") return } // 将 data 转换为 String let html = String(data: data, encoding: .utf8) print(html ?? "") }.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ahoppen/swift
test/AutoDiff/compiler_crashers_fixed/sr14290-missing-debug-scopes-in-pullback-trampoline.swift
11
1334
// RUN: %target-build-swift %s // RUN: %target-swift-frontend -c -g -Xllvm -verify-di-holes=true %s // rdar://74876596 ([SR-14290]: SIL verification fails when differentiating a function of [[Double]]) import _Differentiation let values: [[Double]] = [[0, 0], [0, 0]] let const = 1.12345 let result = add(const, to: values) @differentiable(reverse) func add(_ const: Double, to values: [[Double]]) -> [[Double]] { var result = values for i in withoutDerivative(at: values.indices) { for j in withoutDerivative(at: values.indices) { result.updated(at: i, j, with: values[i][j] + const) } } return result } extension Array where Element == [Double] { @differentiable(reverse) mutating func updated(at i: Int, _ j: Int, with newValue: Double) { self[i][j] = newValue } @derivative(of: updated) mutating func vjpUpdated(at i: Int, _ j: Int, with newValue: Double) -> (value: Void, pullback: (inout TangentVector) -> (Double.TangentVector)) { self.updated(at: i, j, with: newValue) func pullback(dSelf: inout TangentVector) -> (Double.TangentVector) { let dElement = dSelf[i][j] dSelf.base[i].base[j] = 0 return dElement } let value: Void = () return (value, pullback) } }
apache-2.0
EliNextMobile/detectAppExist
DetectAppExistence/DetectAppExistence/lib/CheckAppExistence.swift
1
3049
// // CheckAppExistence.swift // DetectApplication // // Created by Quan Quach on 9/17/15. // Copyright (c) 2015 Quan Quach. All rights reserved. // import UIKit class CheckAppExistence: NSObject { //// The static array containing all url schema of INSTALLED application static var foundedArr:NSMutableArray! //// The static array containing all url schma of NOT INSTALLED application static var notFoundedArr:NSMutableArray! //// static var successDownloadArr: NSMutableArray! static var notSuccessDownloadArr: NSMutableArray! //// verify the list of url schema and arrange them into two sub-categories: INSTALLED AND NOT INSTALL application //// bundleInfos - the input array consists of all unverified url schema of applications. This argument must not be nil //// Returns a string of result static func detectRelatedApplicationWithURLSchema(bundleInfos:NSMutableArray!) -> String { var url:NSURL! foundedArr = NSMutableArray() notFoundedArr = NSMutableArray() successDownloadArr = NSMutableArray() notSuccessDownloadArr = NSMutableArray() for (var i = 0;i < bundleInfos.count;++i) { let bundleInfo = bundleInfos.objectAtIndex(i) as! NSDictionary let schema = String(format: "%@://", bundleInfo.objectForKey("appScheme") as! String) url = NSURL(string: schema) if (UIApplication.sharedApplication().canOpenURL(url)) { foundedArr.addObject(bundleInfo.objectForKey("appScheme") as! String) } else { notFoundedArr.addObject(bundleInfo.objectForKey("appScheme") as! String) if ((bundleInfo.objectForKey("image")) == nil) { let data = NSData(contentsOfURL: NSURL(string: bundleInfo.objectForKey("imageURL") as! String)!) if (data != nil) { let dict = NSMutableDictionary(dictionary: bundleInfo) let image = UIImage(data: data!) if (image != nil) { dict.setObject(data!, forKey: "image") bundleInfos.replaceObjectAtIndex(i, withObject: dict) successDownloadArr.addObject(dict.objectForKey("appScheme") as! String) } else { notSuccessDownloadArr.addObject(bundleInfo.objectForKey("appScheme") as! String) } } else { notSuccessDownloadArr.addObject(bundleInfo.objectForKey("appScheme") as! String) } } } } let message = NSString(format: "Installed app: %@\rNot installed ap:%@\rSuccessfully download:%@\rNot successfully download:%@", self.foundedArr,self.notFoundedArr,self.successDownloadArr,self.notSuccessDownloadArr) return message as String } }
mit
dreamsxin/swift
test/IRGen/module_hash.swift
9
2870
// RUN: rm -rf %t && mkdir -p %t // Test with a single output file // RUN: echo "single-threaded initial" >%t/log // RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: single-threaded initial // CHECK: test.o: MD5=[[TEST_MD5:[0-9a-f]+]] // CHECK-NOT: prev MD5 // RUN: echo "single-threaded same compilation" >>%t/log // RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: single-threaded same compilation // CHECK: test.o: MD5=[[TEST_MD5]] // CHECK: test.o: prev MD5=[[TEST_MD5]] skipping // RUN: echo "single-threaded file changed" >>%t/log // RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple2.swift -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: single-threaded file changed // CHECK: test.o: MD5=[[TEST2_MD5:[0-9a-f]+]] // CHECK: test.o: prev MD5=[[TEST_MD5]] recompiling // RUN: echo "single-threaded option changed" >>%t/log // RUN: %target-swift-frontend -O -wmo %s %S/Inputs/simple2.swift -disable-llvm-optzns -module-name=test -c -o %t/test.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: single-threaded option changed // CHECK: test.o: MD5=[[TEST3_MD5:[0-9a-f]+]] // CHECK: test.o: prev MD5=[[TEST2_MD5]] recompiling // Test with multiple output files // RUN: echo "multi-threaded initial" >>%t/log // RUN: %target-swift-frontend -O -wmo -num-threads 2 %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -o %t/simple.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: multi-threaded initial // CHECK-DAG: test.o: MD5=[[TEST4_MD5:[0-9a-f]+]] // CHECK-DAG: test.o: prev MD5=[[TEST3_MD5]] recompiling // CHECK-DAG: simple.o: MD5=[[SIMPLE_MD5:[0-9a-f]+]] // RUN: echo "multi-threaded same compilation" >>%t/log // RUN: %target-swift-frontend -O -wmo -num-threads 2 %s %S/Inputs/simple.swift -module-name=test -c -o %t/test.o -o %t/simple.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: multi-threaded same compilation // CHECK-DAG: test.o: MD5=[[TEST4_MD5]] // CHECK-DAG: test.o: prev MD5=[[TEST4_MD5]] skipping // CHECK-DAG: simple.o: MD5=[[SIMPLE_MD5]] // CHECK-DAG: simple.o: prev MD5=[[SIMPLE_MD5]] skipping // RUN: echo "multi-threaded one file changed" >>%t/log // RUN: %target-swift-frontend -O -wmo -num-threads 2 %s %S/Inputs/simple2.swift -module-name=test -c -o %t/test.o -o %t/simple.o -Xllvm -debug-only=irgen 2>>%t/log // CHECK-LABEL: multi-threaded one file changed // CHECK-DAG: test.o: MD5=[[TEST4_MD5]] // CHECK-DAG: test.o: prev MD5=[[TEST4_MD5]] skipping // CHECK-DAG: simple.o: MD5=[[SIMPLE2_MD5:[0-9a-f]+]] // CHECK-DAG: simple.o: prev MD5=[[SIMPLE_MD5]] recompiling // RUN: FileCheck %s < %t/log // REQUIRES: asserts public func test_func1() { print("Hello") }
apache-2.0
watson-developer-cloud/ios-sdk
Sources/DiscoveryV2/Models/QueryGroupByAggregation.swift
1
1337
/** * (C) Copyright IBM Corp. 2020. * * 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 /** Returns the top values for the field specified. Enums with an associated value of QueryGroupByAggregation: QueryAggregation */ public struct QueryGroupByAggregation: Codable, Equatable { /** The type of aggregation command used. Options include: term, histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and top_hits. */ public var type: String /** Array of top values for the field. */ public var results: [QueryGroupByAggregationResult]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case type = "type" case results = "results" } }
apache-2.0
miroslavkovac/Lingo
Sources/Lingo/Pluralization/Concrete/nn.swift
1
109
import Foundation final class nn: OneOther, PluralizationRule { let locale: LocaleIdentifier = "nn" }
mit
UTBiomedicalInformaticsLab/ProbabilityWheeliOS
Probability Wheel/Controllers/OptionTableViewCell.swift
1
3314
// // OptionTableViewCell.swift // Probability Wheel // // Created by Allen Wang on 11/1/15. // Copyright © 2015 UT Biomedical Informatics Lab. All rights reserved. // import UIKit protocol OptionCellUpdater { func updateTable() } class OptionTableViewCell: UITableViewCell, UITextFieldDelegate { let maxStringLength = 25 let sharedInfo = SharedInfo.sharedInstance let activeColor = UIColor(red: 82 / 255 , green: 144 / 255, blue: 252 / 255, alpha: 1) let inactiveColor = UIColor(red: 111 / 255, green: 113 / 255, blue: 120 / 255, alpha: 1) @IBOutlet weak var ActiveButton: UIButton! @IBOutlet weak var UserText: UITextField! @IBOutlet weak var Percentage: UILabel! var delegate: OptionCellUpdater? var option : Option? { didSet { updateUI() } } @IBAction func ActivationToggled(sender: UIButton) { if self.option != nil { if self.option!.isActive() { if sharedInfo.activeOptionsCount() <= 2 { return } self.option!.setInactive() sender.setTitleColor(inactiveColor, forState: UIControlState.Normal) print("Option \(option!.getIndex()) set inactive") } else { self.option!.setActive() sender.setTitleColor(activeColor, forState: UIControlState.Normal) print("Option \(option!.getIndex()) set active") } delegate?.updateTable() } } @IBAction func UserTextChanged(sender: UITextField) { if self.option != nil { let oldText = option!.getText() option!.setText(sender.text!) print("Text in Option \(option!.getIndex()) changed from \(oldText) to \(sender.text!)") delegate?.updateTable() } } // This delegate will limit the text field's input to a number of characters // as defined in the constant maxStringLength func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let currentString: NSString = textField.text! let newString: NSString = currentString.stringByReplacingCharactersInRange(range, withString: string) return newString.length <= maxStringLength } func textFieldShouldReturn(textField: UITextField) -> Bool { self.UserText.endEditing(true) return false } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.UserText.endEditing(true) } func updateUI() { if let option = self.option { UserText.delegate = self UserText?.text = option.getText() let displayedPercentage = option.getPercentage() * 100 let displayString = String(format: "%.1f", displayedPercentage) + "%" Percentage?.text = displayString if (option.isActive()) { ActiveButton?.backgroundColor = option.getColor() } else { ActiveButton?.backgroundColor = inactiveColor } } } func getOption() -> Option? { return option } }
mit
Loveswift/BookReview
BookReview/BookReview/ChoiceTableViewCell.swift
1
932
// // ChoiceTableViewCell.swift // BookReview // // Created by xjc on 16/5/22. // Copyright © 2016年 xjc. All rights reserved. // import UIKit class ChoiceTableViewCell: UITableViewCell { @IBOutlet weak var bottomView: UIView! @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var userName: UILabel! @IBOutlet weak var bookName: UILabel! @IBOutlet weak var sendTime: UILabel! @IBOutlet weak var contentLab: UILabel! override func awakeFromNib() { super.awakeFromNib() self.userImage.layer.cornerRadius = self.userImage.layer.bounds.height/2 self.userImage.layer.masksToBounds = true self.bottomView.layer.cornerRadius = 3 self.bottomView.layer.masksToBounds = true } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
apache-2.0
icerockdev/IRPDFKit
IRPDFKit/Classes/Search/IRPDFSearchResult.swift
1
2286
// // Created by Aleksey Mikhailov on 12/10/16. // Copyright © 2016 IceRock Development. All rights reserved. // import Foundation public struct IRPDFSearchResultPart: Equatable { public let startX: Float public let endX: Float public let width: Float public let height: Float public let transform: [Float] public init(startX: Float, endX: Float, width: Float, height: Float, transform: [Float]) { self.startX = startX self.endX = endX self.width = width self.height = height self.transform = transform } } public struct IRPDFSearchResult: Equatable { public let page: Int public let contextString: String public let queryInContextRange: Range<String.Index> public let startPosition: Int public let endPosition: Int public let parts: [IRPDFSearchResultPart] public init(page: Int, contextString: String, queryInContextRange: Range<String.Index>, startPosition: Int, endPosition: Int, parts: [IRPDFSearchResultPart]) { self.page = page self.contextString = contextString self.queryInContextRange = queryInContextRange self.startPosition = startPosition self.endPosition = endPosition self.parts = parts } } public func ==(lhs: IRPDFSearchResult, rhs: IRPDFSearchResult) -> Bool { if lhs.page != rhs.page { return false } if lhs.contextString != rhs.contextString { return false } if lhs.queryInContextRange != rhs.queryInContextRange { return false } if lhs.startPosition != rhs.startPosition { return false } if lhs.endPosition != rhs.endPosition { return false } if lhs.parts.count != rhs.parts.count { return false } if lhs.parts.count > 0 { for i in (0 ... lhs.parts.count - 1) { if lhs.parts[i] != rhs.parts[i] { return false } } } return true } public func ==(lhs: IRPDFSearchResultPart, rhs: IRPDFSearchResultPart) -> Bool { if lhs.startX != rhs.startX { return false } if lhs.endX != rhs.endX { return false } if lhs.width != rhs.width { return false } if lhs.height != rhs.height { return false } if lhs.transform != rhs.transform { return false } return true }
mit
idapgroup/IDPDesign
Tests/iOS/Pods/Quick/Sources/Quick/ExampleMetadata.swift
67
1029
import Foundation // `#if swift(>=3.2) && (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE` // does not work as expected. #if swift(>=3.2) #if (os(macOS) || os(iOS) || os(tvOS) || os(watchOS)) && !SWIFT_PACKAGE @objcMembers public class _ExampleMetadataBase: NSObject {} #else public class _ExampleMetadataBase: NSObject {} #endif #else public class _ExampleMetadataBase: NSObject {} #endif /** A class that encapsulates information about an example, including the index at which the example was executed, as well as the example itself. */ final public class ExampleMetadata: _ExampleMetadataBase { /** The example for which this metadata was collected. */ public let example: Example /** The index at which this example was executed in the test suite. */ public let exampleIndex: Int internal init(example: Example, exampleIndex: Int) { self.example = example self.exampleIndex = exampleIndex } }
bsd-3-clause
satoshi0212/GeoFenceDemo
GeoFenceDemo/Models/GeoFenceItem.swift
1
2518
// // GeoFenceItem.swift // GeoFenceDemo // // Created by Satoshi Hattori on 2016/08/08. // Copyright © 2016年 Satoshi Hattori. All rights reserved. // import MapKit import CoreLocation let GEO_FENCE_ITEM_LatitudeKey = "latitude" let GEO_FENCE_ITEM_LongitudeKey = "longitude" let GEO_FENCE_ITEM_RadiusKey = "radius" let GEO_FENCE_ITEM_IdentifierKey = "identifier" let GEO_FENCE_ITEM_NoteKey = "note" let GEO_FENCE_ITEM_EventTypeKey = "eventType" enum EventType: Int { case OnEntry = 0 case OnExit } class GeoFenceItem: NSObject, NSCoding, MKAnnotation { var coordinate: CLLocationCoordinate2D var radius: CLLocationDistance var identifier: String var note: String var eventType: EventType var title: String? { if note.isEmpty { return "No Note" } return note } var subtitle: String? { let eventTypeString = eventType == .OnEntry ? "On Entry" : "On Exit" return "Radius: \(radius)m - \(eventTypeString)" } init(coordinate: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String, note: String, eventType: EventType) { self.coordinate = coordinate self.radius = radius self.identifier = identifier self.note = note self.eventType = eventType } // MARK: NSCoding required init?(coder decoder: NSCoder) { let latitude = decoder.decodeDoubleForKey(GEO_FENCE_ITEM_LatitudeKey) let longitude = decoder.decodeDoubleForKey(GEO_FENCE_ITEM_LongitudeKey) coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) radius = decoder.decodeDoubleForKey(GEO_FENCE_ITEM_RadiusKey) identifier = decoder.decodeObjectForKey(GEO_FENCE_ITEM_IdentifierKey) as! String note = decoder.decodeObjectForKey(GEO_FENCE_ITEM_NoteKey) as! String eventType = EventType(rawValue: decoder.decodeIntegerForKey(GEO_FENCE_ITEM_EventTypeKey))! } func encodeWithCoder(coder: NSCoder) { coder.encodeDouble(coordinate.latitude, forKey: GEO_FENCE_ITEM_LatitudeKey) coder.encodeDouble(coordinate.longitude, forKey: GEO_FENCE_ITEM_LongitudeKey) coder.encodeDouble(radius, forKey: GEO_FENCE_ITEM_RadiusKey) coder.encodeObject(identifier, forKey: GEO_FENCE_ITEM_IdentifierKey) coder.encodeObject(note, forKey: GEO_FENCE_ITEM_NoteKey) coder.encodeInt(Int32(eventType.rawValue), forKey: GEO_FENCE_ITEM_EventTypeKey) } }
mit
dclelland/HOWL
HOWL/View Controllers/Keyboard/KeyboardViewCell.swift
1
587
// // KeyboardViewCell.swift // HOWL // // Created by Daniel Clelland on 15/11/15. // Copyright © 2015 Daniel Clelland. All rights reserved. // import UIKit import SnapKit class KeyboardViewCell: UICollectionViewCell { @IBOutlet var textLabel: UILabel! override class var layerClass: AnyClass { return CAShapeLayer.self } override func awakeFromNib() { if let layer = layer as? CAShapeLayer { layer.strokeColor = UIColor.protonomeBlack.cgColor layer.lineWidth = CGFloat(2.squareRoot()) } } }
mit
ashfurrow/Swift-Course
Step 3/Step 3/AppDelegate.swift
1
2170
// // AppDelegate.swift // Step 3 // // Created by Ash Furrow on 2014-09-27. // Copyright (c) 2014 Ash Furrow. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
tottokotkd/PopUpPickerView
PopUpPickerViewBase.swift
1
2375
// // PopUpPickerViewBase.swift // AITravel-iOS // // Created by 村田 佑介 on 2016/06/27. // Copyright © 2016年 Best10, Inc. All rights reserved. // import UIKit class PopUpPickerViewBase: UIView { var pickerToolbar: UIToolbar! var toolbarItems = [UIBarButtonItem]() lazy var doneButtonItem: UIBarButtonItem = { return UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(self.endPicker)) }() // MARK: Initializer init() { super.init(frame: CGRect.zero) initFunc() } override init(frame: CGRect) { super.init(frame: frame) initFunc() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initFunc() } private func initFunc() { let screenSize = UIScreen.mainScreen().bounds.size self.backgroundColor = UIColor.blackColor() pickerToolbar = UIToolbar() pickerToolbar.translucent = true self.bounds = CGRectMake(0, 0, screenSize.width, 260) self.frame = CGRectMake(0, parentViewHeight(), screenSize.width, 260) pickerToolbar.bounds = CGRectMake(0, 0, screenSize.width, 44) pickerToolbar.frame = CGRectMake(0, 0, screenSize.width, 44) let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil) space.width = 12 let cancelItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(PopUpPickerView.cancelPicker)) let flexSpaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil) toolbarItems = [space, cancelItem, flexSpaceItem, doneButtonItem, space] pickerToolbar.setItems(toolbarItems, animated: false) self.addSubview(pickerToolbar) } // MARK: Actions func showPicker() { } func cancelPicker() { } func endPicker() { } func hidePicker() { let screenSize = UIScreen.mainScreen().bounds.size UIView.animateWithDuration(0.2) { self.frame = CGRectMake(0, self.parentViewHeight(), screenSize.width, 260.0) } } func parentViewHeight() -> CGFloat { return superview?.frame.height ?? UIScreen.mainScreen().bounds.size.height } }
unlicense
IndhujaG/SpinButton
Example/SpinButton/AppDelegate.swift
1
2141
// // AppDelegate.swift // SpinButton // // Created by Indhuja on 08/17/2016. // Copyright (c) 2016 Indhuja. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
MattLewin/Interview-Prep
Cracking the Coding Interview.playground/Sources/Trees and Graphs.swift
1
5407
import Foundation //: # Trees and Graphs /*: --- Helper methods and data structures */ public class BinaryTreeNode<Element>: CustomStringConvertible { public var value: Element public var left: BinaryTreeNode<Element>? public var right: BinaryTreeNode<Element>? public var parent: BinaryTreeNode<Element>? /// An optional function to be executed when "visiting" this node public var visit: (() -> Void)? public init(value: Element) { self.value = value } // MARK: CustomStringConvertible public var description: String { return String(describing: value) } } // MARK: Binary Tree Traversal /// Perform in-order traversal of `node`. (i.e., left branch, current node, right branch) /// /// - Parameters /// - node: the node to be traversed /// - debug: whether to print the tree while traversing (defaults to `false`) /// - indent: the indentation string used in debug output public func inOrderTraversal<T>(_ node: BinaryTreeNode<T>?, debug: Bool = false, indent: String = "") { guard let root = node else { return } inOrderTraversal(root.left, debug: debug, indent: indent + "L") if debug { print("\(indent) \(root.value)") } if let visitor = root.visit { visitor() } inOrderTraversal(root.right, debug: debug, indent: indent + "R") } /// Perform pre-order traversal of `node`. (i.e., current node, left branch, right branch) /// /// - Parameters /// - node: the node to be traversed /// - debug: whether to print the tree while traversing (defaults to `false`) /// - indent: the indentation string used in debug output public func preOrderTraversal<T>(_ node: BinaryTreeNode<T>?, debug: Bool = false, indent: String = "") { guard let root = node else { return } if debug { print("\(indent) \(root.value)") } if let visitor = root.visit { visitor() } preOrderTraversal(root.left, debug: debug, indent: indent + "L") preOrderTraversal(root.right, debug: debug, indent: indent + "R") } /// Perform post-order traversal of `node`. (i.e., left branch, right branch, current node) /// /// - Parameters /// - node: the node to be traversed /// - debug: whether to print the tree while traversing (defaults to `false`) /// - indent: the indentation string used in debug output public func postOrderTraversal<T>(_ node: BinaryTreeNode<T>?, debug: Bool = false, indent: String = "") { guard let root = node else { return } postOrderTraversal(root.left, debug: debug, indent: indent + "L") postOrderTraversal(root.right, debug: debug, indent: indent + "$") if debug { print("\(indent) \(root.value)") } if let visitor = root.visit { visitor() } } /// Make a complete binary tree from the provided text /// /// - Parameter string: the text to transform into a binary tree /// - Returns: the root node of the binary tree public func makeBinaryTree(from string: String) -> BinaryTreeNode<Character>? { var rootNode: BinaryTreeNode<Character>? var nodeQueue = [BinaryTreeNode<Character>]() func hasBothChildren<T>(_ node: BinaryTreeNode<T>) -> Bool { return node.left != nil && node.right != nil } for char in string { let newNode = BinaryTreeNode(value: char) if rootNode == nil { rootNode = newNode } else { if nodeQueue.first?.left == nil { nodeQueue.first?.left = newNode } else if nodeQueue.first?.right == nil { nodeQueue.first?.right = newNode } if hasBothChildren(nodeQueue.first!) { nodeQueue.removeFirst() } } nodeQueue.append(newNode) } return rootNode } // MARK: - public class Graph<Element>: CustomStringConvertible { public var nodes = [GraphNode<Element>]() // MARK: CustomStringConvertible public var description: String { return "*** DESCRIPTION NOT YET IMPLEMENTED ***" } } public class GraphNode<Element>: CustomStringConvertible { public var value: Element public var adjacent = [GraphNode<Element>]() public var visit: (() -> Void)? public var visited = false public init(value: Element) { self.value = value } // MARK: CustomStringConvertible public var description: String { let elementType = String(describing: Element.self) return "GraphNode<\(elementType)> { value:\(value), adjacent nodes:\(adjacent.count) }" } } // MARK: Graph Search / Traversal public func depthFirstSearch<T>(_ root: GraphNode<T>?) { guard let root = root else { return } if let visitor = root.visit { visitor() } root.visited = true for node in root.adjacent { if !node.visited { depthFirstSearch(node) } } } public func breadthFirstSearch<T>(_ root: GraphNode<T>?) { guard let root = root else { return } let toProcess = Queue<GraphNode<T>>() root.visited = true toProcess.enqueue(root) repeat { let head = try! toProcess.dequeue() if let visitor = head.visit { visitor() } for node in head.adjacent { if node.visited == false { node.visited = true toProcess.enqueue(node) } } } while !toProcess.isEmpty() }
unlicense
asharijuang/iOS-timer
iOS StopWatchUITests/iOS_StopWatchUITests.swift
1
1072
// // iOS_StopWatchUITests.swift // iOS StopWatchUITests // // Created by Ashari Juang on 8/14/15. // Copyright © 2015 kodejs. All rights reserved. // import XCTest class iOS_StopWatchUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
mapsme/omim
iphone/Maps/Core/DeepLink/Strategies/DeepLinkSearchStrategy.swift
5
1076
class DeepLinkSearchStrategy: IDeepLinkHandlerStrategy{ var deeplinkURL: DeepLinkURL private var data: DeepLinkSearchData init(url: DeepLinkURL, data: DeepLinkSearchData) { self.deeplinkURL = url self.data = data } func execute() { let kSearchInViewportZoom: Int32 = 16; // Set viewport only when cll parameter was provided in url. if (data.centerLat != 0.0 && data.centerLon != 0.0) { MapViewController.setViewport(data.centerLat, lon: data.centerLon, zoomLevel: kSearchInViewportZoom) // We need to update viewport for search api manually because of drape engine // will not notify subscribers when search view is shown. if (!data.isSearchOnMap) { data.onViewportChanged(kSearchInViewportZoom) } } if (data.isSearchOnMap) { MWMMapViewControlsManager.manager()?.searchText(onMap: data.query, forInputLocale: data.locale) } else { MWMMapViewControlsManager.manager()?.searchText(data.query, forInputLocale: data.locale) } sendStatisticsOnSuccess(type: kStatSearch) } }
apache-2.0
artsy/eigen
ios/ArtsyTests/View_Controller_Tests/Auction/Views/TextStackTests.swift
1
1511
import Quick import Nimble import Nimble_Snapshots import Interstellar import UIKit @testable import Artsy class TextStackTests: QuickSpec { override func spec() { it("looks like the API spec") { let subject = TextStack() subject.constrainWidth("280") subject.backgroundColor = .white subject.addBigHeading("Biggest Heading") subject.addThickLineBreak() subject.addSmallHeading("Smaller Heading") subject.addSmallLineBreak() subject.addArtistName("Artist Name") subject.addArtworkName("Artwork Name", date: "date") subject.addSmallLineBreak() subject.addBodyMarkdown("Markdown body text with [link](/link).") subject.addSmallLineBreak() subject.addBodyText("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.") subject.addSmallLineBreak() expect(subject) == snapshot() } } }
mit
Bartlebys/Bartleby
Bartleby.xOS/core/RelationShip.swift
1
560
// // RelationShip.swift // bartleby // // Created by Benoit Pereira da silva on 26/12/2016. // Copyright © 2016 Benoit Pereira da silva. All rights reserved. // import Foundation public enum Relationship:String{ /// Serialized into the Object case free = "free" case ownedBy = "ownedBy" /// "owns" is Computed at runtime during registration to determine the the Subject /// Ownership is computed asynchronously for better resilience to distributed pressure /// Check ManagedCollection.propagate() case owns = "owns" }
apache-2.0
dbaldwin/DronePan
DronePanTests/PanoramaControllerTests.swift
1
4012
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import XCTest @testable import DronePan class PanoramaControllerTests: XCTestCase { let panoramaController = PanoramaController() func testPitchesForAircraftMaxPitch0False() { let value = panoramaController.pitchesForLoop(maxPitch: 0, maxPitchEnabled: false, type: .Aircraft, rowCount: 3) XCTAssertEqual([0, -30, -60], value, "Incorrect pitches for max pitch 0 ac false \(value)") } func testPitchesForAircraftMaxPitch0True() { let value = panoramaController.pitchesForLoop(maxPitch: 0, maxPitchEnabled: true, type: .Aircraft, rowCount: 3) XCTAssertEqual([0, -30, -60], value, "Incorrect pitches for max pitch 0 ac true \(value)") } func testPitchesForAircraftMaxPitch30False() { let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: false, type: .Aircraft, rowCount: 3) XCTAssertEqual([0, -30, -60], value, "Incorrect pitches for max pitch 30 ac false \(value)") } func testPitchesForAircraftMaxPitch30True() { let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: true, type: .Aircraft, rowCount: 3) XCTAssertEqual([30, -10, -50], value, "Incorrect pitches for max pitch 30 ac true \(value)") } func testPitchesForAircraftMaxPitch305Rows() { let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: true, type: .Aircraft, rowCount: 5) XCTAssertEqual([30, 6, -18, -42, -66], value, "Incorrect pitches for max pitch 30 row count 5 ac \(value)") } func testPitchesForHandheldMaxPitch30() { let value = panoramaController.pitchesForLoop(maxPitch: 30, maxPitchEnabled: true, type: .Handheld, rowCount: 4) XCTAssertEqual([-60, -30, 0, 30], value, "Incorrect pitches for max pitch 30 handheld \(value)") } func testYawAnglesForCount10WithHeading0() { let value = panoramaController.yawAngles(count: 10, heading: 0) XCTAssertEqual([36, 72, 108, 144, 180, 216, 252, 288, 324, 360], value, "Incorrect angles for count 10 heading 0 \(value)") } func testYawAnglesForCount6WithHeading0() { let value = panoramaController.yawAngles(count: 6, heading: 0) XCTAssertEqual([60, 120, 180, 240, 300, 360], value, "Incorrect angles for count 6 heading 0 \(value)") } func testYawAnglesForCount10WithHeading84() { let value = panoramaController.yawAngles(count: 10, heading: 84) XCTAssertEqual([120, 156, 192, 228, 264, 300, 336, 12, 48, 84], value, "Incorrect angles for count 10 heading 84 \(value)") } func testYawAnglesForCount6WithHeadingNeg84() { let value = panoramaController.yawAngles(count: 6, heading: -84) XCTAssertEqual([-24, 36, 96, 156, 216, 276], value, "Incorrect angles for count 6 heading -84 \(value)") } func testHeadingTo360() { let value = panoramaController.headingTo360(0) XCTAssertEqual(0, value, "Incorrect heading for 0 \(value)") } func testHeadingTo360Negative() { let value = panoramaController.headingTo360(-117) XCTAssertEqual(243, value, "Incorrect heading for -117 \(value)") } func testHeadingTo360Positive() { let value = panoramaController.headingTo360(117) XCTAssertEqual(117, value, "Incorrect heading for 117 \(value)") } }
gpl-3.0
khizkhiz/swift
validation-test/stdlib/HashingICU.swift
8
621
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: OS=linux-gnu // Validation of hashes produced by ICU-based methods used on linux. Doesn't // use StdlibUnittest because that doesn't work on linux yet. May go away in // favour of the more comprehensive tests that already exist once it does. // Let's not crash on changing case. let upper = "\u{00df}".uppercased() let lower = "\u{0130}".lowercased() // ASCII strings // CHECK: true print("abc".hashValue == "\0abc".hashValue) // Unicode strings // CHECK-NEXT: true print("abc\u{0130}".hashValue == "\0abc\u{0130}".hashValue)
apache-2.0
ti-gars/BugTracker
macOS/BugTracker_macOS/BugTracker_macOS/GlobalVariables.swift
1
342
// // GlobalVariables.swift // BugTracker_macOS // // Created by Charles-Olivier Demers on 2015-09-20. // Copyright (c) 2015 Charles-Olivier Demers. All rights reserved. // import Foundation var ISSUETYPE_BUG = 0 var ISSUETYPE_FEATURES = 1 var ISSUETYPE_TOTRY = 2 var globalIssue: [Issue] = [Issue]() var globalUsers: [User] = [User]()
mit
Floater-ping/DYDemo
DYDemo/DYDemo/Classes/Home/Model/CycleModel.swift
1
830
// // CycleModel.swift // DYDemo // // Created by ZYP-MAC on 2017/8/9. // Copyright © 2017年 ZYP-MAC. All rights reserved. // import UIKit class CycleModel: NSObject { /// 标题 var title : String = "" /// 图片地址 var pic_url : String = "" /// 主播信息对应的字典 var room : [String : Any]? { didSet { guard let room = room else { return } anchor = AnchorModel(dict: room) } } /// 主播信息对应的模型对象 var anchor : AnchorModel? /// 自定义构造函数 init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
mit
SheffieldKevin/swiftsvg2
SwiftSVGiOSTests/SwiftSVGiOSTests.swift
1
985
// // SwiftSVGiOSTests.swift // SwiftSVGiOSTests // // Created by Kevin Meaney on 03/11/2015. // Copyright © 2015 No. All rights reserved. // import XCTest @testable import SwiftSVGiOS class SwiftSVGiOSTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
bsd-2-clause
joerocca/GitHawk
Pods/Tabman/Sources/Tabman/Utilities/ColorUtils.swift
1
1241
// // ColorUtils.swift // Tabman // // Created by Merrick Sapsford on 22/02/2017. // Copyright © 2017 Merrick Sapsford. All rights reserved. // import UIKit internal extension UIColor { static func interpolate(betweenColor colorA: UIColor, and colorB: UIColor, percent: CGFloat) -> UIColor? { var redA: CGFloat = 0.0 var greenA: CGFloat = 0.0 var blueA: CGFloat = 0.0 var alphaA: CGFloat = 0.0 guard colorA.getRed(&redA, green: &greenA, blue: &blueA, alpha: &alphaA) else { return nil } var redB: CGFloat = 0.0 var greenB: CGFloat = 0.0 var blueB: CGFloat = 0.0 var alphaB: CGFloat = 0.0 guard colorB.getRed(&redB, green: &greenB, blue: &blueB, alpha: &alphaB) else { return nil } let iRed = CGFloat(redA + percent * (redB - redA)) let iBlue = CGFloat(blueA + percent * (blueB - blueA)) let iGreen = CGFloat(greenA + percent * (greenB - greenA)) let iAlpha = CGFloat(alphaA + percent * (alphaB - alphaA)) return UIColor(red: iRed, green: iGreen, blue: iBlue, alpha: iAlpha) } }
mit
prebid/prebid-mobile-ios
InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Adapters/Prebid/MAX/PrebidMAXInterstitialController.swift
1
7821
/*   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 UIKit import AppLovinSDK import PrebidMobile import PrebidMobileMAXAdapters class PrebidMAXInterstitialController: NSObject, AdaptedController, PrebidConfigurableController { var prebidConfigId: String = "" var storedAuctionResponse = "" var maxAdUnitId = "" var adFormats: Set<AdFormat>? private var adUnit: MediationInterstitialAdUnit? private var mediationDelegate: MAXMediationInterstitialUtils? private var interstitial: MAInterstitialAd? private weak var adapterViewController: AdapterViewController? private let fetchDemandFailedButton = EventReportContainer() private let didLoadAdButton = EventReportContainer() private let didFailToLoadAdForAdUnitIdentifierButton = EventReportContainer() private let didFailToDisplayButton = EventReportContainer() private let didDisplayAdButton = EventReportContainer() private let didHideAdButton = EventReportContainer() private let didClickAdButton = EventReportContainer() private let configIdLabel = UILabel() // Custom video configuarion var maxDuration: Int? var closeButtonArea: Double? var closeButtonPosition: Position? var skipButtonArea: Double? var skipButtonPosition: Position? var skipDelay: Double? // MARK: - AdaptedController required init(rootController: AdapterViewController) { self.adapterViewController = rootController super.init() setupAdapterController() } deinit { Prebid.shared.storedAuctionResponse = nil } func configurationController() -> BaseConfigurationController? { return BaseConfigurationController(controller: self) } func loadAd() { Prebid.shared.storedAuctionResponse = storedAuctionResponse configIdLabel.isHidden = false configIdLabel.text = "Config ID: \(prebidConfigId)" interstitial = MAInterstitialAd(adUnitIdentifier: maxAdUnitId) interstitial?.delegate = self mediationDelegate = MAXMediationInterstitialUtils(interstitialAd: interstitial!) adUnit = MediationInterstitialAdUnit(configId: prebidConfigId, minSizePercentage: CGSize(width: 30, height: 30), mediationDelegate: mediationDelegate!) // Custom video configuarion if let maxDuration = maxDuration { adUnit?.videoParameters.maxDuration = SingleContainerInt(integerLiteral: maxDuration) } if let closeButtonArea = closeButtonArea { adUnit?.closeButtonArea = closeButtonArea } if let closeButtonPosition = closeButtonPosition { adUnit?.closeButtonPosition = closeButtonPosition } if let skipButtonArea = skipButtonArea { adUnit?.skipButtonArea = skipButtonArea } if let skipButtonPosition = skipButtonPosition { adUnit?.skipButtonPosition = skipButtonPosition } if let skipDelay = skipDelay { adUnit?.skipDelay = skipDelay } if let adFormats = adFormats { adUnit?.adFormats = adFormats } if let adUnitContext = AppConfiguration.shared.adUnitContext { for dataPair in adUnitContext { adUnit?.addContextData(dataPair.value, forKey: dataPair.key) } } if let userData = AppConfiguration.shared.userData { for dataPair in userData { let appData = PBMORTBContentData() appData.ext = [dataPair.key: dataPair.value] adUnit?.addUserData([appData]) } } if let appData = AppConfiguration.shared.appContentData { for dataPair in appData { let appData = PBMORTBContentData() appData.ext = [dataPair.key: dataPair.value] adUnit?.addAppContentData([appData]) } } adUnit?.fetchDemand { [weak self] result in guard let self = self else { return } if result != .prebidDemandFetchSuccess { self.fetchDemandFailedButton.isEnabled = true } self.interstitial?.load() } } // MARK: - Private Methods private func setupAdapterController() { adapterViewController?.bannerView.isHidden = true setupShowButton() setupActions() configIdLabel.isHidden = true adapterViewController?.actionsView.addArrangedSubview(configIdLabel) } private func setupShowButton() { adapterViewController?.showButton.isEnabled = false adapterViewController?.showButton.addTarget(self, action:#selector(self.showButtonClicked), for: .touchUpInside) } private func setupActions() { adapterViewController?.setupAction(fetchDemandFailedButton, "fetchDemandFailed called") adapterViewController?.setupAction(didLoadAdButton, "didLoadAd called") adapterViewController?.setupAction(didFailToLoadAdForAdUnitIdentifierButton, "didFailToLoadAdForAdUnitIdentifier called") adapterViewController?.setupAction(didFailToDisplayButton, "didFailToDisplay called") adapterViewController?.setupAction(didDisplayAdButton, "didDisplayAd called") adapterViewController?.setupAction(didHideAdButton, "didHideAd called") adapterViewController?.setupAction(didClickAdButton, "didClickAd called") } private func resetEvents() { fetchDemandFailedButton.isEnabled = false didLoadAdButton.isEnabled = false didFailToLoadAdForAdUnitIdentifierButton.isEnabled = false didFailToDisplayButton.isEnabled = false didDisplayAdButton.isEnabled = false didHideAdButton.isEnabled = false didClickAdButton.isEnabled = false } @IBAction func showButtonClicked() { if let interstitial = interstitial, interstitial.isReady { adapterViewController?.showButton.isEnabled = false interstitial.show() } } } extension PrebidMAXInterstitialController: MAAdDelegate { func didLoad(_ ad: MAAd) { resetEvents() didLoadAdButton.isEnabled = true adapterViewController?.showButton.isEnabled = true } func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) { Log.error(error.message) resetEvents() didFailToLoadAdForAdUnitIdentifierButton.isEnabled = true } func didFail(toDisplay ad: MAAd, withError error: MAError) { Log.error(error.message) resetEvents() didFailToDisplayButton.isEnabled = true } func didDisplay(_ ad: MAAd) { didDisplayAdButton.isEnabled = true } func didHide(_ ad: MAAd) { didHideAdButton.isEnabled = true } func didClick(_ ad: MAAd) { didClickAdButton.isEnabled = true } }
apache-2.0