repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
firebase/SwiftLint | Source/SwiftLintFramework/Rules/SyntacticSugarRule.swift | 2 | 3668 | //
// SyntacticSugarRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 21/10/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct SyntacticSugarRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "syntactic_sugar",
name: "Syntactic Sugar",
description: "Shorthand syntactic sugar should be used, i.e. [Int] instead of Array<Int>",
nonTriggeringExamples: [
"let x: [Int]",
"let x: [Int: String]",
"let x: Int?",
"func x(a: [Int], b: Int) -> [Int: Any]",
"let x: Int!",
"extension Array { \n func x() { } \n }",
"extension Dictionary { \n func x() { } \n }",
"let x: CustomArray<String>",
"var currentIndex: Array<OnboardingPage>.Index?",
"func x(a: [Int], b: Int) -> Array<Int>.Index",
"unsafeBitCast(nonOptionalT, to: Optional<T>.self)",
"type is Optional<String>.Type",
"let x: Foo.Optional<String>"
],
triggeringExamples: [
"let x: ↓Array<String>",
"let x: ↓Dictionary<Int, String>",
"let x: ↓Optional<Int>",
"let x: ↓ImplicitlyUnwrappedOptional<Int>",
"func x(a: ↓Array<Int>, b: Int) -> [Int: Any]",
"func x(a: [Int], b: Int) -> ↓Dictionary<Int, String>",
"func x(a: ↓Array<Int>, b: Int) -> ↓Dictionary<Int, String>",
"let x = ↓Array<String>.array(of: object)",
"let x: ↓Swift.Optional<String>"
]
)
public func validate(file: File) -> [StyleViolation] {
let types = ["Optional", "ImplicitlyUnwrappedOptional", "Array", "Dictionary"]
let negativeLookBehind = "(?:(?<!\\.)|Swift\\.)"
let pattern = negativeLookBehind + "\\b(?:" + types.joined(separator: "|") + ")\\s*<.*?>"
let kinds = SyntaxKind.commentAndStringKinds()
let contents = file.contents.bridge()
return file.match(pattern: pattern, excludingSyntaxKinds: kinds).flatMap { range in
// avoid triggering when referring to an associatedtype
let start = range.location + range.length
let restOfFileRange = NSRange(location: start, length: contents.length - start)
if regex("\\s*\\.").firstMatch(in: file.contents, options: [],
range: restOfFileRange)?.range.location == start {
guard let byteOffset = contents.NSRangeToByteRange(start: range.location,
length: range.length)?.location else {
return nil
}
let kinds = file.structure.kinds(forByteOffset: byteOffset)
.flatMap { SwiftExpressionKind(rawValue: $0.kind) }
guard kinds.contains(.call) else {
return nil
}
if let (range, kinds) = file.match(pattern: "\\s*\\.(?:self|Type)", range: restOfFileRange).first,
range.location == start, kinds == [.keyword] || kinds == [.identifier] {
return nil
}
}
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location))
}
}
}
| mit | 8466f5f84503592e8b34b6779d04a160 | 41.406977 | 114 | 0.535509 | 4.553059 | false | false | false | false |
Great-Li-Xin/Xcode | Fake Tencent iOS/Fake Tencent iOS/TCPChatBundle.swift | 1 | 5331 | //
// TCPChatBundle.swift
// Fake Tencent Server
//
// Created by 李欣 on 2017/10/9.
// Copyright © 2017年 李欣. All rights reserved.
//
import Foundation
import Dispatch
/// 服务器地址设定
// let serverAddress = "127.0.0.1" // "139.129.46.224"
/// 定义服务器端口
let serverPort: Int32 = 5005
/// TCP 服务端类
class TcpSocketServer: NSObject {
var clients: [ChatUser] = []
var server: TCPServer = TCPServer(address: "127.0.0.1", port: serverPort)
var serverRunning: Bool = false
/// 启动服务
func start() {
_ = server.listen()
self.serverRunning = true
DispatchQueue.global(qos: .background).async {
while self.serverRunning {
let client = self.server.accept()
if let clientCopy = client {
DispatchQueue.global(qos: .background).async {
self.handleClient(client: clientCopy)
}
}
}
}
self.log(msg: "[+] Server Established")
}
/// 停止服务
func stop() {
self.serverRunning = false
_ = self.server.close()
/// 强制关闭所有客户端 socket
for client: ChatUser in self.clients {
client.kill()
}
self.log(msg: "[-] Server Eliminated")
}
/// 处理连接的客户端
func handleClient(client: TCPClient) {
/// TODO: 按照IP地址分类LOG,并写成单独文件。
self.log(msg: "[+] New Client from: " + client.address)
let user = ChatUser()
user.tcpClient = client
clients.append(user)
user.socketServer = self
user.messageLoop()
}
/// 处理客户端发来的指令
func processUserMsg(user: ChatUser, msg: [String: Any]) {
self.log(msg: "\(user.username)[\(user.tcpClient!.address)] cmd: " + (msg["cmd"] as! String))
/// 广播收到的信息
var msgToSend = [String: String]()
let cmd = msg["cmd"] as! String
/// TODO: 按照标准化命令交互改造此部分,添加:注册,登陆,等功能
if cmd == "username" {
if cmd == "username" {
msgToSend["cmd"] = "join"
msgToSend["username"] = user.username
msgToSend["address"] = user.tcpClient!.address
} else if (cmd == "msg") {
msgToSend["cmd"] = "msg"
msgToSend["from"] = user.username
msgToSend["content"] = (msg["content"] as! String)
} else if (cmd == "leave") {
msgToSend["cmd"] = "leave"
msgToSend["username"] = user.username
msgToSend["address"] = user.tcpClient!.address
}
for user: ChatUser in self.clients {
user.sendMsg(msg: msgToSend)
}
}
}
func removeUser(user: ChatUser) {
self.log(msg: "remove user\(user.tcpClient!.address)")
if let suspectIndex = self.clients.index(of: user) {
self.clients.remove(at: suspectIndex)
self.processUserMsg(user: user, msg: ["cmd": "leave"])
}
}
/// 日志打印
func log(msg: String) {
/// TODO: 聊天记录功能开发。
print(msg)
}
}
/// 客户端管理类 (便于服务端管理所有连接的客户端)
class ChatUser: NSObject {
var tcpClient: TCPClient?
var username: String = ""
var socketServer: TcpSocketServer?
/// 解析收到的消息
func readMsg() -> [String: Any]? {
/// 读取 Int32(4 Byte int) 类型
if let data = self.tcpClient!.read(4) {
if data.count == 4 {
let ndata = NSData(bytes: data, length: data.count)
var len: Int32 = 0
ndata.getBytes(&len, length: data.count)
if let buff = self.tcpClient!.read(Int(len)) {
let msgData = Data(bytes: buff, count: buff.count)
let msgCmd = (try! JSONSerialization.jsonObject(with: msgData, options: .mutableContainers)) as! [String: Any]
return msgCmd
}
}
}
return nil
}
/// 循环接收消息
func messageLoop() {
while true {
if let msg = self.readMsg() {
self.processMsg(msg: msg)
} else {
self.removeMe()
break
}
}
}
/// 处理收到的消息
func processMsg(msg: [String: Any]) {
if msg["cmd"] as! String == "username" {
self.username = msg["username"] as! String
}
self.socketServer!.processUserMsg(user: self, msg: msg)
}
/// 发送消息
func sendMsg(msg: [String: Any]) {
let jsonData = try? JSONSerialization.data(withJSONObject: msg, options: JSONSerialization.WritingOptions.prettyPrinted)
var len: Int32 = Int32(jsonData!.count)
let data = Data(bytes: &len, count: 4)
_ = self.tcpClient!.send(data: data)
_ = self.tcpClient!.send(data: jsonData!)
}
/// 移除该客户端
func removeMe() {
self.socketServer!.removeUser(user: self)
}
/// 关闭连接
func kill() {
_ = self.tcpClient!.close()
}
}
| mit | d0d05d45983d44834bb8a92dd01e4039 | 28.294118 | 130 | 0.524498 | 3.848532 | false | false | false | false |
julio-rivera/FeedMe | FeedMe/Model/FMRestaurant.swift | 1 | 1127 | //
// FMRestaurant.swift
// FeedMe
//
// Created by Julio Rivera on 3/6/15.
// Copyright (c) 2015 Julio Rivera. All rights reserved.
//
import Foundation
import CoreLocation
import MapKit
class FMRestaurant : NSObject, DebugPrintable {
// restrict setter access to within this class
private(set) var name:String?
private(set) var phoneNumber:String?
private(set) var websiteURL:NSURL?
private(set) var coordinate:CLLocationCoordinate2D?
private(set) var distance:String?
init(mapItem:MKMapItem?, location:CLLocation?) {
if let item = mapItem {
self.name = item.name
self.coordinate = item.placemark?.coordinate
self.phoneNumber = item.phoneNumber
self.websiteURL = item.url
if let distance = location?.distanceFromLocation(mapItem?.placemark.location) {
self.distance = String(format:"%.2f mi", distance/Constants.Floats.MetersToMiles)
}
}
}
override var debugDescription : String {
return "Name: \( self.name) \nDistance: \(self.distance)"
}
}
| mit | f58340bd58da5f3d7f155021f49577ef | 29.459459 | 97 | 0.643301 | 4.25283 | false | false | false | false |
Senspark/ee-x | src/ios/ee/firebase_performance/FirebasePerformanceBridge.swift | 1 | 2953 | //
// FirebasePerformanceBridge.swift
// ee-x-bb8dc50f
//
// Created by eps on 2/3/21.
//
private let kPrefix = "FirebasePerformanceBridge"
private let kInitialize = "\(kPrefix)Initialize"
private let kIsDataCollectionEnabled = "\(kPrefix)IsDataCollectionEnabled"
private let kSetDataCollectionEnabled = "\(kPrefix)SetDataCollectionEnabled"
private let kNewTrace = "\(kPrefix)NewTrace"
@objc(EEFirebasePerformanceBridge)
class FirebasePerformanceBridge: NSObject, IPlugin {
private let _bridge: IMessageBridge
private var _plugin: Performance?
private var _traces: [String: FirebasePerformanceTrace]
public required init(_ bridge: IMessageBridge, _ logger: ILogger) {
_bridge = bridge
_plugin = nil
_traces = [:]
super.init()
registerHandlers()
}
public func destroy() {
deregisterHandlers()
}
func registerHandlers() {
_bridge.registerAsyncHandler(kInitialize) { _, resolver in
resolver(Utils.toString(self.initialize()))
}
_bridge.registerHandler(kIsDataCollectionEnabled) { _ in
Utils.toString(self.isDataCollectionEnabled)
}
_bridge.registerHandler(kSetDataCollectionEnabled) { message in
self.isDataCollectionEnabled = Utils.toBool(message)
return ""
}
_bridge.registerHandler(kNewTrace) { message in
Utils.toString(self.newTrace(message))
}
}
func deregisterHandlers() {
_bridge.deregisterHandler(kInitialize)
_bridge.deregisterHandler(kIsDataCollectionEnabled)
_bridge.deregisterHandler(kSetDataCollectionEnabled)
_bridge.deregisterHandler(kNewTrace)
}
func initialize() -> Bool {
if FirebaseInitializer.instance.initialize() {
_plugin = Performance.sharedInstance()
return true
}
return false
}
var isDataCollectionEnabled: Bool {
get {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return false
}
return plugin.isDataCollectionEnabled
}
set(value) {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return
}
return plugin.isDataCollectionEnabled = value
}
}
func newTrace(_ traceName: String) -> Bool {
guard let plugin = _plugin else {
assert(false, "Please call initialize() first")
return false
}
if _traces.contains(where: { key, _ in key == traceName }) {
return false
}
guard let trace = plugin.trace(name: traceName) else {
return false
}
_traces[traceName] = FirebasePerformanceTrace(_bridge, traceName, trace)
return true
}
}
| mit | 51d6803ca2628fd3a72c6b634451b146 | 30.414894 | 80 | 0.610566 | 4.665087 | false | false | false | false |
ChristianDeckert/CDTools | CDTools/UI/CDTableViewController.swift | 1 | 9964 | //
// CDTableViewController.swift
//
//
// Created by Christian Deckert on 22.10.16.
// Copyright (c) 2014 Christian Deckert GmbH. All rights reserved.
//
import Foundation
import UIKit
public extension UINib {
public static func nibForCDTableViewCell(_ cell: CDTableViewCell.Type, bundle: Bundle? = nil) -> UINib {
return UINib(nibName: cell.cellReuseIdentifier(), bundle: bundle)
}
}
public extension UITableView {
public func registerCDTableViewCell(_ cell: CDTableViewCell.Type, bundle: Bundle? = nil) {
self.register(UINib.nibForCDTableViewCell(cell, bundle: bundle ?? Bundle(for: cell.classForCoder())), forCellReuseIdentifier: cell.cellReuseIdentifier())
}
}
public protocol CDTableControllertableModel: NSObjectProtocol {
func CDTableControllerGetTableView() -> UITableView?
}
open class CDTableController<T: Equatable>: NSObject, UITableViewDelegate {
weak var cdTableControllertableModel: CDTableControllertableModel?
var tableView: UITableView? {
get {
return self.cdTableControllertableModel?.CDTableControllerGetTableView()
}
}
var tableModel = CDTableViewTableModel<T>()
weak var weakTableViewController: CDTableViewController? //STRONG TABLEVIEW TO BE DEFINED IN SUBCLASSES
public init(CDTableControllertableModel tableModel: CDTableControllertableModel?) {
self.cdTableControllertableModel = tableModel
super.init()
commontInit()
}
public required init(tableViewController: CDTableViewController) {
super.init()
self.weakTableViewController = tableViewController
commontInit()
}
public override init() {
super.init()
commontInit()
}
func commontInit() {
self.tableModel.tableController = self
}
// MARK: - UITableViewDelegate & -tableModel
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfItems = self.tableModel.numberOfItemsInSection(section)
return numberOfItems
}
open func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell: CDTableViewCell = tableView.dequeueReusableCell(withIdentifier: CDTableViewCell.cellReuseIdentifier()) as! CDTableViewCell
if let item = self.tableModel.item(atIndex: indexPath) as? NSObject {
cell.textLabel?.text = item.description
} else {
cell.textLabel?.text = "Please override cellForRowAtIndexPath"
}
return cell
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if UIDevice.current.userInterfaceIdiom == .phone {
return 44.0
}
return 64.0
}
open func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let cdCell = cell as? CDTableViewCell else {
return
}
cdCell.indexPath = indexPath
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
open func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return self.tableModel.numberOfSections
}
open func hightlightSelectedBackgroundView(_ indexPath: IndexPath) -> Void {
let selectedBackgroundView = UIView()
selectedBackgroundView.backgroundColor = self.weakTableViewController?.selectedBackgroundViewColor
let cell = weakTableViewController?.weakTableView?.cellForRow(at: indexPath)
cell?.selectedBackgroundView = selectedBackgroundView
}
}
/// A custom view controller with a tableview embedded
///
/// ###Benefits
/// - Embedded tableModel and controller will drastically improve implementation speeds
/// - Type safety data
/// - Automatically returns number of sections/rows by implementing UITableViewtableModel / UITableViewDelegate
//public class CDTableViewController<T: Equatable>: CDBaseViewController, UITableViewtableModel, UITableViewDelegate,
open class CDTableViewController: CDBaseViewController, UITableViewDataSource, UITableViewDelegate,
UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate, CDTableControllertableModel {
open var selectedBackgroundViewEnabled: Bool = true
open var selectedBackgroundViewColor = UIColor.white
open var cdTableController = CDTableController<NSObject>(CDTableControllertableModel: nil)
open var tableModel: CDTableViewTableModel<NSObject> {
get {
return self.cdTableController.tableModel
}
}
open var searchController: UISearchController?
open weak var weakTableView: UITableView? //STRONG TABLEVIEW TO BE DEFINED IN SUBCLASSES (Storyboard) AN SET WEAK VAR IN LOADVIEW()
open var refreshControl: UIRefreshControl?
// MARK: - Life cycle
open override func loadView() {
super.loadView()
self.cdTableController.cdTableControllertableModel = self
findTableView()
}
open override func viewDidLoad() {
super.viewDidLoad()
self.cdTableController.weakTableViewController = self
if let tv = self.weakTableView {
tv.delegate = self
tv.dataSource = self
tv.separatorInset = UIEdgeInsets.zero
tv.separatorColor = UIColor.clear
}
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
// MARK: - Batch Updates
open func insertAnimated(_ sectionIndizes: IndexSet, rowIndizes: Array<IndexPath>, animation: UITableViewRowAnimation) -> Void {
if let tv = self.weakTableView {
tv.beginUpdates()
if sectionIndizes.count > 0 {
tv.insertSections(sectionIndizes, with: animation)
}
if !rowIndizes.isEmpty {
tv.insertRows(at: rowIndizes, with: animation)
}
tv.endUpdates()
}
}
open func deleteAnimated(_ sectionIndizes: IndexSet, rowIndizes: Array<IndexPath>, animation: UITableViewRowAnimation) -> Void {
if let tv = self.weakTableView {
tv.beginUpdates()
if sectionIndizes.count > 0 {
tv.deleteSections(sectionIndizes, with: animation)
}
if !rowIndizes.isEmpty {
tv.deleteRows(at: rowIndizes, with: animation)
}
tv.endUpdates()
}
}
// MARK: - Refresh Control
open func addRefreshControl() {
let refreshControl = UIRefreshControl()
self.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
if let tableView = self.weakTableView {
tableView.addSubview(refreshControl)
}
}
// MARK: - Refresh Control
open func refreshAction() {
self.refreshControl?.endRefreshing()
}
// MARK: - UITableViewDelegate & -tableModel
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.cdTableController.tableView(tableView, heightForRowAt: indexPath)
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cdTableController.tableView(tableView, numberOfRowsInSection: section)
}
open func numberOfSections(in tableView: UITableView) -> Int {
return self.cdTableController.numberOfSectionsInTableView(tableView)
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.cdTableController.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.self.cdTableController.tableView(tableView, didSelectRowAt: indexPath)
if self.selectedBackgroundViewEnabled {
self.self.cdTableController.hightlightSelectedBackgroundView(indexPath)
}
}
// MARK: - Search Controller
open func addSearchController() {
let uselessView = UIView()
uselessView.backgroundColor = UIColor.clear
self.weakTableView?.backgroundView = uselessView
self.searchController = {
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.definesPresentationContext = true
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.searchBarStyle = .minimal
controller.searchBar.sizeToFit()
self.weakTableView?.tableHeaderView = controller.searchBar
return controller
}()
}
open func updateSearchResults(for searchController: UISearchController) {
}
// MARK: - CDTableControllertableModel
open func CDTableControllerGetTableView() -> UITableView? {
return self.weakTableView
}
// MARK: - Other
fileprivate func findTableView() {
guard nil == self.weakTableView else {
return
}
for view in self.view.subviews {
if let tableView = view as? UITableView {
self.weakTableView = tableView
tableView.register(CDTableViewCell.self, forCellReuseIdentifier: CDTableViewCell.cellReuseIdentifier())
break;
}
}
}
}
| mit | ae5d17743e505f49387b1f10a69edfa0 | 32.891156 | 161 | 0.657668 | 5.544797 | false | false | false | false |
prachigauriar/PropertyListEditor | PropertyListEditor/Models/Property Lists/Converters/PropertyListXMLWritable.swift | 1 | 5236 | //
// PropertyListXMLWritable.swift
// PropertyListEditor
//
// Created by Prachi Gauriar on 7/19/2015.
// Copyright © 2015 Quantum Lens Cap. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The `PropertyListXMLWritable` protocol defines a single method that adds a property list item’s
/// data as child XML elements of a property List XML element. It is used to save Property List XML
/// documents instead of using `NSPropertyListSerialization`; the former maintains the order or
/// a dictionary’s key/value pairs, while the latter does not. All PropertyListItems conform to
/// this protocol via the extensions below.
///
/// While one could conceivably use the method in this protocol directly, it is better to use
/// `PropertyListXMLWritable.propertyListXMLDocumentData()`, which will produce a complete Property
/// List XML document.
protocol PropertyListXMLWritable {
/// Adds the conforming instance’s data to the specified XML element as children.
/// - parameter parentXMLElement: The element to which children should be added.
func addPropertyListXMLElement(to parentXMLElement: XMLElement)
}
/// This protocol extension adds the ability to get a complete property list XML document
extension PropertyListXMLWritable {
/// Returns the instance’s data as the root property list type in a property list XML document.
/// - returns: An `NSData` instance containing the XML
func propertyListXMLDocumentData() -> Data {
let baseXMLString = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
</plist>
"""
let document = try! XMLDocument(xmlString: baseXMLString, options: XMLNode.Options(rawValue: 0))
addPropertyListXMLElement(to: document.rootElement()!)
return document.xmlData(options: [.nodePrettyPrint, .nodeCompactEmptyElement])
}
}
extension PropertyListItem : PropertyListXMLWritable {
func addPropertyListXMLElement(to parentXMLElement: XMLElement) {
switch self {
case let .array(array):
array.addPropertyListXMLElement(to: parentXMLElement)
case let .boolean(boolean):
parentXMLElement.addChild(XMLElement(name: boolean.boolValue ? "true" : "false"))
case let .data(data):
parentXMLElement.addChild(XMLElement(name: "data", stringValue: data.base64EncodedString(options: [])))
case let .date(date):
parentXMLElement.addChild(XMLElement(name: "date", stringValue: DateFormatter.propertyListXML.string(from: date as Date)))
case let .dictionary(dictionary):
dictionary.addPropertyListXMLElement(to: parentXMLElement)
case let .number(number):
if number.isInteger {
parentXMLElement.addChild(XMLElement(name: "integer", stringValue: "\(number.intValue)"))
} else {
parentXMLElement.addChild(XMLElement(name: "real", stringValue: "\(number.doubleValue)"))
}
case let .string(string):
parentXMLElement.addChild(XMLElement(name: "string", stringValue: string as String))
}
}
}
extension PropertyListArray : PropertyListXMLWritable {
func addPropertyListXMLElement(to parentXMLElement: XMLElement) {
let arrayXMLElement = XMLElement(name: "array")
for element in elements {
element.addPropertyListXMLElement(to: arrayXMLElement)
}
parentXMLElement.addChild(arrayXMLElement)
}
}
extension PropertyListDictionary : PropertyListXMLWritable {
func addPropertyListXMLElement(to parentXMLElement: XMLElement) {
let dictionaryXMLElement = XMLElement(name: "dict")
for keyValuePair in elements {
dictionaryXMLElement.addChild(XMLElement(name: "key", stringValue: keyValuePair.key))
keyValuePair.value.addPropertyListXMLElement(to: dictionaryXMLElement)
}
parentXMLElement.addChild(dictionaryXMLElement)
}
}
| mit | 497c90fec6ce5dd9f366d84dfbdedf7a | 44.850877 | 134 | 0.706906 | 4.738894 | false | false | false | false |
github410117/MBProgressHUD-Swift | MBProgressHUD-Swift/MBProgressHUD-Swift/XHMBProgressHUD/XHProgressHUD.swift | 1 | 1698 | //
// XHProgressHUD.swift
// XHBaseProject
//
// Created by xh on 2017/4/26.
// Copyright © 2017年 xh. All rights reserved.
//
import UIKit
class XHProgressHUD: MBProgressHUD {
fileprivate class func showText(text: String, icon: String) {
let view = viewWithShow()
let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.label.text = text
let img = UIImage(named: "MBProgressHUD.bundle/\(icon)")
hud.customView = UIImageView(image: img)
hud.mode = MBProgressHUDMode.customView
hud.removeFromSuperViewOnHide = true
hud.hide(animated: true, afterDelay: 1)
}
class func viewWithShow() -> UIView {
var window = UIApplication.shared.keyWindow
if window?.windowLevel != UIWindowLevelNormal {
let windowArray = UIApplication.shared.windows
for tempWin in windowArray {
if tempWin.windowLevel == UIWindowLevelNormal {
window = tempWin;
break
}
}
}
return window!
}
class func showStatusInfo(_ info: String) {
let view = viewWithShow()
let hud = MBProgressHUD.showAdded(to: view, animated: true)
hud.label.text = info
}
class func dismiss() {
let view = viewWithShow()
MBProgressHUD.hide(for: view, animated: true)
}
class func showSuccess(_ status: String) {
showText(text: status, icon: "success.png")
}
class func showError(_ status: String) {
showText(text: status, icon: "error.png")
}
}
| mit | 467e751e8831ba99f750de29f119500f | 25.484375 | 67 | 0.570501 | 4.656593 | false | false | false | false |
frapperino/MultiPlayerMemory | MultiPlayer Memory/MultiPlayer Memory/AppDelegate.swift | 1 | 3360 | //
// AppDelegate.swift
// MultiPlayer Memory
//
// Created by Magnus Huttu on 03/10/16.
// Copyright © 2016 Magnus Huttu. All rights reserved.
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
return true
}
func handleEnterEvent(forRegion region: CLRegion!) {
GpsLocation.sharedInstance.inside = true
if let label = GpsLocation.sharedInstance.warnLabel {
label.textColor = UIColor.green
label.text = "Located at museum"
}
}
func handleExitEvent(forRegion region: CLRegion!) {
GpsLocation.sharedInstance.inside = false
if let label = GpsLocation.sharedInstance.warnLabel {
label.textColor = UIColor.red
label.text = "Not located at museum"
}
}
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:.
}
}
extension AppDelegate: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if region is CLCircularRegion {
handleEnterEvent(forRegion: region)
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
if region is CLCircularRegion {
handleExitEvent(forRegion: region)
}
}
}
| apache-2.0 | 28d40cbf659a0cbfb1aba79bf7a578c6 | 40.469136 | 285 | 0.717475 | 5.524671 | false | false | false | false |
Anders123fr/DGRunkeeperSwitch | DGRunkeeperSwitch/DGRunkeeperSwitch.swift | 1 | 10028 | //
// DGRunkeeperSwitch.swift
// DGRunkeeperSwitchExample
//
// Created by Danil Gontovnik on 9/3/15.
// Copyright © 2015 Danil Gontovnik. All rights reserved.
//
import UIKit
// MARK: - DGRunkeeperSwitchRoundedLayer
open class DGRunkeeperSwitchRoundedLayer: CALayer {
}
// MARK: - DGRunkeeperSwitch
@IBDesignable
open class DGRunkeeperSwitch: UIControl {
// MARK: - Public vars
open var titles: [String] {
set {
(titleLabels + selectedTitleLabels).forEach { $0.removeFromSuperview() }
titleLabels = newValue.map { title in
let label = UILabel()
label.text = title
label.textColor = titleColor
label.font = titleFont
label.textAlignment = .center
label.lineBreakMode = .byTruncatingTail
titleLabelsContentView.addSubview(label)
return label
}
selectedTitleLabels = newValue.map { title in
let label = UILabel()
label.text = title
label.textColor = selectedTitleColor
label.font = titleFont
label.textAlignment = .center
label.lineBreakMode = .byTruncatingTail
selectedTitleLabelsContentView.addSubview(label)
return label
}
}
get { return titleLabels.map { $0.text! } }
}
fileprivate(set) open var selectedIndex: Int = 0
open var selectedBackgroundInset: CGFloat = 2.0 {
didSet { setNeedsLayout() }
}
@IBInspectable
open var selectedBackgroundColor: UIColor! {
set { selectedBackgroundView.backgroundColor = newValue }
get { return selectedBackgroundView.backgroundColor }
}
@IBInspectable
// Set a custom corner radius or use the default
open var cornerRadius: CGFloat? {
didSet {
guard let cornerRadius = self.cornerRadius else { return }
self.layer.cornerRadius = cornerRadius
selectedBackgroundView.layer.cornerRadius = cornerRadius
}
}
@IBInspectable
open var titleColor: UIColor! {
didSet { titleLabels.forEach { $0.textColor = titleColor } }
}
@IBInspectable
open var selectedTitleColor: UIColor! {
didSet { selectedTitleLabels.forEach { $0.textColor = selectedTitleColor } }
}
open var titleFont: UIFont! {
didSet { (titleLabels + selectedTitleLabels).forEach { $0.font = titleFont } }
}
@IBInspectable
open var titleFontFamily: String = "HelveticaNeue"
@IBInspectable
open var titleFontSize: CGFloat = 18.0
open var animationDuration: TimeInterval = 0.3
open var animationSpringDamping: CGFloat = 0.75
open var animationInitialSpringVelocity: CGFloat = 0.0
// MARK: - Private vars
fileprivate var titleLabelsContentView = UIView()
fileprivate var titleLabels = [UILabel]()
fileprivate var selectedTitleLabelsContentView = UIView()
fileprivate var selectedTitleLabels = [UILabel]()
fileprivate(set) var selectedBackgroundView = UIView()
fileprivate var titleMaskView: UIView = UIView()
fileprivate var tapGesture: UITapGestureRecognizer!
fileprivate var panGesture: UIPanGestureRecognizer!
fileprivate var initialSelectedBackgroundViewFrame: CGRect?
// MARK: - Constructors
public init(titles: [String]) {
super.init(frame: CGRect.zero)
self.titles = titles
finishInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
finishInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
finishInit()
backgroundColor = .black // don't set background color in finishInit(), otherwise IB settings which are applied in init?(coder:) are overwritten
}
fileprivate func finishInit() {
// Setup views
addSubview(titleLabelsContentView)
object_setClass(selectedBackgroundView.layer, DGRunkeeperSwitchRoundedLayer.self)
addSubview(selectedBackgroundView)
addSubview(selectedTitleLabelsContentView)
object_setClass(titleMaskView.layer, DGRunkeeperSwitchRoundedLayer.self)
titleMaskView.backgroundColor = .black
selectedTitleLabelsContentView.layer.mask = titleMaskView.layer
// Setup defaul colors
if backgroundColor == nil {
backgroundColor = .black
}
selectedBackgroundColor = .white
titleColor = .white
selectedTitleColor = .black
// Gestures
tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapped))
addGestureRecognizer(tapGesture)
panGesture = UIPanGestureRecognizer(target: self, action: #selector(pan))
panGesture.delegate = self
addGestureRecognizer(panGesture)
addObserver(self, forKeyPath: "selectedBackgroundView.frame", options: .new, context: nil)
// Set default corner radius
cornerRadius = bounds.height / 2.0
}
override open func awakeFromNib() {
super.awakeFromNib()
self.titleFont = UIFont(name: self.titleFontFamily, size: self.titleFontSize)
}
// MARK: - Destructor
deinit {
removeObserver(self, forKeyPath: "selectedBackgroundView.frame")
}
// MARK: - Observer
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "selectedBackgroundView.frame" {
titleMaskView.frame = selectedBackgroundView.frame
}
}
// MARK: -
override open class var layerClass : AnyClass {
return DGRunkeeperSwitchRoundedLayer.self
}
func tapped(_ gesture: UITapGestureRecognizer!) {
let location = gesture.location(in: self)
let index = Int(location.x / (bounds.width / CGFloat(titleLabels.count)))
setSelectedIndex(index, animated: true)
}
func pan(_ gesture: UIPanGestureRecognizer!) {
if gesture.state == .began {
initialSelectedBackgroundViewFrame = selectedBackgroundView.frame
} else if gesture.state == .changed {
var frame = initialSelectedBackgroundViewFrame!
frame.origin.x += gesture.translation(in: self).x
frame.origin.x = max(min(frame.origin.x, bounds.width - selectedBackgroundInset - frame.width), selectedBackgroundInset)
selectedBackgroundView.frame = frame
} else if gesture.state == .ended || gesture.state == .failed || gesture.state == .cancelled {
let index = max(0, min(titleLabels.count - 1, Int(selectedBackgroundView.center.x / (bounds.width / CGFloat(titleLabels.count)))))
setSelectedIndex(index, animated: true)
}
}
open func setSelectedIndex(_ selectedIndex: Int, animated: Bool) {
guard 0..<titleLabels.count ~= selectedIndex else { return }
// Reset switch on half pan gestures
var catchHalfSwitch = false
if self.selectedIndex == selectedIndex {
catchHalfSwitch = true
}
self.selectedIndex = selectedIndex
if animated {
if (!catchHalfSwitch) {
self.sendActions(for: .valueChanged)
}
UIView.animate(withDuration: animationDuration, delay: 0.0, usingSpringWithDamping: animationSpringDamping, initialSpringVelocity: animationInitialSpringVelocity, options: [UIViewAnimationOptions.beginFromCurrentState, UIViewAnimationOptions.curveEaseOut], animations: { () -> Void in
self.layoutSubviews()
}, completion: nil)
} else {
layoutSubviews()
sendActions(for: .valueChanged)
}
}
// MARK: - Layout
override open func layoutSubviews() {
super.layoutSubviews()
let selectedBackgroundWidth = bounds.width / CGFloat(titleLabels.count) - selectedBackgroundInset * 2.0
selectedBackgroundView.frame = CGRect(x: selectedBackgroundInset + CGFloat(selectedIndex) * (selectedBackgroundWidth + selectedBackgroundInset * 2.0), y: selectedBackgroundInset, width: selectedBackgroundWidth, height: bounds.height - selectedBackgroundInset * 2.0)
(titleLabelsContentView.frame, selectedTitleLabelsContentView.frame) = (bounds, bounds)
let titleLabelMaxWidth = selectedBackgroundWidth
let titleLabelMaxHeight = bounds.height - selectedBackgroundInset * 2.0
zip(titleLabels, selectedTitleLabels).forEach { label, selectedLabel in
let index = titleLabels.index(of: label)!
var size = label.sizeThatFits(CGSize(width: titleLabelMaxWidth, height: titleLabelMaxHeight))
size.width = min(size.width, titleLabelMaxWidth)
let x = floor((bounds.width / CGFloat(titleLabels.count)) * CGFloat(index) + (bounds.width / CGFloat(titleLabels.count) - size.width) / 2.0)
let y = floor((bounds.height - size.height) / 2.0)
let origin = CGPoint(x: x, y: y)
let frame = CGRect(origin: origin, size: size)
label.frame = frame
selectedLabel.frame = frame
}
}
}
// MARK: - UIGestureRecognizerDelegate
extension DGRunkeeperSwitch: UIGestureRecognizerDelegate {
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == panGesture {
return selectedBackgroundView.frame.contains(gestureRecognizer.location(in: self))
}
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
}
| mit | 866e750961b7c15ff88af4d1aef92e57 | 34.059441 | 296 | 0.639473 | 5.288502 | false | false | false | false |
kagenZhao/cnBeta | iOS/CnBeta/Foundation Components/Cycle Scroll View/CycleScrollView.swift | 1 | 2665 | //
// CycleScrollView.swift
// CnBeta
//
// Created by 赵国庆 on 2017/8/17.
// Copyright © 2017年 Kagen. All rights reserved.
//
import UIKit
import FSPagerView
import Kingfisher
import SnapKit
import RxSwift
import Nuke
class CycleScrollView: FSPagerView {
/// url or image name
var images: [String] = [] {
didSet {
reloadData()
pageControl.numberOfPages = images.count
}
}
var titles: [String] = [] {
didSet {
reloadData()
}
}
var placeHolderImage: UIImage?
var didSelectItemClosure: ((_ url: String, _ index: Int) -> Void)?
private let disposeBag = DisposeBag()
private var pageControl = FSPageControl()
override func awakeFromNib() {
super.awakeFromNib()
delegate = self
dataSource = self
isInfinite = true
automaticSlidingInterval = 5
// transformer = FSPagerViewTransformer(type: .in)
register(FSPagerViewCell.self, forCellWithReuseIdentifier: "FSPagerViewCell")
pageControl.setFillColor(.gray, for: .normal)
pageControl.setFillColor(.white, for: .selected)
pageControl.contentHorizontalAlignment = .right
pageControl.contentInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
addSubview(pageControl)
pageControl.snp.makeConstraints { maker in
maker.bottom.left.right.equalTo(0)
maker.height.equalTo(15)
}
rx.observe(Int.self, "currentIndex").subscribe(onNext: { [unowned self] i in
if self.images.count > 0 {
self.pageControl.currentPage = i!
}
}).addDisposableTo(disposeBag)
}
}
extension CycleScrollView: FSPagerViewDataSource, FSPagerViewDelegate {
func numberOfItems(in _: FSPagerView) -> Int {
return images.count
}
func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "FSPagerViewCell", at: index)
if let url = URL(string: images[index]) {
cell.imageView!.image = placeHolderImage
ImageLoader.loadImage(with: url, into: cell.imageView!)
} else {
cell.imageView?.image = UIImage(named: images[index])
}
cell.textLabel?.text = titles[index]
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
return cell
}
func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
pagerView.deselectItem(at: index, animated: true)
didSelectItemClosure?(images[index], index)
}
}
| mit | 87c4667d7ca11eafd8df0bd9e59f67e8 | 30.247059 | 99 | 0.633283 | 4.69258 | false | false | false | false |
Adorkable/Eunomia | Source/Core/UtilityExtensions/MPMediaItem+Utility.swift | 1 | 1005 | //
// MPMediaItem+Utility.swift
// Eunomia
//
// Created by Ian Grossberg on 9/20/18.
// Copyright © 2018 Adorkable. All rights reserved.
//
import MediaPlayer
#if os(iOS)
extension MPMediaItem {
public static func sortByPlaybackDuration(left: MPMediaItem, right: MPMediaItem) -> Bool {
let comparison: ComparisonResult = self.sortByPlaybackDuration(left: left, right: right)
return comparison == .orderedDescending
}
public static func sortByPlaybackDuration(left: MPMediaItem, right: MPMediaItem) -> ComparisonResult {
if left.playbackDuration < right.playbackDuration {
return .orderedDescending
}
if left.playbackDuration == right.playbackDuration {
return .orderedSame
}
return .orderedAscending
}
}
extension Array where Element == MPMediaItem {
public func sortedByPlaybackDuration() -> [MPMediaItem] {
return self.sorted(by: MPMediaItem.sortByPlaybackDuration)
}
}
#endif
| mit | 6feb7af17a18654561eef637559bfbd9 | 28.529412 | 106 | 0.688247 | 4.758294 | false | false | false | false |
mownier/photostream | Photostream/UI/Settings/SettingsViewController.swift | 1 | 2216 | //
// SettingsViewController.swift
// Photostream
//
// Created by Mounir Ybanez on 14/12/2016.
// Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
@objc protocol SettingsViewControllerAction: class {
func didTapBack()
}
class SettingsViewController: UITableViewController, SettingsViewControllerAction {
let reuseId = "Cell"
var presenter: SettingsModuleInterface!
convenience init() {
self.init(style: .grouped)
}
override func loadView() {
super.loadView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseId)
setupNavigationItem()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return presenter.sectionCount
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.itemCount(for: section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId)!
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = presenter.itemName(at: indexPath.row, for: indexPath.section)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let itemName = presenter.itemName(at: indexPath.row, for: indexPath.section)
if itemName.lowercased() == "log out" {
presenter.presentLogout()
}
}
func setupNavigationItem() {
navigationItem.title = "Settings"
let barItem = UIBarButtonItem(image: #imageLiteral(resourceName: "back_nav_icon"), style: .plain, target: self, action: #selector(self.didTapBack))
navigationItem.leftBarButtonItem = barItem
}
}
extension SettingsViewController {
func didTapBack() {
presenter.exit()
}
}
extension SettingsViewController: SettingsScene {
var controller: UIViewController? {
return self
}
}
| mit | 1017ca76516f6026284157dcf9c94b4b | 26.012195 | 155 | 0.663205 | 5.261283 | false | false | false | false |
Ossus/eponyms-2 | Sources/Sync/SyncController.swift | 1 | 6834 | //
// SyncController.swift
// eponyms-2
//
// Created by Pascal Pfiffner on 4/25/15.
// Copyright (c) 2015 Ossus. All rights reserved.
//
import Foundation
import CouchbaseLite
let kSyncGatewayUrl = URL(string: "http://192.168.10.22:4999/eponyms")!
open class SyncController {
deinit {
NotificationCenter.default.removeObserver(self)
}
/// Handle to our database.
open let database: CBLDatabase
/// The pull replicator.
let pull: CBLReplication
/// The push replicator.
let push: CBLReplication
/// The URL protection space for our Sync Gateway.
lazy var protectionSpace: URLProtectionSpace = {
return URLProtectionSpace(
host: kSyncGatewayUrl.host!,
port: (kSyncGatewayUrl as NSURL).port as! Int,
protocol: kSyncGatewayUrl.scheme,
realm: nil,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic
)
}()
/**
Designated initializer.
*/
public init(databaseName name: String) throws {
let manager = CBLManager.sharedInstance()
database = try manager.databaseNamed(name)
// register model classes
if let factory = database.modelFactory {
MainDocument.register(in: factory)
}
// setup replication
pull = database.createPullReplication(kSyncGatewayUrl)
pull.continuous = false
push = database.createPushReplication(kSyncGatewayUrl)
push.continuous = true
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblReplicationChange, object: push, queue: nil, using: replicationChanged)
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblReplicationChange, object: pull, queue: nil, using: replicationChanged)
logIfVerbose("--> Initialized SyncController with database at \(manager.directory)/\(database), \(database.documentCount) documents")
}
// MARK: - Local Import
/**
Import all documents found in a JSON document. The JSON document must have a top level "documents" key that is an array of documents.
- parameter file: The filename WITHOUT "json" extension
- parameter deleteExisting: If true, will drop the whole DB first!
*/
public func importLocalDocuments(from file: String, deleteExisting: Bool = false) throws {
guard let url = Bundle.main.url(forResource: file, withExtension: "json") else {
throw NSError(domain: "ch.ossus.eponyms.Sync", code: 389, userInfo: [NSLocalizedDescriptionKey: "There does not seem to exist a file “\(file).json” in the main Bundle"])
}
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: []) as! JSONDoc
guard let all = json["documents"] as? [JSONDoc] else {
throw NSError(domain: "ch.ossus.eponyms.Sync", code: 786, userInfo: [NSLocalizedDescriptionKey: "There must be an array of dictionaries under the top-level “documents” key in \(file).json, but there isn't"])
}
// delete existing?
if deleteExisting {
// try database.delete()
// TODO: doesn't work
}
// import all documents
database.inTransaction {
for epo in all {
let document = self.database.createDocument()
do {
try document.putProperties(epo)
}
catch let error {
print("xxxx> ERROR IMPORTING, ROLLING BACK. Error was: \(error)")
return false
}
}
print("====> Imported \(self.database.documentCount) documents")
return true
}
}
// MARK: - Sync Gateway
/**
Start push and pull replication. Will automatically suspend when the app goes into background.
*/
open func sync() {
push.start()
pull.start()
}
public var isSyncing: Bool {
return (pull.status == CBLReplicationStatus.active) || (push.status == CBLReplicationStatus.active)
}
open var syncStatus: String {
switch pull.status {
case .active:
return "active"
case .idle:
return "idle"
case .stopped:
return "stopped"
case .offline:
return "offline"
}
}
func replicationChanged(_ notification: Notification) {
guard let replicator = notification.object as? CBLReplication else {
logIfVerbose("Sync: unexpected notification.object \(notification.object)")
return
}
let repl = (pull == replicator) ? "pulling" : "pushing"
if isSyncing {
var progress = 1.0
let total = push.changesCount + pull.changesCount
let completed = push.completedChangesCount + pull.completedChangesCount
if total > 0 {
progress = Double(completed) / Double(total);
}
if let err = replicator.lastError {
logIfVerbose("Sync: error \(repl) [\(syncStatus)]: \(err), progress \(progress * 100)%")
}
else {
logIfVerbose("Sync: progress \(repl) \(progress * 100)% [\(syncStatus)]")
}
}
else if let err = replicator.lastError {
logIfVerbose("Sync: error \(repl) [\(syncStatus)]: \(err)")
}
}
// MARK: - Credentials
/**
Check if a user with given name has credentials in the keychain, if not and a password is given, create and store one.
*/
func authorize(user: User) throws {
guard let username = user.name else {
throw SyncError.noUsername
}
if let found = existingCredentials(for: username, space: protectionSpace) {
logIfVerbose("Sync: found password for “\(username)”")
pull.credential = found
push.credential = found
return
}
// log in if we have a password
if let pass = user.password {
logIfVerbose("Sync: logging in as “\(username)”")
let cred = logIn(user: username, password: pass, space: protectionSpace)
pull.credential = cred
push.credential = cred
}
throw SyncError.noPassword
}
open func deAuthorize(_ user: User) throws {
guard let username = user.name else {
throw SyncError.noUsername
}
logOut(user: username, space: protectionSpace)
}
/** Returns a list of usernames that have credentials for our Sync Gateway. */
func loggedInUsers(_ space: URLProtectionSpace) -> [String]? {
let store = URLCredentialStorage.shared
guard let found = store.credentials(for: space) else {
return nil
}
var usernames = [String]()
for (usr, _) in found {
usernames.append(usr)
}
return usernames
}
func existingCredentials(for user: String, space: URLProtectionSpace) -> URLCredential? {
let store = URLCredentialStorage.shared
if let found = store.credentials(for: space) {
for (usr, cred) in found {
if usr == user {
return cred
}
}
}
return nil
}
open func logIn(user: String, password: String, space: URLProtectionSpace) -> URLCredential {
let store = URLCredentialStorage.shared
let credentials = URLCredential(user: user, password: password, persistence: .permanent)
store.set(credentials, for: space)
return credentials
}
open func logOut(user: String, space: URLProtectionSpace) {
if let found = existingCredentials(for: user, space: space) {
let store = URLCredentialStorage.shared
store.remove(found, for: space)
}
}
}
| apache-2.0 | 5163c456d1f9f332d3172d307d42c57e | 27.647059 | 210 | 0.701819 | 3.73589 | false | false | false | false |
avario/LayoutKit | LayoutKit/LayoutKit/Corner.swift | 1 | 2394 | //
// Corner.swift
// LayoutKit
//
// Created by Avario.
//
import Foundation
import UIKit
public extension Layout {
/// Apply constraints to position the view in a corner created by any two edges.
/// The view's `size` can be constrained by using the `layout.size()` method.
///
/// - parameters:
/// - horizontalEdge: Horizontal (`top` or `bottom`) `SidedLayoutItem` to use as one edge of the corner.
/// Use `inside` to position on the inside of a view, and `outside` to position on the outside of it.
/// Use `+` and `-` operators to add padding.
/// - verticalEdge: Vertical (`left` or `right`) `SidedLayoutItem` to use as the other edge of the corner.
/// Use `inside` to position on the inside of a view, and `outside` to position on the outside of it.
/// Use `+` and `-` operators to add padding.
///
/// - returns: A labeled tuple containing the applied `horizontalEdge` and `verticalEdge` constraints.
@discardableResult public func corner<I>(_ horizontalEdge: SidedLayoutItem<I, YAxis>, _ verticalEdge: SidedLayoutItem<LayoutRegion, XAxis>) ->
(horizontalEdgeConstraint: NSLayoutConstraint,
verticalEdgeConstraint: NSLayoutConstraint) {
let horizontalEdgeConstraint: NSLayoutConstraint
switch (horizontalEdge.layoutItem.attribute, horizontalEdge.side) {
case (.top, .inside), (.bottom, .outside):
horizontalEdgeConstraint = (base.top == horizontalEdge.layoutItem)
case (.bottom, .inside), (.top, .outside):
horizontalEdgeConstraint = (base.bottom == horizontalEdge.layoutItem)
default:
fatalError("Invalid layout item.")
}
let verticalEdgeConstraint: NSLayoutConstraint
switch (verticalEdge.layoutItem.attribute, verticalEdge.side) {
case (.left, .inside), (.right, .outside):
verticalEdgeConstraint = (base.left == verticalEdge.layoutItem)
case (.right, .inside), (.left, .outside):
verticalEdgeConstraint = (base.right == verticalEdge.layoutItem)
default:
fatalError("Invalid layout item.")
}
NSLayoutConstraint.activate([horizontalEdgeConstraint, verticalEdgeConstraint])
return (horizontalEdgeConstraint, verticalEdgeConstraint)
}
}
| mit | 1d7324117c8e52a7c9a7673e74978fc9 | 39.576271 | 146 | 0.646199 | 4.684932 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/FoundationErrors.swift | 1 | 8963 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
public struct NSCocoaError : RawRepresentable, Swift.Error, __BridgedNSError {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static var __NSErrorDomain: String { return NSCocoaErrorDomain }
}
/// Enumeration that describes the error codes within the Cocoa error
/// domain.
public extension NSCocoaError {
public static var FileNoSuchFileError: NSCocoaError {
return NSCocoaError(rawValue: 4)
}
public static var FileLockingError: NSCocoaError {
return NSCocoaError(rawValue: 255)
}
public static var FileReadUnknownError: NSCocoaError {
return NSCocoaError(rawValue: 256)
}
public static var FileReadNoPermissionError: NSCocoaError {
return NSCocoaError(rawValue: 257)
}
public static var FileReadInvalidFileNameError: NSCocoaError {
return NSCocoaError(rawValue: 258)
}
public static var FileReadCorruptFileError: NSCocoaError {
return NSCocoaError(rawValue: 259)
}
public static var FileReadNoSuchFileError: NSCocoaError {
return NSCocoaError(rawValue: 260)
}
public static var FileReadInapplicableStringEncodingError: NSCocoaError {
return NSCocoaError(rawValue: 261)
}
public static var FileReadUnsupportedSchemeError: NSCocoaError {
return NSCocoaError(rawValue: 262)
}
public static var FileReadTooLargeError: NSCocoaError {
return NSCocoaError(rawValue: 263)
}
public static var FileReadUnknownStringEncodingError: NSCocoaError {
return NSCocoaError(rawValue: 264)
}
public static var FileWriteUnknownError: NSCocoaError {
return NSCocoaError(rawValue: 512)
}
public static var FileWriteNoPermissionError: NSCocoaError {
return NSCocoaError(rawValue: 513)
}
public static var FileWriteInvalidFileNameError: NSCocoaError {
return NSCocoaError(rawValue: 514)
}
public static var FileWriteFileExistsError: NSCocoaError {
return NSCocoaError(rawValue: 516)
}
public static var FileWriteInapplicableStringEncodingError: NSCocoaError {
return NSCocoaError(rawValue: 517)
}
public static var FileWriteUnsupportedSchemeError: NSCocoaError {
return NSCocoaError(rawValue: 518)
}
public static var FileWriteOutOfSpaceError: NSCocoaError {
return NSCocoaError(rawValue: 640)
}
public static var FileWriteVolumeReadOnlyError: NSCocoaError {
return NSCocoaError(rawValue: 642)
}
public static var FileManagerUnmountUnknownError: NSCocoaError {
return NSCocoaError(rawValue: 768)
}
public static var FileManagerUnmountBusyError: NSCocoaError {
return NSCocoaError(rawValue: 769)
}
public static var KeyValueValidationError: NSCocoaError {
return NSCocoaError(rawValue: 1024)
}
public static var FormattingError: NSCocoaError {
return NSCocoaError(rawValue: 2048)
}
public static var UserCancelledError: NSCocoaError {
return NSCocoaError(rawValue: 3072)
}
public static var FeatureUnsupportedError: NSCocoaError {
return NSCocoaError(rawValue: 3328)
}
public static var ExecutableNotLoadableError: NSCocoaError {
return NSCocoaError(rawValue: 3584)
}
public static var ExecutableArchitectureMismatchError: NSCocoaError {
return NSCocoaError(rawValue: 3585)
}
public static var ExecutableRuntimeMismatchError: NSCocoaError {
return NSCocoaError(rawValue: 3586)
}
public static var ExecutableLoadError: NSCocoaError {
return NSCocoaError(rawValue: 3587)
}
public static var ExecutableLinkError: NSCocoaError {
return NSCocoaError(rawValue: 3588)
}
public static var PropertyListReadCorruptError: NSCocoaError {
return NSCocoaError(rawValue: 3840)
}
public static var PropertyListReadUnknownVersionError: NSCocoaError {
return NSCocoaError(rawValue: 3841)
}
public static var PropertyListReadStreamError: NSCocoaError {
return NSCocoaError(rawValue: 3842)
}
public static var PropertyListWriteStreamError: NSCocoaError {
return NSCocoaError(rawValue: 3851)
}
public static var PropertyListWriteInvalidError: NSCocoaError {
return NSCocoaError(rawValue: 3852)
}
public static var XPCConnectionInterrupted: NSCocoaError {
return NSCocoaError(rawValue: 4097)
}
public static var XPCConnectionInvalid: NSCocoaError {
return NSCocoaError(rawValue: 4099)
}
public static var XPCConnectionReplyInvalid: NSCocoaError {
return NSCocoaError(rawValue: 4101)
}
public static var UbiquitousFileUnavailableError: NSCocoaError {
return NSCocoaError(rawValue: 4353)
}
public static var UbiquitousFileNotUploadedDueToQuotaError: NSCocoaError {
return NSCocoaError(rawValue: 4354)
}
public static var UbiquitousFileUbiquityServerNotAvailable: NSCocoaError {
return NSCocoaError(rawValue: 4355)
}
public static var UserActivityHandoffFailedError: NSCocoaError {
return NSCocoaError(rawValue: 4608)
}
public static var UserActivityConnectionUnavailableError: NSCocoaError {
return NSCocoaError(rawValue: 4609)
}
public static var UserActivityRemoteApplicationTimedOutError: NSCocoaError {
return NSCocoaError(rawValue: 4610)
}
public static var UserActivityHandoffUserInfoTooLargeError: NSCocoaError {
return NSCocoaError(rawValue: 4611)
}
public static var CoderReadCorruptError: NSCocoaError {
return NSCocoaError(rawValue: 4864)
}
public static var CoderValueNotFoundError: NSCocoaError {
return NSCocoaError(rawValue: 4865)
}
public var isCoderError: Bool {
return rawValue >= 4864 && rawValue <= 4991
}
public var isExecutableError: Bool {
return rawValue >= 3584 && rawValue <= 3839
}
public var isFileError: Bool {
return rawValue >= 0 && rawValue <= 1023
}
public var isFormattingError: Bool {
return rawValue >= 2048 && rawValue <= 2559
}
public var isPropertyListError: Bool {
return rawValue >= 3840 && rawValue <= 4095
}
public var isUbiquitousFileError: Bool {
return rawValue >= 4352 && rawValue <= 4607
}
public var isUserActivityError: Bool {
return rawValue >= 4608 && rawValue <= 4863
}
public var isValidationError: Bool {
return rawValue >= 1024 && rawValue <= 2047
}
public var isXPCConnectionError: Bool {
return rawValue >= 4096 && rawValue <= 4224
}
}
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
internal func _NSErrorWithErrno(_ posixErrno : Int32, reading : Bool, path : String? = nil, url : URL? = nil, extraUserInfo : [String : Any]? = nil) -> NSError {
var cocoaError : NSCocoaError
if reading {
switch posixErrno {
case EFBIG: cocoaError = NSCocoaError.FileReadTooLargeError
case ENOENT: cocoaError = NSCocoaError.FileReadNoSuchFileError
case EPERM, EACCES: cocoaError = NSCocoaError.FileReadNoPermissionError
case ENAMETOOLONG: cocoaError = NSCocoaError.FileReadUnknownError
default: cocoaError = NSCocoaError.FileReadUnknownError
}
} else {
switch posixErrno {
case ENOENT: cocoaError = NSCocoaError.FileNoSuchFileError
case EPERM, EACCES: cocoaError = NSCocoaError.FileWriteNoPermissionError
case ENAMETOOLONG: cocoaError = NSCocoaError.FileWriteInvalidFileNameError
case EDQUOT, ENOSPC: cocoaError = NSCocoaError.FileWriteOutOfSpaceError
case EROFS: cocoaError = NSCocoaError.FileWriteVolumeReadOnlyError
case EEXIST: cocoaError = NSCocoaError.FileWriteFileExistsError
default: cocoaError = NSCocoaError.FileWriteUnknownError
}
}
var userInfo = extraUserInfo ?? [String : Any]()
if let path = path {
userInfo[NSFilePathErrorKey] = path._nsObject
} else if let url = url {
userInfo[NSURLErrorKey] = url
}
return NSError(domain: NSCocoaErrorDomain, code: cocoaError.rawValue, userInfo: userInfo)
}
| apache-2.0 | f85db5d0160cfab424fd825a21fe5651 | 30.783688 | 161 | 0.683811 | 5.560174 | false | false | false | false |
jixuhui/HJHeartSwift | HJHeartSwift/HJHeartSwift/ViewController.swift | 1 | 1043 | //
// ViewController.swift
// HJHeartSwift
//
// Created by jixuhui on 16/1/8.
// Copyright © 2016年 Hubbert. 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.
// let anotherVC = SNShareAndThreeDTouchViewController()
// print(anotherVC.threeDTouchAction())
var outerValueA = OuterValueType()
let outerValueB = outerValueA
outerValueA.changeMe("outerValueA changed")
outerValueB.printMe("outerValueB")
var outerReferenceA = OuterReferenceType()
let outerReferenceB = outerReferenceA
outerReferenceA.changeMe("outerReferenceA changed")
outerReferenceB.printMe("outerReferenceB")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 8a2de33fc264f58518546350352faaa4 | 25 | 80 | 0.655769 | 4.705882 | false | false | false | false |
LYM-mg/MGDYZB | MGDYZB简单封装版/MGDYZB/Class/Tools/Category/UIBarButtonItem-Extension.swift | 1 | 2215 | //
// UIBarButtonItem-Extension.swift
// MGDYZB
//
// Created by ming on 16/10/26.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
//
import UIKit
extension UIBarButtonItem {
/**
推荐使用: 类方法创建UIBarButtonItem
- parameter imageName: 图片名称
- parameter highImageName: 高亮时的图片名称(默认为"")
- parameter size: 按钮的尺寸(默认为"CGSizeZero")
- returns: UIBarButtonItem
*/
// 便利构造函数: 1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.zero, target: Any,action: Selector) {
// 1.创建UIButton
let btn = UIButton()
// 2.设置btn的图片
btn.setImage(UIImage(named: imageName), for: UIControl.State())
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
// 3.设置btn的尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
btn.addTarget(target, action: action, for: .touchUpInside)
// 4.创建UIBarButtonItem
self.init(customView : btn)
}
/**
不推荐使用: 类方法创建UIBarButtonItem
- parameter imageName: 图片名称
- parameter highImageName: 高亮时的图片名称
- parameter size: 按钮的尺寸
- returns: UIBarButtonItem
*/
class func createItem(_ imageName: String, highImageName: String = "", size: CGSize = CGSize.zero) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: UIControl.State())
btn.setImage(UIImage(named: highImageName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
btn.sizeToFit()
return UIBarButtonItem(customView: btn)
}
}
| mit | adb2e897391fe72f735b1b3cf56a1e51 | 27.84058 | 128 | 0.596482 | 4.11157 | false | false | false | false |
gregomni/swift | test/SourceKit/ExpressionType/basic.swift | 10 | 686 | func foo() -> Int { return 1 }
func bar(f: Float) -> Float { return bar(f: 1) }
protocol P {}
func fooP(_ p: P) { fooP(p) }
class C {}
func ArrayC(_ a: [C]) {
_ = a.count
_ = a.description.count.advanced(by: 1).description
}
struct S {
let val = 4
}
func DictS(_ a: [Int: S]) {
_ = a[2]?.val.advanced(by: 1).byteSwapped
}
// RUN: %sourcekitd-test -req=collect-type %s -- %s | %FileCheck %s
// CHECK: (183, 202): Int
// CHECK: (183, 196): String
// CHECK: (183, 184): [C]
// CHECK: (203, 211): (Int) -> (Int) -> Int
// CHECK: (216, 217): Int
// CHECK: (257, 258): Int
// CHECK: (291, 332): ()
// CHECK: (291, 292): Int?
// CHECK: (295, 332): Int?
// CHECK: (295, 320): Int
| apache-2.0 | f15cef679272027cfd15214fb8367690 | 19.787879 | 67 | 0.546647 | 2.485507 | false | false | false | false |
LunaGao/cnblogs-Mac-Swift | CNBlogsForMac/News/NewsDetailViewController.swift | 1 | 2115 | //
// NewsDetailViewController.swift
// CNBlogsForMac
//
// Created by Luna Gao on 15/12/2.
// Copyright © 2015年 gao.luna.com. All rights reserved.
//
import Cocoa
import WebKit
class NewsDetailViewController: BaseViewController {
@IBOutlet weak var detailNewsWebView: WebView!
var newsId = 0;
var newsTitle = "";
let newsApi = NewsWebApi()
override func viewDidLoad() {
super.viewDidLoad()
self.title = newsTitle
}
override func viewDidAppear() {
newsApi.newsBodyRequest(newsId) { (response) -> Void in
var localHtmlString = NSString.init(data: response, encoding: NSUTF8StringEncoding)!
localHtmlString = localHtmlString.substringToIndex(localHtmlString.length - 1)
localHtmlString = localHtmlString.substringFromIndex(1)
localHtmlString = self.transferredString(localHtmlString as String)
// NSLog("%@", localHtmlString)
self.detailNewsWebView.mainFrame.loadHTMLString(localHtmlString as String, baseURL: nil)
// self.detailBlogWebView.mainFrame.loadData(response, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: nil)
}
}
func transferredString(var string:String) -> String {
string = string.stringByReplacingOccurrencesOfString("\\\"", withString: "\"")
string = string.stringByReplacingOccurrencesOfString("\\r\\n", withString: "\n")
string = string.stringByReplacingOccurrencesOfString("\\t", withString: "\t")
string = string.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
// 基本样式
string = string + "<link type=\"text/css\" rel=\"stylesheet\" href=\"http://www.cnblogs.com/bundles/news.css\"/>"
// 有代码段时用来收起和展示的js
string = string + "<script src=\"http://www.cnblogs.com/bundles/news.js\" type=\"text/javascript\"></script>"
string = string + "<script src=\"http://common.cnblogs.com/script/jquery.js\" type=\"text/javascript\"></script>"
return string
}
}
| mit | 21efa7b7ad86a9cf3307c7a5626df0ed | 41.408163 | 141 | 0.653032 | 4.383966 | false | false | false | false |
kristopherjohnson/kjchess | kjchess/UCIEngine.swift | 1 | 8982 | //
// UCIEngine.swift
// kjchess
//
// Copyright © 2017 Kristopher Johnson. All rights reserved.
//
import Foundation
import os.log
import QuartzCore
/// Implementation of UCI (Universal Chess Interface) protocol.
/// Includes a few non-standard extensions that are useful for debugging.
public class UCIEngine {
public private(set) var position = Position.newGame()
/// Search depth used when determining best move.
///
/// A search depth of 6 provides moves in a few seconds
/// on an Early 2013 MacBook Pro.
public var searchDepth = 6
/// Number of concurrent move search tasks that will run.
///
/// On an Early 2013 MacBook Pro, values above 4 lead to
/// slower searches.
public var concurrentTasks = 4
/// Function called to read a line of input.
///
/// By default, this reads a line from standard input.
///
/// It can be set to another function to obtain input by
/// other means.
public var getLine: () -> String? = {
if let line = readLine(strippingNewline: true) {
if isLogEnabled { os_log("Read: %{public}@", log: uciLog, line) }
return line
}
else {
return nil
}
}
/// Function called to write a line of output.
///
/// By default, this writes to standard output.
///
/// It can be set to another function to send output by
/// other means.
public var putLine: (String) -> () = { line in
if isLogEnabled { os_log("Write: %{public}@", log: uciLog, line) }
print(line)
}
/// If true, emit diagnostic output to the client.
public var isDebugEnabled: Bool = false
/// Initializer
public init() {
}
/// Read UCI commands and process them until "quit" or end-of-stream.
public func runCommandLoop() throws {
if isLogEnabled { os_log("Enter runCommandLoop()", log: uciLog) }
while let line = getLine() {
if !processInput(line) {
break
}
}
if isLogEnabled { os_log("Exit runCommandLoop()", log: uciLog) }
}
/// Process a line of input.
///
/// This is invoked by `runCommandLoop()` for each line of input.
/// It may be called directly to "push" input to the engine instead
/// of using `runCommandLoop()`.
public func processInput(_ line: String) -> Bool {
return processCommand(tokens: line.whitespaceSeparatedTokens())
}
/// Process the given command.
///
/// - returns: `false` if the command loop should exit. `true` if it should continue.
public func processCommand(tokens: [String]) -> Bool {
if tokens.count == 0 {
return true
}
let cmd = tokens[0]
if isLogEnabled { os_log("Command: %{public}@", log: uciLog, "\(tokens)") }
switch cmd {
case "uci":
onUCICommand(tokens: tokens)
case "debug":
onDebugCommand(tokens: tokens)
case "isready":
putLine("readyok")
case "setoption":
onSetOptionCommand(tokens: tokens)
case "register":
onRegisterCommand(tokens: tokens)
case "ucinewgame":
onNewGameCommand(tokens: tokens)
case "position":
onPositionCommand(tokens: tokens)
case "go":
onGoCommand(tokens: tokens)
case "stop":
onStopCommand(tokens: tokens)
case "ponderhit":
onPonderHitCommand(tokens: tokens)
case "quit":
return false
default:
putInfoLine("unexpected command \(cmd)")
}
return true
}
private func onUCICommand(tokens: [String]) {
putLine("id name kjchess")
putLine("id author Kristopher Johnson")
putLine("uciok")
}
private func onDebugCommand(tokens: [String]) {
if tokens.count > 1 {
switch tokens[1] {
case "on":
isDebugEnabled = true
case "off":
isDebugEnabled = false
default:
if isDebugEnabled { putInfoLine("Unrecognized argument: \(tokens)") }
}
}
else if isDebugEnabled {
putInfoLine("Missing argument to debug command")
}
}
private func onSetOptionCommand(tokens: [String]) {
if isDebugEnabled { putInfoLine("Ignoring command \(tokens)") }
}
private func onRegisterCommand(tokens: [String]) {
if isDebugEnabled { putInfoLine("Ignoring command \(tokens)") }
}
private func onNewGameCommand(tokens: [String]) {
position = Position.newGame()
}
/// Parse a "position" command.
///
/// Syntax: `position [fen <fenstring> | startpos ] moves <move1> .... <movei>`
private func onPositionCommand(tokens: [String]) {
if tokens.count < 2 {
if isLogEnabled { os_log("Missing tokens after \"position\"", log: uciLog, type: .error) }
return
}
if tokens[1] == "startpos" {
// position startpos moves <move1> ... <moveN>
if tokens.count < 3 || tokens[2] != "moves" {
if isLogEnabled {
os_log("Missing tokens after \"startpos\"", log: uciLog, type: .error)
}
return
}
position = Position.newGame()
for i in 3..<tokens.count {
do {
let newPosition = try position.after(coordinateMove: tokens[i])
position = newPosition
if isDebugEnabled {
putLine("Applied move \(tokens[i])")
}
}
catch (let error) {
if isLogEnabled {
os_log("\"position\" error: move %{public}@: %{public}@",
log: uciLog,
type: .error,
tokens[i],
error.localizedDescription)
}
}
}
}
else if tokens[1] == "fen" {
if tokens.count < 8 {
if isLogEnabled {
os_log("\"position fen\" error: not enough elements", log: uciLog)
return
}
}
let fenrecord = tokens[2...7].joined(separator: " ")
do {
position = try Position(fen: fenrecord)
}
catch (let error) {
if isLogEnabled {
os_log("\"position fen\" error: \"%{public}@\": %{public}@",
log: uciLog,
type: .error,
fenrecord,
error.localizedDescription)
}
}
// TODO: If "move" follows FEN string, process it
}
else {
if isLogEnabled {
os_log("Only \"position startpos\" is supported",
log: uciLog, type: .error)
}
}
if isLogEnabled {
os_log("Position: %{public}@", log: uciLog, position.description)
}
}
private func onGoCommand(tokens: [String]) {
// TODO: look at the additional tokens. For now, we immediately return a bestmove.
let startTime = CACurrentMediaTime()
if let (move, score, pv) = bestMove(position: position,
searchDepth: searchDepth,
concurrentTasks: concurrentTasks) {
let endTime = CACurrentMediaTime()
let searchTimeMs = Int(((endTime - startTime) * 1000.0).rounded())
// score could be +/-Infinity, so clamp it before converting to centipawns.
let clampedScore = min(32767.0, max(-32767.0, score))
let scoreCentipawns = Int((clampedScore * 100).rounded())
var pvString: String
if pv.count > 0 {
pvString = pv.map{ $0.coordinateForm }.joined(separator: " ")
}
else {
pvString = move.coordinateForm
}
putLine("info depth \(searchDepth) score cp \(scoreCentipawns) time \(searchTimeMs) pv \(pvString)")
putLine("bestmove \(move.coordinateForm)")
}
else {
putLine("bestmove 0000")
}
}
private func onStopCommand(tokens: [String]) {
if isDebugEnabled { putInfoLine("Ignoring command \(tokens)") }
}
private func onPonderHitCommand(tokens: [String]) {
if isDebugEnabled { putInfoLine("Ignoring command \(tokens)") }
}
private func putInfoLine(_ s: String) {
if isLogEnabled { os_log("Info: %{public}@", log: uciLog, s) }
putLine("info string \(s)")
}
}
| mit | d0d73dda55b255569700278129c09714 | 29.341216 | 112 | 0.522659 | 4.598566 | false | false | false | false |
yuppielabel/YPMagnifyingGlass | source/YPMagnifyingView.swift | 2 | 2381 | //
// YPMagnifyingView.swift
// YPMagnifyingGlass
//
// Created by Geert-Jan Nilsen on 02/06/15.
// Copyright (c) 2015 Yuppielabel.com All rights reserved.
//
import UIKit
public class YPMagnifyingView: UIView {
private var magnifyingGlassShowDelay: TimeInterval = 0.2
private var touchTimer: Timer!
public var magnifyingGlass: YPMagnifyingGlass = YPMagnifyingGlass()
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Touch Events
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch: UITouch = touches.first {
self.touchTimer = Timer.scheduledTimer(timeInterval: magnifyingGlassShowDelay, target: self, selector: #selector(YPMagnifyingView.addMagnifyingGlassTimer(timer:)), userInfo: NSValue(cgPoint: touch.location(in: self)), repeats: false)
}
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch: UITouch = touches.first {
self.updateMagnifyingGlassAtPoint(point: touch.location(in: self))
}
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchTimer.invalidate()
self.touchTimer = nil
self.removeMagnifyingGlass()
}
// MARK: - Private Functions
private func addMagnifyingGlassAtPoint(point: CGPoint) {
self.magnifyingGlass.viewToMagnify = self as UIView
self.magnifyingGlass.touchPoint = point
let selfView: UIView = self as UIView
selfView.addSubview(self.magnifyingGlass)
self.magnifyingGlass.setNeedsDisplay()
}
private func removeMagnifyingGlass() {
self.magnifyingGlass.removeFromSuperview()
}
private func updateMagnifyingGlassAtPoint(point: CGPoint) {
self.magnifyingGlass.touchPoint = point
self.magnifyingGlass.setNeedsDisplay()
}
public func addMagnifyingGlassTimer(timer: Timer) {
let value: AnyObject? = timer.userInfo as AnyObject?
if let point = value?.cgPointValue {
self.addMagnifyingGlassAtPoint(point: point)
}
}
}
| mit | c43d69841791aef43f855d74c27d9b3e | 30.328947 | 245 | 0.654347 | 4.41744 | false | false | false | false |
coolryze/YZPlayer | YZPlayer/YZPlayer.swift | 1 | 1247 | //
// YZPlayer.swift
// YZPlayerDemo
//
// Created by heyuze on 2017/5/15.
// Copyright © 2017年 heyuze. All rights reserved.
//
import UIKit
// MARK: - Size
let kScreenWidth = UIScreen.main.bounds.size.width
let kScreenHeight = UIScreen.main.bounds.size.height
let kScreenBounds = UIScreen.main.bounds
let PlayerViewHeight: CGFloat = kScreenWidth * (750/1334)
// MARK: - Color
let WHITE = RGB(r: 0xff, g: 0xff, b: 0xff, alpha: 1)
let BLUE = RGB(r: 0x00, g: 0x56, b: 0xff, alpha: 1)
// MARK: - String
private let ResourcePath = Bundle.main.path(forResource: "Resource", ofType: "bundle")
// MARK: - Function
// 加载 Resource.bundle 存放的图片
func YZPlayerImage(named: String) -> UIImage? {
let imageName = ResourcePath?.appending("/\(named)")
let image = UIImage(named: imageName!)
return image
}
// RGB 颜色
func RGB(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor(red: r / 255, green: g / 255, blue: b / 255, alpha: alpha)
}
// 自定义 Log
func printLog(_ message: Any, file: String = #file, line: Int = #line, function: String = #function)
{
#if DEBUG
print("\((file as NSString).lastPathComponent)[\(line)], \(function): \(message)\n")
#endif
}
| mit | 910ac6f80b32c16fcfbf15a078c20296 | 22.461538 | 100 | 0.663934 | 3.227513 | false | false | false | false |
t4thswm/Course | Course/AssignmentDetailViewController.swift | 1 | 12644 | //
// AssignmentDetailViewController.swift
// Course
//
// Created by Archie Yu on 2016/12/4.
// Copyright © 2016年 Archie Yu. All rights reserved.
//
import UIKit
class AssignmentDetailViewController : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var assignmentNo = -1
var courseName = ""
let max = 16384
var year = 0
var timePicker : UIPickerView?
@IBOutlet weak var courseLabel: UILabel!
@IBOutlet weak var assignmentContent: UILabel!
@IBOutlet weak var assignmentNote: UILabel!
@IBOutlet weak var battery: UILabel!
@IBOutlet weak var remainingTime: UILabel!
@IBOutlet weak var batteryTrailingConstraint: NSLayoutConstraint!
var batteryWidth : CGFloat!
var timer: Timer!
override func viewDidLoad() {
super.viewDidLoad()
timePicker = UIPickerView()
timePicker?.delegate = self
timePicker?.dataSource = self
batteryWidth = UIScreen.main.bounds.width - 96
fresh()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AssignmentDetailViewController.fresh), userInfo: nil, repeats: true)
// 得到当前年份
let curTime = Date()
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyyy"
year = Int(timeFormatter.string(from: curTime))!
}
override func viewWillAppear(_ animated: Bool) {
courseLabel.text = assignmentList[assignmentNo].course
assignmentContent.text = assignmentList[assignmentNo].content
if assignmentList[assignmentNo].note == "" {
assignmentNote.text = "备注"
} else {
assignmentNote.text = assignmentList[assignmentNo].note
}
}
override func viewDidDisappear(_ animated: Bool) {
timer.invalidate()
}
func fresh() {
let current = Date()
let end = assignmentList[assignmentNo].endTime
let fromNow = end.timeIntervalSince(current)
var ratio: CGFloat!
// 处理过期任务
if fromNow < 0 {
ratio = 0
remainingTime.text = "任务过期"
} else {
let begin = assignmentList[assignmentNo].beginTime
let fromBegin = end.timeIntervalSince(begin)
// 计算电量显示条长度和剩余时间
if fromNow > fromBegin {
remainingTime.text = "任务还未开始"
} else {
ratio = CGFloat(fromNow / fromBegin)
var sec = Int(fromNow)
var min = sec / 60
sec %= 60
var hour = min / 60
min %= 60
let day = hour / 24
hour %= 24
if day > 0 {
remainingTime.text = String(format: "剩余时间 %d:%02d:%02d:%02d", arguments: [day, hour, min, sec])
} else if hour > 0 {
remainingTime.text = String(format: "剩余时间 %02d:%02d:%02d", arguments: [hour, min, sec])
} else {
remainingTime.text = String(format: "剩余时间 %02d:%02d", arguments: [min, sec])
}
}
}
batteryTrailingConstraint.constant = -8 - batteryWidth * (1 - ratio)
}
@IBAction func checkRemainingTime(_ sender: Any) {
let editTimeController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// 编辑开始时间
let beginHandler = {(action:UIAlertAction!) -> Void in
let editBeginTimeController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: .actionSheet)
// 定义时间选择器占用的空间
let margin : CGFloat = 0.0
let rect = CGRect(x: 0, y: margin, width: editTimeController.view.bounds.size.width, height: 230)
self.timePicker?.frame = rect
// self.timePicker?.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.5)
// 选择器初始值设置为开始时间
let beginTime = assignmentList[self.assignmentNo].beginTime
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyyy"
let year = Int(timeFormatter.string(from: beginTime))!
timeFormatter.dateFormat = "MM"
let month = Int(timeFormatter.string(from: beginTime))!
timeFormatter.dateFormat = "dd"
let day = Int(timeFormatter.string(from: beginTime))!
timeFormatter.dateFormat = "HH"
let hour = Int(timeFormatter.string(from: beginTime))!
timeFormatter.dateFormat = "mm"
let minute = Int(timeFormatter.string(from: beginTime))!
let middle = self.max / 2
let yearRow = middle - (middle % 9) + year - self.year + 4
let monthRow = middle - (middle % 12) + month - 1
let dayRow = middle - (middle % 31) + day - 1
let hourRow = middle - (middle % 24) + hour
let minuteRow = middle - (middle % 60) + minute
self.timePicker?.selectRow(yearRow, inComponent: 0, animated: true)
self.timePicker?.selectRow(monthRow, inComponent: 1, animated: true)
self.timePicker?.selectRow(dayRow, inComponent: 2, animated: true)
self.timePicker?.selectRow(hourRow, inComponent: 3, animated: true)
self.timePicker?.selectRow(minuteRow, inComponent: 4, animated: true)
// 将时间选择器添加到AlertController的视图中
editBeginTimeController.view.addSubview(self.timePicker!)
let confirmHandler = {(action:UIAlertAction!) -> Void in
let year = self.year + (self.timePicker?.selectedRow(inComponent: 0))! % 9 - 4
let month = (self.timePicker?.selectedRow(inComponent: 1))! % 12 + 1
let day = (self.timePicker?.selectedRow(inComponent: 2))! % 31 + 1
let hour = (self.timePicker?.selectedRow(inComponent: 3))! % 24
let minute = (self.timePicker?.selectedRow(inComponent: 4))! % 60
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = 0
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
assignmentList[self.assignmentNo].beginTime = date
}
let confirm = UIAlertAction(title: "确定", style: .default, handler: confirmHandler)
let cancel = UIAlertAction(title: "取消", style: .default, handler: nil)
editBeginTimeController.addAction(confirm)
editBeginTimeController.addAction(cancel)
self.present(editBeginTimeController, animated: true, completion: nil)
}
let begin = UIAlertAction(title: "开始时间", style: .default, handler: beginHandler)
// 编辑结束时间
let endHandler = {(action:UIAlertAction!) -> Void in
let editEndTimeController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: .actionSheet)
// 定义时间选择器占用的空间
let margin : CGFloat = 0.0
let rect = CGRect(x: 0, y: margin, width: editTimeController.view.bounds.size.width, height: 230)
self.timePicker?.frame = rect
// self.timePicker?.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.5)
// 选择器初始值设置为结束时间
let endTime = assignmentList[self.assignmentNo].endTime
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyyy"
let year = Int(timeFormatter.string(from: endTime))!
timeFormatter.dateFormat = "MM"
let month = Int(timeFormatter.string(from: endTime))!
timeFormatter.dateFormat = "dd"
let day = Int(timeFormatter.string(from: endTime))!
timeFormatter.dateFormat = "HH"
let hour = Int(timeFormatter.string(from: endTime))!
timeFormatter.dateFormat = "mm"
let minute = Int(timeFormatter.string(from: endTime))!
let middle = self.max / 2
let yearRow = middle - (middle % 9) + year - self.year + 4
let monthRow = middle - (middle % 12) + month - 1
let dayRow = middle - (middle % 31) + day - 1
let hourRow = middle - (middle % 24) + hour
let minuteRow = middle - (middle % 60) + minute
self.timePicker?.selectRow(yearRow, inComponent: 0, animated: true)
self.timePicker?.selectRow(monthRow, inComponent: 1, animated: true)
self.timePicker?.selectRow(dayRow, inComponent: 2, animated: true)
self.timePicker?.selectRow(hourRow, inComponent: 3, animated: true)
self.timePicker?.selectRow(minuteRow, inComponent: 4, animated: true)
// 将时间选择器添加到AlertController的视图中
editEndTimeController.view.addSubview(self.timePicker!)
let confirmHandler = {(action:UIAlertAction!) -> Void in
let year = self.year + (self.timePicker?.selectedRow(inComponent: 0))! % 9 - 4
let month = (self.timePicker?.selectedRow(inComponent: 1))! % 12 + 1
let day = (self.timePicker?.selectedRow(inComponent: 2))! % 31 + 1
let hour = (self.timePicker?.selectedRow(inComponent: 3))! % 24
let minute = (self.timePicker?.selectedRow(inComponent: 4))! % 60
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = 0
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
assignmentList[self.assignmentNo].endTime = date
}
let confirm = UIAlertAction(title: "确定", style: .default, handler: confirmHandler)
let cancel = UIAlertAction(title: "取消", style: .default, handler: nil)
editEndTimeController.addAction(confirm)
editEndTimeController.addAction(cancel)
self.present(editEndTimeController, animated: true, completion: nil)
}
let end = UIAlertAction(title: "结束时间", style: .default, handler: endHandler)
let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
editTimeController.addAction(begin)
editTimeController.addAction(end)
editTimeController.addAction(cancel)
self.present(editTimeController, animated: true, completion: nil)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 5
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return max
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int,
reusing view: UIView?) -> UIView {
let title = UILabel()
title.textColor = UIColor.black
title.textAlignment = NSTextAlignment.center
switch component {
case 0: title.text = String(row % 9 + year - 4)
case 1: title.text = String(row % 12 + 1)
case 2: title.text = String(row % 31 + 1)
case 3: title.text = String(row % 24)
case 4: title.text = String(row % 60)
default: title.text = ""
}
return title
}
}
| gpl-3.0 | 9e4054091e105eaa9ae3aea97cc7bb19 | 39.817881 | 156 | 0.563316 | 4.839812 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift | 12 | 7963 | //
// URLSession+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
/// RxCocoa URL errors.
public enum RxCocoaURLError
: Swift.Error {
/// Unknown error occurred.
case unknown
/// Response is not NSHTTPURLResponse
case nonHTTPResponse(response: URLResponse)
/// Response is not successful. (not in `200 ..< 300` range)
case httpRequestFailed(response: HTTPURLResponse, data: Data?)
/// Deserialization error.
case deserializationError(error: Swift.Error)
}
extension RxCocoaURLError
: CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error has occurred."
case let .nonHTTPResponse(response):
return "Response is not NSHTTPURLResponse `\(response)`."
case let .httpRequestFailed(response, _):
return "HTTP request failed with `\(response.statusCode)`."
case let .deserializationError(error):
return "Error during deserialization of the response: \(error)"
}
}
}
fileprivate func escapeTerminalString(_ value: String) -> String {
return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil)
}
fileprivate func convertURLRequestToCurlCommand(_ request: URLRequest) -> String {
let method = request.httpMethod ?? "GET"
var returnValue = "curl -X \(method) "
if let httpBody = request.httpBody, request.httpMethod == "POST" {
let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8)
if let body = maybeBody {
returnValue += "-d \"\(escapeTerminalString(body))\" "
}
}
for (key, value) in request.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString(key as String)
let escapedValue = escapeTerminalString(value as String)
returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" "
}
let URLString = request.url?.absoluteString ?? "<unknown url>"
returnValue += "\n\"\(escapeTerminalString(URLString))\""
returnValue += " -i -v"
return returnValue
}
fileprivate func convertResponseToString(_ data: Data!, _ response: URLResponse!, _ error: NSError!, _ interval: TimeInterval) -> String {
let ms = Int(interval * 1000)
if let response = response as? HTTPURLResponse {
if 200 ..< 300 ~= response.statusCode {
return "Success (\(ms)ms): Status \(response.statusCode)"
}
else {
return "Failure (\(ms)ms): Status \(response.statusCode)"
}
}
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return "Cancelled (\(ms)ms)"
}
return "Failure (\(ms)ms): NSError > \(error)"
}
return "<Unhandled response from server>"
}
extension Reactive where Base: URLSession {
/**
Observable sequence of responses for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
- parameter request: URL request.
- returns: Observable sequence of URL responses.
*/
public func response(request: URLRequest) -> Observable<(HTTPURLResponse, Data)> {
return Observable.create { observer in
// smart compiler should be able to optimize this out
let d: Date?
if Logging.URLRequests(request) {
d = Date()
}
else {
d = nil
}
let task = self.base.dataTask(with: request) { (data, response, error) in
if Logging.URLRequests(request) {
let interval = Date().timeIntervalSince(d ?? Date())
print(convertURLRequestToCurlCommand(request))
print(convertResponseToString(data, response, error as NSError!, interval))
}
guard let response = response, let data = data else {
observer.on(.error(error ?? RxCocoaURLError.unknown))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response)))
return
}
observer.on(.next(httpResponse, data))
observer.on(.completed)
}
let t = task
t.resume()
return Disposables.create(with: task.cancel)
}
}
/**
Observable sequence of response data for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
- parameter request: URL request.
- returns: Observable sequence of response data.
*/
public func data(request: URLRequest) -> Observable<Data> {
return response(request: request).map { (response, data) -> Data in
if 200 ..< 300 ~= response.statusCode {
return data
}
else {
throw RxCocoaURLError.httpRequestFailed(response: response, data: data)
}
}
}
/**
Observable sequence of response JSON for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter request: URL request.
- returns: Observable sequence of response JSON.
*/
public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable<Any> {
return data(request: request).map { (data) -> Any in
do {
return try JSONSerialization.jsonObject(with: data, options: options)
} catch let error {
throw RxCocoaURLError.deserializationError(error: error)
}
}
}
/**
Observable sequence of response JSON for GET request with `URL`.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter url: URL of `NSURLRequest` request.
- returns: Observable sequence of response JSON.
*/
public func json(url: Foundation.URL) -> Observable<Any> {
return json(request: URLRequest(url: url))
}
}
| apache-2.0 | f5d0e86862e14bf12859d31b868a1673 | 34.230088 | 138 | 0.631374 | 5.258917 | false | false | false | false |
GreatfeatServices/gf-mobile-app | olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+Collection.swift | 11 | 4167 | //
// CombineLatest+Collection.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class CombineLatestCollectionTypeSink<C: Collection, O: ObserverType>
: Sink<O> where C.Iterator.Element : ObservableConvertibleType {
typealias R = O.E
typealias Parent = CombineLatestCollectionType<C, R>
typealias SourceElement = C.Iterator.Element.E
let _parent: Parent
let _lock = NSRecursiveLock()
// state
var _numberOfValues = 0
var _values: [SourceElement?]
var _isDone: [Bool]
var _numberOfDone = 0
var _subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_values = [SourceElement?](repeating: nil, count: parent._count)
_isDone = [Bool](repeating: false, count: parent._count)
_subscriptions = Array<SingleAssignmentDisposable>()
_subscriptions.reserveCapacity(parent._count)
for _ in 0 ..< parent._count {
_subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceElement>, atIndex: Int) {
_lock.lock(); defer { _lock.unlock() } // {
switch event {
case .next(let element):
if _values[atIndex] == nil {
_numberOfValues += 1
}
_values[atIndex] = element
if _numberOfValues < _parent._count {
let numberOfOthersThatAreDone = self._numberOfDone - (_isDone[atIndex] ? 1 : 0)
if numberOfOthersThatAreDone == self._parent._count - 1 {
forwardOn(.completed)
dispose()
}
return
}
do {
let result = try _parent._resultSelector(_values.map { $0! })
forwardOn(.next(result))
}
catch let error {
forwardOn(.error(error))
dispose()
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
if _isDone[atIndex] {
return
}
_isDone[atIndex] = true
_numberOfDone += 1
if _numberOfDone == self._parent._count {
forwardOn(.completed)
dispose()
}
else {
_subscriptions[atIndex].dispose()
}
}
// }
}
func run() -> Disposable {
var j = 0
for i in _parent._sources {
let index = j
let source = i.asObservable()
let disposable = source.subscribe(AnyObserver { event in
self.on(event, atIndex: index)
})
_subscriptions[j].setDisposable(disposable)
j += 1
}
return Disposables.create(_subscriptions)
}
}
class CombineLatestCollectionType<C: Collection, R> : Producer<R> where C.Iterator.Element : ObservableConvertibleType {
typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R
let _sources: C
let _resultSelector: ResultSelector
let _count: Int
init(sources: C, resultSelector: @escaping ResultSelector) {
_sources = sources
_resultSelector = resultSelector
_count = Int(self._sources.count.toIntMax())
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R {
let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 76e496d56b6bafb8baee218ff2c9de75 | 31.546875 | 139 | 0.521843 | 5.220551 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.ChatTests/Models/AuthSettingsSpec.swift | 1 | 3473 | //
// AuthSettingsSpec.swift
// Rocket.ChatTests
//
// Created by Vadym Brusko on 10/17/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import XCTest
import SwiftyJSON
@testable import Rocket_Chat
// MARK: Test Instance
extension AuthSettings {
static func testInstance() -> AuthSettings {
let settings = AuthSettings()
settings.siteURL = "https://open.rocket.chat"
settings.cdnPrefixURL = "https://open.rocket.chat"
return settings
}
}
class AuthSettingsSpec: XCTestCase {
// MARK: Base URLs
func testBaseURLsMappingNoSlashInTheEnd() {
let json = JSON([[
"_id": "Site_Url",
"value": "https://foo.bar"
], [
"_id": "CDN_PREFIX",
"value": "https://cdn.foo.bar"
]])
let settings = AuthSettings()
settings.map(json, realm: nil)
XCTAssertEqual(settings.siteURL, "https://foo.bar")
XCTAssertEqual(settings.cdnPrefixURL, "https://cdn.foo.bar")
}
func testBaseURLsMappingWithSlashInTheEnd() {
let json = JSON([[
"_id": "Site_Url",
"value": "https://foo.bar/"
], [
"_id": "CDN_PREFIX",
"value": "https://cdn.foo.bar/"
]])
let settings = AuthSettings()
settings.map(json, realm: nil)
XCTAssertEqual(settings.siteURL, "https://foo.bar")
XCTAssertEqual(settings.cdnPrefixURL, "https://cdn.foo.bar")
}
// MARK: Registration Form
func testRegistrationFormPublic() {
let authSettings = AuthSettings()
authSettings.rawRegistrationForm = "Public"
XCTAssertEqual(authSettings.registrationForm, .isPublic, "type is public for Public")
}
func testRegistrationFormDisabled() {
let authSettings = AuthSettings()
authSettings.rawRegistrationForm = "Disabled"
XCTAssertEqual(authSettings.registrationForm, .isDisabled, "type is disabled for Disabled")
}
func testRegistrationFormSecretURL() {
let authSettings = AuthSettings()
authSettings.rawRegistrationForm = "Secret URL"
XCTAssertEqual(authSettings.registrationForm, .isSecretURL, "type is secretURL for Secret URL")
}
func testRegistrationFormInvalid() {
let authSettings = AuthSettings()
authSettings.rawRegistrationForm = "Foobar"
XCTAssertEqual(authSettings.registrationForm, .isPublic, "type is public for invalid")
}
// MARK: Custom Fields
func testCustomFieldsCorrectJsonMapToArray() {
let authSettings = AuthSettings()
authSettings.rawCustomFields = jsonCustomFields()
let customFields = authSettings.customFields
XCTAssertEqual(customFields.count, 2, "will have correct custom fields")
}
private func jsonCustomFields() -> String {
return "{ \"role\": { \"type\": \"select\", \"defaultValue\": \"student\", \"options\": [\"teacher\", \"student\"], \"required\": true, }, \"twitter\": { \"type\": \"text\", \"required\": true, \"minLength\": 2, \"maxLength\": 10 }}"
.removingWhitespaces()
}
func testCustomFieldsBadJsonMapToEmptyArray() {
let authSettings = AuthSettings()
authSettings.rawCustomFields = ""
let customFields = authSettings.customFields
XCTAssert(customFields.isEmpty, "will have empty array of custom fields")
}
}
| mit | 8f32c75d96318a0a4840264fc6dd8d75 | 29.642857 | 249 | 0.628497 | 4.263354 | false | true | false | false |
taketo1024/SwiftyAlgebra | Sources/SwmCore/Numbers/Quaternion.swift | 1 | 3519 | //
// Quaternion
// SwiftyMath
//
// Created by Taketo Sano on 2018/03/16.
// Copyright © 2018年 Taketo Sano. All rights reserved.
//
// see: https://en.wikipedia.org/wiki/quaternion
// memo: a skew field, i.e. product is non-commutative.
public typealias 𝐇 = Quaternion<𝐑>
public struct Quaternion<Base: Ring>: Ring {
public typealias BaseRing = Base
private let x: Base
private let y: Base
private let z: Base
private let w: Base
public init(from x: 𝐙) {
self.init(Base(from: x))
}
public init(_ x: Base) {
self.init(x, .zero, .zero, .zero)
}
public init(_ z: Complex<Base>, _ w: Complex<Base>) {
self.init(z.realPart, z.imaginaryPart, w.realPart, w.imaginaryPart)
}
public init(_ x: Base, _ y: Base, _ z: Base, _ w: Base) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public static var i: Self {
.init(.zero, .identity, .zero, .zero)
}
public static var j: Self {
.init(.zero, .zero, .identity, .zero)
}
public static var k: Self {
.init(.zero, .zero, .zero, .identity)
}
public var components: [Base] {
[x, y, z, w]
}
public var realPart: Base {
x
}
public var imaginaryPart: Self {
.init(.zero, y, z, w)
}
public var conjugate: Self {
.init(x, -y, -z, -w)
}
public var inverse: Self? {
let r2 = components.map{ $0 * $0 }.sum()
if let r2Inv = r2.inverse {
return Self(r2Inv) * conjugate
} else {
return nil
}
}
public static func +(a: Self, b: Self) -> Self {
.init(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w)
}
public static prefix func -(a: Self) -> Self {
.init(-a.x, -a.y, -a.z, -a.w)
}
public static func *(a: Self, b: Self) -> Self {
let v = a.asMatrix * b.asVector
return .init(v[0], v[1], v[2], v[3])
}
public var asVector: Vector4<Base> {
[x, y, z, w]
}
public var asMatrix: Matrix4x4<Base> {
[x, -y, -z, -w,
y, x, -w, z,
z, w, x, -y,
w, -z, y, x]
}
public var description: String {
Format.linearCombination([("1", x), ("i", y), ("j", z), ("k", w)])
}
public static var symbol: String {
(Base.self == 𝐑.self) ? "𝐇" : "\(Base.symbol)[i, j, k]"
}
}
extension Quaternion: EuclideanRing, Field where Base: Field {}
extension Quaternion: ExpressibleByIntegerLiteral where Base: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Base.IntegerLiteralType) {
self.init(Base(integerLiteral: value))
}
}
extension Quaternion: ExpressibleByFloatLiteral where Base: ExpressibleByFloatLiteral {
public init(floatLiteral value: Base.FloatLiteralType) {
self.init(Base(floatLiteral: value))
}
}
extension Quaternion where Base == 𝐑 {
public var abs: 𝐑 {
√(x * x + y * y + z * z + w * w)
}
public func isApproximatelyEqualTo(_ b: Self, error e: 𝐑? = nil) -> Bool {
return
self.x.isApproximatelyEqualTo(b.x, error: e) &&
self.y.isApproximatelyEqualTo(b.y, error: e) &&
self.z.isApproximatelyEqualTo(b.z, error: e) &&
self.w.isApproximatelyEqualTo(b.w, error: e)
}
}
extension Quaternion: Hashable where Base: Hashable {}
| cc0-1.0 | 2e6e869b214bc4a5c777ef82cb2ec327 | 24.107914 | 91 | 0.539542 | 3.326978 | false | false | false | false |
intonarumori/OnboardingController | OnboardingControllerExamples/AppDelegate.swift | 1 | 2946 | //
// AppDelegate.swift
// OnboardingViewController
//
// Created by Daniel Langh on 12/12/15.
// Copyright © 2015 rumori. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, OnboardingControllerDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
let onboardingController = self.createMainOnboardingControllerExample()
onboardingController.delegate = self
// create a UINavigationController so we can transition to the examples list later
let navigationController = UINavigationController(rootViewController: onboardingController)
navigationController.isNavigationBarHidden = true
self.navigationController = navigationController
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
func createMainOnboardingControllerExample() -> OnboardingController {
let progressView = PagingProgressView()
progressView.skipButton.addTarget(self, action: #selector(skipOnboarding), for: .touchUpInside)
let onboardingController = OnboardingController(
viewControllers: [
//UIStoryboard(name: "Onboarding", bundle: nil).instantiateViewControllerWithIdentifier("Example1"),
UIStoryboard(name: "OnboardingFlow", bundle: nil)
.instantiateViewController(withIdentifier: "WelcomeViewController"),
LocationSharingViewController(),
ModalExampleViewController(),
BackgroundDescriptionViewController(),
PagingProgressViewDescriptionViewController()
],
backgroundContentView: ParallaxImageBackgroundView(image: UIImage(named: "PanoramaTopBlur.jpg")!),
progressView: progressView
)
return onboardingController
}
@objc func skipOnboarding() {
// replace the onboardingcontroller with the example list
self.navigationController?.setViewControllers([ExamplesViewController()], animated: true)
}
// MARK: -
func onboardingController(_ onboardingController: OnboardingController,
didScrollToViewController viewController: UIViewController) {
// whenever onboardingcontroller scrolls and stops at a viewcontroller, this delegate method will be called
// print("OnboardingController did scroll to viewController: \(viewController)")
}
func onboardingControllerDidFinish(_ onboardingController: OnboardingController) {
self.skipOnboarding()
}
}
| mit | 6a757ed4a44248357a27ca56a7a580b5 | 38.797297 | 116 | 0.705603 | 6.360691 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/Foundation/NSExpression.swift | 1 | 854 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSExpression {
// + (NSExpression *) expressionWithFormat:(NSString *)expressionFormat, ...;
public
convenience init(format expressionFormat: String, _ args: CVarArg...) {
let va_args = getVaList(args)
self.init(format: expressionFormat, arguments: va_args)
}
}
| apache-2.0 | 2e4550ccd8f209f50521a46fe9e5b44c | 37.818182 | 80 | 0.591335 | 5.023529 | false | false | false | false |
jose-camallonga/sample-base | SampleApp/Modules/ShowItem/List/ListView.swift | 1 | 2638 | //
// ListView.swift
// SampleApp
//
// Created by Jose Camallonga on 31/03/2017.
// Copyright © 2017 Jose Camallonga. All rights reserved.
//
import UIKit
protocol ListViewProtocol: class {
weak var presenter: ListPresenterProtocol? { get set }
var refreshControl: UIRefreshControl! { get set }
func showData(_ viewModel: ListViewModel)
}
class ListView: UIViewController, ListViewProtocol {
@IBOutlet weak var tableView: UITableView!
weak var presenter: ListPresenterProtocol?
var refreshControl: UIRefreshControl!
var viewModel: ListViewModel?
override func viewDidLoad() {
super.viewDidLoad()
title = L10n.List.View.title
addRefreshControl()
presenter?.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
tableView.addSubview(refreshControl)
}
func showData(_ viewModel: ListViewModel) {
refreshControl.endRefreshing()
self.viewModel = viewModel
tableView.reloadData()
}
@objc func refresh() {
refreshControl.beginRefreshing()
presenter?.viewDidLoad()
}
}
extension ListView: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
presenter?.selectedRow(index: indexPath.row)
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension ListView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel?.sections.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel?.sections[section].title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel?.sections[section].rows.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let row = viewModel?.sections[indexPath.section].rows[indexPath.row],
let cell = tableView.dequeueReusableCell(withIdentifier: row.id, for: indexPath) as? ListTableViewCell else {
return UITableViewCell()
}
switch row.type {
case .titleRow(let title, let imageUrl):
cell.configure(title: title, urlImage: imageUrl)
}
return cell
}
}
| mit | 7260aace891e7f36afb79ecb2290f758 | 27.978022 | 121 | 0.664391 | 5.190945 | false | false | false | false |
TheDarkCode/Example-Swift-Apps | Exercises and Basic Principles/azure-search-basics/azure-search-basics/AZSResults.swift | 1 | 3015 | //
// AZSResults.swift
// azure-search-basics
//
// Created by Mark Hamilton on 3/10/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import Foundation
// Basic Structure
// "@odata.context": String
// "value": [Dictionary<String, AnyObject>]
// "@odata.nextLink": String
struct AZSResults {
private var _context: String? // @odata.context
private var _value:[Dictionary<String, AnyObject>]? // value
private var _nextLink: String? // @odata.nextLink
// Raw Results from API
private var _results: Dictionary<String, AnyObject>!
// MARK: - Downloaded Results
// var results: AnyObject {
//
// mutating get {
//
// if !isUniquelyReferencedNonObjC(&_results!) {
//
// _results = _results.copy()
//
// }
//
// return _results // as! [AZSResult]
// }
//
// }
var results: Dictionary<String, AnyObject> {
get {
return _results
}
set {
_results = newValue
}
}
// MARK: - Properties of Downloaded Results
var context: String {
get {
return _context ?? String()
}
}
var value: [Dictionary<String, AnyObject>] {
get {
if let results: [Dictionary<String, AnyObject>] = _value ?? [Dictionary<String, AnyObject>]() {
return results
}
}
}
var nextLink: String {
get {
if let nLink: String = _nextLink ?? "" {
return nLink
}
}
}
// MARK: - Initialize with results download from API.
init(results: Dictionary<String, AnyObject>) {
self.init()
if let Results: Dictionary<String, AnyObject> = results {
self._results = Results
}
}
// MARK: - Initialize with already parsed results download from API.
init(context: String, results: [Dictionary<String, AnyObject>], nextLink: String) {
self.init()
if let ctx: String = context where ctx != "" {
self._context = ctx
}
if let values: [Dictionary<String, AnyObject>] = results where values.count > 0 {
self._value = values
}
if let nxtLink: String = nextLink where nxtLink != "" {
self._nextLink = nxtLink
}
}
init() {
self._results = Dictionary<String,AnyObject>()
}
} | mit | 4e9fcef55c0d3ab0d2370c316267ebc1 | 19.510204 | 107 | 0.435965 | 5.22357 | false | false | false | false |
GorCat/TSImagePicker | ImagePicker/ImagePicker/ImagePicker/UI/preview/custom/CustomPHPreViewVC+Collection.swift | 1 | 1570 | //
// CustomPHPreViewVC+Collection.swift
// ImagePicker
//
// Created by GorCat on 2017/7/8.
// Copyright © 2017年 GorCat. All rights reserved.
//
import UIKit
extension CustomPHPreViewVC: UICollectionViewDelegate, UICollectionViewDataSource {
// MARK: - UI
func setCollcetionUI() {
let height = view.frame.height - TSImagePickerUX.toolBarHeight
collection.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: view.frame.width, height: height))
collection.delegate = self
collection.dataSource = self
collection.register(PreviewCollectionCell.self, forCellWithReuseIdentifier: PreviewCollectionCell.identifier)
if collection.superview == nil {
view.addSubview(collection)
}
}
// MARK: - Delegate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allAssets.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collection.dequeueReusableCell(withReuseIdentifier: PreviewCollectionCell.identifier, for: indexPath) as! PreviewCollectionCell
// 获取 cell 数据
let asset = allAssets[indexPath.item]
cell.set(image: asset)
// 设置 cell 的选中状态
let isSelected = selectedAssets.filter{ $0.localIdentifier == asset.localIdentifier }
cell.isImageSelected = !isSelected.isEmpty
return cell
}
}
| mit | 072a26213fe48c99f0e02b036192cf60 | 34.113636 | 146 | 0.683495 | 5.016234 | false | false | false | false |
cpmpercussion/microjam | chirpey/UserPerfTableViewCell.swift | 1 | 1593 | //
// UserPerfTableViewCell.swift
// microjam
//
// Created by Charles Martin on 1/5/18.
// Copyright © 2018 Charles Martin. All rights reserved.
//
import UIKit
class UserPerfTableViewCell: UITableViewCell {
/// A player controller for the ChirpView in the present cell
var player: ChirpPlayer?
/// Container view for the one or more ChirpViews for the cell
@IBOutlet weak var chirpContainer: UIView!
/// A play button layered over the ChirpContainer
@IBOutlet weak var playButton: UIButton!
/// A reply button layered over the ChirpContainer
@IBOutlet weak var replyButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
chirpContainer.layer.cornerRadius = 8
chirpContainer.layer.borderWidth = 1
chirpContainer.layer.borderColor = UIColor(white: 0.8, alpha: 1).cgColor
chirpContainer.backgroundColor = .white
chirpContainer.clipsToBounds = true
playButton.layer.cornerRadius = 18 // Button size is 36
playButton.setImage(#imageLiteral(resourceName: "microjam-play"), for: .normal)
playButton.tintColor = UIColor.darkGray
replyButton.layer.cornerRadius = 18 // Button size is 36
replyButton.setImage(#imageLiteral(resourceName: "microjam-reply"), for: .normal)
replyButton.tintColor = UIColor.darkGray
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 581dd9bf3368234c8e6588a519def349 | 34.377778 | 89 | 0.682161 | 4.459384 | false | false | false | false |
swift-gtk/SwiftGTK | Sources/UIKit/ImageType.swift | 1 | 1676 |
public enum ImageType: RawRepresentable {
/// There is no image displayed by the widget
case empty
/// The widget contains a `Pixbuf`
case pixbuf
/// The widget contains a stock item name
case stock
/// the widget contains a `PixbufAnimation`
case pixbufAnimation
/// The widget contains a named icon. This image type was added in GTK+ 2.6
case iconName
/// The widget contains a GIcon. This image type was added in GTK+ 2.14
case icon
/// The widget contains a `Surface`. This image type was added in GTK+ 3.10
case surface
public typealias RawValue = GtkImageType
public var rawValue: RawValue {
switch self {
case .empty:
return GTK_IMAGE_EMPTY
case .pixbuf:
return GTK_IMAGE_PIXBUF
case .stock:
return GTK_IMAGE_STOCK
case .pixbufAnimation:
return GTK_IMAGE_ANIMATION
case .iconName:
return GTK_IMAGE_ICON_NAME
case .icon:
return GTK_IMAGE_GICON
case .surface:
return GTK_IMAGE_SURFACE
}
}
public init?(rawValue: RawValue) {
switch rawValue {
case GTK_IMAGE_EMPTY:
self = .empty
case GTK_IMAGE_PIXBUF:
self = .pixbuf
case GTK_IMAGE_STOCK:
self = .stock
case GTK_IMAGE_ANIMATION:
self = .pixbufAnimation
case GTK_IMAGE_ICON_NAME:
self = .iconName
case GTK_IMAGE_GICON:
self = .icon
case GTK_IMAGE_SURFACE:
self = .surface
default:
return nil
}
}
}
| gpl-2.0 | ee7ccbbbb7300a93a7fcfbfda591725f | 26.933333 | 79 | 0.566826 | 4.422164 | false | false | false | false |
swift-gtk/SwiftGTK | Sources/UIKit/Container.swift | 1 | 5977 |
open class Container: Widget {
fileprivate (set) var widgets = [Widget]()
open func add(_ widget: Widget) {
guard widget.parent == nil else {
print("Attempting to add a widget to a container, but the widget is " +
"already inside a container, please remove the widget from its " +
"existing container first.")
return
}
widgets.append(widget)
widget.parentWidget = self
gtk_container_add(object.asGObject(), widget.object.asGObject())
/*
gtk_container_add(object.asGObject(), widget.n_Widget)
if !_children.contains(widget) {
_children.append(widget)
}
widget.parent = self
*/
}
open func remove(_ widget: Widget) {
if let index = widgets.index(where: { $0 === widget }) {
gtk_container_remove(object.asGObject(), widget.object.asGObject())
widgets.remove(at: index)
widget.parentWidget = nil
}
}
internal var _children = [Widget]()
internal var _internalChildren = [Widget]()
override class var n_Type: UInt {
return gtk_container_get_type()
}
// internal init(n_Container: UnsafeMutablePointer<GtkContainer>) {
// self.n_Container = n_Container
// super.init(n_Widget: unsafeBitCast(n_Container, to: UnsafeMutablePointer<GtkWidget>.self))
// }
internal func outsideGtkAddWidget(_ widget: Widget) {
guard widget.parent == nil else {
print("Attempting to add a widget to a container, but the widget is " +
"already inside a container, please remove the widget from its " +
"existing container first.")
return
}
_children.append(widget)
// widget.parent = self
}
/*
internal func _childWithPointer(_ pointer: UnsafeMutablePointer<GtkWidget>) -> Widget {
var child = _children.filter{ $0.asGObject() == pointer }.first
if child == nil {
let widget = Widget()
widget.object = object.asGObject()
child = Container.correctWidgetForWidget(widget)
_children.append(child!)
}
return child!
}
public func removeWidget(_ widget: Widget) {
guard widget != self else { return }
gtk_container_remove(object.asGObject(), object.asGObject())
guard let index = _children.index(of: widget) else { return }
_children.remove(at: index)
widget.parent = nil
}
internal func _clearChildren() {
var children = [Widget]()
let n_Children = Array<UnsafeMutablePointer<GtkWidget>>(gList: gtk_container_get_children(object.asGObject()))
for n_Child in n_Children {
var child = _children.filter{ $0.n_Widget == n_Child }.first
if child == nil {
child = Container.correctWidgetForWidget(Widget(n_Widget: n_Child))
}
children.append(child!)
}
_children = children
}
*/
// TODO: some for gtk_container_add_with_properties, vardic func
public func checkResize() {
gtk_container_check_resize(object.asGObject())
}
public func forEach(_ f: (Widget) -> Void) {
_ = _children.map(f)
}
public func getChildren() -> [Widget] {
return _children
}
// TODO: some for gtk_container_get_path_for_child(), need GtkWidgetPath class
public var focusChild: Widget? {
get {
let pWidget = gtk_container_get_focus_child(object.asGObject())
for widget in _children {
guard widget.object == pWidget?.asGObject() else { continue }
return widget
}
for widget in _internalChildren {
guard widget.object == pWidget?.asGObject() else { continue }
return widget
}
return nil
}
set(value) {
if let value = value {
guard _children.contains(value) || _internalChildren.contains(value)
else { return }
}
let pWidget = value?.object ?? nil
gtk_container_set_focus_child(object.asGObject(), pWidget?.asGObject())
}
}
// TODO: some for gtk_container_get_focus_vadjustment(),
// gtk_container_set_focus_vadjustment(), need GtkAdjustment class
// TODO: some for gtk_container_get_focus_hadjustment(),
// gtk_container_set_focus_hadjustment(), need GtkAdjustment class
public func childType() -> AnyObject.Type? {
return GTypeHelper.convertToClass(gtk_container_child_type(object.asGObject()))
}
// TODO: some for gtk_container_child_get(), gtk_container_child_set(),
// need vardic
// TODO: some for gtk_container_child_get_property(),
// gtk_container_child_set_property(), realy need?
// TODO: some for gtk_container_child_get_valist(),
// gtk_container_child_set_valist(), need valist
// TODO: some for gtk_container_child_notify(), idea about signal
public func forAll(_ f: (Widget) -> Void) {
_ = _children.map(f)
_ = _internalChildren.map(f)
}
public var borderWidth: Int {
get {
return Int(gtk_container_get_border_width(object.asGObject()))
}
set(value) {
gtk_container_set_border_width(object.asGObject(), UInt32(value))
}
}
// TODO: some for gtk_container_propagate_draw(), use cario-swift
// TODO: finish class
}
| gpl-2.0 | 114e58a2cbc53eb0499f6db812a4aecf | 30.293194 | 118 | 0.546595 | 4.463779 | false | false | false | false |
typarker/LotLizard | KitchenSink/ExampleFiles/ViewControllers/ExampleCenterTableViewController.swift | 2 | 13120 | // Copyright (c) 2014 evolved.io (http://evolved.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 UIKit
enum CenterViewControllerSection: Int {
case LeftViewState
case LeftDrawerAnimation
case RightViewState
case RightDrawerAnimation
}
class ExampleCenterTableViewController: ExampleViewController, UITableViewDataSource, UITableViewDelegate {
var tableView: UITableView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.restorationIdentifier = "ExampleCenterControllerRestorationKey"
}
override init() {
super.init()
self.restorationIdentifier = "ExampleCenterControllerRestorationKey"
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView = UITableView(frame: self.view.bounds, style: .Grouped)
self.tableView.delegate = self
self.tableView.dataSource = self
self.view.addSubview(self.tableView)
self.tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTap:")
doubleTap.numberOfTapsRequired = 2
self.view.addGestureRecognizer(doubleTap)
let twoFingerDoubleTap = UITapGestureRecognizer(target: self, action: "twoFingerDoubleTap:")
twoFingerDoubleTap.numberOfTapsRequired = 2
twoFingerDoubleTap.numberOfTouchesRequired = 2
self.view.addGestureRecognizer(twoFingerDoubleTap)
self.setupLeftMenuButton()
self.setupRightMenuButton()
let barColor = UIColor(red: 247/255, green: 249/255, blue: 250/255, alpha: 1.0)
self.navigationController?.navigationBar.barTintColor = barColor
self.navigationController?.view.layer.cornerRadius = 10.0
let backView = UIView()
backView.backgroundColor = UIColor(red: 208/255, green: 208/255, blue: 208/255, alpha: 1.0)
self.tableView.backgroundView = backView
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("Center will appear")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
println("Center did appear")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
println("Center will disappear")
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
println("Center did disappear")
}
func setupLeftMenuButton() {
let leftDrawerButton = DrawerBarButtonItem(target: self, action: "leftDrawerButtonPress:")
self.navigationItem.setLeftBarButtonItem(leftDrawerButton, animated: true)
}
func setupRightMenuButton() {
let rightDrawerButton = DrawerBarButtonItem(target: self, action: "rightDrawerButtonPress:")
self.navigationItem.setRightBarButtonItem(rightDrawerButton, animated: true)
}
override func contentSizeDidChange(size: String) {
self.tableView.reloadData()
}
// MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case CenterViewControllerSection.LeftDrawerAnimation.rawValue, CenterViewControllerSection.RightDrawerAnimation.rawValue:
return 6
case CenterViewControllerSection.LeftViewState.rawValue, CenterViewControllerSection.RightViewState.rawValue:
return 1
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as? UITableViewCell
if cell == nil {
cell = CenterTableViewCell(style: .Default, reuseIdentifier: CellIdentifier)
cell.selectionStyle = .Gray
}
let selectedColor = UIColor(red: 1 / 255, green: 15 / 255, blue: 25 / 255, alpha: 1.0)
let unselectedColor = UIColor(red: 79 / 255, green: 93 / 255, blue: 102 / 255, alpha: 1.0)
switch indexPath.section {
case CenterViewControllerSection.LeftDrawerAnimation.rawValue, CenterViewControllerSection.RightDrawerAnimation.rawValue:
var animationTypeForSection: DrawerAnimationType
if indexPath.section == CenterViewControllerSection.LeftDrawerAnimation.rawValue {
animationTypeForSection = ExampleDrawerVisualStateManager.sharedManager.leftDrawerAnimationType
} else {
animationTypeForSection = ExampleDrawerVisualStateManager.sharedManager.rightDrawerAnimationType
}
if animationTypeForSection.rawValue == indexPath.row {
cell.accessoryType = .Checkmark
cell.textLabel?.textColor = selectedColor
} else {
cell.accessoryType = .None
cell.textLabel?.textColor = unselectedColor
}
switch indexPath.row {
case DrawerAnimationType.None.rawValue:
cell.textLabel?.text = "None"
case DrawerAnimationType.Slide.rawValue:
cell.textLabel?.text = "Slide"
case DrawerAnimationType.SlideAndScale.rawValue:
cell.textLabel?.text = "Slide and Scale"
case DrawerAnimationType.SwingingDoor.rawValue:
cell.textLabel?.text = "Swinging Door"
case DrawerAnimationType.Parallax.rawValue:
cell.textLabel?.text = "Parallax"
case DrawerAnimationType.AnimatedBarButton.rawValue:
cell.textLabel?.text = "Animated Menu Button"
default:
break
}
case CenterViewControllerSection.LeftViewState.rawValue:
cell.textLabel?.text = "Enabled"
if self.evo_drawerController?.leftDrawerViewController != nil {
cell.accessoryType = .Checkmark
cell.textLabel?.textColor = selectedColor
} else {
cell.accessoryType = .None
cell.textLabel?.textColor = unselectedColor
}
case CenterViewControllerSection.RightViewState.rawValue:
cell.textLabel?.text = "Enabled"
if self.evo_drawerController?.rightDrawerViewController != nil {
cell.accessoryType = .Checkmark
cell.textLabel?.textColor = selectedColor
} else {
cell.accessoryType = .None
cell.textLabel?.textColor = unselectedColor
}
default:
break
}
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case CenterViewControllerSection.LeftDrawerAnimation.rawValue:
return "Left Drawer Animation";
case CenterViewControllerSection.RightDrawerAnimation.rawValue:
return "Right Drawer Animation";
case CenterViewControllerSection.LeftViewState.rawValue:
return "Left Drawer";
case CenterViewControllerSection.RightViewState.rawValue:
return "Right Drawer";
default:
return nil
}
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case CenterViewControllerSection.LeftDrawerAnimation.rawValue, CenterViewControllerSection.RightDrawerAnimation.rawValue:
if indexPath.section == CenterViewControllerSection.LeftDrawerAnimation.rawValue {
ExampleDrawerVisualStateManager.sharedManager.leftDrawerAnimationType = DrawerAnimationType(rawValue: indexPath.row)!
} else {
ExampleDrawerVisualStateManager.sharedManager.rightDrawerAnimationType = DrawerAnimationType(rawValue: indexPath.row)!
}
tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: .None)
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
case CenterViewControllerSection.LeftViewState.rawValue, CenterViewControllerSection.RightViewState.rawValue:
var sideDrawerViewController: UIViewController?
var drawerSide = DrawerSide.None
if indexPath.section == CenterViewControllerSection.LeftViewState.rawValue {
sideDrawerViewController = self.evo_drawerController?.leftDrawerViewController
drawerSide = .Left
} else if indexPath.section == CenterViewControllerSection.RightViewState.rawValue {
sideDrawerViewController = self.evo_drawerController?.rightDrawerViewController
drawerSide = .Right
}
if sideDrawerViewController != nil {
self.evo_drawerController?.closeDrawerAnimated(true, completion: { (finished) -> Void in
if drawerSide == DrawerSide.Left {
self.evo_drawerController?.leftDrawerViewController = nil
self.navigationItem.setLeftBarButtonItems(nil, animated: true)
} else if drawerSide == .Right {
self.evo_drawerController?.rightDrawerViewController = nil
self.navigationItem.setRightBarButtonItems(nil, animated: true)
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
})
} else {
if drawerSide == .Left {
let vc = ExampleLeftSideDrawerViewController()
let navC = UINavigationController(rootViewController: vc)
self.evo_drawerController?.leftDrawerViewController = navC
self.setupLeftMenuButton()
} else if drawerSide == .Right {
let vc = ExampleRightSideDrawerViewController()
let navC = UINavigationController(rootViewController: vc)
self.evo_drawerController?.rightDrawerViewController = navC
self.setupRightMenuButton()
}
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
default:
break
}
}
// MARK: - Button Handlers
func leftDrawerButtonPress(sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.Left, animated: true, completion: nil)
}
func rightDrawerButtonPress(sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.Right, animated: true, completion: nil)
}
func doubleTap(gesture: UITapGestureRecognizer) {
self.evo_drawerController?.bouncePreviewForDrawerSide(.Left, completion: nil)
}
func twoFingerDoubleTap(gesture: UITapGestureRecognizer) {
self.evo_drawerController?.bouncePreviewForDrawerSide(.Right, completion: nil)
}
}
| mit | 243be70eccbf5640b1323eee1af2e767 | 43.62585 | 134 | 0.653811 | 5.891334 | false | false | false | false |
pistolenernie/Spotify4Me | Talk2Spotify/Api2Spotify.swift | 1 | 3894 | //
// Api2Spotify.swift
// Talk2Spotify4Me
//
// Created by Lucas Backert on 02.11.14.
// Copyright (c) 2014 Lucas Backert. All rights reserved.
//
import Foundation
import AppKit
import AVFoundation
struct Api2Spotify {
static let osaStart = "tell application \"Spotify\" to"
static func getState() ->String{
return executeScript("player state")
}
static func getTitle() -> String{
return executeScript("name of current track")
}
static func getAlbum() -> String{
return executeScript("album of current track")
}
static func getArtist() -> String{
return executeScript("artist of current track")
}
static func getCover() -> Data{
var result: Data?
let artworkURL = executeScript("artwork url of current track")
if(artworkURL.contains("spotify:localfileimage")){
let artworkURLArray = artworkURL.components(separatedBy: ":")
var artworkURLString = artworkURLArray[2]
artworkURLString = artworkURLString.removingPercentEncoding!
let asset = AVURLAsset.init(url: URL(fileURLWithPath: artworkURLString))
let metadata = asset.commonMetadata
for (_,element) in metadata.enumerated() {
if element.commonKey == AVMetadataCommonKeyArtwork {
if element.dataValue != nil {
result = NSData(data: element.dataValue!) as Data
}
break
}
}
}else if(artworkURL.contains("http://i.scdn.co/image/")){
let session = URLSession.shared
var urlRequest = URLRequest(url: URL(string: artworkURL)!)
urlRequest.httpMethod = "GET"
let taskWithRequest = session.dataTask(with: urlRequest, completionHandler: {(data, response, error) -> Void in
if(error != nil){
print("error: \(error)")
}
if(data != nil){
result = data!
}else{
result = Data()
}
})
taskWithRequest.resume()
}else if (artworkURL == ""){
result = Data()
}
var counter = 0
while(result == nil && counter < 100){ //Wait for the task to finish
usleep(10000)
counter = counter + 1
}
if(result == nil) {result = Data()}
return result!
}
static func getVolume() -> String{
return executeScript("sound volume")
}
static func setVolume(_ level: Int){
_ = executeScript("set sound volume to \(level)")
}
static func toNextTrack(){
_ = executeScript("next track")
}
static func toPreviousTrack(){
_ = executeScript("previous track")
}
static func toPlayPause(){
_ = executeScript("playpause")
}
static func executeScript(_ phrase: String) -> String{
var output = ""
let spotifyapp: [NSRunningApplication] = NSRunningApplication.runningApplications(withBundleIdentifier: "com.spotify.client") as [NSRunningApplication]
if( !spotifyapp.isEmpty ){
let script = NSAppleScript(source: "\(osaStart) \(phrase)" )
var errorInfo: NSDictionary?
let descriptor = script?.executeAndReturnError(&errorInfo)
if(descriptor?.stringValue != nil){
output = descriptor!.stringValue!
}
}
return output
}
// NOT USED AT THE MOMENT
static func getDuration() -> String{
return executeScript("duration of current track")
}
static func getPosition() -> String{
return executeScript("position of current track")
}
}
| mit | f4b5a9f3aadb4a6aba4c94dae12d644a | 30.403226 | 159 | 0.556754 | 5.018041 | false | false | false | false |
aschwaighofer/swift | stdlib/public/Darwin/Accelerate/vImage_Buffer.swift | 2 | 8654 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// vImage_Buffer
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vImage_Buffer {
/// The size of the vImage buffer.
///
/// The `CGSize` is rounded down to the nearest representable `CGFloat` that
/// is less than or equal to the actual size of the image. In practice the
/// conversion will always be exact, except for really big images. In that
/// case, some part of the bottom or right edge might be truncated.
public var size: CGSize {
var mutableSelf = self
return vImageBuffer_GetSize(&mutableSelf)
}
//===----------------------------------------------------------------------===//
/// Returns the preferred alignment and row bytes for a specified buffer
/// size and bits-per-pixel.
///
/// - Parameter width: The width of the buffer.
/// - Parameter height: The height of the buffer.
/// - Parameter bitsPerPixel: The number of bits in a pixel of image data.
///
/// - Returns: The preferred alignment and row bytes.
public static func preferredAlignmentAndRowBytes(width: Int,
height: Int,
bitsPerPixel: UInt32) throws -> (alignment: Int, rowBytes: Int) {
if width < 0 || height < 0 {
throw vImage.Error.invalidParameter
}
var buffer = vImage_Buffer()
let error = vImageBuffer_Init(&buffer,
vImagePixelCount(height),
vImagePixelCount(width),
bitsPerPixel,
vImage_Flags(kvImageNoAllocate))
if error < kvImageNoError {
throw vImage.Error(vImageError: error)
} else {
return(alignment: error,
rowBytes: buffer.rowBytes)
}
}
//===----------------------------------------------------------------------===//
//
// Initializers.
//
//===----------------------------------------------------------------------===//
/// Initializes a vImage buffer of a specified size.
///
/// - Parameter width: The width of the buffer.
/// - Parameter height: The height of the buffer.
/// - Parameter bitsPerPixel: The number of bits in a pixel of image data.
///
/// - Returns: An initialized vImage buffer.
public init(width: Int,
height: Int,
bitsPerPixel: UInt32) throws {
if width < 0 || height < 0 {
throw vImage.Error.invalidParameter
}
self.init()
let error = vImageBuffer_Init(&self,
vImagePixelCount(height),
vImagePixelCount(width),
bitsPerPixel,
vImage_Flags(kvImageNoFlags))
if error < kvImageNoError {
throw vImage.Error(vImageError: error)
}
}
public func free() {
Darwin.free(data)
}
}
// MARK: Core Graphics Support
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vImage_Buffer {
/// Initialize a vImage buffer with the contents of a Core Graphics image.
///
/// - Parameter cgImage: A `CGImage` instance to be used as the source.
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: An initialized vImage buffer.
///
/// This function will instantiate and initialize a vImage buffer from a `CGImage` using a `CGImageFormat` based on the provided image's properties.
public init(cgImage: CGImage,
flags options: vImage.Options = .noFlags) throws {
self.init()
guard var format = vImage_CGImageFormat(cgImage: cgImage) else {
throw vImage.Error.invalidImageFormat
}
let error = vImageBuffer_InitWithCGImage(&self,
&format,
nil,
cgImage,
options.flags)
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
}
}
//===----------------------------------------------------------------------===//
/// Initialize a vImage buffer with the contents of a Core Graphics image,
/// using a supplied format.
///
/// - Parameter cgImage: A `CGImage` instance to be used as the source.
/// - Parameter format: A `vImage_CGImageFormat` that describes the source image/
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: An initialized vImage buffer.
///
/// This function will instantiate and initialize a vImage buffer from a `CGImage` using a provided `CGImageFormat`.
public init(cgImage: CGImage,
format: vImage_CGImageFormat,
flags options: vImage.Options = .noFlags) throws {
self.init()
var format = format
let error = vImageBuffer_InitWithCGImage(&self,
&format,
nil,
cgImage,
options.flags)
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
}
}
//===----------------------------------------------------------------------===//
/// Creates a `CGImage` instance from a vImage buffer
///
/// - Parameter format: The image format of this vImage buffer.
/// - Parameter options: The options to use when performing this operation.
///
/// - Returns: A Core Graphics image containing a representation of the vImage buffer.
public func createCGImage(format: vImage_CGImageFormat,
flags options: vImage.Options = .noFlags) throws -> CGImage {
var format = format
var error = kvImageNoError
var cgImage: CGImage?
withUnsafePointer(to: self) {
cgImage = vImageCreateCGImageFromBuffer(
$0,
&format,
nil,
nil,
options.flags,
&error).takeRetainedValue()
}
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
} else if cgImage == nil {
throw vImage.Error.internalError
}
return cgImage!
}
//===----------------------------------------------------------------------===//
/// Copies this buffer to `destinationBuffer`.
///
/// - Parameter destinationBuffer: The destination vImage buffer.
/// - Parameter pixelSize: The number of bytes for one pixel.
/// - Parameter options: The options to use when performing this operation.
public func copy(destinationBuffer: inout vImage_Buffer,
pixelSize: Int,
flags options: vImage.Options = .noFlags) throws {
if Int(width) == 0 {
throw vImage.Error(vImageError: kvImageInvalidParameter)
}
var error = kvImageNoError
withUnsafePointer(to: self) {
error = vImageCopyBuffer($0,
&destinationBuffer,
pixelSize,
options.flags)
}
if error != kvImageNoError {
throw vImage.Error(vImageError: error)
}
}
}
| apache-2.0 | 96736c251e3bf15337d3b00b4b08122c | 36.301724 | 152 | 0.479316 | 5.867119 | false | false | false | false |
edison9888/D3View | D3View/D3View/D3View.swift | 1 | 2003 | // Created by mozhenhau on 14/11/21.
// Copyright (c) 2014年 mozhenhau. All rights reserved.
// 初始化话是基于tag的,比如D3Button默认tag为0时是圆角
// 使用方法1:在mainstoryboard继承D3__ ,然后tag设置为对应样式。(tag被占用的时候不可用)
// 2: 在viewcontroller实例化后在viewdiload进行初始化initstyle,可以传多个样式
//
import UIKit
//MARK: OTHER widget
public class D3View: UIView {
//对应enum ViewStyle
@IBInspectable var viewStyle: Int = 0
//对应enum ViewStyle,可写多个用逗号隔开
@IBInspectable var viewStyles: String = ""{
didSet{
var styles = viewStyles.split(",")
for style in styles{
if let styleInt = style.toInt() {
if let style:ViewStyle = ViewStyle(rawValue: style.toInt()!){
initStyle(style)
}
}
}
}
}
@IBInspectable var isShadowDown: Bool = false {
didSet {
if isShadowDown{
initStyle(ViewStyle.ShadowDown)
}
}
}
@IBInspectable var isShadow: Bool = false {
didSet {
if isShadow{
initStyle(ViewStyle.Shadow)
}
}
}
@IBInspectable var isGrayBorder: Bool = false {
didSet {
if isGrayBorder{
initStyle(ViewStyle.Border,ViewStyle.GrayBorder)
}
}
}
//是否圆形
@IBInspectable var isRound: Bool = false {
didSet {
if isRound{
initStyle(ViewStyle.Round)
}
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor(){
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
} | mit | 6f6ebd1c28b397fd62d43ba563b337fd | 24.527778 | 81 | 0.526946 | 4.37381 | false | false | false | false |
yanyuqingshi/ios-charts | Charts/Classes/Data/PieChartData.swift | 7 | 1831 | //
// PieData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/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
public class PieChartData: ChartData
{
public override init()
{
super.init();
}
public override init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
var dataSet: PieChartDataSet?
{
get
{
return dataSets.count > 0 ? dataSets[0] as? PieChartDataSet : nil;
}
set
{
if (newValue != nil)
{
dataSets = [newValue!];
}
else
{
dataSets = [];
}
}
}
public override func getDataSetByIndex(index: Int) -> ChartDataSet?
{
if (index != 0)
{
return nil;
}
return super.getDataSetByIndex(index);
}
public override func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet?
{
if (dataSets.count == 0 || dataSets[0].label == nil)
{
return nil;
}
if (ignorecase)
{
if (label.caseInsensitiveCompare(dataSets[0].label!) == NSComparisonResult.OrderedSame)
{
return dataSets[0];
}
}
else
{
if (label == dataSets[0].label)
{
return dataSets[0];
}
}
return nil;
}
}
| apache-2.0 | 8db04f53422c6a7ad18ee90535da4f12 | 20.797619 | 99 | 0.499181 | 4.5775 | false | false | false | false |
joncardasis/ChromaColorPicker | Tests/TestHelpers/UIColor+TestHelpers.swift | 1 | 773 | //
// UIColor+TestHelpers.swift
// ChromaColorPickerTests
//
// Created by Jon Cardasis on 5/2/19.
// Copyright © 2019 Jonathan Cardasis. All rights reserved.
//
import UIKit
extension UIColor {
var rgbValues: (red: CGFloat, green: CGFloat, blue: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: nil)
return (red, green, blue)
}
var hsbaValues: (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) {
var h: CGFloat = 0
var s: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return (h,s,b,a)
}
}
| mit | f0308afab7d287820d6bb6f5765eec50 | 24.733333 | 94 | 0.581606 | 3.641509 | false | true | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | source/RSTBSupport/Classes/EnhancedMultipleChoice/RSEnhancedChoiceItemDescriptor.swift | 1 | 1101 | //
// RSEnhancedChoiceItemDescriptor.swift
// Pods
//
// Created by James Kizer on 4/8/17.
//
//
import UIKit
import ResearchSuiteTaskBuilder
import Gloss
open class RSEnhancedChoiceItemDescriptor: RSTBChoiceItemDescriptor {
public let identifier: String
public let auxiliaryItem: JSON?
public required init?(json: JSON) {
//for backwards compatibility, use value for identifer if it's a string
//note this might still break stuff
let idOpt: String? = "identifier" <~~ json
let valueOpt: String? = {
if let value: String = "value" <~~ json {
return value
}
else if let value: NSNumber = "value" <~~ json {
return "\(value)"
}
else {
return nil
}
}()
guard let identifier: String = idOpt ?? valueOpt else {
return nil
}
self.identifier = identifier
self.auxiliaryItem = "auxiliaryItem" <~~ json
super.init(json: json)
}
}
| apache-2.0 | 34b8f0a0a544b37c3f3011308e6ac05a | 23.466667 | 79 | 0.546776 | 4.85022 | false | false | false | false |
DianQK/RxExtensions | RxExtensions/Transition.swift | 1 | 1316 | //
// Transition.swift
// SelectCell
//
// Created by DianQK on 20/10/2016.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
public func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
public let pop: () -> () = {
topViewController()?.navigationController?.popViewController(animated: true).ignore()
}
public let show: (UIViewController) -> () = { vc in
topViewController()?.show(vc, sender: nil)
}
public let showDetailViewController: (UIViewController) -> () = { vc in
topViewController()?.showDetailViewController(vc, sender: nil)
}
public let push: (UIViewController) -> () = { vc in
topViewController()?.navigationController?.pushViewController(vc, animated: true)
}
public let present: (UIViewController) -> () = { vc in
topViewController()?.present(vc, animated: true, completion: nil)
}
| mit | a2379b8e6f0f1c6643c793274a8a1c19 | 28.886364 | 132 | 0.692776 | 4.630282 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/ProjectPageViewModel.swift | 1 | 26213 | import Foundation
import KsApi
import Prelude
import ReactiveSwift
public protocol ProjectPageViewModelInputs {
/// Call when didSelectRowAt is called on a `ProjectFAQAskAQuestionCell`
func askAQuestionCellTapped()
/// Call when `AppDelegate`'s `applicationDidEnterBackground` is triggered.
func applicationDidEnterBackground()
/// Call with the project given to the view controller.
func configureWith(projectOrParam: Either<Project, Param>, refTag: RefTag?)
/// Call when the Thank you page is dismissed after finishing backing the project
func didBackProject()
/// Call with the `Int` (index) of the cell selected and the existing values (`[Bool]`) in the data source
func didSelectFAQsRowAt(row: Int, values: [Bool])
/// Call with the `URL` of the `ImageViewElement` cell selected in the Campaign section of the data source.
func didSelectCampaignImageLink(url: URL)
/// Call when the navigation bar should be hidden/shown.
func showNavigationBar(_ flag: Bool)
/// Call when the ManagePledgeViewController finished updating/cancelling a pledge with an optional message
func managePledgeViewControllerFinished(with message: String?)
/// Call when the pledge CTA button is tapped
func pledgeCTAButtonTapped(with state: PledgeStateCTAType)
/// Call when pledgeRetryButton is tapped.
func pledgeRetryButtonTapped()
/// Call for image view elements that are missing inside `prefetchRowsAt` delegate in `ProjectPageViewController`
func prepareImageAt(_ indexPath: IndexPath)
/// Call for audio/video view elements that are missing a player inside `prefetchRowsAt` delegate in `ProjectPageViewController`
func prepareAudioVideoAt(_ indexPath: IndexPath, with audioVideoViewElement: AudioVideoViewElement)
/// Call when the delegate method for the `ProjectEnvironmentalCommitmentFooterCellDelegate` is called.
func projectEnvironmentalCommitmentDisclaimerCellDidTapURL(_ URL: URL)
/// Call when the `ProjectNavigationSelectorViewDelegate` delegate method is called
func projectNavigationSelectorViewDidSelect(index: Int)
/// Call when the delegate method for the `ProjectRisksDisclaimerCellDelegate` is called.
func projectRisksDisclaimerCellDidTapURL(_ url: URL)
/// Call when didSelectRow is called on the comments cell.
func tappedComments()
/// Call when didSelectRow is called on the updates cell.
func tappedUpdates()
/// Call when the creator header cell progress view is tapped.
func tappedViewProgress(of project: Project)
/// Call when the user session starts and we want to reload the data source.
func userSessionStarted()
/// Call when the view did appear, and pass the animated parameter.
func viewDidAppear(animated: Bool)
/// Call when the view loads.
func viewDidLoad()
/// Call when right before orientation change on view
func viewWillTransition()
}
public protocol ProjectPageViewModelOutputs {
/// Emits a tuple of a `NavigationSection`, `Project` and `RefTag?` to configure the data source
var configureDataSource: Signal<(NavigationSection, Project, RefTag?), Never> { get }
/// Emits a project that should be used to configure all children view controllers.
var configureChildViewControllersWithProject: Signal<(Project, RefTag?), Never> { get }
/// Emits PledgeCTAContainerViewData to configure PledgeCTAContainerView
var configurePledgeCTAView: Signal<PledgeCTAContainerViewData, Never> { get }
/// Emits `(Project, RefTag?)` to configure `ProjectNavigationSelectorView`
var configureProjectNavigationSelectorView: Signal<(Project, RefTag?), Never> { get }
/// Emits a message to show on `MessageBannerViewController`
var dismissManagePledgeAndShowMessageBannerWithMessage: Signal<String, Never> { get }
/// Emits a `Project` when the comments are to be rendered.
var goToComments: Signal<Project, Never> { get }
/// Emits a `Param` when the creator header cell progress view is tapped.
var goToDashboard: Signal<Param, Never> { get }
/// Emits `ManagePledgeViewParamConfigData` to take the user to the `ManagePledgeViewController`
var goToManagePledge: Signal<ManagePledgeViewParamConfigData, Never> { get }
/// Emits a `Project` when the updates are to be rendered.
var goToUpdates: Signal<Project, Never> { get }
/// Emits a project and refTag to be used to navigate to the reward selection screen.
var goToRewards: Signal<(Project, RefTag?), Never> { get }
/// Emits a URL that will be opened by an external Safari browser.
var goToURL: Signal<URL, Never> { get }
/// Emits a `Bool` to hide the navigation bar.
var navigationBarIsHidden: Signal<Bool, Never> { get }
/// Emits a signal when the app is no longer being actively used to pause any playing media.
var pauseMedia: Signal<Void, Never> { get }
/// Emits when the navigation stack should be popped to the root view controller.
var popToRootViewController: Signal<(), Never> { get }
/// Emits `Project` when the MessageDialogViewController should be presented
var presentMessageDialog: Signal<Project, Never> { get }
/// Emits `AudioVideoViewElement` and `IndexPath` when the project has campaign data to download for a row
var precreateAudioVideoURLs: Signal<(AudioVideoViewElement, IndexPath), Never> { get }
/// Emits `[AudioVideoViewElement]` to preload the data source with `AVPlayer` objects for video player cells.
var precreateAudioVideoURLsOnFirstLoad: Signal<[AudioVideoViewElement], Never> { get }
/// Emits `[URL]` and `IndexPath` when the project has campaign data to download for a row
var prefetchImageURLs: Signal<([URL], IndexPath), Never> { get }
/// Emits `[ImageViewElement]` when the project has campaign data to download for an image row as soon as the urls are available.
var prefetchImageURLsOnFirstLoad: Signal<[ImageViewElement], Never> { get }
/// Emits a signal when an orientation change happens if the currently selected tab is campaign.
var reloadCampaignData: Signal<Void, Never> { get }
/// Emits a `HelpType` to use when presenting a HelpWebViewController.
var showHelpWebViewController: Signal<HelpType, Never> { get }
/// Emits a tuple of a `NavigationSection`, `Project`, `RefTag?`, `[Bool]` (isExpanded values) and `[URL]` for campaign data to instruct the data source which section it is loading.
var updateDataSource: Signal<(NavigationSection, Project, RefTag?, [Bool], [URL]), Never> { get }
/// Emits a tuple of `Project`, `RefTag?` and `[Bool]` (isExpanded values) for the FAQs.
var updateFAQsInDataSource: Signal<(Project, RefTag?, [Bool]), Never> { get }
}
public protocol ProjectPageViewModelType {
var inputs: ProjectPageViewModelInputs { get }
var outputs: ProjectPageViewModelOutputs { get }
}
public final class ProjectPageViewModel: ProjectPageViewModelType, ProjectPageViewModelInputs,
ProjectPageViewModelOutputs {
public init() {
let isLoading = MutableProperty(false)
self.popToRootViewController = self.didBackProjectProperty.signal.ignoreValues()
let freshProjectAndRefTagEvent = self.configDataProperty.signal.skipNil()
.takePairWhen(Signal.merge(
self.viewDidLoadProperty.signal.mapConst(true),
self.userSessionStartedProperty.signal.mapConst(true),
self.didBackProjectProperty.signal.ignoreValues().mapConst(false),
self.managePledgeViewControllerFinishedWithMessageProperty.signal.ignoreValues().mapConst(false),
self.pledgeRetryButtonTappedProperty.signal.mapConst(false)
))
.map(unpack)
.switchMap { projectOrParam, refTag, shouldPrefix in
fetchProject(projectOrParam: projectOrParam, shouldPrefix: shouldPrefix)
.on(
starting: { isLoading.value = true },
terminated: { isLoading.value = false }
)
.map { project in
(project, refTag.map(cleanUp(refTag:)))
}
.materialize()
}
let projectFriends = MutableProperty([User]())
projectFriends <~ self.configDataProperty.signal.skipNil()
.switchMap { projectParamAndRefTag -> SignalProducer<[User], Never> in
let (projectOrParam, _) = projectParamAndRefTag
return fetchProjectFriends(projectOrParam: projectOrParam).demoteErrors()
}
let freshProjectAndRefTag = freshProjectAndRefTagEvent.values()
.map { project, refTag -> (Project, RefTag?) in
let updatedProjectWithFriends = project
|> Project.lens.personalization.friends .~ projectFriends.value
|> Project.lens.extendedProjectProperties .~ project.extendedProjectProperties
return (updatedProjectWithFriends, refTag)
}
let project = freshProjectAndRefTag
.map(first)
self.prefetchImageURLs = project.signal
.skip(first: 1)
.combineLatest(with: self.prepareImageAtProperty.signal.skipNil())
.filterWhenLatestFrom(
self.projectNavigationSelectorViewDidSelectProperty.signal.skipNil(),
satisfies: { NavigationSection(rawValue: $0) == .campaign }
)
.switchMap { project, indexPath -> SignalProducer<([URL], IndexPath)?, Never> in
let imageViewElements = project.extendedProjectProperties?.story.htmlViewElements
.compactMap { $0 as? ImageViewElement } ?? []
if imageViewElements.count > 0 {
let urlStrings = imageViewElements.map { $0.src }
let urls = urlStrings.compactMap { URL(string: $0) }
return SignalProducer(value: (urls, indexPath))
}
return SignalProducer(value: nil)
}
.skipNil()
self.prefetchImageURLsOnFirstLoad = project.signal
.skip(first: 1)
.switchMap { project -> SignalProducer<[ImageViewElement], Never> in
let imageViewElements = project.extendedProjectProperties?.story.htmlViewElements
.compactMap { $0 as? ImageViewElement } ?? []
return SignalProducer(value: imageViewElements)
}
self.precreateAudioVideoURLsOnFirstLoad = project.signal
.skip(first: 1)
.switchMap { project -> SignalProducer<[AudioVideoViewElement], Never> in
let audioVideoViewElements = project.extendedProjectProperties?.story.htmlViewElements
.compactMap { $0 as? AudioVideoViewElement } ?? []
return SignalProducer(value: audioVideoViewElements)
}
self.precreateAudioVideoURLs = self.prepareAudioVideoAtProperty.signal.skipNil()
// The first tab we render by default is overview
self.configureDataSource = freshProjectAndRefTag
.combineLatest(with: self.viewDidLoadProperty.signal)
.map { projectAndRefTag, _ in
let (project, refTag) = projectAndRefTag
return (.overview, project, refTag)
}
let projectAndBacking = project
.filter { $0.personalization.isBacking ?? false }
.compactMap { project -> (Project, Backing)? in
guard let backing = project.personalization.backing else {
return nil
}
return (project, backing)
}
let ctaButtonTappedWithType = self.pledgeCTAButtonTappedProperty.signal
.skipNil()
let shouldGoToRewards = ctaButtonTappedWithType
.filter { $0.isAny(of: .pledge, .viewRewards, .viewYourRewards) }
.ignoreValues()
let shouldGoToManagePledge = ctaButtonTappedWithType
.filter(shouldGoToManagePledge(with:))
.ignoreValues()
self.goToRewards = freshProjectAndRefTag
.takeWhen(shouldGoToRewards)
self.goToManagePledge = projectAndBacking
.takeWhen(shouldGoToManagePledge)
.map(first)
.map { project -> ManagePledgeViewParamConfigData? in
guard let backing = project.personalization.backing else {
return nil
}
return (projectParam: Param.slug(project.slug), backingParam: Param.id(backing.id))
}
.skipNil()
let projectError: Signal<ErrorEnvelope, Never> = freshProjectAndRefTagEvent.errors()
self.configurePledgeCTAView = Signal.combineLatest(
Signal.merge(freshProjectAndRefTag.map(Either.left), projectError.map(Either.right)),
isLoading.signal
)
.map { ($0, $1, PledgeCTAContainerViewContext.projectPamphlet) }
self.configureChildViewControllersWithProject = freshProjectAndRefTag
.map { project, refTag in (project, refTag) }
self.dismissManagePledgeAndShowMessageBannerWithMessage
= self.managePledgeViewControllerFinishedWithMessageProperty.signal
.skipNil()
let cookieRefTag = freshProjectAndRefTag
.map { project, refTag -> RefTag? in
let r = cookieRefTagFor(project: project) ?? refTag
return r
}
.take(first: 1)
self.goToComments = project
.takeWhen(self.tappedCommentsProperty.signal)
self.goToDashboard = self.tappedViewProgressProperty.signal
.skipNil()
.map { .id($0.id) }
self.goToUpdates = project
.takeWhen(self.tappedUpdatesProperty.signal)
// Hide the custom navigation bar when pushing a new view controller
// Unhide the custom navigation bar when viewWillAppear is called
self.navigationBarIsHidden = self.showNavigationBarProperty.signal.negate()
self.configureProjectNavigationSelectorView = freshProjectAndRefTag
.map { projectAndRefTag in
let (project, refTag) = projectAndRefTag
return (project: project, refTag: refTag)
}
let trackFreshProjectAndRefTagViewed: Signal<(Project, RefTag?), Never> = Signal.zip(
freshProjectAndRefTag.skip(first: 1),
self.viewDidAppearAnimatedProperty.signal.ignoreValues()
)
.map(unpack)
.map { project, refTag, _ in
(project: project, refTag: refTag)
}
trackFreshProjectAndRefTagViewed
.observeValues { project, refTag in
AppEnvironment.current.ksrAnalytics.trackProjectViewed(
project,
refTag: refTag,
sectionContext: .overview
)
}
Signal.combineLatest(cookieRefTag.skipNil(), freshProjectAndRefTag.map(first))
.take(first: 1)
.map(cookieFrom(refTag:project:))
.skipNil()
.observeValues { AppEnvironment.current.cookieStorage.setCookie($0) }
self.presentMessageDialog = project
.takeWhen(self.askAQuestionCellTappedProperty.signal)
let tappableCellURLs = Signal.merge(
self.projectEnvironmentalCommitmentDisclaimerCellDidTapURLProperty.signal,
self.projectRisksDisclaimerCellDidTapURLProperty.signal
)
.skipNil()
self.showHelpWebViewController =
tappableCellURLs
.map(HelpType.helpType)
.skipNil()
// We skip the first one here because on `viewDidLoad` we are setting .overview so we don't need a useless emission here
self.updateDataSource = self.projectNavigationSelectorViewDidSelectProperty.signal
.skipNil()
.skipRepeats()
.map { index in NavigationSection(rawValue: index) }
.skipNil()
.combineLatest(with: freshProjectAndRefTag)
.map { navSection, projectAndRefTag in
let (project, refTag) = projectAndRefTag
let initialIsExpandedArray = Array(
repeating: false,
count: project.extendedProjectProperties?.faqs.count ?? 0
)
var dataSourceUpdate = (navSection, project, refTag, initialIsExpandedArray, [URL]())
switch navSection {
case .campaign:
let imageViewElements = project.extendedProjectProperties?.story.htmlViewElements
.compactMap { $0 as? ImageViewElement } ?? []
if imageViewElements.count > 0 {
let urlStrings = imageViewElements.map { $0.src }
let urls = urlStrings.compactMap { URL(string: $0) }
dataSourceUpdate = (navSection, project, refTag, initialIsExpandedArray, urls)
}
default:
break
}
return dataSourceUpdate
}
.skip(first: 1)
self.updateFAQsInDataSource = freshProjectAndRefTag
.combineLatest(with: self.didSelectFAQsRowAtProperty.signal.skipNil())
.map { projectAndRefTag, indexAndDataSourceValues in
let (project, refTag) = projectAndRefTag
let (index, isExpandedValues) = indexAndDataSourceValues
var updatedValues = isExpandedValues
updatedValues[index] = !updatedValues[index]
return (project, refTag, updatedValues)
}
self.pauseMedia = self.applicationDidEnterBackgroundProperty.signal
self.reloadCampaignData = self.projectNavigationSelectorViewDidSelectProperty.signal.skipNil()
.takeWhen(self.viewWillTransitionProperty.signal)
.filter { NavigationSection(rawValue: $0) == .campaign }
.ignoreValues()
self.goToURL = self.didSelectCampaignImageLinkProperty.signal.skipNil()
}
fileprivate let askAQuestionCellTappedProperty = MutableProperty(())
public func askAQuestionCellTapped() {
self.askAQuestionCellTappedProperty.value = ()
}
fileprivate let applicationDidEnterBackgroundProperty = MutableProperty(())
public func applicationDidEnterBackground() {
self.applicationDidEnterBackgroundProperty.value = ()
}
private let configDataProperty = MutableProperty<(Either<Project, Param>, RefTag?)?>(nil)
public func configureWith(projectOrParam: Either<Project, Param>, refTag: RefTag?) {
self.configDataProperty.value = (projectOrParam, refTag)
}
private let didBackProjectProperty = MutableProperty<Void>(())
public func didBackProject() {
self.didBackProjectProperty.value = ()
}
fileprivate let didSelectFAQsRowAtProperty = MutableProperty<(Int, [Bool])?>(nil)
public func didSelectFAQsRowAt(row: Int, values: [Bool]) {
self.didSelectFAQsRowAtProperty.value = (row, values)
}
fileprivate let didSelectCampaignImageLinkProperty = MutableProperty<(URL)?>(nil)
public func didSelectCampaignImageLink(url: URL) {
self.didSelectCampaignImageLinkProperty.value = url
}
fileprivate let showNavigationBarProperty = MutableProperty<Bool>(false)
public func showNavigationBar(_ flag: Bool) {
self.showNavigationBarProperty.value = flag
}
private let managePledgeViewControllerFinishedWithMessageProperty = MutableProperty<String?>(nil)
public func managePledgeViewControllerFinished(with message: String?) {
self.managePledgeViewControllerFinishedWithMessageProperty.value = message
}
private let pledgeCTAButtonTappedProperty = MutableProperty<PledgeStateCTAType?>(nil)
public func pledgeCTAButtonTapped(with state: PledgeStateCTAType) {
self.pledgeCTAButtonTappedProperty.value = state
}
private let pledgeRetryButtonTappedProperty = MutableProperty(())
public func pledgeRetryButtonTapped() {
self.pledgeRetryButtonTappedProperty.value = ()
}
private let prepareImageAtProperty = MutableProperty<IndexPath?>(nil)
public func prepareImageAt(_ indexPath: IndexPath) {
self.prepareImageAtProperty.value = indexPath
}
private let prepareAudioVideoAtProperty = MutableProperty<(AudioVideoViewElement, IndexPath)?>(nil)
public func prepareAudioVideoAt(_ indexPath: IndexPath, with audioVideoViewElement: AudioVideoViewElement) {
self.prepareAudioVideoAtProperty.value = (audioVideoViewElement, indexPath)
}
fileprivate let projectEnvironmentalCommitmentDisclaimerCellDidTapURLProperty = MutableProperty<URL?>(nil)
public func projectEnvironmentalCommitmentDisclaimerCellDidTapURL(_ url: URL) {
self.projectEnvironmentalCommitmentDisclaimerCellDidTapURLProperty.value = url
}
private let projectNavigationSelectorViewDidSelectProperty = MutableProperty<Int?>(nil)
public func projectNavigationSelectorViewDidSelect(index: Int) {
self.projectNavigationSelectorViewDidSelectProperty.value = index
}
fileprivate let projectRisksDisclaimerCellDidTapURLProperty = MutableProperty<URL?>(nil)
public func projectRisksDisclaimerCellDidTapURL(_ url: URL) {
self.projectRisksDisclaimerCellDidTapURLProperty.value = url
}
fileprivate let tappedCommentsProperty = MutableProperty(())
public func tappedComments() {
self.tappedCommentsProperty.value = ()
}
fileprivate let tappedUpdatesProperty = MutableProperty(())
public func tappedUpdates() {
self.tappedUpdatesProperty.value = ()
}
fileprivate let tappedViewProgressProperty = MutableProperty<Project?>(nil)
public func tappedViewProgress(of project: Project) {
self.tappedViewProgressProperty.value = project
}
fileprivate let userSessionStartedProperty = MutableProperty(())
public func userSessionStarted() {
self.userSessionStartedProperty.value = ()
}
fileprivate let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
fileprivate let viewDidAppearAnimatedProperty = MutableProperty(false)
public func viewDidAppear(animated: Bool) {
self.viewDidAppearAnimatedProperty.value = animated
}
fileprivate let viewWillTransitionProperty = MutableProperty(())
public func viewWillTransition() {
self.viewWillTransitionProperty.value = ()
}
public let configureDataSource: Signal<(NavigationSection, Project, RefTag?), Never>
public let configureChildViewControllersWithProject: Signal<(Project, RefTag?), Never>
public let configurePledgeCTAView: Signal<PledgeCTAContainerViewData, Never>
public let configureProjectNavigationSelectorView: Signal<(Project, RefTag?), Never>
public let dismissManagePledgeAndShowMessageBannerWithMessage: Signal<String, Never>
public let goToComments: Signal<Project, Never>
public let goToDashboard: Signal<Param, Never>
public let goToManagePledge: Signal<ManagePledgeViewParamConfigData, Never>
public let goToRewards: Signal<(Project, RefTag?), Never>
public let goToUpdates: Signal<Project, Never>
public let goToURL: Signal<URL, Never>
public let navigationBarIsHidden: Signal<Bool, Never>
public let pauseMedia: Signal<Void, Never>
public let popToRootViewController: Signal<(), Never>
public let presentMessageDialog: Signal<Project, Never>
public let precreateAudioVideoURLs: Signal<(AudioVideoViewElement, IndexPath), Never>
public let precreateAudioVideoURLsOnFirstLoad: Signal<[AudioVideoViewElement], Never>
public let prefetchImageURLs: Signal<([URL], IndexPath), Never>
public let prefetchImageURLsOnFirstLoad: Signal<[ImageViewElement], Never>
public let reloadCampaignData: Signal<Void, Never>
public let showHelpWebViewController: Signal<HelpType, Never>
public let updateDataSource: Signal<(NavigationSection, Project, RefTag?, [Bool], [URL]), Never>
public let updateFAQsInDataSource: Signal<(Project, RefTag?, [Bool]), Never>
public var inputs: ProjectPageViewModelInputs { return self }
public var outputs: ProjectPageViewModelOutputs { return self }
}
private func fetchProjectFriends(projectOrParam: Either<Project, Param>)
-> SignalProducer<[User], ErrorEnvelope> {
let param = projectOrParam.ifLeft({ Param.id($0.id) }, ifRight: id)
let projectFriendsProducer = AppEnvironment.current.apiService.fetchProjectFriends(param: param)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
return projectFriendsProducer
}
private func fetchProject(projectOrParam: Either<Project, Param>, shouldPrefix: Bool)
-> SignalProducer<Project, ErrorEnvelope> {
let param = projectOrParam.ifLeft({ Param.id($0.id) }, ifRight: id)
let configCurrency = AppEnvironment.current.launchedCountries.countries
.first(where: { $0.countryCode == AppEnvironment.current.countryCode })?.currencyCode
let projectAndBackingIdProducer = AppEnvironment.current.apiService
.fetchProject(projectParam: param, configCurrency: configCurrency)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
let projectAndBackingProducer = projectAndBackingIdProducer
.switchMap { projectPamphletData -> SignalProducer<Project, ErrorEnvelope> in
guard let backingId = projectPamphletData.backingId else {
return fetchProjectRewards(project: projectPamphletData.project)
}
let projectWithBackingAndRewards = AppEnvironment.current.apiService
.fetchBacking(id: backingId, withStoredCards: false)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.switchMap { projectWithBacking -> SignalProducer<Project, ErrorEnvelope> in
let updatedProjectWithBacking = projectWithBacking.project
|> Project.lens.personalization.backing .~ projectWithBacking.backing
|> Project.lens.personalization.isBacking .~ true
|> Project.lens.extendedProjectProperties .~ projectWithBacking.project.extendedProjectProperties
// INFO: Seems like in the `fetchBacking` call we nil out the chosen currency set by `fetchProject` b/c the query for backing doesn't have `me { chosenCurrency }`, so its' being included here.
|> Project.lens.stats.currentCurrency .~ projectPamphletData.project.stats.currentCurrency
return fetchProjectRewards(project: updatedProjectWithBacking)
}
return projectWithBackingAndRewards
}
if let project = projectOrParam.left, shouldPrefix {
return projectAndBackingProducer.prefix(value: project)
}
return projectAndBackingProducer
}
private func fetchProjectRewards(project: Project) -> SignalProducer<Project, ErrorEnvelope> {
return AppEnvironment.current.apiService
.fetchProjectRewards(projectId: project.id)
.ksr_delay(AppEnvironment.current.apiDelayInterval, on: AppEnvironment.current.scheduler)
.switchMap { projectRewards -> SignalProducer<Project, ErrorEnvelope> in
var allRewards = projectRewards
if let noRewardReward = project.rewardData.rewards.first {
allRewards.insert(noRewardReward, at: 0)
}
let projectWithBackingAndRewards = project
|> Project.lens.rewardData.rewards .~ allRewards
|> Project.lens.extendedProjectProperties .~ project.extendedProjectProperties
return SignalProducer(value: projectWithBackingAndRewards)
}
}
private func shouldGoToManagePledge(with type: PledgeStateCTAType) -> Bool {
return type.isAny(of: .viewBacking, .manage, .fix)
}
| apache-2.0 | b4cad61db86ca45911b3143fcaf1f0eb | 40.674086 | 204 | 0.740816 | 4.701883 | false | false | false | false |
joearms/joearms.github.io | includes/swift/experiment4.swift | 1 | 1043 | // experiment4.swift
// run with:
// $ swift experiment4.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate
{
let window = NSWindow()
func applicationDidFinishLaunching(aNotification: NSNotification)
{
window.setContentSize(NSSize(width:600, height:200))
window.styleMask = NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask |
NSResizableWindowMask
window.opaque = false
window.center();
window.title = "Experiment 4"
let text = NSTextView(frame: NSMakeRect(20, 150, 180, 30))
text.string = "Some Text"
text.editable = false
text.backgroundColor = window.backgroundColor
text.selectable = false
window.contentView!.addSubview(text)
window.makeKeyAndOrderFront(window)
window.level = 1
}
}
let app = NSApplication.sharedApplication()
let controller = AppDelegate()
app.delegate = controller
app.run()
| mit | 38e901c955662f23882093b37998072b | 25.74359 | 70 | 0.641419 | 4.943128 | false | false | false | false |
davidhuynh/ludi.graphics-samples | Metal/MetalTexturedMesh/MetalTexturedMesh/Mesh.swift | 1 | 1752 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Basic mesh class that exposes buffers generated by Model I/O for rendering with Metal
*/
import Foundation
import Metal
import MetalKit
import ModelIO
class Mesh {
var vertexBuffer: MTLBuffer
var vertexDescriptor: MTLVertexDescriptor
var primitiveType: MTLPrimitiveType
var indexBuffer: MTLBuffer
var indexCount: Int
var indexType: MTLIndexType
init?(cubeWithSize size: Float, device: MTLDevice)
{
let allocator = MTKMeshBufferAllocator(device: device)
let mdlMesh = MDLMesh(boxWithExtent: vector_float3(size, size, size),
segments: vector_uint3(10, 10, 10),
inwardNormals: false,
geometryType: .triangles,
allocator: allocator)
do {
let mtkMesh = try MTKMesh(mesh: mdlMesh, device: device)
let mtkVertexBuffer = mtkMesh.vertexBuffers[0]
let submesh = mtkMesh.submeshes[0]
let mtkIndexBuffer = submesh.indexBuffer
vertexBuffer = mtkVertexBuffer.buffer
vertexBuffer.label = "Mesh Vertices"
vertexDescriptor = MTKMetalVertexDescriptorFromModelIO(mdlMesh.vertexDescriptor)
primitiveType = submesh.primitiveType
indexBuffer = mtkIndexBuffer.buffer
indexBuffer.label = "Mesh Indices"
indexCount = submesh.indexCount
indexType = submesh.indexType
} catch _ {
return nil // Unable to create MTK mesh from MDL mesh
}
}
}
| mit | a59de568102fcdb0c409361e1963473a | 32.653846 | 92 | 0.616 | 5.177515 | false | false | false | false |
SeaHub/ImgTagging | ImgMaster/ImgMaster/ImageResultList.swift | 1 | 1012 | //
// ImageResult.swift
// ImgMaster
//
// Created by SeaHub on 2017/6/25.
// Copyright © 2017年 SeaCluster. All rights reserved.
//
import UIKit
import SwiftyJSON
typealias TagName = String
struct ImageResultListJSONParsingKeys {
static let kImageIDKey = "i_id"
static let kTagKey = "tag"
static let kAlternationKey = "Alternation"
}
class ImageResultList: NSObject {
let imageID: Int!
let tagNames: [TagName]!
let alternation: Int!
init(JSON: Dictionary<String, JSON>) {
self.imageID = JSON[ImageResultListJSONParsingKeys.kImageIDKey]!.int!
self.alternation = JSON[ImageResultListJSONParsingKeys.kAlternationKey]!.int!
var tagDatas: [TagName] = []
for idx in 1 ... 5 {
let key = "\(ImageResultListJSONParsingKeys.kTagKey)\(idx)"
let aTagName = JSON[key]!.string!
tagDatas.append(aTagName)
}
self.tagNames = tagDatas
}
}
| gpl-3.0 | 367cec5e5403a8e8175f2fddfaa671a6 | 27.027778 | 92 | 0.616452 | 3.880769 | false | false | false | false |
lenssss/whereAmI | Whereami/Controller/Login/EmailLoginViewController.swift | 1 | 11740 | //
// EmailLoginViewController.swift
// Whereami
//
// Created by WuQifei on 16/2/4.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
import PureLayout
import ReactiveCocoa
import SocketIOClientSwift
class EmailLoginViewController: UIViewController {
private var validEmail:Bool = false
private var validPwd:Bool = false
var nextButton:UIButton? = nil
var emailField:UITextField? = nil
var passwordField:UITextField? = nil
var tipLabel:UILabel? = nil
private let placeHolderColor:UIColor = UIColor(red: 149/255.0, green: 148/255.0, blue: 151/255.0, alpha: 1.0)
private let textColor:UIColor = UIColor(red: 40/255.0, green: 40/255.0, blue: 40/255.0, alpha: 1.0)
private let borderColor:UIColor = UIColor(red: 218/255.0, green: 218/255.0, blue: 220/255.0, alpha: 1.0)
private let tipColor:UIColor = UIColor(red: 34/255.0, green: 34/255.0, blue: 34/255.0, alpha: 1.0)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setConfig()
self.setupUI()
self.title = "LOGIN"
self.signalAction()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
LApplication().setStatusBarHidden(false, withAnimation: .None)
}
func nextButtonActivited () {
if self.validPwd && self.validEmail {
self.nextButton!.enabled = true
self.nextButton!.backgroundColor = UIColor(red: 71/255.0, green: 95/255.0, blue: 161/255.0, alpha: 1.0)
}
else
{
self.nextButton!.enabled = false
self.nextButton!.backgroundColor = UIColor(red: 183/255.0, green: 183/255.0, blue: 183/255.0, alpha: 1.0)
}
}
/**
rac部分,由于对rac这个框架不是很熟悉,故增加标志位处理,以后在修改到这里的时候,再进行修改
*/
func signalAction() {
let emailFieldSignal:RACSignal = self.emailField!.rac_textSignal()
let passwordSignal:RACSignal = self.passwordField!.rac_textSignal()
emailFieldSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".isEmail() {
return true
}
return false
}.subscribeNext { (finishedStr) -> Void in
// self.emailField?.textColor = UIColor.greenColor()
self.validEmail = true
self.nextButtonActivited()
}
emailFieldSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".isEmail() {
return false
}
return true
}.subscribeNext { (finishedStr) -> Void in
// self.emailField?.textColor = UIColor.blackColor()
self.validEmail = false
self.nextButtonActivited()
}
passwordSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".length > 5 {
return true
}
return false
}.subscribeNext { (finishedStr) -> Void in
// self.passwordField?.textColor = UIColor.greenColor()
self.validPwd = true
self.nextButtonActivited()
}
passwordSignal.filter { (currentStr) -> Bool in
if "\(currentStr)".length > 5 {
return false
}
return true
}.subscribeNext { (finishedStr) -> Void in
// self.passwordField?.textColor = UIColor.blackColor()
self.validPwd = false
self.nextButtonActivited()
}
self.nextButton?.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext({ (button) -> Void in
var dict = [String:AnyObject]()
dict["account"] = self.emailField!.text
dict["password"] = self.passwordField!.text
dict["type"] = "login"
// dict["nickname"] = ""
// dict["headPortraitId"] = ""
// dict["countryCode"] = ""
//print("================\(dict)")
let status = SocketManager.sharedInstance.socket?.status
if status != SocketIOClientStatus.Connected {
let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: "网络异常", preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: { (confirmAction) in
SocketManager.sharedInstance.connection({ (ifConnection) in
})
})
alertController.addAction(confirmAction)
self.presentViewController(alertController, animated: true, completion: nil)
return
}
SocketManager.sharedInstance.sendMsg("login", data: dict, onProto: "logined", callBack: { (code, objs) -> Void in
if code == statusCode.Normal.rawValue {
let dic = objs[0] as! [String:AnyObject]
let userData:[AnyObject] = dic["userData"] as! [AnyObject]
let modelDic = userData[0] as! [String:AnyObject]
let userModel = UserModel.getModelFromDictionary(modelDic)
CoreDataManager.sharedInstance.increaseOrUpdateUser(userModel)
let userDefaults = LUserDefaults()
print("==============\(userDefaults.objectForKey("sessionId"))")
userDefaults.setObject(userModel.sessionId, forKey: "sessionId")
userDefaults.setObject(userModel.id, forKey: "uniqueId")
userDefaults.synchronize()
print("==============\(userDefaults.objectForKey("sessionId"))")
self.runInMainQueue({() -> Void in
LNotificationCenter().postNotificationName(KNotificationLogin, object: userModel)
})
}
else{
self.runInMainQueue({() -> Void in
let dic:[String:AnyObject] = objs[0] as! [String:AnyObject]
let errorMsg = dic["message"] as! String
let alertController = UIAlertController(title: NSLocalizedString("warning",tableName:"Localizable", comment: ""), message: errorMsg, preferredStyle: .Alert)
let confirmAction = UIAlertAction(title: NSLocalizedString("ok",tableName:"Localizable", comment: ""), style: .Default, handler: nil)
alertController.addAction(confirmAction)
self.presentViewController(alertController, animated: true, completion: nil)
})
}
})
})
// self.runInMainQueue({ () -> Void in
// NSNotificationCenter.defaultCenter().postNotificationName(KNotificationLogin, object: nil)
// })
}
func setupUI() {
self.view.backgroundColor = UIColor.getMainColor()
emailField = UITextField()
self.view.addSubview(emailField!)
passwordField = UITextField()
self.view.addSubview(passwordField!)
nextButton = UIButton()
self.view.addSubview(nextButton!)
tipLabel = UILabel()
self.view.addSubview(tipLabel!)
tipLabel?.text = NSLocalizedString("enterEmail",tableName:"Localizable", comment: "")
tipLabel?.font = UIFont.systemFontOfSize(13.0)
tipLabel?.textAlignment = .Center
tipLabel?.textColor = tipColor
tipLabel?.backgroundColor = UIColor.clearColor()
emailField?.leftViewMode = .Always
emailField?.leftView = UIView(frame:CGRect(x: 0, y: 0, width: 13, height: 0))
// emailField?.borderStyle = .RoundedRect
emailField?.layer.borderWidth = 0.5
emailField?.layer.borderColor = borderColor.CGColor
emailField?.keyboardType = UIKeyboardType.EmailAddress
emailField?.rightViewMode = .WhileEditing
emailField?.autocapitalizationType = .None
emailField!.autocorrectionType = .No
emailField!.spellCheckingType = .No
emailField?.clearButtonMode = .WhileEditing
passwordField?.leftViewMode = .Always
passwordField?.leftView = UIView(frame:CGRect(x: 0, y: 0, width: 13, height: 0))
passwordField?.secureTextEntry = true
passwordField?.rightViewMode = .WhileEditing
passwordField?.clearButtonMode = .WhileEditing
passwordField?.backgroundColor = UIColor.whiteColor()
emailField?.backgroundColor = UIColor.whiteColor()
passwordField?.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("passwordPlaceholder",tableName:"Localizable", comment: ""), attributes: [NSForegroundColorAttributeName:placeHolderColor])
emailField?.attributedPlaceholder = NSAttributedString(string: NSLocalizedString("emailPlaceholder",tableName:"Localizable", comment: ""), attributes: [NSForegroundColorAttributeName:placeHolderColor])
passwordField?.textColor = textColor
emailField?.textColor = textColor
nextButton?.setTitle(NSLocalizedString("Continue",tableName:"Localizable", comment: ""), forState: .Normal)
tipLabel?.autoPinEdgeToSuperviewEdge(.Top)
tipLabel?.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0)
tipLabel?.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: 0)
tipLabel?.autoSetDimension(.Height, toSize: 50)
emailField?.autoPinEdge(.Top, toEdge: .Bottom, ofView: tipLabel!, withOffset: 0)
emailField?.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0)
emailField?.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: 0)
emailField?.autoSetDimension(.Height, toSize: 46)
passwordField?.autoPinEdge(.Top, toEdge: .Bottom, ofView: emailField!, withOffset: 0)
passwordField?.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 0)
passwordField?.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: 0)
passwordField?.autoSetDimension(.Height, toSize: 46)
nextButton?.enabled = false
nextButton?.layer.cornerRadius = 23.0
nextButton?.layer.masksToBounds = true
nextButton?.backgroundColor = UIColor(red: 183/255.0, green: 183/255.0, blue: 183/255.0, alpha: 1.0)
nextButton?.autoPinEdge(.Top, toEdge: .Bottom, ofView: passwordField!, withOffset: 30)
nextButton?.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: 50)
nextButton?.autoPinEdgeToSuperviewEdge(ALEdge.Right, withInset: 50)
nextButton?.autoSetDimension(.Height, toSize: 46)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 052460d09bd940c6c109d7e30e32fdb4 | 42.778195 | 215 | 0.599914 | 5.33196 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/longest-consecutive-sequence.swift | 2 | 2034 | /**
* Problem Link: https://leetcode.com/problems/longest-consecutive-sequence/
*
*
*/
class Solution {
func longestConsecutive(_ nums: [Int]) -> Int {
var set = Set<Int>(nums)
var maxn = 0
for x in nums {
var count = 1
var left = x - 1
var right = x + 1
while (set.contains(left)) {
count += 1
set.remove(left)
left -= 1
}
while (set.contains(right)) {
count += 1
set.remove(right)
right += 1
}
maxn = max(maxn, count)
}
return maxn
}
}
/**
* https://leetcode.com/problems/longest-consecutive-sequence/
*
*
*/
// Date: Sun Apr 26 10:30:40 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(n)
/// - Space: O(n)
/// Although the time complexity appears to be quadratic due to the while loop nested within the for loop, closer inspection reveals it to be linear. Because the while loop is reached only when currentNum marks the beginning of a sequence (i.e. currentNum-1 is not present in nums), the while loop can only run for n iterations throughout the entire runtime of the algorithm. This means that despite looking like O( n ⋅ n ) complexity, the nested loops actually run in O(n+n)=O(n) time. All other computations occur in constant time, so the overall runtime is linear.
///
func longestConsecutive(_ nums: [Int]) -> Int {
var set: Set<Int> = []
for n in nums {
set.insert(n)
}
var longestCS = 0
for n in set {
if set.contains(n - 1) == false {
var count = 1
var current = n
while set.contains(current + 1) {
current += 1
count += 1
}
longestCS = max(longestCS, count)
}
}
return longestCS
}
}
| mit | 6edc2a90f7ee73b4e1385d49dc4ac5ff | 31.253968 | 575 | 0.515256 | 4.277895 | false | false | false | false |
cpageler93/RAML-Swift | Sources/ResourceType.swift | 1 | 4954 | //
// ResourceType.swift
// RAML
//
// Created by Christoph on 12.07.17.
//
import Foundation
import Yaml
import PathKit
public class ResourceType: HasResourceMethods, HasLibraries, HasAnnotations {
public var identifier: String
public var usage: String?
public var description: String?
public var methods: [ResourceMethod]?
public var uses: [Library]?
public var annotations: [Annotation]?
public init(identifier: String) {
self.identifier = identifier
}
internal init() {
self.identifier = ""
}
}
// MARK: Parsing Resource Types
internal extension RAML {
internal func parseResourceTypes(_ input: ParseInput) throws -> [ResourceType]? {
guard let yaml = input.yaml else { return nil }
switch yaml {
case .dictionary(let yamlDict):
return try parseResourceTypes(dict: yamlDict, parentFilePath: input.parentFilePath)
case .string(let yamlString):
let (yaml, path) = try parseResourceTypesFromIncludeString(yamlString, parentFilePath: input.parentFilePath)
guard let resourceTypesDict = yaml.dictionary else {
throw RAMLError.ramlParsingError(.invalidInclude)
}
return try parseResourceTypes(dict: resourceTypesDict, parentFilePath: path)
default:
return nil
}
}
private func parseResourceTypes(dict: [Yaml: Yaml], parentFilePath: Path?) throws -> [ResourceType] {
var resourceTypes: [ResourceType] = []
for (key, value) in dict {
guard let keyString = key.string else {
throw RAMLError.ramlParsingError(.invalidDataType(for: "ResourceType Key",
mustBeKindOf: "String"))
}
let resourceType = try parseResourceType(identifier: keyString,
yaml: value,
parentFilePath: parentFilePath)
resourceTypes.append(resourceType)
}
return resourceTypes
}
private func parseResourceType(identifier: String, yaml: Yaml, parentFilePath: Path?) throws -> ResourceType {
let resourceType = ResourceType(identifier: identifier)
switch yaml {
case .dictionary(let yamlDict):
resourceType.usage = yamlDict["usage"]?.string
resourceType.description = yamlDict["description"]?.string
resourceType.methods = try parseResourceMethods(ParseInput(yaml, parentFilePath))
resourceType.uses = try parseLibraries(ParseInput(yaml["uses"], parentFilePath))
resourceType.annotations = try parseAnnotations(ParseInput(yaml, parentFilePath))
case .string(let yamlString):
let (yamlFromInclude, path) = try parseResourceTypesFromIncludeString(yamlString, parentFilePath: parentFilePath)
return try parseResourceType(identifier: identifier,
yaml: yamlFromInclude,
parentFilePath: path)
default:
throw RAMLError.ramlParsingError(.failedParsingResourceType)
}
return resourceType
}
private func parseResourceTypesFromIncludeString(_ includeString: String, parentFilePath: Path?) throws -> (Yaml, Path) {
return try parseYamlFromIncludeString(includeString, parentFilePath: parentFilePath, permittedFragmentIdentifier: "ResourceType")
}
}
public protocol HasResourceTypes {
var resourceTypes: [ResourceType]? { get set }
}
public extension HasResourceTypes {
public func resourceTypeWith(identifier: String) -> ResourceType? {
for resourceType in resourceTypes ?? [] {
if resourceType.identifier == identifier {
return resourceType
}
}
return nil
}
public func hasResourceTypeWith(identifier: String) -> Bool {
return resourceTypeWith(identifier: identifier) != nil
}
}
// MARK: Default Values
public extension ResourceType {
public convenience init(initWithDefaultsBasedOn resourceType: ResourceType, raml: RAML) {
self.init()
self.identifier = resourceType.identifier
self.usage = resourceType.usage
self.description = resourceType.description
self.methods = resourceType.methods?.map { $0.applyDefaults(raml: raml) }
self.uses = resourceType.uses?.map { $0.applyDefaults(raml: raml) }
self.annotations = resourceType.annotations?.map { $0.applyDefaults() }
}
public func applyDefaults(raml: RAML) -> ResourceType {
return ResourceType(initWithDefaultsBasedOn: self, raml: raml)
}
}
| mit | c09c60e743bc09aaea742ff8a57b78cb | 34.898551 | 137 | 0.617481 | 5.101957 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/Data Model/Extensions/Task+Commitment.swift | 1 | 1387 | //
// Task+Committing.swift
// YourGoals
//
// Created by André Claaßen on 01.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
enum CommittingState {
case notCommitted
case committedForDate
case committedForPast
case committedForFuture
}
extension Task {
/// check the commitment state of a task. is it a commitment for day or is the commitment pas?
///
/// *Important*: Commitment past is for a commitment you have failed. the state is active
/// but the commitment date has past. Future commitments will be ignored
///
/// - Parameter date: check for this date
/// - Returns: commitment state
func committingState(forDate date:Date) -> CommittingState {
let dayOfDate = date.day()
guard let commitmentDate = self.commitmentDate?.day() else {
return .notCommitted
}
if commitmentDate.compare(dayOfDate) == .orderedSame {
return .committedForDate
}
if commitmentDate.compare(dayOfDate) == .orderedAscending &&
self.getTaskState() == .active {
return .committedForPast
}
if commitmentDate.compare(dayOfDate) == .orderedDescending {
return .committedForFuture
}
return .notCommitted
}
}
| lgpl-3.0 | 7d79a4a4867032073b07bcc02e6c7464 | 27.204082 | 98 | 0.617221 | 4.606667 | false | false | false | false |
andersio/goofy | Goofy/TitleLabel.swift | 2 | 2480 | //
// TitleLabel.swift
// Goofy
//
// Created by Daniel Büchele on 11/04/15.
// Copyright (c) 2015 Daniel Büchele. All rights reserved.
//
import Cocoa
class TitleLabel: NSViewController {
var titleLabel : NSTextField?
var activeLabel : NSTextField?
// MARK: - NSView Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
activeLabel = NSTextField(frame: CGRectMake(40, -18, self.view.frame.width, 36))
activeLabel?.stringValue = ""
activeLabel?.editable = false
activeLabel?.bezeled = false
activeLabel?.selectable = false
activeLabel?.drawsBackground = false
activeLabel?.alignment = .Center
activeLabel?.font = NSFont(name: "HelveticaNeue", size: 10.0)
self.view.addSubview(activeLabel!)
titleLabel = NSTextField(frame: CGRectMake(40, 0, self.view.frame.width, 36))
titleLabel?.stringValue = ""
titleLabel?.editable = false
titleLabel?.bezeled = false
titleLabel?.selectable = false
titleLabel?.drawsBackground = false
titleLabel?.alignment = .Center
titleLabel?.textColor = NSColor.blackColor()
titleLabel?.font = NSFont(name: "HelveticaNeue", size: 14.0)
self.view.addSubview(titleLabel!)
}
// MARK: - Title
func setTitle(title: String, active: String) {
var rect :CGRect? = titleLabel?.frame
var y :CGFloat = 0.0
if active=="" {
y = -6
}
rect?.origin.y = y
titleLabel?.frame = rect!
titleLabel?.stringValue = title
activeLabel?.stringValue = active
}
// MARK: - Window
func windowDidResize() {
var toolbarItem : NSToolbarItem!
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate;
for item in appDelegate.toolbar.items {
let i = item
if i.view == self.view {
toolbarItem = i
break
}
}
var rect :CGRect? = titleLabel?.frame
var width = toolbarItem.view?.frame.width
width = width!-40
rect?.size.width = width!
titleLabel?.frame = rect!
var rect2 = activeLabel?.frame
rect2?.size.width = width!
activeLabel?.frame = rect2!
}
}
| mit | 75ba667d3fc4bd44d698b38b0ab91467 | 25.645161 | 88 | 0.56699 | 4.747126 | false | false | false | false |
iosdevelopershq/code-challenges | CodeChallenge/Challenges/TwoSum/Entries/Logan.swift | 1 | 554 | //
// Logan.swift
// CodeChallenge
//
// Created by Ryan Arana on 11/1/15.
// Copyright © 2015 iosdevelopers. All rights reserved.
//
import Foundation
let loganTwoSumEntry = CodeChallengeEntry<TwoSumChallenge>(name: "Logan") { input in
let lastIdx = input.numbers.count - 1
for firstIdx in 0..<lastIdx {
let nextIdx = firstIdx + 1
for secondIdx in nextIdx...lastIdx where input.numbers[firstIdx] + input.numbers[secondIdx] == input.target {
return (firstIdx + 1, secondIdx + 1)
}
}
return nil
} | mit | d7813607c631e824861872defd93a60a | 26.7 | 117 | 0.654611 | 3.567742 | false | false | false | false |
googleprojectzero/fuzzilli | Sources/Fuzzilli/Modules/NetworkSync.swift | 1 | 30053 | // Copyright 2019 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import libsocket
// Explicitly import `Foundation.UUID` to avoid the conflict with `WinSDK.UUID`
import struct Foundation.UUID
// Module for synchronizing over the network.
//
// This module implementes a simple TCP-based protocol
// to exchange programs and statistics between fuzzer
// instances.
//
// The protocol consists of messages of the following
// format being sent between the parties. Messages are
// sent in both directions and are not answered.
// Messages are padded with zero bytes to the next
// multiple of four. The message length includes the
// size of the header but excludes any padding bytes.
//
// +----------------------+----------------------+------------------+-----------+
// | length | type | payload | padding |
// | 4 byte little endian | 4 byte little endian | length - 8 bytes | |
// +----------------------+----------------------+------------------+-----------+
/// Supported message types.
enum MessageType: UInt32 {
// A simple ping message to keep the TCP connection alive.
case keepalive = 0
// Informs the other side that the sender is terminating.
case shutdown = 1
// Send by workers after connecting. Identifies a worker through a UUID.
case identify = 2
// A synchronization packet sent by a master to a newly connected worker.
// Contains the exported state of the master so the worker can
// synchronize itself with that.
case sync = 3
// A FuzzIL program that is interesting and should be imported by the receiver.
case program = 4
// A crashing program that is sent from a worker to a master.
case crash = 5
// A statistics package send by a worker to a master.
case statistics = 6
// Log messages are forwarded from workers to masters.
case log = 7
}
fileprivate let messageHeaderSize = 8
fileprivate let maxMessageSize = 1024 * 1024 * 1024
/// Protocol for an object capable of receiving messages.
protocol MessageHandler {
func handleMessage(_ payload: Data, ofType type: MessageType, from connection: Connection)
func handleError(_ err: String, on connection: Connection)
// The fuzzer instance on which to schedule the handler calls
var fuzzer: Fuzzer { get }
}
/// A connection to a network peer that speaks the above protocol.
class Connection {
/// The file descriptor on POSIX or SOCKET handle on Windows of the socket.
let socket: libsocket.socket_t
// Whether this connection has been closed.
private(set) var closed = false
/// Message handler to which incoming messages are delivered.
private let handler: MessageHandler
/// DispatchQueue on which data is sent to and received from the socket.
private let queue: DispatchQueue
/// DispatchSource to trigger when data is available.
private var readSource: DispatchSourceRead? = nil
/// DispatchSource to trigger when data can be sent.
private var writeSource: DispatchSourceWrite? = nil
/// Buffer for incoming messages. Must only be accessed on this connection's dispatch queue.
private var currentMessageData = Data()
/// Buffer to receive incoming data into. Must only be accessed on this connection's dispatch queue.
private var receiveBuffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 1024*1024)
/// Pending outgoing data. Must only be accessed on this connection's dispatch queue.
private var sendQueue: [Data] = []
init(socket: libsocket.socket_t, handler: MessageHandler) {
self.socket = socket
self.handler = handler
self.queue = DispatchQueue(label: "Socket \(socket)")
#if os(Windows)
self.readSource = DispatchSource.makeReadSource(handle: HANDLE(bitPattern: UInt(socket))!, queue: self.queue)
#else
self.readSource = DispatchSource.makeReadSource(fileDescriptor: socket, queue: self.queue)
#endif
self.readSource?.setEventHandler { [weak self] in
self?.handleDataAvailable()
}
self.readSource?.activate()
}
deinit {
libsocket.socket_close(socket)
receiveBuffer.deallocate()
}
/// Closes this connection.
/// This does not need to be called after receiving an error, as in that case the connection will already have been closed.
func close() {
self.queue.sync {
self.internalClose()
}
}
/// Cancels the read and write sources and shuts down the socket.
private func internalClose() {
dispatchPrecondition(condition: .onQueue(queue))
readSource?.cancel()
readSource = nil
writeSource?.cancel()
writeSource = nil
if !closed {
libsocket.socket_shutdown(socket)
closed = true
}
}
/// Send a message.
///
/// This will queue the given data for delivery as soon as the remote peer can accept more data.
func sendMessage(_ data: Data, ofType type: MessageType, syncWith group: DispatchGroup? = nil) {
dispatchPrecondition(condition: .notOnQueue(queue))
group?.enter()
self.queue.async {
self.internalSendMessage(data, ofType: type)
// Note: this isn't completely correct since the data might have to be queue. But it should be good enough...
group?.leave()
}
}
private func internalSendMessage(_ data: Data, ofType type: MessageType) {
dispatchPrecondition(condition: .onQueue(queue))
guard !closed else {
return error("Attempted to send data on a closed connection")
}
guard data.count + messageHeaderSize <= maxMessageSize else {
return error("Message too large to send (\(data.count + messageHeaderSize)B)")
}
var length = UInt32(data.count + messageHeaderSize).littleEndian
var type = type.rawValue.littleEndian
let padding = Data(repeating: 0, count: align(Int(length), to: 4))
// We are careful not to copy the passed data here
self.sendQueue.append(Data(bytes: &length, count: 4))
self.sendQueue.append(Data(bytes: &type, count: 4))
self.sendQueue.append(data)
self.sendQueue.append(padding)
self.sendPendingData()
}
private func sendPendingData() {
dispatchPrecondition(condition: .onQueue(queue))
var i = 0
while i < sendQueue.count {
let chunk = sendQueue[i]
let length = chunk.count
let startIndex = chunk.startIndex
let rv = chunk.withUnsafeBytes { content -> Int in
return libsocket.socket_send(socket, content.bindMemory(to: UInt8.self).baseAddress, length)
}
if rv < 0 {
return error("Failed to send data")
} else if rv != length {
assert(rv < length)
// Only managed to send part of the data. Requeue the rest.
let newStart = startIndex.advanced(by: rv)
sendQueue[i] = chunk[newStart...]
break
}
i += 1
}
// Remove all chunks that were successfully sent
sendQueue.removeFirst(i)
// If we were able to send all chunks, remove the writer source
if sendQueue.isEmpty {
writeSource?.cancel()
writeSource = nil
} else if writeSource == nil {
// Otherwise ensure we have an active write source to notify us when the next chunk can be sent
#if os(Windows)
writeSource = DispatchSource.makeWriteSource(handle: HANDLE(bitPattern: UInt(socket))!, queue: self.queue)
#else
writeSource = DispatchSource.makeWriteSource(fileDescriptor: socket, queue: self.queue)
#endif
writeSource?.setEventHandler { [weak self] in
self?.sendPendingData()
}
writeSource?.activate()
}
}
private func handleDataAvailable() {
dispatchPrecondition(condition: .onQueue(queue))
// Receive all available data
var numBytesRead = 0
var gotData = false
repeat {
numBytesRead = socket_recv(socket, receiveBuffer.baseAddress, receiveBuffer.count)
if numBytesRead > 0 {
gotData = true
currentMessageData.append(receiveBuffer.baseAddress!, count: numBytesRead)
}
} while numBytesRead > 0
guard gotData else {
// We got a read event but no data was available so the remote end must have closed the connection.
return error("Connection closed by peer")
}
// ... and process it
while currentMessageData.count >= messageHeaderSize {
let length = Int(readUint32(from: currentMessageData, atOffset: 0))
guard length <= maxMessageSize && length >= messageHeaderSize else {
// For now we just close the connection if an invalid message is received.
return error("Received message with invalid length")
}
let totalMessageLength = length + align(length, to: 4)
guard totalMessageLength <= currentMessageData.count else {
// Not enough data available right now. Wait until next packet is received.
break
}
let message = Data(currentMessageData.prefix(length))
// Explicitely make a copy of the data here so the discarded data is also freed from memory
currentMessageData = currentMessageData.subdata(in: totalMessageLength..<currentMessageData.count)
let type = readUint32(from: message, atOffset: 4)
if let type = MessageType(rawValue: type) {
let payload = message.suffix(from: messageHeaderSize)
handler.fuzzer.async {
self.handler.handleMessage(payload, ofType: type, from: self)
}
} else {
return error("Received message with invalid type")
}
}
}
/// Handle an error: close the connection and inform our handler.
/// Must execute on the connection's dispatch queue.
private func error(_ err: String = "") {
internalClose()
handler.fuzzer.async {
self.handler.handleError(err, on: self)
}
}
/// Helper function to unpack a little-endian, 32-bit unsigned integer from a data packet.
private func readUint32(from data: Data, atOffset offset: Int) -> UInt32 {
assert(offset >= 0 && data.count >= offset + 4)
let value = data.withUnsafeBytes { $0.load(fromByteOffset: offset, as: UInt32.self) }
return UInt32(littleEndian: value)
}
}
public enum NetworkCorpusSynchronizationMode {
// Only sent corpus samples to master instances. This way, workers
// are forced to create their own corpus, potentially leading to
// more diverse samples overall.
case up
// Only sent corpus samples to worker instances. May be useful
// when importing a corpus at a master instance which should be
// shared with workers.
case down
// Send corpus samples to both workers and masters. If all instances
// in the network use this mode, then they will all operate on roughly
// the same corpus.
case full
// Don't send corpus samples to any other instance.
case none
}
public class NetworkMaster: Module, MessageHandler {
/// File descriptor or SOCKET handle of the server socket.
private var serverFd: libsocket.socket_t = INVALID_SOCKET
/// Associated fuzzer.
unowned let fuzzer: Fuzzer
/// Logger for this module.
private let logger: Logger
/// Address and port on which the master listens.
let address: String
let port: UInt16
/// Dispatch source to trigger when a new client connection is available.
private var connectionSource: DispatchSourceRead? = nil
/// DispatchQueue on which to accept client connections
private var serverQueue: DispatchQueue? = nil
/// Active workers. The key is the socket filedescriptor number.
private var workers = [libsocket.socket_t: Worker]()
/// The corpus synchronization mode used by this instance.
private let corpusSynchronizationMode: NetworkCorpusSynchronizationMode
/// Since fuzzer state can grow quite large (> 100MB) and takes long to serialize,
/// we cache the serialized state for a short time.
private var cachedState = Data()
private var cachedStateCreationTime = Date.distantPast
public init(for fuzzer: Fuzzer, address: String, port: UInt16, corpusSynchronizationMode: NetworkCorpusSynchronizationMode) {
self.fuzzer = fuzzer
self.logger = Logger(withLabel: "NetworkMaster")
self.address = address
self.port = port
self.corpusSynchronizationMode = corpusSynchronizationMode
}
public func initialize(with fuzzer: Fuzzer) {
assert(self.fuzzer === fuzzer)
self.serverFd = libsocket.socket_listen(address, port)
guard serverFd > 0 else {
logger.fatal("Failed to open server socket")
}
self.serverQueue = DispatchQueue(label: "Server Queue \(serverFd)")
#if os(Windows)
self.connectionSource = DispatchSource.makeReadSource(handle: HANDLE(bitPattern: UInt(serverFd))!, queue: serverQueue)
#else
self.connectionSource = DispatchSource.makeReadSource(fileDescriptor: serverFd, queue: serverQueue)
#endif
self.connectionSource?.setEventHandler {
let socket = libsocket.socket_accept(self.serverFd)
fuzzer.async {
self.handleNewConnection(socket)
}
}
connectionSource?.activate()
logger.info("Accepting worker connections on \(address):\(port)")
fuzzer.registerEventListener(for: fuzzer.events.Shutdown) { _ in
let shutdownGroup = DispatchGroup()
for worker in self.workers.values {
worker.conn.sendMessage(Data(), ofType: .shutdown, syncWith: shutdownGroup)
}
// Attempt to make sure that the shutdown messages have been sent before continuing.
let _ = shutdownGroup.wait(timeout: .now() + .seconds(5))
}
fuzzer.registerEventListener(for: fuzzer.events.InterestingProgramFound) { ev in
guard self.shouldSendCorpusSamplesToWorkers() else { return }
let proto = ev.program.asProtobuf()
guard let data = try? proto.serializedData() else {
return self.logger.error("Failed to serialize program")
}
for worker in self.workers.values {
guard let workerId = worker.id else { continue }
// Don't send programs back to where they came from originally
if case .worker(let id) = ev.origin, id == workerId { continue }
worker.conn.sendMessage(data, ofType: .program)
}
}
// Regularly send keepalive messages.
fuzzer.timers.scheduleTask(every: 1 * Minutes) {
for worker in self.workers.values {
worker.conn.sendMessage(Data(), ofType: .keepalive)
}
}
}
func handleMessage(_ payload: Data, ofType type: MessageType, from connection: Connection) {
if let worker = workers[connection.socket] {
handleMessageInternal(payload, ofType: type, from: worker)
}
}
func handleError(_ err: String, on connection: Connection) {
// In case the worker isn't known, we probably already disconnected it, so there's nothing to do.
if let worker = workers[connection.socket] {
logger.warning("Error on connection \(connection.socket): \(err). Disconnecting client.")
if let id = worker.id {
let activeSeconds = Int(-worker.connectionTime.timeIntervalSinceNow)
let activeMinutes = activeSeconds / 60
let activeHours = activeMinutes / 60
logger.warning("Lost connection to worker \(id). Worker was active for \(activeHours)h \(activeMinutes % 60)m \(activeSeconds % 60)s")
}
disconnect(worker)
}
}
private func handleNewConnection(_ socket: libsocket.socket_t) {
guard socket > 0 else {
return logger.error("Failed to accept client connection")
}
let worker = Worker(conn: Connection(socket: socket, handler: self), id: nil, connectionTime: Date())
workers[socket] = worker
logger.info("New worker connected")
}
private func handleMessageInternal(_ payload: Data, ofType type: MessageType, from worker: Worker) {
// Workers must identify themselves first.
if type != .identify && worker.id == nil {
logger.warning("Received message from unidentified worker. Closing connection...")
return disconnect(worker)
}
switch type {
case .keepalive:
break
case .shutdown:
if let id = worker.id {
logger.info("Worker \(id) shut down")
}
disconnect(worker)
case .identify:
guard let proto = try? Fuzzilli_Protobuf_Identification(serializedData: payload), let uuid = UUID(uuidData: proto.uuid) else {
logger.warning("Received malformed identification message from worker")
break
}
guard worker.id == nil else {
logger.warning("Received multiple identification messages from client. Ignoring message")
break
}
workers[worker.conn.socket] = Worker(conn: worker.conn, id: uuid, connectionTime: worker.connectionTime)
logger.info("Worker identified as \(uuid)")
fuzzer.dispatchEvent(fuzzer.events.WorkerConnected, data: uuid)
guard shouldSendCorpusSamplesToWorkers() else {
// We're not synchronizing our corpus/state with workers, so just send an empty message.
worker.conn.sendMessage(Data(), ofType: .sync)
break
}
// Send our fuzzing state to the worker
let now = Date()
if cachedState.isEmpty || now.timeIntervalSince(cachedStateCreationTime) > 15 * Minutes {
// No cached state or it is too old. Recreate it.
let (maybeState, duration) = measureTime { try? fuzzer.exportState() }
if let state = maybeState {
logger.info("Encoding fuzzer state took \((String(format: "%.2f", duration)))s. Data size: \(ByteCountFormatter.string(fromByteCount: Int64(state.count), countStyle: .memory))")
cachedState = state
cachedStateCreationTime = now
} else {
logger.error("Failed to export fuzzer state")
}
}
worker.conn.sendMessage(cachedState, ofType: .sync)
case .crash:
do {
let proto = try Fuzzilli_Protobuf_Program(serializedData: payload)
let program = try Program(from: proto)
fuzzer.importCrash(program, origin: .worker(id: worker.id!))
} catch {
logger.warning("Received malformed program from worker: \(error)")
}
case .program:
guard shouldAcceptCorpusSamplesFromWorkers() else {
logger.warning("Received corpus sample from worker but not configured to accept them (corpus synchronization mode is \(corpusSynchronizationMode)). Ignoring message.")
return
}
do {
let proto = try Fuzzilli_Protobuf_Program(serializedData: payload)
let program = try Program(from: proto)
fuzzer.importProgram(program, enableDropout: false, origin: .worker(id: worker.id!))
} catch {
logger.warning("Received malformed program from worker: \(error)")
}
case .statistics:
if let data = try? Fuzzilli_Protobuf_Statistics(serializedData: payload) {
if let stats = Statistics.instance(for: fuzzer) {
stats.importData(data, from: worker.id!)
}
} else {
logger.warning("Received malformed statistics update from worker")
}
case .log:
if let proto = try? Fuzzilli_Protobuf_LogMessage(serializedData: payload),
let origin = UUID(uuidString: proto.origin),
let level = LogLevel(rawValue: Int(clamping: proto.level)) {
fuzzer.dispatchEvent(fuzzer.events.Log, data: (origin: origin, level: level, label: proto.label, message: proto.content))
} else {
logger.warning("Received malformed log message data from worker")
}
default:
logger.warning("Received unexpected packet from worker")
}
}
private func disconnect(_ worker: Worker) {
worker.conn.close()
if let id = worker.id {
// If the id is nil then the worker never registered, so no need to deregister it internally
fuzzer.dispatchEvent(fuzzer.events.WorkerDisconnected, data: id)
}
workers.removeValue(forKey: worker.conn.socket)
}
private func shouldSendCorpusSamplesToWorkers() -> Bool {
return corpusSynchronizationMode == .down || corpusSynchronizationMode == .full
}
private func shouldAcceptCorpusSamplesFromWorkers() -> Bool {
return corpusSynchronizationMode == .up || corpusSynchronizationMode == .full
}
private struct Worker {
// The network connection to the worker.
let conn: Connection
// The id of the worker.
let id: UUID?
// The time the worker connected.
let connectionTime: Date
}
}
public class NetworkWorker: Module, MessageHandler {
/// Associated fuzzer.
unowned let fuzzer: Fuzzer
/// Logger for this module.
private let logger: Logger
/// Hostname of the master instance.
let masterHostname: String
/// Port of the master instance.
let masterPort: UInt16
/// Indicates whether the corpus has been synchronized with the master yet.
private var synchronized = false
/// Used when receiving a shutdown message from the master to avoid sending it further data.
private var masterIsShuttingDown = false
/// The corpus synchronization mode used by this instance.
private let corpusSynchronizationMode: NetworkCorpusSynchronizationMode
/// Connection to the master instance.
private var conn: Connection! = nil
public init(for fuzzer: Fuzzer, hostname: String, port: UInt16, corpusSynchronizationMode: NetworkCorpusSynchronizationMode) {
self.fuzzer = fuzzer
self.logger = Logger(withLabel: "NetworkWorker")
self.masterHostname = hostname
self.masterPort = port
self.corpusSynchronizationMode = corpusSynchronizationMode
}
public func initialize(with fuzzer: Fuzzer) {
assert(self.fuzzer === fuzzer)
connect()
fuzzer.registerEventListener(for: fuzzer.events.CrashFound) { ev in
self.sendProgram(ev.program, type: .crash)
}
fuzzer.registerEventListener(for: fuzzer.events.Shutdown) { _ in
if !self.masterIsShuttingDown {
let shutdownGroup = DispatchGroup()
self.conn.sendMessage(Data(), ofType: .shutdown, syncWith: shutdownGroup)
// Attempt to make sure that the shutdown messages have been sent before continuing.
let _ = shutdownGroup.wait(timeout: .now() + .seconds(5))
}
}
fuzzer.registerEventListener(for: fuzzer.events.InterestingProgramFound) { ev in
guard self.shouldSendCorpusSamplesToMaster() else { return }
if self.synchronized {
// If the program came from the master instance, don't send it back to it :)
if case .master = ev.origin { return }
self.sendProgram(ev.program, type: .program)
}
}
// Regularly send local statistics to the master.
if let stats = Statistics.instance(for: fuzzer) {
fuzzer.timers.scheduleTask(every: 1 * Minutes) {
let data = stats.compute()
if let payload = try? data.serializedData() {
self.conn.sendMessage(payload, ofType: .statistics)
}
}
}
// Forward log events to the master.
fuzzer.registerEventListener(for: fuzzer.events.Log) { ev in
let msg = Fuzzilli_Protobuf_LogMessage.with {
$0.origin = ev.origin.uuidString
$0.level = UInt32(ev.level.rawValue)
$0.label = ev.label
$0.content = ev.message
}
let payload = try! msg.serializedData()
self.conn.sendMessage(payload, ofType: .log)
}
// Set a timeout for synchronization.
fuzzer.timers.runAfter(60 * Minutes) {
if !self.synchronized {
self.logger.error("Synchronization with master timed out. Continuing without synchronizing...")
self.synchronized = true
}
}
}
func handleMessage(_ payload: Data, ofType type: MessageType, from connection: Connection) {
switch type {
case .keepalive:
break
case .shutdown:
logger.info("Master is shutting down. Stopping this worker...")
masterIsShuttingDown = true
self.fuzzer.shutdown(reason: .masterShutdown)
case .program:
guard shouldAcceptCorpusSamplesFromMaster() else {
logger.warning("Received corpus sample from master but not configured to accept them (corpus synchronization mode is \(corpusSynchronizationMode)). Ignoring message.")
break
}
do {
let proto = try Fuzzilli_Protobuf_Program(serializedData: payload)
let program = try Program(from: proto)
// Dropout can, if enabled in the fuzzer config, help workers become more independent
// from the rest of the fuzzers by forcing them to rediscover edges in different ways.
fuzzer.importProgram(program, enableDropout: true, origin: .master)
} catch {
logger.warning("Received malformed program from master")
}
case .sync:
synchronized = true
guard shouldAcceptCorpusSamplesFromMaster() else { break }
guard !payload.isEmpty else {
logger.warning("Received empty synchronization message from master. Is the master configured to synchronize its corpus with workers?")
break
}
let start = Date()
do {
try fuzzer.importState(from: payload)
} catch {
logger.error("Failed to import state from master: \(error)")
}
let end = Date()
logger.info("Decoding fuzzer state took \((String(format: "%.2f", end.timeIntervalSince(start))))s")
logger.info("Synchronized with master. Corpus now contains \(fuzzer.corpus.size) programs")
default:
logger.warning("Received unexpected packet from master")
}
}
func handleError(_ err: String, on connection: Connection) {
logger.warning("Error on connection to master instance: \(err). Trying to reconnect to master...")
connect()
}
private func connect() {
var fd: libsocket.socket_t = INVALID_SOCKET
for _ in 0..<10 {
fd = libsocket.socket_connect(masterHostname, masterPort)
if fd != INVALID_SOCKET {
break
}
logger.warning("Failed to connect to master. Retrying in 30 seconds")
Thread.sleep(forTimeInterval: 30)
}
if fd == INVALID_SOCKET {
logger.fatal("Failed to connect to master")
}
logger.info("Connected to master, our id: \(fuzzer.id)")
conn = Connection(socket: fd, handler: self)
// Identify ourselves.
let msg = Fuzzilli_Protobuf_Identification.with { $0.uuid = fuzzer.id.uuidData }
let payload = try! msg.serializedData()
conn.sendMessage(payload, ofType: .identify)
}
private func sendProgram(_ program: Program, type: MessageType) {
assert(type == .program || type == .crash)
let proto = program.asProtobuf()
guard let data = try? proto.serializedData() else {
return logger.error("Failed to serialize program")
}
conn.sendMessage(data, ofType: type)
}
private func shouldSendCorpusSamplesToMaster() -> Bool {
return corpusSynchronizationMode == .up || corpusSynchronizationMode == .full
}
private func shouldAcceptCorpusSamplesFromMaster() -> Bool {
return corpusSynchronizationMode == .down || corpusSynchronizationMode == .full
}
}
| apache-2.0 | 5e4e80c8d704c336922dec7befe6e66e | 38.491459 | 197 | 0.6225 | 4.837894 | false | false | false | false |
samodom/TestableUIKit | TestableUIKit/UIResponder/UIView/UICollectionView/UICollectionViewDeleteItemsSpy.swift | 1 | 2808 | //
// UICollectionViewDeleteItemsSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/21/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UICollectionView {
private static let deleteItemsCalledKeyString = UUIDKeyString()
private static let deleteItemsCalledKey =
ObjectAssociationKey(deleteItemsCalledKeyString)
private static let deleteItemsCalledReference =
SpyEvidenceReference(key: deleteItemsCalledKey)
private static let deleteItemsIndexPathsKeyString = UUIDKeyString()
private static let deleteItemsIndexPathsKey =
ObjectAssociationKey(deleteItemsIndexPathsKeyString)
private static let deleteItemsIndexPathsReference =
SpyEvidenceReference(key: deleteItemsIndexPathsKey)
private static let deleteItemsCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UICollectionView.deleteItems(at:)),
spy: #selector(UICollectionView.spy_deleteItems(at:))
)
/// Spy controller for ensuring that a collection view has had `deleteItems(at:)` called on it.
public enum DeleteItemsSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UICollectionView.self
public static let vector = SpyVector.direct
public static let coselectors: Set = [deleteItemsCoselectors]
public static let evidence: Set = [
deleteItemsCalledReference,
deleteItemsIndexPathsReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `deleteItems(at:)`
dynamic public func spy_deleteItems(at indexPaths: [IndexPath]) {
deleteItemsCalled = true
deleteItemsIndexPaths = indexPaths
spy_deleteItems(at: indexPaths)
}
/// Indicates whether the `deleteItems(at:)` method has been called on this object.
public final var deleteItemsCalled: Bool {
get {
return loadEvidence(with: UICollectionView.deleteItemsCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UICollectionView.deleteItemsCalledReference)
}
}
/// Provides the index paths passed to `deleteItems(at:)` if called.
public final var deleteItemsIndexPaths: [IndexPath]? {
get {
return loadEvidence(with: UICollectionView.deleteItemsIndexPathsReference) as? [IndexPath]
}
set {
let reference = UICollectionView.deleteItemsIndexPathsReference
guard let items = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(items, with: reference)
}
}
}
| mit | 930c8da3a7f89070f2a586672accfa0b | 32.416667 | 102 | 0.697542 | 5.740286 | false | false | false | false |
BinaryDennis/SwiftPocketBible | Extensions/UIImageView+AsyncLoading.swift | 1 | 895 | import UIKit
extension UIImageView {
private static let keyCurrentImageUrl = "keyCurrentImageUrl"
///Asynchronously sets self.image from the image at the received URL
func setImageFromUrl(_ url: URL) {
//Keep track of the URL for the current/latest image
layer.setValue(url.absoluteString, forKey: UIImageView.keyCurrentImageUrl)
DispatchQueue.global(qos: .background).async {
if let data = try? Data(contentsOf: url) {
guard url.absoluteString == self.layer.value(forKey: UIImageView.keyCurrentImageUrl) as! String else {
//An old image download has completed - do nothing
return
}
DispatchQueue.main.async {
self.image = UIImage(data: data)
}
}
}
}
}
| mit | df8e81da9541455794a826c83190fd78 | 33.423077 | 118 | 0.568715 | 5.295858 | false | true | false | false |
cdebortoli/JsonManagedObject-Swift | JsonManagedObject/JsonManagedObject/JMOExtension.swift | 1 | 5931 | //
// JMOExtension.swift
// JsonManagedObject
//
// Created by christophe on 18/06/14.
// Copyright (c) 2014 cdebortoli. All rights reserved.
//
import Foundation
import CoreData
import JsonManagedObject
/*
* JSON -> SWIFT
*/
public extension NSManagedObject {
// Set property value
internal func setProperty(jmoParameter:JMOParameterModel, fromJson jsonDict:[String: AnyObject]) {
if jsonDict[jmoParameter.jsonKey] != nil {
if let managedObjectValue : AnyObject = getValue(jmoParameter, fromJsonDictionary: jsonDict) {
setValue(managedObjectValue, forKey: jmoParameter.attributeName)
}
}
}
// Get NSPropertyDescription
internal func getPropertyDescription(jmoParameter:JMOParameterModel) -> NSPropertyDescription? {
if let propertyDescription = self.entity.propertiesByName[jmoParameter.attributeName] as? NSPropertyDescription {
return propertyDescription
}
return nil
}
// Retrieve formated property value from json
internal func getValue(jmoParameter:JMOParameterModel, fromJsonDictionary jsonDict:[String: AnyObject]) -> AnyObject? {
var propertyDescriptionOptional = getPropertyDescription(jmoParameter) as NSPropertyDescription?
if let propertyDescription = propertyDescriptionOptional {
if propertyDescription is NSAttributeDescription {
if let jsonString = jsonDict[jmoParameter.jsonKey]! as? String {
return (propertyDescription as NSAttributeDescription).getAttributeValueForJmoJsonValue(jsonString)
} else if let jsonNumber = jsonDict[jmoParameter.jsonKey]! as? NSNumber {
let jsonString = "\(jsonNumber)"
return (propertyDescription as NSAttributeDescription).getAttributeValueForJmoJsonValue(jsonString)
}
} else if propertyDescription is NSRelationshipDescription {
if let jsonArray = jsonDict[jmoParameter.jsonKey]! as? [[String: AnyObject]] {
return (propertyDescription as NSRelationshipDescription).getRelationshipValueForJmoJsonArray(jsonArray)
} else if let jsonDictRelation = jsonDict[jmoParameter.jsonKey]! as? [String: AnyObject] {
return jsonManagedObjectSharedInstance.analyzeJsonDictionary(jsonDictRelation, forClass: NSClassFromString((propertyDescription as NSRelationshipDescription).destinationEntity?.managedObjectClassName))
}
}
}
return nil
}
}
/*
* SWIFT -> JSON
*/
public extension NSManagedObject {
public func getJson(relationshipClassesToIgnore:[String] = [String]()) -> Dictionary <String, AnyObject>{
var jsonDict = Dictionary <String, AnyObject>()
var newRelationshipClassesToIgnore = [String]()
newRelationshipClassesToIgnore += relationshipClassesToIgnore
newRelationshipClassesToIgnore.append(NSStringFromClass(self.classForCoder))
if let configObject = jsonManagedObjectSharedInstance.configDatasource[NSStringFromClass(self.classForCoder)] {
for parameter in configObject.parameters {
if let managedObjectValue:AnyObject? = self.valueForKey(parameter.attributeName) {
if managedObjectValue is NSSet {
var relationshipObjects = [AnyObject]()
setloop: for objectFromSet:AnyObject in (managedObjectValue as NSSet).allObjects {
if (contains(newRelationshipClassesToIgnore, NSStringFromClass(objectFromSet.classForCoder))) {
break setloop
}
relationshipObjects.append((objectFromSet as NSManagedObject).getJson(relationshipClassesToIgnore: newRelationshipClassesToIgnore))
}
if !relationshipObjects.isEmpty {
jsonDict[parameter.jsonKey] = relationshipObjects
}
} else {
jsonDict[parameter.jsonKey] = managedObjectValue
}
}
}
if JMOConfig.jsonWithEnvelope == true {
return [configObject.classInfo.jsonKey : jsonDict]
}
}
return jsonDict
}
}
internal extension NSAttributeDescription {
internal func getAttributeValueForJmoJsonValue(jsonValue:String) -> AnyObject? {
switch(self.attributeType){
case .DateAttributeType:
return jsonManagedObjectSharedInstance.dateFormatter.dateFromString(jsonValue)
case .StringAttributeType:
return jsonValue
case .DecimalAttributeType,.DoubleAttributeType:
return NSNumber(double:(jsonValue as NSString).doubleValue)
case .FloatAttributeType:
return (jsonValue as NSString).floatValue
case .Integer16AttributeType,.Integer32AttributeType,.Integer64AttributeType:
return (jsonValue as NSString).integerValue
case .BooleanAttributeType:
return (jsonValue as NSString).boolValue
default:
return nil
}
}
}
internal extension NSRelationshipDescription {
internal func getRelationshipValueForJmoJsonArray(jsonArray:[[String: AnyObject]]) -> NSMutableSet {
var relationshipSet = NSMutableSet()
for jsonValue in jsonArray {
if let relationshipObject: AnyObject = jsonManagedObjectSharedInstance.analyzeJsonDictionary(jsonValue, forClass: NSClassFromString(self.destinationEntity?.managedObjectClassName)) {
relationshipSet.addObject(relationshipObject)
}
}
return relationshipSet
}
} | mit | 09163cdc18bae4869b65c972106e7dde | 42.29927 | 221 | 0.651324 | 5.97281 | false | false | false | false |
pavankataria/SwiftDataTables | SwiftDataTables/Classes/Cells/DataCell/DataCellViewModel.swift | 1 | 2027 | //
// DataCellViewModel.swift
// SwiftDataTables
//
// Created by Pavan Kataria on 22/02/2017.
// Copyright © 2017 Pavan Kataria. All rights reserved.
//
import Foundation
import UIKit
open class DataCellViewModel: VirtualPositionTrackable, CollectionViewCellRepresentable {
//MARK: - Public Properties
var xPositionRunningTotal: CGFloat? = nil
var yPositionRunningTotal: CGFloat? = nil
var virtualHeight: CGFloat = 0
public let data: DataTableValueType
var highlighted: Bool = false
//
public var stringRepresentation: String {
return self.data.stringRepresentation
}
//MARK: - Lifecycle
init(data: DataTableValueType){
self.data = data
}
static func registerCell(collectionView: UICollectionView) {
let identifier = String(describing: DataCell.self)
collectionView.register(DataCell.self, forCellWithReuseIdentifier: identifier)
let nib = UINib(nibName: identifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: identifier)
}
func dequeueCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let identifier = String(describing: DataCell.self)
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? DataCell else {
fatalError("error in collection view cell")
}
cell.configure(self)
return cell
}
}
extension DataCellViewModel: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: DataCellViewModel, rhs: DataCellViewModel) -> Bool {
return lhs.data == rhs.data
&& lhs.highlighted == rhs.highlighted
}
}
| mit | a26e8b864a40e21cd1bf73093387b0e6 | 33.338983 | 128 | 0.676703 | 4.733645 | false | false | false | false |
apple/swift-syntax | CodeGeneration/Sources/SyntaxSupport/Node.swift | 1 | 4642 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// A Syntax node, possibly with children.
/// If the kind is "SyntaxCollection", then this node is considered a Syntax
/// Collection that will expose itself as a typedef rather than a concrete
/// subclass.
public class Node {
public let syntaxKind: String
public let swiftSyntaxKind: String
public let name: String
public let nameForDiagnostics: String?
public let description: String?
public let baseKind: String
public let traits: [String]
public let children: [Child]
public let nonUnexpectedChildren: [Child]
public let collectionElementName: String?
public let collectionElementChoices: [String]?
public let omitWhenEmpty: Bool
public let elementsSeparatedByNewline: Bool
public let collectionElement: String
/// Returns `True` if this node declares one of the base syntax kinds.
public var isBase: Bool {
return SYNTAX_BASE_KINDS.contains(syntaxKind)
}
/// Returns `True` if this node is a subclass of SyntaxCollection.
public var isSyntaxCollection: Bool {
return baseKind == "SyntaxCollection"
}
/// Returns `True` if this node should have a `validate` method associated.
public var requiresValidation: Bool {
return isBuildable
}
/// Returns `True` if this node is an `Unknown` syntax subclass.
public var isUnknown: Bool {
return syntaxKind.contains("Unknown")
}
/// Returns `True` if this node is an `Unknown` syntax subclass.
public var isMissing: Bool {
return syntaxKind.contains("Missing")
}
/// Returns `True` if this node should have a builder associated.
public var isBuildable: Bool {
return !isBase && !isUnknown && !isMissing && !isSyntaxCollection
}
/// Returns 'True' if this node shall not be created while parsing if it has no children.
public var shallBeOmittedWhenEmpty: Bool {
return omitWhenEmpty
}
/// Returns true if this child has a token kind.
public var isToken: Bool {
return syntaxKind.contains("Token") || collectionElement.contains("Token")
}
init(name: String,
nameForDiagnostics: String?,
description: String? = nil,
kind: String,
traits: [String] = [],
children: [Child] = [],
element: String = "",
elementName: String? = nil,
elementChoices: [String]? = nil,
omitWhenEmpty: Bool = false,
elementsSeparatedByNewline: Bool = false) {
self.syntaxKind = name
self.swiftSyntaxKind = lowercaseFirstWord(name: name)
self.name = kindToType(kind: self.syntaxKind)
self.nameForDiagnostics = nameForDiagnostics
self.description = description
self.traits = traits
self.baseKind = kind
if kind == "SyntaxCollection" {
self.children = children
} else {
// Add implicitly generated UnexpectedNodes children between
// any two defined children
self.children = children.enumerated().flatMap { (i, child) -> [Child] in
let unexpectedName: String
if i == 0 {
unexpectedName = "UnexpectedBefore\(child.name)"
} else {
unexpectedName = "UnexpectedBetween\(children[i - 1].name)And\(child.name)"
}
return [
Child(
name: unexpectedName,
kind: "UnexpectedNodes",
isOptional: true,
collectionElementName: unexpectedName
),
child,
]
}
}
self.nonUnexpectedChildren = children.filter { !$0.isUnexpectedNodes }
if !SYNTAX_BASE_KINDS.contains(baseKind) {
fatalError("unknown base kind '\(baseKind)' for node '\(syntaxKind)'")
}
self.omitWhenEmpty = omitWhenEmpty
self.collectionElement = element
// If there's a preferred name for the collection element that differs
// from its supertype, use that.
self.collectionElementName = elementName ?? self.collectionElement
self.collectionElementChoices = elementChoices ?? []
self.elementsSeparatedByNewline = elementsSeparatedByNewline
// For SyntaxCollections make sure that the elementName is set.
assert(!isSyntaxCollection || elementName != nil || element != "")
}
}
| apache-2.0 | 4f73187008b58f8dee236ba1ba3ee6ca | 32.883212 | 91 | 0.660922 | 4.609732 | false | false | false | false |
segmentio/analytics-swift | Sources/Segment/Utilities/OutputFileStream.swift | 1 | 2317 | //
// OutputFileStream.swift
//
//
// Created by Brandon Sneed on 10/15/22.
//
import Foundation
/** C style output filestream ----------------- */
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
internal class OutputFileStream {
enum OutputStreamError: Error {
case invalidPath(String)
case unableToOpen(String)
case unableToWrite(String)
case unableToCreate(String)
}
var filePointer: UnsafeMutablePointer<FILE>? = nil
let fileURL: URL
init(fileURL: URL) throws {
self.fileURL = fileURL
let path = fileURL.path
guard path.isEmpty == false else { throw OutputStreamError.invalidPath(path) }
}
/// Create attempts to create + open
func create() throws {
let path = fileURL.path
if FileManager.default.fileExists(atPath: path) {
throw OutputStreamError.unableToCreate(path)
} else {
let created = FileManager.default.createFile(atPath: fileURL.path, contents: nil)
if created == false {
throw OutputStreamError.unableToCreate(path)
} else {
try open()
}
}
}
/// Open simply opens the file, no attempt at creation is made.
func open() throws {
if filePointer != nil { return }
let path = fileURL.path
path.withCString { file in
filePointer = fopen(file, "w")
}
guard filePointer != nil else { throw OutputStreamError.unableToOpen(path) }
}
func write(_ data: Data) throws {
guard let string = String(data: data, encoding: .utf8) else { return }
try write(string)
}
func write(_ string: String) throws {
guard string.isEmpty == false else { return }
_ = try string.utf8.withContiguousStorageIfAvailable { str in
if let baseAddr = str.baseAddress {
fwrite(baseAddr, 1, str.count, filePointer)
} else {
throw OutputStreamError.unableToWrite(fileURL.path)
}
if ferror(filePointer) != 0 {
throw OutputStreamError.unableToWrite(fileURL.path)
}
}
}
func close() {
fclose(filePointer)
filePointer = nil
}
}
| mit | 220a1436a9deaaf87fdc126ef76e8e63 | 26.583333 | 93 | 0.578334 | 4.579051 | false | false | false | false |
AlicJ/CPUSimulator | CPUSimulator/PathController.swift | 1 | 4396 | //
// PathController.swift
// CPUSimulator
//
// Created by Alic on 2017-06-19.
// Copyright © 2017 4ZC3. All rights reserved.
//
import UIKit
protocol PathDelegate {
func updateTargetView(nthDigit: Int, withValue: String)
}
class PathController: UIViewController {
var PATHS: Dictionary<String, Path> = [:]
var pathViews: [PathView] = []
var timer: Timer?
var nthDigit: Int = 0
var nthDigitStack: [Int] = []
var speed: Double = 400.0 // px/s
var pathKey: String = ""
var digits: [String] = []
var delegate: PathDelegate?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
PATHS["instructionBlockToRegisterBlock"] = Path(points: PathData.instructionBlock.toRegisterBlock)
PATHS["instructionBlockToALUBlock"] = Path(points: PathData.instructionBlock.toALUBlock)
PATHS["registerBlockToALUBlock"] = Path(points: PathData.registerBlock.toALUBlock)
PATHS["registerBlockToMemoryBlock"] = Path(points: PathData.registerBlock.toMemoryBlock)
PATHS["ALUBlockToRegisterBlock"] = Path(points: PathData.ALUBlock.toRegisterBlock)
PATHS["memoryBlockToRegisterBlock"] = Path(points: PathData.memoryBlock.toRegisterBlock)
pathViews.append(PathView(path: PATHS["instructionBlockToRegisterBlock"]!))
pathViews.append(PathView(path: PATHS["instructionBlockToALUBlock"]!))
pathViews.append(PathView(path: PATHS["registerBlockToALUBlock"]!))
pathViews.append(PathView(path: PATHS["memoryBlockToRegisterBlock"]!))
for view in pathViews {
self.view.addSubview(view)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
func animate(pathKey: String, digits: String) {
self.pathKey = pathKey
self.digits = digits.characters.map { String($0) }
startTimer(delay: 0)
}
internal func startTimer(delay: Double) {
timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(runAnimation), userInfo: nil, repeats: false)
}
func runAnimation(_ timer: Timer){
if let currentPath: Path = PATHS[pathKey] {
let duration = currentPath.length / speed
if nthDigit >= digits.count{
nthDigit = 0
return
}else {
let i = digits[nthDigit]
nthDigitStack.append(nthDigit)
nthDigit += 1
var d1 = UILabel()
startTimer(delay: 0.25)
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: .calculationModePaced, animations: {
d1 = UILabel(frame: CGRect(x: 100, y: 100, width: 20, height: 20))
d1.text = String(i)
d1.textAlignment = .center
d1.layer.backgroundColor = UIColor(white: 1, alpha: 0).cgColor
d1.textColor = UIColor.black
self.view.addSubview(d1)
let anim = CAKeyframeAnimation(keyPath: "position")
anim.path = currentPath.getCGPath()
anim.duration = duration
d1.layer.add(anim, forKey: "animate position along path \(i)")
}, completion: { finished in
if finished {
if !self.nthDigitStack.isEmpty {
// let nth = self.digits.count - self.nthDigitStack.removeLast() - 1
let nth = self.nthDigitStack.removeLast()
self.delegate?.updateTargetView(nthDigit: nth, withValue: d1.text!)
d1.removeFromSuperview()
}
}
return
})
}
}
}
}
| mit | 60ae65e47555268ec016adf017c0b2b6 | 35.625 | 137 | 0.559954 | 4.675532 | false | false | false | false |
onevcat/Kingfisher | Demo/Demo/Kingfisher-Demo/ViewControllers/IndicatorCollectionViewController.swift | 2 | 4303 | //
// IndicatorCollectionViewController.swift
// Kingfisher
//
// Created by onevcat on 2018/11/26.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Kingfisher
private let reuseIdentifier = "IndicatorCell"
let gifData: Data = {
let url = Bundle.main.url(forResource: "loader", withExtension: "gif")!
return try! Data(contentsOf: url)
}()
class IndicatorCollectionViewController: UICollectionViewController {
class MyIndicator: Indicator {
var timer: Timer?
func startAnimatingView() {
view.isHidden = false
timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { _ in
UIView.animate(withDuration: 0.2, animations: {
if self.view.backgroundColor == .red {
self.view.backgroundColor = .orange
} else {
self.view.backgroundColor = .red
}
})
}
}
func stopAnimatingView() {
view.isHidden = true
timer?.invalidate()
}
var view: IndicatorView = {
let view = UIView()
view.heightAnchor.constraint(equalToConstant: 30).isActive = true
view.widthAnchor.constraint(equalToConstant: 30).isActive = true
view.backgroundColor = .red
return view
}()
}
let indicators: [String] = [
"None",
"UIActivityIndicatorView",
"GIF Image",
"Custom"
]
var selectedIndicatorIndex: Int = 1 {
didSet {
collectionView.reloadData()
}
}
var selectedIndicatorType: IndicatorType {
switch selectedIndicatorIndex {
case 0: return .none
case 1: return .activity
case 2: return .image(imageData: gifData)
case 3: return .custom(indicator: MyIndicator())
default: fatalError()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupOperationNavigationBar()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ImageLoader.sampleImageURLs.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
cell.cellImageView.kf.indicatorType = selectedIndicatorType
KF.url(ImageLoader.sampleImageURLs[indexPath.row])
.memoryCacheExpiration(.expired)
.diskCacheExpiration(.expired)
.set(to: cell.cellImageView)
return cell
}
override func alertPopup(_ sender: Any) -> UIAlertController {
let alert = super.alertPopup(sender)
for item in indicators.enumerated() {
alert.addAction(UIAlertAction.init(title: item.element, style: .default) { _ in
self.selectedIndicatorIndex = item.offset
})
}
return alert
}
}
| mit | b089b84a5670c2ddc607ade82b21b084 | 35.159664 | 135 | 0.639321 | 5.021004 | false | false | false | false |
fleurdeswift/extra-appkit | ExtraAppKit/FilterableDataSource.swift | 1 | 6795 | //
// FilterableDataSource.swift
// ExtraAppKit
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Cocoa
public class FilterableDataSource : OutlineViewDataSourceProxy {
private let queue = dispatch_queue_create("FilterableDataSource", DISPATCH_QUEUE_CONCURRENT);
private let queueMap = dispatch_queue_create("FilterableDataSource.Map", DISPATCH_QUEUE_SERIAL);
private let loadGroup = dispatch_group_create();
private var generation = UInt(0);
private let root = NSNull();
public typealias PredicateBlockType = (object: AnyObject) -> Bool;
private var filtered: NSMapTable?;
public override init(dataSource: NSOutlineViewDataSource) {
super.init(dataSource: dataSource);
}
private(set) public var filterPredicate: PredicateBlockType?
public override func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if filterPredicate == nil {
return super.outlineView(outlineView, numberOfChildrenOfItem: item)
}
var ritem: AnyObject;
if let item = item {
ritem = item;
}
else {
ritem = root;
}
dispatch_group_wait(loadGroup, DISPATCH_TIME_FOREVER);
if let a = filtered?.objectForKey(ritem) as? NSArray {
return a.count;
}
return 0;
}
public override func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if filterPredicate == nil {
return super.outlineView(outlineView, child: index, ofItem: item)
}
var ritem: AnyObject;
if let item = item {
ritem = item;
}
else {
ritem = root;
}
dispatch_group_wait(loadGroup, DISPATCH_TIME_FOREVER);
if let a = filtered?.objectForKey(ritem) as? NSArray {
return a[index];
}
return Int();
}
public override func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
if filterPredicate == nil {
return super.outlineView(outlineView, isItemExpandable: item)
}
dispatch_group_wait(loadGroup, DISPATCH_TIME_FOREVER);
if let a = filtered?.objectForKey(item) as? NSArray {
return a.count > 0;
}
return false;
}
public func loadDataForItem(
outlineView: NSOutlineView,
item: AnyObject?,
table: NSMapTable,
container array: NSMutableArray,
generation: UInt,
predicate: PredicateBlockType,
parentGroup: dispatch_group_t) {
dispatch_group_enter(parentGroup);
dispatch_async(queue) {
if (generation != self.generation) {
dispatch_group_leave(parentGroup);
return;
}
let count = super.outlineView(outlineView, numberOfChildrenOfItem: item);
if count == 0 {
if let item = item {
if !predicate(object: item) {
dispatch_async(self.queueMap) {
array.removeObject(item);
dispatch_group_leave(parentGroup);
}
return;
}
}
dispatch_group_leave(parentGroup);
return;
}
let childGroup = dispatch_group_create();
let childArray = NSMutableArray();
var hasSpinned = false;
for (var index = 0; index < count; ++index) {
let child = super.outlineView(outlineView, child: index, ofItem: item);
let expandable = super.outlineView(outlineView, isItemExpandable: child);
if expandable {
if hasSpinned {
dispatch_async(self.queueMap) {
childArray.addObject(child);
}
}
else {
childArray.addObject(child);
}
hasSpinned = true;
self.loadDataForItem(outlineView,
item: child,
table: table,
container: childArray,
generation: generation,
predicate: predicate,
parentGroup: childGroup);
}
else {
if predicate(object: child) {
if hasSpinned {
dispatch_async(self.queueMap) {
childArray.addObject(child);
}
}
else {
childArray.addObject(child);
}
}
}
}
dispatch_group_notify(childGroup, self.queueMap) {
if let item = item {
if (childArray.count == 0) {
if !predicate(object: item) {
array.removeObject(item);
}
}
else {
table.setObject(childArray, forKey:item);
}
}
else {
table.setObject(childArray, forKey: self.root);
}
dispatch_group_leave(parentGroup);
};
}
}
public func reloadData(outlineView: NSOutlineView) {
if let predicate = filterPredicate {
self.generation++;
let f = NSMapTable(keyOptions: NSMapTableStrongMemory, valueOptions: NSMapTableStrongMemory, capacity: 0);
dispatch_async(queueMap) {
self.filtered = f;
}
loadDataForItem(outlineView,
item: nil,
table: f,
container: NSMutableArray(),
generation: generation,
predicate: predicate,
parentGroup: loadGroup);
}
}
public func setFilterPredicate(predicate: PredicateBlockType?, outlineView: NSOutlineView) {
self.filterPredicate = predicate;
reloadData(outlineView);
}
}
| mit | b5ecd6eba24695a1e4765c822be0ae6f | 32.303922 | 122 | 0.481454 | 5.801879 | false | false | false | false |
shahmishal/swift | test/decl/protocol/req/recursion.swift | 1 | 3177 | // RUN: %target-typecheck-verify-swift
protocol SomeProtocol {
associatedtype T
}
extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}}
// rdar://problem/19840527
class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}}
// expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}}
var type: T { return Swift.type(of: self) } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}}
}
// FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic
// should also become "associated type 'Foo' references itself"
protocol CircularAssocTypeDefault {
associatedtype Z = Z // expected-error{{associated type 'Z' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}}
associatedtype Z2 = Z3
// expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}}
associatedtype Z3 = Z2
// expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}}
associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}}
// expected-note@-1{{type declared here}}
// expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}}
associatedtype Z5 = Self.Z6
// expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}}
associatedtype Z6 = Self.Z5
// expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}}
}
struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { }
// expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}}
// rdar://problem/20000145
public protocol P {
associatedtype T
}
public struct S<A: P> where A.T == S<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'S' references itself}}
func f(a: A.T) {
g(a: id(t: a))
// expected-error@-1 {{cannot convert value of type 'A.T' to expected argument type 'S<A>'}}
_ = A.T.self
}
func g(a: S<A>) {
f(a: id(t: a))
// expected-note@-1 {{expected an argument list of type '(a: A.T)'}}
// expected-error@-2 {{cannot invoke 'f' with an argument list of type '(a: S<A>)'}}
_ = S<A>.self
}
func id<T>(t: T) -> T {
return t
}
}
protocol I {
init()
}
protocol PI {
associatedtype T : I
}
struct SI<A: PI> : I where A : I, A.T == SI<A> {
// expected-note@-1 {{type declared here}}
// expected-error@-2 {{generic struct 'SI' references itself}}
func ggg<T : I>(t: T.Type) -> T {
return T()
}
func foo() {
_ = A()
_ = A.T()
_ = SI<A>()
_ = ggg(t: A.self)
_ = ggg(t: A.T.self)
_ = self.ggg(t: A.self)
_ = self.ggg(t: A.T.self)
}
}
// Used to hit infinite recursion
struct S4<A: PI> : I where A : I {
}
struct S5<A: PI> : I where A : I, A.T == S4<A> { }
// Used to hit ArchetypeBuilder assertions
struct SU<A: P> where A.T == SU {
}
struct SIU<A: PI> : I where A : I, A.T == SIU {
}
| apache-2.0 | 57a045e341f26b16cf426889ebca74f0 | 28.691589 | 140 | 0.6418 | 3.177 | false | false | false | false |
modocache/swift | stdlib/public/SDK/Foundation/AffineTransform.swift | 3 | 9918 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
#if os(OSX)
private let ε: CGFloat = 2.22045e-16
extension AffineTransform : ReferenceConvertible, Hashable, CustomStringConvertible {
public typealias ReferenceType = NSAffineTransform
private init(reference: NSAffineTransform) {
self = reference.transformStruct
}
private var reference : NSAffineTransform {
let ref = NSAffineTransform()
ref.transformStruct = self
return ref
}
/**
Creates an affine transformation matrix from translation values.
The matrix takes the following form:
[ 1 0 0 ]
[ 0 1 0 ]
[ x y 1 ]
*/
public init(translationByX x: CGFloat, byY y: CGFloat) {
self.init(m11: CGFloat(1.0), m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: CGFloat(1.0),
tX: x, tY: y)
}
/**
Creates an affine transformation matrix from scaling values.
The matrix takes the following form:
[ x 0 0 ]
[ 0 y 0 ]
[ 0 0 1 ]
*/
public init(scaleByX x: CGFloat, byY y: CGFloat) {
self.init(m11: x, m12: CGFloat(0.0),
m21: CGFloat(0.0), m22: y,
tX: CGFloat(0.0), tY: CGFloat(0.0))
}
/**
Creates an affine transformation matrix from scaling a single value.
The matrix takes the following form:
[ f 0 0 ]
[ 0 f 0 ]
[ 0 0 1 ]
*/
public init(scale factor: CGFloat) {
self.init(scaleByX: factor, byY: factor)
}
/**
Creates an affine transformation matrix from rotation value (angle in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public init(rotationByRadians angle: CGFloat) {
let α = Double(angle)
let sine = CGFloat(sin(α))
let cosine = CGFloat(cos(α))
self.init(m11: cosine, m12: sine, m21: -sine, m22: cosine, tX: 0, tY: 0)
}
/**
Creates an affine transformation matrix from a rotation value (angle in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public init(rotationByDegrees angle: CGFloat) {
let α = Double(angle) * M_PI / 180.0
self.init(rotationByRadians: CGFloat(α))
}
/**
An identity affine transformation matrix
[ 1 0 0 ]
[ 0 1 0 ]
[ 0 0 1 ]
*/
public static let identity = AffineTransform(m11: 1, m12: 0, m21: 0, m22: 1, tX: 0, tY: 0)
// Translating
public mutating func translate(x: CGFloat, y: CGFloat) {
tX += m11 * x + m21 * y
tY += m12 * x + m22 * y
}
/**
Mutates an affine transformation matrix from a rotation value (angle α in degrees).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public mutating func rotate(byDegrees angle: CGFloat) {
let α = Double(angle) * M_PI / 180.0
return rotate(byRadians: CGFloat(α))
}
/**
Mutates an affine transformation matrix from a rotation value (angle α in radians).
The matrix takes the following form:
[ cos α sin α 0 ]
[ -sin α cos α 0 ]
[ 0 0 1 ]
*/
public mutating func rotate(byRadians angle: CGFloat) {
let α = Double(angle)
let sine = CGFloat(sin(α))
let cosine = CGFloat(cos(α))
m11 = cosine
m12 = sine
m21 = -sine
m22 = cosine
}
/**
Creates an affine transformation matrix by combining the receiver with `transformStruct`.
That is, it computes `T * M` and returns the result, where `T` is the receiver's and `M` is
the `transformStruct`'s affine transformation matrix.
The resulting matrix takes the following form:
[ m11_T m12_T 0 ] [ m11_M m12_M 0 ]
T * M = [ m21_T m22_T 0 ] [ m21_M m22_M 0 ]
[ tX_T tY_T 1 ] [ tX_M tY_M 1 ]
[ (m11_T*m11_M + m12_T*m21_M) (m11_T*m12_M + m12_T*m22_M) 0 ]
= [ (m21_T*m11_M + m22_T*m21_M) (m21_T*m12_M + m22_T*m22_M) 0 ]
[ (tX_T*m11_M + tY_T*m21_M + tX_M) (tX_T*m12_M + tY_T*m22_M + tY_M) 1 ]
*/
private func concatenated(_ other: AffineTransform) -> AffineTransform {
let (t, m) = (self, other)
// this could be optimized with a vector version
return AffineTransform(
m11: (t.m11 * m.m11) + (t.m12 * m.m21), m12: (t.m11 * m.m12) + (t.m12 * m.m22),
m21: (t.m21 * m.m11) + (t.m22 * m.m21), m22: (t.m21 * m.m12) + (t.m22 * m.m22),
tX: (t.tX * m.m11) + (t.tY * m.m21) + m.tX,
tY: (t.tX * m.m12) + (t.tY * m.m22) + m.tY
)
}
// Scaling
public mutating func scale(_ scale: CGFloat) {
self.scale(x: scale, y: scale)
}
public mutating func scale(x: CGFloat, y: CGFloat) {
m11 *= x
m12 *= x
m21 *= y
m22 *= y
}
/**
Inverts the transformation matrix if possible. Matrices with a determinant that is less than
the smallest valid representation of a double value greater than zero are considered to be
invalid for representing as an inverse. If the input AffineTransform can potentially fall into
this case then the inverted() method is suggested to be used instead since that will return
an optional value that will be nil in the case that the matrix cannot be inverted.
D = (m11 * m22) - (m12 * m21)
D < ε the inverse is undefined and will be nil
*/
public mutating func invert() {
guard let inverse = inverted() else {
fatalError("Transform has no inverse")
}
self = inverse
}
public func inverted() -> AffineTransform? {
let determinant = (m11 * m22) - (m12 * m21)
if fabs(determinant) <= ε {
return nil
}
var inverse = AffineTransform()
inverse.m11 = m22 / determinant
inverse.m12 = -m12 / determinant
inverse.m21 = -m21 / determinant
inverse.m22 = m11 / determinant
inverse.tX = (m21 * tY - m22 * tX) / determinant
inverse.tY = (m12 * tX - m11 * tY) / determinant
return inverse
}
// Transforming with transform
public mutating func append(_ transform: AffineTransform) {
self = concatenated(transform)
}
public mutating func prepend(_ transform: AffineTransform) {
self = transform.concatenated(self)
}
// Transforming points and sizes
public func transform(_ point: NSPoint) -> NSPoint {
var newPoint = NSPoint()
newPoint.x = (m11 * point.x) + (m21 * point.y) + tX
newPoint.y = (m12 * point.x) + (m22 * point.y) + tY
return newPoint
}
public func transform(_ size: NSSize) -> NSSize {
var newSize = NSSize()
newSize.width = (m11 * size.width) + (m21 * size.height)
newSize.height = (m12 * size.width) + (m22 * size.height)
return newSize
}
public var hashValue : Int {
return Int(m11 + m12 + m21 + m22 + tX + tY)
}
public var description: String {
return "{m11:\(m11), m12:\(m12), m21:\(m21), m22:\(m22), tX:\(tX), tY:\(tY)}"
}
public var debugDescription: String {
return description
}
public static func ==(lhs: AffineTransform, rhs: AffineTransform) -> Bool {
return lhs.m11 == rhs.m11 && lhs.m12 == rhs.m12 &&
lhs.m21 == rhs.m21 && lhs.m22 == rhs.m22 &&
lhs.tX == rhs.tX && lhs.tY == rhs.tY
}
}
extension AffineTransform : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSAffineTransform.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSAffineTransform {
let t = NSAffineTransform()
t.transformStruct = self
return t
}
public static func _forceBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge type")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSAffineTransform, result: inout AffineTransform?) -> Bool {
result = x.transformStruct
return true // Can't fail
}
public static func _unconditionallyBridgeFromObjectiveC(_ x: NSAffineTransform?) -> AffineTransform {
var result: AffineTransform?
_forceBridgeFromObjectiveC(x!, result: &result)
return result!
}
}
extension NSAffineTransform : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as AffineTransform)
}
}
#endif
| apache-2.0 | b97245ac7253cb095c08397b999116ab | 31.523026 | 123 | 0.550622 | 3.951639 | false | false | false | false |
Jnosh/swift | test/stdlib/OptionalRenames.swift | 21 | 1034 | // RUN: %target-typecheck-verify-swift
func getInt(x: Int) -> Int? {
if x == 0 {
return .None // expected-error {{'None' has been renamed to 'none'}} {{13-17=none}}
}
return .Some(1) // expected-error {{'Some' has been renamed to 'some'}} {{11-15=some}}
}
let x = Optional.Some(1) // expected-error {{'Some' has been renamed to 'some'}} {{18-22=some}}
switch x {
case .None: break // expected-error {{'None' has been renamed to 'none'}} {{9-13=none}}
case .Some(let x): print(x) // expected-error {{'Some' has been renamed to 'some'}} {{9-13=some}}
}
let optionals: (Int?, Int?) = (Optional.Some(1), .None)
// expected-error@-1 {{'Some' has been renamed to 'some'}} {{41-45=some}}
// expected-error@-2 {{'None' has been renamed to 'none'}} {{51-55=none}}
switch optionals {
case (.None, .none): break // expected-error {{'None' has been renamed to 'none'}} {{10-14=none}}
case (.Some(let left), .some(let right)): break // expected-error {{'Some' has been renamed to 'some'}} {{10-14=some}}
default: break
}
| apache-2.0 | 9882a0eb8f5c120bf25d8663b3898d46 | 38.769231 | 120 | 0.62089 | 3.105105 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/Help/LinearEquations/Landing/MHelpLinearEquationsLandingItemGauss.swift | 1 | 1726 | import UIKit
class MHelpLinearEquationsLandingItemGauss:MHelpItemLong
{
init()
{
let image:UIImage = #imageLiteral(resourceName: "assetGenericGauss")
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:17),
NSForegroundColorAttributeName:UIColor.black]
let attributesDate:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:13),
NSForegroundColorAttributeName:UIColor.black]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:17),
NSForegroundColorAttributeName:UIColor.black]
let rawTitle:String = NSLocalizedString("MHelpLinearEquationsLandingItemGauss_title", comment:"")
let rawDate:String = NSLocalizedString("MHelpLinearEquationsLandingItemGauss_date", comment:"")
let rawSubtitle:String = NSLocalizedString("MHelpLinearEquationsLandingItemGauss_subtitle", comment:"")
let stringTitle:NSAttributedString = NSAttributedString(
string:rawTitle,
attributes:attributesTitle)
let stringDate:NSAttributedString = NSAttributedString(
string:rawDate,
attributes:attributesDate)
let stringSubtitle:NSAttributedString = NSAttributedString(
string:rawSubtitle,
attributes:attributesSubtitle)
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
mutableString.append(stringTitle)
mutableString.append(stringDate)
mutableString.append(stringSubtitle)
super.init(
image:image,
title:mutableString)
}
}
| mit | 8772e30ba9da13ce4cb82600443bc8f2 | 41.097561 | 111 | 0.684241 | 5.791946 | false | false | false | false |
harlanhaskins/SwiftSAT | Sources/SAT/Clause.swift | 1 | 4283 | //
// Clause.swift
// SAT
//
// Created by Harlan Haskins on 9/21/17.
// Copyright © 2017 Harlan Haskins. All rights reserved.
//
import Foundation
/// A Clause represents the logical OR of a collection of variables.
struct Clause {
/// The result of assigning a literal.
enum AssignmentResult {
/// The variable was removed from the clause, but the clause still has
/// variables remaining.
case removedVariable
/// The variable was removed from the clause, and it was the only
/// variable in the clause, thus obviating the need for the clause
/// in the first place.
case clauseObviated
/// The variable did not appear in the clause, and so it remained
/// unchanged.
case clauseUnchanged
}
/// The set of variables in the clause. This is stored as a set because
/// duplicate variables in a clause will fold down to a single instance
/// of the variable, and using a set makes lookups O(1) amortized.
private(set) var variables: Set<Variable>
/// Whether this clause contains both a variable and its inverse, rendering
/// it trivially false.
var containsConflict: Bool {
return variables.contains {
variables.contains($0.inverse)
}
}
/// If this clause has a single variable in it, returns that variable.
/// Otherwise returns `nil`.
var unitTerm: Variable? {
guard let first = variables.first, variables.count == 1 else { return nil }
return first
}
/// Removes the variables in the provided set from this clause's set of
/// variables.
/// - Parameter pureVariables: The set of variables to remove.
mutating func eliminate(pureVariables: Set<Variable>) {
variables.subtract(pureVariables)
}
/// Creates a version of this clause where the provided variables are
/// removed.
/// - Parameter pureVariables: The set of variables to remove.
/// - Returns: A copy of this clause without the provided variables.
func eliminating(pureVariables: Set<Variable>) -> Clause {
var copy = self
copy.eliminate(pureVariables: pureVariables)
return copy
}
/// Assigns the specified variable to `true`, then simplifies the clause
/// with that knowledge. Specifically:
/// - If the variable was not found in the clause, return the clause
/// unchanged.
/// - If the inverse of the variable was found, remove the variable from our set
/// and continue. This is because `(false | x) == x`.
/// - If the variable was found:
/// - If it was the only variable, leave the clause unchanged as that
/// is a unit term and affects the satisfiability of the whole
/// formula.
/// - Otherwise, the clause is trivially true and can be eliminated
/// from the whole formula.
/// - Parameter variable: The variable to assume `true`.
/// - Returns: A description of what change was made to the clause.
mutating func assign(_ variable: Variable) -> AssignmentResult {
guard let found = variables.first(where: { $0.number == variable.number }) else {
return .clauseUnchanged
}
if found.isNegative == variable.isNegative {
return variables.count == 1 ? .clauseUnchanged : .clauseObviated
}
variables.remove(found)
return .removedVariable
}
/// Returns the result of assigning the variable in the clause's set.
/// If the change renders the clause useless, this function returns `nil`.
/// - Parameter variable: The variable to consider `true`.
/// - Returns: The clause after assigning the variable. If the clause was
/// rendered useless after assignment, then it returns `nil`.
func assigning(_ variable: Variable) -> Clause? {
var copy = self
switch copy.assign(variable) {
case .clauseUnchanged, .removedVariable: return copy
case .clauseObviated: return nil
}
}
/// Converts the clause to DIMACS representation.
func asDIMACS() -> String {
var vars = variables.map { $0.asDIMACS }
vars.append("0")
return vars.joined(separator: " ")
}
}
| mit | 12d21db313375aca77ae3997c2c06159 | 37.927273 | 89 | 0.642223 | 4.609257 | false | false | false | false |
vmachiel/swift | LearningSwift.playground/Pages/Interface Builder and Views.xcplaygroundpage/Contents.swift | 1 | 6892 | import UIKit
// A View is created inside your main ViewController when that is created.
// A view is a box, in which things are drawn.
// You defined coordinates with CGFloat (core graphics float). They are special
// Floats/Doubles
let xCoor: CGFloat = 37.0
let yCoor: CGFloat = 55.2
// You define a CGPoint on the View with
var point = CGPoint(x: xCoor, y: yCoor)
// Operations: move the point:
point.y -= 30
point.x += 20.0
point
// You can define a size within a view as a struct, it's an area:
var size = CGSize(width: 100.0, height: 50.0)
// and change that size:
size.width += 42.5
size.height += 75
size
// And than you can use that size in a CGRect, which defines an origin and a size
let rect = CGRect(origin: point, size: size)
// OTHER INITS
let rect2 = CGRect(x: 40.0, y: 25.0, width: 30, height: 30)
// It has methods like:
rect.minX // left edge
rect.midY // Midpoint vertically
rect.intersects(rect2) // Does it intersect with -> Bool
rect.contains(point) // Does it contain a point -> Bool
// 0,0 is in the UPPER LEFT!!!! NOT CART. COORDS!!
// INCREASING Y is thus going DOWN!
// Units that you draw are points not pixels. You know the 1x, 2x and 3x rendering.
// 3GS and 4 have the same ammount of points, but 4 has 4X (2x2) the ammount of pixels.
// You draw with point system, and iOS will render.
// Check the pixels per point (1,2 or 3) with in your project.
let contentScaleFactor: CGFloat // get
// Bounds: in your coor system, what is the space you have to draw in?
// What are the bounds of your view
var bounds: CGRect // get
// A view also has properties on where it is in it's superviews coor system
// These aren't used for drawing, but just to indicate where the whole view is inside
// its super
var center: CGPoint // where is the center
var frame: CGRect // the rect of the view
// !!!!!!!!!!!
// frame.size and bounds.size can be different because the view might be rotated
// or translated. SO BOUNDS indicates in ITS COORD SYSTEM what the bounds are, and FRAME
// indicates what are the view ACTUALLY takes up in its SUPERVIEW!
// So FRAME AND CENTER position a view in a superview and BOUNDS indicates where you'll
// actually be drawing
// !!!!!!!!!!!
// Creating views:
// You drag a generic view into the interface builder, inspect and change it's class to
// your custom subclass (usually of UIView).
// or in code.. sometimes. Something like this: UIlabel example
let labelRect = CGRect(x: 20, y: 20, width: 100, height: 50)
let label = UILabel(frame: labelRect)
label.text = "Hello"
// You would add it to a top level view with
// nameOfTopView.addSubview(label)
// You create custom view to draw custom things or handle custom touch events
// Drawing:
// You override func draw(_ rect: CGRect). YOU NEVER CALL THIS FUNC YOURSELF. The
// controller does that. That rect is a sub area that you draw in.
// If you do need to draw you call UIView.setNeedsDisplay(_ rect: CGRect) to redraw
// an area
// PATHS and CoreGraphics
// you can draw by defining paths or UIBezierPath class. You have to:
// 1. Get a context to draw in: UIGraphicsGetCurrentContext()
// 2. Create paths (lines, arcs etc)
// 3. Set drawing attributes like color, font, texture, linewidth etc.
// 4. Stroke or fill the paths with the attributes
// UIBezierPath auto draws in the current context, has methods to draw (lineto, arcs),
// set attributes (linewidth). UIColor can be used to set storkes and fill colors.
// example:
let path = UIBezierPath()
// Draw a triangle: move to a point and draw from that point to another. Then to another,
// and finally back to where you started by calling close
path.move(to: CGPoint(x: 80, y: 50)) // Starting
path.addLine(to: CGPoint(x: 140, y: 150)) // First line
path.addLine(to: CGPoint(x: 140, y: 150)) // Second Line
path.close() // Close by going back to the start
// So now the path is set, now you stroke and fill it
UIColor.green.setFill() // You actually call a color and tell it to fill
UIColor.red.setStroke() // Set the line to red
path.lineWidth = 3.0 // the linewidth is property of path
path.fill() // Fill with green
path.stroke() // Stroke the red line.
// contains method
path.contains(CGPoint(x: 130, y: 100))
// UIColor and transparency
// UIcolor sets colors
// UIViews have a background color property
let green = UIColor.green
let randomColor = UIColor.init(red: 0.3, green: 0.5, blue: 0.4, alpha: 1.0)
let transparentYellow = UIColor.yellow.withAlphaComponent(0.5) // 0 is transparent
// If you want to use transparency, set the views opaque = false
// Make the entire view transparent by setting alpha = 0.0
// subviews are layered on top of each other. You can hide a layer with hidden = false
// Text.
// You can use UILabel to draw text, done with calculator.
// Or you use NSAttributedString, which is a string like object with attributes like
// color etc.
// You can set the attributes of a attributedstring by sending it a dictionary with
// attribute keys and their values, and an NSRange to apply them to.
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
let text = NSAttributedString(string: "Hello", attributes: attributes)
// If you use different attributes, you need to set the value of the attributes dict
// to ANY (Obj-c legacy)
let attribbutes2: [NSAttributedString.Key: Any] =
[NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.strokeWidth: 4.0
]
let text2 = NSAttributedString(string: "Snor", attributes: attribbutes2)
text.draw(at: CGPoint(x: 40.0, y: 30.0)) // Draw it with that point at upperleft corner
let textSize: CGSize = text.size() // How much space it'll take up
// It's an old style.. so you have to make it an
let mutableText = NSMutableString(string: "Test")
// Fonts (mostly set in interface builder)
// Get a font in code using a UIFfont Type Method. It takes an enum of availible
// kinds of text. These give preferred fonts, for users to see.
let chosenFont = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline)
let chosenFont2 = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
// System fonts go on buttons etc.
let systemFont = UIFont.systemFont(ofSize: 12.0)
let boldSystemFont = UIFont.boldSystemFont(ofSize: 14.0)
// Drawing images
// Use UIImageView
let image: UIImage? = UIImage(named: "Some Image.jpg")
// This will (in a project) add it to Images.xcassets. You can also get them from the file
// system or draw them yourself using Core Graphics.
// Draw it at a point, inside a CGRect, or tile it into a CGRect
image?.draw(at: point) // etc
// Whe UIView changes it size, it'll stretch or squich and image into the new size. Ask for
// a redraw using UIView.contentMode. You can ask it to put it somewhere or scale it.
// OR Simply ask for a .redraw This is possible in interface builder's inspector.
| mit | 7c3c7416c74587d2032f8de0f406e669 | 36.868132 | 91 | 0.72664 | 3.701396 | false | false | false | false |
Visual-Engineering/HiringApp | HiringApp/HiringAppCore/Extensions/NSBundle.swift | 1 | 1034 | //
// NSBundle.swift
// Pods
//
// Created by Alba Luján on 21/6/17.
//
//
import Foundation
class BundleDummyTracker {}
extension Bundle {
class func currentBundle() -> Bundle {
guard let bundleURL = Bundle(for: BundleDummyTracker.self).url(forResource: "HiringAppCoreBundle", withExtension: "bundle") else {
return Bundle.main
}
return Bundle(url: bundleURL)!
}
class func jsonData(named: String) -> Data? {
guard let existingURL = currentBundle().url(forResource: named, withExtension: "json") else {
return nil
}
return try? Data(contentsOf: existingURL)
}
}
extension Optional where Wrapped: Equatable {
static func ==(left: Optional, right: Optional) -> Bool {
switch (left, right) {
case (nil, nil):
return true
case (nil, _):
return false
case (_, nil):
return false
default:
return left! == right!
}
}
}
| apache-2.0 | 097974460572be329f7733f923b9b191 | 21.955556 | 138 | 0.566312 | 4.322176 | false | false | false | false |
stripe/stripe-ios | StripeUICore/StripeUICore/Source/Categories/Locale+StripeUICore.swift | 1 | 1389 | //
// Locale+StripeUICore.swift
// StripeUICore
//
// Created by Mel Ludowise on 9/29/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) public extension Locale {
/// Returns the given array of country/region codes sorted alphabetically by their localized display names
func sortedByTheirLocalizedNames<T: RegionCodeProvider>(
_ regionCollection: [T],
thisRegionFirst: Bool = false
) -> [T] {
var mutableRegionCollection = regionCollection
// Pull out the current country if needed
var prepend: [T] = []
if thisRegionFirst,
let regionCode = self.regionCode,
let index = regionCollection.firstIndex(where: { $0.regionCode == regionCode }) {
prepend = [mutableRegionCollection.remove(at: index)]
}
// Convert to display strings, sort, then map back to value
mutableRegionCollection = mutableRegionCollection.map { (
value: $0,
display: localizedString(forRegionCode: $0.regionCode) ?? $0.regionCode
) }.sorted {
$0.display.compare($1.display, options: [.diacriticInsensitive, .caseInsensitive], locale: self) == .orderedAscending
}.map({
$0.value
})
// Prepend current country if needed
return prepend + mutableRegionCollection
}
}
| mit | fb31b28baa50182e59738e9a3b330978 | 33.7 | 129 | 0.636888 | 4.565789 | false | false | false | false |
yoichitgy/Swinject | Sources/GraphIdentifier.swift | 2 | 461 | //
// Copyright © 2019 Swinject Contributors. All rights reserved.
//
/// Unique identifier of an object graph during a resolution process.
public final class GraphIdentifier {}
extension GraphIdentifier: Equatable, Hashable {
public static func == (lhs: GraphIdentifier, rhs: GraphIdentifier) -> Bool {
return lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self).hashValue)
}
}
| mit | f819b4d7a3f7e2c6a3e69096d1edc0e7 | 27.75 | 80 | 0.7 | 4.554455 | false | false | false | false |
BenziAhamed/Nevergrid | NeverGrid/Source/LocationBasedCache.swift | 1 | 1089 | //
// LocationBasedCache.swift
// OnGettingThere
//
// Created by Benzi on 21/07/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
class LocationBasedCache<T> {
var cache = [Int:[Int:T]]()
func clear() {
cache.removeAll(keepCapacity: true)
}
func clear(location:LocationComponent) {
self[location.column, location.row] = nil
}
func set(location:LocationComponent, item:T) {
self[location.column, location.row] = item
}
func get(location:LocationComponent) -> T? {
return self[location.column, location.row]
}
subscript (column:Int, row:Int) -> T? {
get {
if let rowItems = cache[column] {
return rowItems[row]
}
return nil
}
set(newValue) {
if cache[column] == nil {
cache[column] = [Int:T]()
}
var rowItems = cache[column]!
rowItems[row] = newValue
cache[column] = rowItems
}
}
} | isc | 63fc025c44b81d486f9d1579e26d6c60 | 21.708333 | 57 | 0.53168 | 4.078652 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/XCTEurofurenceModel/Random Value Generation/Entities/KnowledgeEntry+RandomValueProviding.swift | 1 | 896 | import EurofurenceModel
import Foundation
import TestUtilities
public final class FakeKnowledgeEntry: KnowledgeEntry {
public var identifier: KnowledgeEntryIdentifier
public var title: String
public var order: Int
public var contents: String
public var links: [Link]
public init(
identifier: KnowledgeEntryIdentifier,
title: String,
order: Int,
contents: String,
links: [Link]
) {
self.identifier = identifier
self.title = title
self.order = order
self.contents = contents
self.links = links
}
public let contentURL: URL = .random
}
extension FakeKnowledgeEntry: RandomValueProviding {
public static var random: FakeKnowledgeEntry {
FakeKnowledgeEntry(identifier: .random, title: .random, order: .random, contents: .random, links: .random)
}
}
| mit | 7ccc84ba43b910d904fbb66515782272 | 23.216216 | 114 | 0.66183 | 4.950276 | false | false | false | false |
TENDIGI/Obsidian-iOS-SDK | Obsidian-iOS-SDK/Constants.swift | 1 | 4827 | //
// Constants.swift
// ObsidianSDK
//
// Created by Nick Lee on 6/29/15.
// Copyright (c) 2015 TENDIGI, LLC. All rights reserved.
//
import Foundation
internal struct Constants {
struct Security {
static let KeychainName = "com.tendigi.obsidian"
}
struct Environment {
static let ChangeQueueName = "com.tendigi.obsidian.environmentChangesQueue"
}
struct Client {
static let SessionName = "com.tendigi.obsidian.defaultSession"
static let LogIdentifier = "Client"
struct Response {
static let TypeKey = "_type"
struct Types {
static let Error = "error"
}
}
struct Headers {
static let ClientKey = "Tendigi-Client-Key"
static let ClientSecret = "Tendigi-Client-Secret"
static let BearerToken = "Tendigi-Bearer-Token"
static let Accept = "Accept"
static let ContentType = "Content-Type"
}
struct MIMETypes {
static let JSON = "application/json"
}
struct ServerError {
static let Domain = "com.tendigi.obsidian.serverError"
static let DefaultCode = -1000
}
struct InternalError {
static let Domain = "com.tendigi.obsidian.internalError"
static let DebugInfoKey = "TDDebugInfo"
enum Code: Int {
case Unknown
case BadRequest
case InvalidFormat
}
static let descriptionsMap: [Code : String] = [
.Unknown : "An unknown error occurred.",
.BadRequest : "The request is invalid",
.InvalidFormat : "The data recieved was formatted incorrectly."
]
static func make(code: Code, userInfo: [String : AnyObject] = [:]) -> NSError {
let uInfo: NSMutableDictionary = [ NSLocalizedDescriptionKey : Constants.Client.InternalError.descriptionsMap[code]! ]
uInfo.addEntriesFromDictionary(userInfo)
return NSError(domain: Constants.Client.InternalError.Domain, code: code.rawValue, userInfo: uInfo as [NSObject : AnyObject])
}
}
}
struct Criteria {
struct Operator {
static let GreaterThan = ">"
static let GreaterThanOrEqual = ">="
static let LessThan = "<"
static let LessThanOrEqual = "<="
static let Or = "or"
}
}
struct Pagination {
static let DefaultLimit = 25
static let InitialPage = 1
static let PageKey = "page"
static let LimitKey = "limit"
}
struct Request {
struct ResourceRequest {
static let CriteriaKey = "criteria"
static let RecordKey = "record"
struct CreateRequest {
static let MethodName = "create"
}
struct ReadRequest {
static let MethodName = "read"
static let SortKey = "sort"
static let PaginationKey = "pagination"
static let IncludeKey = "include"
}
struct UpdateRequest {
static let MethodName = "update"
}
struct DeleteRequest {
static let MethodName = "destroy"
}
}
}
struct Credential {
static let TokenKey = "token"
}
struct Resource {
struct Builtin {
static let CreatedAtKey = "createdAt"
static let UpdatedAtKey = "updatedAt"
static let IDKey = "id"
}
struct Metadata {
static let ResourceName = "_metadata"
static let NameKey = "name"
static let VersionKey = "version"
}
struct Auth {
static let MethodName = "user_authentication_login"
static let UsernameKey = "user_authentication_username"
static let EmailKey = "user_authentication_email"
static let PasswordKey = "user_authentication_password"
}
}
struct Response {
struct Builtin {
static let RequestIDKey = "_requestID"
static let RequestTimestampKey = "_requestTimestamp"
static let ResponseTimestampKey = "_responseTimestamp"
static let DataKey = "_data"
}
}
struct Date {
static let Format = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
static let LocaleIdentifier = "en_US_POSIX"
}
}
| mit | da150cecd81564df9bdfc5acd835de0f | 28.796296 | 141 | 0.524757 | 5.218378 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/network/GiphyAPI.swift | 1 | 18624 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
// There's no UTI type for webp!
enum GiphyFormat {
case gif, mp4, jpg
}
enum GiphyError: Error {
case assertionError(description: String)
case fetchFailure
}
extension GiphyError: LocalizedError {
public var errorDescription: String? {
switch self {
case .assertionError:
return NSLocalizedString("GIF_PICKER_ERROR_GENERIC", comment: "Generic error displayed when picking a gif")
case .fetchFailure:
return NSLocalizedString("GIF_PICKER_ERROR_FETCH_FAILURE", comment: "Error displayed when there is a failure fetching gifs from the remote service.")
}
}
}
// Represents a "rendition" of a GIF.
// Giphy offers a plethora of renditions for each image.
// They vary in content size (i.e. width, height),
// format (.jpg, .gif, .mp4, webp, etc.),
// quality, etc.
@objc class GiphyRendition: NSObject {
let format: GiphyFormat
let name: String
let width: UInt
let height: UInt
let fileSize: UInt
let url: NSURL
init(format: GiphyFormat,
name: String,
width: UInt,
height: UInt,
fileSize: UInt,
url: NSURL) {
self.format = format
self.name = name
self.width = width
self.height = height
self.fileSize = fileSize
self.url = url
}
public var fileExtension: String {
switch format {
case .gif:
return "gif"
case .mp4:
return "mp4"
case .jpg:
return "jpg"
}
}
public var utiType: String {
switch format {
case .gif:
return kUTTypeGIF as String
case .mp4:
return kUTTypeMPEG4 as String
case .jpg:
return kUTTypeJPEG as String
}
}
public var isStill: Bool {
return name.hasSuffix("_still")
}
public var isDownsampled: Bool {
return name.hasSuffix("_downsampled")
}
public func log() {
Logger.verbose("\t \(format), \(name), \(width), \(height), \(fileSize)")
}
}
// Represents a single Giphy image.
@objc class GiphyImageInfo: NSObject {
let giphyId: String
let renditions: [GiphyRendition]
// We special-case the "original" rendition because it is the
// source of truth for the aspect ratio of the image.
let originalRendition: GiphyRendition
init(giphyId: String,
renditions: [GiphyRendition],
originalRendition: GiphyRendition) {
self.giphyId = giphyId
self.renditions = renditions
self.originalRendition = originalRendition
}
// TODO: We may need to tweak these constants.
let kMaxDimension = UInt(618)
let kMinPreviewDimension = UInt(60)
let kMinSendingDimension = UInt(101)
let kPreferedPreviewFileSize = UInt(256 * 1024)
let kPreferedSendingFileSize = UInt(3 * 1024 * 1024)
private enum PickingStrategy {
case smallerIsBetter, largerIsBetter
}
public func log() {
Logger.verbose("giphyId: \(giphyId), \(renditions.count)")
for rendition in renditions {
rendition.log()
}
}
public func pickStillRendition() -> GiphyRendition? {
// Stills are just temporary placeholders, so use the smallest still possible.
return pickRendition(renditionType: .stillPreview, pickingStrategy:.smallerIsBetter, maxFileSize:kPreferedPreviewFileSize)
}
public func pickPreviewRendition() -> GiphyRendition? {
// Try to pick a small file...
if let rendition = pickRendition(renditionType: .animatedLowQuality, pickingStrategy:.largerIsBetter, maxFileSize:kPreferedPreviewFileSize) {
return rendition
}
// ...but gradually relax the file restriction...
if let rendition = pickRendition(renditionType: .animatedLowQuality, pickingStrategy:.smallerIsBetter, maxFileSize:kPreferedPreviewFileSize * 2) {
return rendition
}
// ...and relax even more until we find an animated rendition.
return pickRendition(renditionType: .animatedLowQuality, pickingStrategy:.smallerIsBetter, maxFileSize:kPreferedPreviewFileSize * 3)
}
public func pickSendingRendition() -> GiphyRendition? {
// Try to pick a small file...
if let rendition = pickRendition(renditionType: .animatedHighQuality, pickingStrategy:.largerIsBetter, maxFileSize:kPreferedSendingFileSize) {
return rendition
}
// ...but gradually relax the file restriction...
if let rendition = pickRendition(renditionType: .animatedHighQuality, pickingStrategy:.smallerIsBetter, maxFileSize:kPreferedSendingFileSize * 2) {
return rendition
}
// ...and relax even more until we find an animated rendition.
return pickRendition(renditionType: .animatedHighQuality, pickingStrategy:.smallerIsBetter, maxFileSize:kPreferedSendingFileSize * 3)
}
enum RenditionType {
case stillPreview, animatedLowQuality, animatedHighQuality
}
// Picking a rendition must be done very carefully.
//
// * We want to avoid incomplete renditions.
// * We want to pick a rendition of "just good enough" quality.
private func pickRendition(renditionType: RenditionType, pickingStrategy: PickingStrategy, maxFileSize: UInt) -> GiphyRendition? {
var bestRendition: GiphyRendition?
for rendition in renditions {
switch renditionType {
case .stillPreview:
// Accept GIF or JPEG stills. In practice we'll
// usually select a JPEG since they'll be smaller.
guard [.gif, .jpg].contains(rendition.format) else {
continue
}
// Only consider still renditions.
guard rendition.isStill else {
continue
}
// Accept still renditions without a valid file size. Note that fileSize
// will be zero for renditions without a valid file size, so they will pass
// the maxFileSize test.
//
// Don't worry about max content size; still images are tiny in comparison
// with animated renditions.
guard rendition.width >= kMinPreviewDimension &&
rendition.height >= kMinPreviewDimension &&
rendition.fileSize <= maxFileSize
else {
continue
}
case .animatedLowQuality:
// Only use GIFs for animated renditions.
guard rendition.format == .gif else {
continue
}
// Ignore stills.
guard !rendition.isStill else {
continue
}
// Ignore "downsampled" renditions which skip frames, etc.
guard !rendition.isDownsampled else {
continue
}
guard rendition.width >= kMinPreviewDimension &&
rendition.width <= kMaxDimension &&
rendition.height >= kMinPreviewDimension &&
rendition.height <= kMaxDimension &&
rendition.fileSize > 0 &&
rendition.fileSize <= maxFileSize
else {
continue
}
case .animatedHighQuality:
// Only use GIFs for animated renditions.
guard rendition.format == .gif else {
continue
}
// Ignore stills.
guard !rendition.isStill else {
continue
}
// Ignore "downsampled" renditions which skip frames, etc.
guard !rendition.isDownsampled else {
continue
}
guard rendition.width >= kMinSendingDimension &&
rendition.width <= kMaxDimension &&
rendition.height >= kMinSendingDimension &&
rendition.height <= kMaxDimension &&
rendition.fileSize > 0 &&
rendition.fileSize <= maxFileSize
else {
continue
}
}
if let currentBestRendition = bestRendition {
if rendition.width == currentBestRendition.width &&
rendition.fileSize > 0 &&
currentBestRendition.fileSize > 0 &&
rendition.fileSize < currentBestRendition.fileSize {
// If two renditions have the same content size, prefer
// the rendition with the smaller file size, e.g.
// prefer JPEG over GIF for stills.
bestRendition = rendition
} else if pickingStrategy == .smallerIsBetter {
// "Smaller is better"
if rendition.width < currentBestRendition.width {
bestRendition = rendition
}
} else {
// "Larger is better"
if rendition.width > currentBestRendition.width {
bestRendition = rendition
}
}
} else {
bestRendition = rendition
}
}
return bestRendition
}
}
@objc class GiphyAPI: NSObject {
// MARK: - Properties
static let TAG = "[GiphyAPI]"
let TAG = "[GiphyAPI]"
static let sharedInstance = GiphyAPI()
// Force usage as a singleton
override private init() {
super.init()
SwiftSingletons.register(self)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private let kGiphyBaseURL = "https://api.giphy.com/"
public class func giphySessionConfiguration() -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.ephemeral
let proxyHost = "giphy-proxy-production.whispersystems.org"
let proxyPort = 80
configuration.connectionProxyDictionary = [
"HTTPEnable": 1,
"HTTPProxy": proxyHost,
"HTTPPort": proxyPort,
"HTTPSEnable": 1,
"HTTPSProxy": proxyHost,
"HTTPSPort": proxyPort
]
return configuration
}
private func giphyAPISessionManager() -> AFHTTPSessionManager? {
guard let baseUrl = NSURL(string:kGiphyBaseURL) else {
Logger.error("\(TAG) Invalid base URL.")
return nil
}
let sessionManager = AFHTTPSessionManager(baseURL:baseUrl as URL,
sessionConfiguration:GiphyAPI.giphySessionConfiguration())
sessionManager.requestSerializer = AFJSONRequestSerializer()
sessionManager.responseSerializer = AFJSONResponseSerializer()
return sessionManager
}
// MARK: Search
public func search(query: String, success: @escaping (([GiphyImageInfo]) -> Void), failure: @escaping ((NSError?) -> Void)) {
guard let sessionManager = giphyAPISessionManager() else {
Logger.error("\(TAG) Couldn't create session manager.")
failure(nil)
return
}
guard NSURL(string:kGiphyBaseURL) != nil else {
Logger.error("\(TAG) Invalid base URL.")
failure(nil)
return
}
// This is the Signal iOS API key.
let kGiphyApiKey = "ZsUpUm2L6cVbvei347EQNp7HrROjbOdc"
let kGiphyPageSize = 200
let kGiphyPageOffset = 0
guard let queryEncoded = query.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
Logger.error("\(TAG) Could not URL encode query: \(query).")
failure(nil)
return
}
let urlString = "/v1/gifs/search?api_key=\(kGiphyApiKey)&offset=\(kGiphyPageOffset)&limit=\(kGiphyPageSize)&q=\(queryEncoded)"
sessionManager.get(urlString,
parameters: {},
progress:nil,
success: { _, value in
Logger.error("\(GiphyAPI.TAG) search request succeeded")
guard let imageInfos = self.parseGiphyImages(responseJson:value) else {
failure(nil)
return
}
success(imageInfos)
},
failure: { _, error in
Logger.error("\(GiphyAPI.TAG) search request failed: \(error)")
failure(error as NSError)
})
}
// MARK: Parse API Responses
private func parseGiphyImages(responseJson:Any?) -> [GiphyImageInfo]? {
guard let responseJson = responseJson else {
Logger.error("\(TAG) Missing response.")
return nil
}
guard let responseDict = responseJson as? [String:Any] else {
Logger.error("\(TAG) Invalid response.")
return nil
}
guard let imageDicts = responseDict["data"] as? [[String:Any]] else {
Logger.error("\(TAG) Invalid response data.")
return nil
}
return imageDicts.flatMap { imageDict in
return parseGiphyImage(imageDict: imageDict)
}
}
// Giphy API results are often incomplete or malformed, so we need to be defensive.
private func parseGiphyImage(imageDict: [String:Any]) -> GiphyImageInfo? {
guard let giphyId = imageDict["id"] as? String else {
Logger.warn("\(TAG) Image dict missing id.")
return nil
}
guard giphyId.count > 0 else {
Logger.warn("\(TAG) Image dict has invalid id.")
return nil
}
guard let renditionDicts = imageDict["images"] as? [String:Any] else {
Logger.warn("\(TAG) Image dict missing renditions.")
return nil
}
var renditions = [GiphyRendition]()
for (renditionName, renditionDict) in renditionDicts {
guard let renditionDict = renditionDict as? [String:Any] else {
Logger.warn("\(TAG) Invalid rendition dict.")
continue
}
guard let rendition = parseGiphyRendition(renditionName:renditionName,
renditionDict:renditionDict) else {
continue
}
renditions.append(rendition)
}
guard renditions.count > 0 else {
Logger.warn("\(TAG) Image has no valid renditions.")
return nil
}
guard let originalRendition = findOriginalRendition(renditions:renditions) else {
Logger.warn("\(TAG) Image has no original rendition.")
return nil
}
return GiphyImageInfo(giphyId : giphyId,
renditions : renditions,
originalRendition: originalRendition)
}
private func findOriginalRendition(renditions: [GiphyRendition]) -> GiphyRendition? {
for rendition in renditions where rendition.name == "original" {
return rendition
}
return nil
}
// Giphy API results are often incomplete or malformed, so we need to be defensive.
//
// We should discard renditions which are missing or have invalid properties.
private func parseGiphyRendition(renditionName: String,
renditionDict: [String:Any]) -> GiphyRendition? {
guard let width = parsePositiveUInt(dict:renditionDict, key:"width", typeName:"rendition") else {
return nil
}
guard let height = parsePositiveUInt(dict:renditionDict, key:"height", typeName:"rendition") else {
return nil
}
// Be lenient when parsing file sizes - we don't require them for stills.
let fileSize = parseLenientUInt(dict:renditionDict, key:"size")
guard let urlString = renditionDict["url"] as? String else {
return nil
}
guard urlString.count > 0 else {
Logger.warn("\(TAG) Rendition has invalid url.")
return nil
}
guard let url = NSURL(string:urlString) else {
Logger.warn("\(TAG) Rendition url could not be parsed.")
return nil
}
guard let fileExtension = url.pathExtension?.lowercased() else {
Logger.warn("\(TAG) Rendition url missing file extension.")
return nil
}
var format = GiphyFormat.gif
if fileExtension == "gif" {
format = .gif
} else if fileExtension == "jpg" {
format = .jpg
} else if fileExtension == "mp4" {
format = .mp4
} else if fileExtension == "webp" {
return nil
} else {
Logger.warn("\(TAG) Invalid file extension: \(fileExtension).")
return nil
}
return GiphyRendition(
format : format,
name : renditionName,
width : width,
height : height,
fileSize : fileSize,
url : url
)
}
private func parsePositiveUInt(dict: [String:Any], key: String, typeName: String) -> UInt? {
guard let value = dict[key] else {
return nil
}
guard let stringValue = value as? String else {
return nil
}
guard let parsedValue = UInt(stringValue) else {
return nil
}
guard parsedValue > 0 else {
Logger.verbose("\(TAG) \(typeName) has non-positive \(key): \(parsedValue).")
return nil
}
return parsedValue
}
private func parseLenientUInt(dict: [String:Any], key: String) -> UInt {
let defaultValue = UInt(0)
guard let value = dict[key] else {
return defaultValue
}
guard let stringValue = value as? String else {
return defaultValue
}
guard let parsedValue = UInt(stringValue) else {
return defaultValue
}
return parsedValue
}
}
| gpl-3.0 | 28d4d7ad6bf5c1384df29057d81a7437 | 35.733728 | 161 | 0.564701 | 5.472818 | false | false | false | false |
rnystrom/GitHawk | Local Pods/GitHubAPI/GitHubAPI/V3SetRepositoryLabelsRequest.swift | 1 | 868 | //
// V3SetRepositoryLabelsRequest.swift
// GitHubAPI
//
// Created by Ryan Nystrom on 3/4/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
public struct V3SetRepositoryLabelsRequest: V3Request {
public typealias ResponseType = V3StatusCodeResponse<V3StatusCode200>
public var pathComponents: [String] {
return ["repos", owner, repo, "issues", "\(number)"]
}
public var method: HTTPMethod { return .patch }
public var parameters: [String : Any]? {
return ["labels": labels]
}
public let owner: String
public let repo: String
public let number: Int
public let labels: [String]
public init(owner: String, repo: String, number: Int, labels: [String]) {
self.owner = owner
self.repo = repo
self.number = number
self.labels = labels
}
}
| mit | f6c073ac98ae901f0364dfa4f6044453 | 26.09375 | 77 | 0.653979 | 4.032558 | false | false | false | false |
Eflet/Charts | Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift | 2 | 13236 | //
// ChartXAxisRendererHorizontalBarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/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/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart
{
public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart)
}
public override func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?])
{
guard let xAxis = xAxis else { return }
xAxis.values = xValues
let longest = xAxis.getLongestLabel() as NSString
let labelSize = longest.sizeWithAttributes([NSFontAttributeName: xAxis.labelFont])
let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5)
let labelHeight = labelSize.height
let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(rectangleWidth: labelSize.width, rectangleHeight: labelHeight, degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5)
xAxis.labelRotatedHeight = round(labelRotatedSize.height)
}
public override func renderAxisLabels(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil
{
return
}
let xoffset = xAxis.xOffset
if (xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else if (xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if (xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
else if (xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
}
}
/// draws the x-labels on the specified y-position
public override func drawLabels(context context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard let
xAxis = xAxis,
bd = chart?.data as? BarChartData
else { return }
let labelFont = xAxis.labelFont
let labelTextColor = xAxis.labelTextColor
let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
let step = bd.dataSetCount
for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus)
{
let label = xAxis.values[i]
if (label == nil)
{
continue
}
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0
// consider groups (center label for each group)
if (step > 1)
{
position.y += (CGFloat(step) - 1.0) / 2.0
}
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
drawLabel(context: context, label: label!, xIndex: i, x: pos, y: position.y, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: anchor, angleRadians: labelRotationAngleRadians)
}
}
}
public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], anchor: CGPoint, angleRadians: CGFloat)
{
guard let xAxis = xAxis else { return }
let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label
ChartUtils.drawText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians)
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext)
{
guard let
xAxis = xAxis,
bd = chart?.data as? BarChartData
else { return }
if !xAxis.isEnabled || !xAxis.isDrawGridLinesEnabled
{
return
}
CGContextSaveGState(context)
CGContextSetShouldAntialias(context, xAxis.gridAntialiasEnabled)
CGContextSetStrokeColorWithColor(context, xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, xAxis.gridLineWidth)
CGContextSetLineCap(context, xAxis.gridLineCap)
if (xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, xAxis.gridLineDashPhase, xAxis.gridLineDashLengths, xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var position = CGPoint(x: 0.0, y: 0.0)
// take into consideration that multiple DataSets increase _deltaX
let step = bd.dataSetCount
for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus)
{
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
_gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_gridLineSegmentsBuffer[0].y = position.y
_gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_gridLineSegmentsBuffer[1].y = position.y
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, xAxis.axisLineWidth)
if (xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, xAxis.axisLineDashPhase, xAxis.axisLineDashLengths, xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (xAxis.labelPosition == .Top
|| xAxis.labelPosition == .TopInside
|| xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (xAxis.labelPosition == .Bottom
|| xAxis.labelPosition == .BottomInside
|| xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(context context: CGContext)
{
guard let xAxis = xAxis else { return }
var limitLines = xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
position.x = 0.0
position.y = CGFloat(l.limit)
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_limitLineSegmentsBuffer[0].y = position.y
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_limitLineSegmentsBuffer[1].y = position.y
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
let label = l.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = l.valueFont.lineHeight
let xOffset: CGFloat = 4.0 + l.xOffset
let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
if (l.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
}
}
CGContextRestoreGState(context)
}
} | apache-2.0 | 23375d5db24283d8230f6f6f5deaf886 | 37.368116 | 243 | 0.573965 | 5.591888 | false | false | false | false |
M-Hamed/photo-editor | iOSPhotoEditor/PhotoEditor+UITextView.swift | 2 | 1938 | //
// PhotoEditor+UITextView.swift
// Pods
//
// Created by Mohamed Hamed on 6/16/17.
//
//
import Foundation
import UIKit
extension PhotoEditorViewController: UITextViewDelegate {
public func textViewDidChange(_ textView: UITextView) {
let rotation = atan2(textView.transform.b, textView.transform.a)
if rotation == 0 {
let oldFrame = textView.frame
let sizeToFit = textView.sizeThatFits(CGSize(width: oldFrame.width, height:CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: oldFrame.width, height: sizeToFit.height)
}
}
public func textViewDidBeginEditing(_ textView: UITextView) {
isTyping = true
lastTextViewTransform = textView.transform
lastTextViewTransCenter = textView.center
lastTextViewFont = textView.font!
activeTextView = textView
textView.superview?.bringSubviewToFront(textView)
textView.font = UIFont(name: "Helvetica", size: 30)
UIView.animate(withDuration: 0.3,
animations: {
textView.transform = CGAffineTransform.identity
textView.center = CGPoint(x: UIScreen.main.bounds.width / 2,
y: UIScreen.main.bounds.height / 5)
}, completion: nil)
}
public func textViewDidEndEditing(_ textView: UITextView) {
guard lastTextViewTransform != nil && lastTextViewTransCenter != nil && lastTextViewFont != nil
else {
return
}
activeTextView = nil
textView.font = self.lastTextViewFont!
UIView.animate(withDuration: 0.3,
animations: {
textView.transform = self.lastTextViewTransform!
textView.center = self.lastTextViewTransCenter!
}, completion: nil)
}
}
| mit | de964d0289ed505aab49c4e267768794 | 35.566038 | 120 | 0.604231 | 5.140584 | false | false | false | false |
visualitysoftware/swift-sdk | CloudBoost/CloudPush.swift | 1 | 3244 | //
// CloudPush.swift
// CloudBoost
//
// Created by Randhir Singh on 14/05/16.
// Copyright © 2016 Randhir Singh. All rights reserved.
//
import Foundation
public class CloudPush {
public static func send(data: AnyObject, query: CloudQuery?, callback: (CloudBoostResponse)->Void) throws {
if CloudApp.getAppId() == nil {
throw CloudBoostError.AppIdNotSet
}
if CloudApp.getAppKey() == nil {
throw CloudBoostError.AppIdNotSet
}
var pushQuery: CloudQuery
if query == nil {
pushQuery = CloudQuery(tableName: "Device")
}else{
pushQuery = query!
}
let params = NSMutableDictionary()
params["query"] = pushQuery.getQuery()
params["sort"] = pushQuery.getSort()
params["limit"] = pushQuery.getLimit()
params["skip"] = pushQuery.getSkip()
params["key"] = CloudApp.getAppKey()
params["data"] = data
let url = CloudApp.getApiUrl() + "/push/" + CloudApp.getAppId()! + "/send"
CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: {response in
print("Response !!")
callback(response)
})
}
public static func registerDeviceWithToken(token: NSData,
timezone: String,
channels: [String]?,
callback: (CloudBoostResponse)->Void) {
var tokenString = NSString(format: "%@", token)
tokenString = tokenString.stringByReplacingOccurrencesOfString("<", withString: "")
tokenString = tokenString.stringByReplacingOccurrencesOfString(">", withString: "")
tokenString = tokenString.stringByReplacingOccurrencesOfString(" ", withString: "")
let device = CloudObject(tableName: "Device")
device.set("deviceToken", value: tokenString)
device.set("deviceOS", value: "iOS")
device.set("timezone", value: timezone)
if let channels = channels {
device.set("channels", value: channels)
}
device.save { response in
callback(response)
}
}
public static func unregisterDeviceWithToken(token: NSData,
callback: (CloudBoostResponse)->Void) {
var tokenString = NSString(format: "%@", token)
tokenString = tokenString.stringByReplacingOccurrencesOfString("<", withString: "")
tokenString = tokenString.stringByReplacingOccurrencesOfString(">", withString: "")
tokenString = tokenString.stringByReplacingOccurrencesOfString(" ", withString: "")
let query = CloudQuery(tableName: "Device")
try! query.equalTo("deviceToken", obj: tokenString)
try! query.findOne { (response) in
if let device = response.object as? CloudObject {
device.delete({ (response) in
callback(response)
})
}
}
}
} | mit | 0d1125aaadaeab6096e6cdd7ba634b04 | 33.88172 | 111 | 0.550108 | 5.423077 | false | false | false | false |
ahmadbaraka/SwiftLayoutConstraints | Example/Tests/LhsLayoutConstraintSpec.swift | 1 | 2075 | //
// LhsLayoutConstraintSpec.swift
// SwiftLayoutConstraints
//
// Created by Ahmad Baraka on 7/21/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Nimble
import Quick
import SwiftLayoutConstraints
class LhsLayoutConstraintSpec: QuickSpec {
override func spec() {
describe("inits") {
var object: NSObject!
var constraint: LhsLayoutConstraint<NSObject>!
beforeEach {
object = NSObject()
}
afterEach {
expect(constraint.object) == object
expect(constraint.constant) == 0
expect(constraint.multiplier) == 1
}
it("should init with object and attribute") {
let attribute = NSLayoutAttribute.Bottom
constraint = LhsLayoutConstraint(object, attribute: attribute)
expect(constraint.attribute) == attribute
}
it("should init with object") {
constraint = LhsLayoutConstraint(object)
expect(constraint.attribute) == NSLayoutAttribute.NotAnAttribute
}
it("should copy values from another constraint with other type") {
let object2 = NSURL()
let attribute = NSLayoutAttribute.Bottom
let org = LhsLayoutConstraint(object2, attribute: attribute)
constraint = LhsLayoutConstraint(object, constraint: org)
expect(constraint.attribute) == attribute
}
it("should copy values from another constraint") {
let attribute = NSLayoutAttribute.Bottom
let org = LhsLayoutConstraint(object, attribute: attribute)
constraint = LhsLayoutConstraint(constraint: org)
expect(constraint.attribute) == attribute
}
}
}
}
| mit | b2d9995ce356afdee1a5dfb2c5095e74 | 31.920635 | 80 | 0.532787 | 6.303951 | false | false | false | false |
ezefranca/kit-iot-wearable-ios-1 | Kit Iot Wearable/ViewController.swift | 1 | 6893 | //
// ViewController.swift
// Kit Iot Wearable
//
// Created by Vitor Leal on 4/1/15.
// Copyright (c) 2015 Telefonica VIVO. All rights reserved.
//
import UIKit
import CoreBluetooth
class ViewController: UIViewController {
// IB Outlets
@IBOutlet weak var accelerometrX: UILabel!
@IBOutlet weak var accelerometrY: UILabel!
@IBOutlet weak var accelerometrZ: UILabel!
@IBOutlet weak var luminosityValue: UILabel!
@IBOutlet weak var temperatureValue: UILabel!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var loader: UIActivityIndicatorView!
@IBOutlet weak var redSlider: UISlider!
@IBOutlet weak var greenSlider: UISlider!
@IBOutlet weak var blueSlider: UISlider!
let blueColor = UIColor(red: 51/255, green: 73/255, blue: 96/255, alpha: 1.0)
var timer: NSTimer?
// MARK: - View did load
override func viewDidLoad() {
super.viewDidLoad()
// Notification center observers
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("connectionChanged:"),
name: WearableServiceStatusNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("characteristicNewValue:"),
name: WearableCharacteristicNewValue, object: nil)
//Wearable instance
wearable
}
// MARK: - On characteristic new value update interface
func characteristicNewValue(notification: NSNotification) {
let userInfo = notification.userInfo as! Dictionary<String, NSString>
let value = userInfo["value"]!
let val = value.substringFromIndex(3).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let sensor = value.substringWithRange(NSMakeRange(0, 3))
dispatch_async(dispatch_get_main_queue()) {
switch sensor {
case "#TE":
self.temperatureValue.text = "\(val)º"
break
case "#LI":
self.luminosityValue.text = val
break
case "#AX":
self.accelerometrX.text = val
break
case "#AY":
self.accelerometrY.text = val
break
case "#AZ":
self.accelerometrZ.text = val
break
default:
break
}
}
}
// MARK: - On connection change
func connectionChanged(notification: NSNotification) {
let userInfo = notification.userInfo as! [String: Bool]
dispatch_async(dispatch_get_main_queue(), {
if let isConnected: Bool = userInfo["isConnected"] {
if isConnected {
self.wearableConnected()
} else {
self.wearableDisconnected()
}
}
});
}
// MARK: - On wearable disconnection
func wearableDisconnected() {
// Change the title
self.navigationController!.navigationBar.topItem?.title = "Buscando Wearable"
// Change naviagation color
self.navigationController!.navigationBar.barTintColor = UIColor.grayColor()
// Show loader
self.loader.hidden = false
// Show content view
self.contentView.hidden = true
// Cancel timer
self.timer!.invalidate()
}
// MARK: - On wearable connection
func wearableConnected() {
//Change the title
self.navigationController!.navigationBar.topItem?.title = "Conectado"
//Change naviagation color
self.navigationController!.navigationBar.barTintColor = self.blueColor
// Hide loader
self.loader.hidden = true
// Show content view
self.contentView.hidden = false
// Get the sensor values
self.getSensorValues()
// Start timer
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("getSensorValues"), userInfo: nil, repeats: true)
}
// MARK: - Deinit and memory warning
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: WearableServiceStatusNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self,
name: WearableCharacteristicNewValue, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Slider change
@IBAction func sliderChange(slider: UISlider) {
if let wearableService = wearable.wearableService {
if (slider.isEqual(redSlider)) {
wearableService.sendCommand(String(format: "#LR0%.0f\n\r", slider.value))
}
if (slider.isEqual(greenSlider)) {
wearableService.sendCommand(String(format: "#LG0%.0f\n\r", slider.value))
}
if (slider.isEqual(blueSlider)) {
wearableService.sendCommand(String(format: "#LB0%.0f\n\r", slider.value))
}
}
}
// MARK: - Button click
@IBAction func ledOFF(sender: AnyObject) {
if let wearableService = wearable.wearableService {
wearableService.sendCommand("#LL0000\n\r")
redSlider.setValue(0, animated: true)
greenSlider.setValue(0, animated: true)
blueSlider.setValue(0, animated: true)
}
}
// MARK: - Get {light,temperature,accelerometer} value
func getSensorValues() {
if let wearableService = wearable.wearableService {
wearableService.sendCommand("#TE0000\n\r")
wearableService.sendCommand("#LI0000\n\r")
wearableService.sendCommand("#AC0003\n\r")
}
}
// MARK: - Melody buttons click
@IBAction func playMelody(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
if let wearableService = wearable.wearableService {
wearableService.sendCommand("#PM1234\n\r")
}
case 1:
if let wearableService = wearable.wearableService {
wearableService.sendCommand("#PM6789\n\r")
}
case 2:
if let wearableService = wearable.wearableService {
wearableService.sendCommand("#PM4567\n\r")
}
default:
break;
}
}
}
| mit | ec05ff55adea9186dd6a3e0f121f0b59 | 31.205607 | 145 | 0.56776 | 5.143284 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/common/repos/GsRepoReadmeViewController.swift | 1 | 4626 | //
// GsRepoReadmeViewController.swift
// GitHubStar
//
// Created by midoks on 16/3/12.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
import SwiftyJSON
class GsRepoReadmeViewController: UIViewController {
var _webView:UIWebView = UIWebView()
var progress: UIProgressView?
var progressEnd = false
var progressTimer: Timer?
var _readmeData:JSON = JSON.parse("")
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController!.tabBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = sysLang(key: "Readme")
self.view.backgroundColor = UIColor.white
_webView.delegate = self
_webView.frame = self.view.bounds
_webView.frame.size.height += self.tabBarController!.tabBar.frame.height
self.view.addSubview(_webView)
//加载进度条
self.progress = UIProgressView(progressViewStyle: UIProgressViewStyle.bar)
self.progress!.frame = CGRect(x: 0, y: 64, width: self.view.frame.width, height:2)
self.progress!.progress = 0
self.progress!.isHidden = false
self.view.addSubview(self.progress!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func strToEncode64(strVal:String) -> String {
let strValData = strVal.data(using: String.Encoding.utf8)
let strValEncodeData = strValData?.base64EncodedData(options: Data.Base64EncodingOptions.init(rawValue: 0))
let strValEncode = String(data: strValEncodeData!, encoding: String.Encoding.utf8)
return strValEncode!
}
func strToDecode64(strVal:String) -> String {
let data = NSData(base64Encoded:strVal ,options: .ignoreUnknownCharacters)!
let strValDecode = String(data: data as Data, encoding: String.Encoding.utf8)
return strValDecode!
}
func setReadmeData(data:JSON){
self._readmeData = data
//print(data["_links"])
let content = data["content"].stringValue
let contentDecode = strToDecode64(strVal: content)
self.asynTask { () -> Void in
//let v = MarkNoteParser.toHtml(contentDecode)
//print(v)
self._webView.loadHTMLString(contentDecode, baseURL: nil)
}
}
func setReadmeUrl(url:NSURL){
let u = NSURLRequest(url: url as URL)
_webView.loadRequest(u as URLRequest)
}
}
//MARK: - UIWebViewDelegate -
extension GsRepoReadmeViewController:UIWebViewDelegate {
//进度条回调
func progressCallback() {
self.progress!.progress += 0.01
if self.progressEnd {
if self.progress!.progress >= 0.99 {
self.progress!.progress = 1
self.progress!.isHidden = true
self.progressTimer!.invalidate()
}
} else {
if self.progress!.progress >= 0.99 {
self.progress!.progress = 1
self.progress!.isHidden = true
self.progressTimer!.invalidate()
}
}
}
//开启进度条定时检查
func beginLoadProgressTimer(){
if(self.progress!.progress == 0){
if self.progressTimer != nil {
self.progressTimer!.invalidate()
}
self.progressTimer = Timer.scheduledTimer(timeInterval: 0.01667, target: self, selector: #selector(GsRepoReadmeViewController.progressCallback), userInfo: nil, repeats: true)
}
self.progress!.progress = 0
self.progress!.isHidden = false
self.progressEnd = false
self.progressTimer!.fire()
}
//进度条结束
func endLoadProgressTimer(){
self.progressEnd = true
}
func webViewDidFinishLoad(_ webView: UIWebView) {
endLoadProgressTimer()
}
func webViewDidStartLoad(_ webView: UIWebView) {
beginLoadProgressTimer()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
endLoadProgressTimer()
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
beginLoadProgressTimer()
return true
}
}
| apache-2.0 | dd58fa8ab45e31702933151b2fdcee8a | 28.326923 | 186 | 0.605902 | 4.721362 | false | false | false | false |
Miridescen/M_365key | 365KEY_swift/365KEY_swift/MainController/Class/News/controller/SKNewsSearchVC.swift | 1 | 4747 | //
// SKNewsSearchVC.swift
// 365KEY_swift
//
// Created by 牟松 on 2017/1/4.
// Copyright © 2017年 DoNews. All rights reserved.
//
import UIKit
private let NewsSearchID = "NewsSearchID"
class SKNewsSearchVC: UIViewController {
var navBar: UINavigationBar?
var navItem: UINavigationItem?
var tableView: UITableView?
var data = [[String : [SKNewsListModel]]]()
override func viewDidLoad() {
super.viewDidLoad()
addSubView()
}
}
extension SKNewsSearchVC {
@objc private func backBtnDidClick(){
_ = navigationController?.popViewController(animated: true)
}
func addSubView() {
navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64))
navBar?.isTranslucent = false
navBar?.barTintColor = UIColor().mainColor
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
view.addSubview(navBar!)
navItem = UINavigationItem()
navItem?.title = "365KEY"
navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: UIImage(named:"icon_back"), selectorImage: UIImage(named:"icon_back"), tragtic: self, action: #selector(backBtnDidClick))
navBar?.items = [navItem!]
tableView = UITableView(frame: view.bounds)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.separatorStyle = .none
tableView?.register(UINib(nibName: "SKNewsCell", bundle: nil), forCellReuseIdentifier: NewsSearchID)
tableView?.contentInset = UIEdgeInsets(top: 44, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
tableView?.scrollIndicatorInsets = UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0)
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.estimatedRowHeight = 300
view.insertSubview(tableView!, at: 0)
}
}
extension SKNewsSearchVC: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dic = data[section] as [String : [SKNewsListModel]]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
return value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: NewsSearchID, for: indexPath) as! SKNewsCell
let dic = data[indexPath.section]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
cell.newsListModel = value[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.frame = CGRect(x: 0, y: -10, width: SKScreenWidth, height: 40)
view.backgroundColor = UIColor.white
let todayDate = Date().description
let strIndex = todayDate.index(todayDate.startIndex, offsetBy: 10)
let todayDateStr = todayDate.substring(to: strIndex)
let dic = data[section] as [String : [SKNewsListModel]]
let keyValue = dic[dic.startIndex]
let value = keyValue.0
let titleText = value == todayDateStr ? "Today":value
let titleLabel = UILabel()
titleLabel.frame = CGRect(x: 16, y: 20, width: SKScreenWidth-10, height: 20)
titleLabel.textAlignment = .left
titleLabel.textColor = UIColor(red: 254/255.0, green: 216/255.0, blue: 203/255.0, alpha: 1.0)
titleLabel.font = UIFont.systemFont(ofSize: 19)
titleLabel.text = titleText
view.addSubview(titleLabel)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 113
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let dic = data[indexPath.section]
let keyValue = dic[dic.startIndex]
let value = keyValue.1
let newsDetailVC = SKNewsDetailController()
newsDetailVC.newsListModel = value[indexPath.row]
navigationController?.pushViewController(newsDetailVC, animated: true)
}
}
| apache-2.0 | dd15f7a5e3aa0590b719869c6c48b4d4 | 30.812081 | 192 | 0.627004 | 4.963351 | false | false | false | false |
cao903775389/OLNetwork | OLNetwork/Classes/HttpNetwork/OLHttpRequestManager.swift | 1 | 19232 | //
// OLHttpRequestManager.swift
// BeautyHttpNetwork
//
// Created by 逢阳曹 on 2016/10/18.
// Copyright © 2016年 逢阳曹. All rights reserved.
//
import UIKit
import AFNetworking
import YYKit
//网络连接池
public class OLHttpRequestManager {
/**
* !@brief 单例方法
* @note 网络连接池
*/
public static let sharedOLHttpRequestManager: OLHttpRequestManager = OLHttpRequestManager()
//AFHTTPSessionManager
private var manager: AFHTTPSessionManager!
//请求配置信息
private var requestConfig: OLHttpConfiguration!
//请求缓存池
private var requestRecord: [NSNumber: OLHttpRequest]!
//AFJSONResponseSerializer
private lazy var jsonResponseSerializer: AFJSONResponseSerializer = {
let json = AFJSONResponseSerializer()
json.acceptableContentTypes = Set(["application/json", "text/json", "text/javascript","text/html", "application/x-javascript"])
return json
}()
//AFXMLResponseSerializer
private lazy var xmlResponseSerializer: AFXMLParserResponseSerializer = {
let xml = AFXMLParserResponseSerializer()
xml.acceptableContentTypes = Set(["application/json", "text/json", "text/javascript","text/html", "application/x-javascript"])
return xml
}()
//MARK: - 发送请求
//发起普通请求
public func sendHttpRequest(request: OLHttpRequest) {
self.sendHttpRequest(request: request, uploadProgressBlock: nil, downloadProgressBlock: nil)
}
//发起带有上传进度回调的请求
public func sendHttpRequest(request: OLHttpRequest, uploadProgressBlock: @escaping ((Progress) -> Void)) {
self.sendHttpRequest(request: request, uploadProgressBlock: uploadProgressBlock, downloadProgressBlock: nil)
}
//发起带有下载进度回调的请求
public func sendHttpRequest(request: OLHttpRequest, downloadProgressBlock: ((Progress) -> Void)?) {
self.sendHttpRequest(request: request, uploadProgressBlock: nil, downloadProgressBlock: downloadProgressBlock)
}
//取消某个请求
public func cancleHttpRequest(request: OLHttpRequest?) {
guard request?.requestTask != nil else { return }
if self.requestRecord[NSNumber(integerLiteral: request!.requestTask!.taskIdentifier)] != nil {
if request!.requestTask?.state == URLSessionTask.State.running {
print("========请求已取消: \(request!.requestCode)========")
request!.requestTask?.cancel()
self.removeRequestFromPool(request: request!)
}
}
}
//取消所有请求
public func cancleAllHttpRequests() {
let allKeys = self.requestRecord.keys
if allKeys.count > 0 {
let copiedKeys = allKeys
for key in copiedKeys {
let request = self.requestRecord[key]
request?.cancleDelegateAndRequest()
}
}
}
//MARK: Private
private init() {
self.requestConfig = OLHttpConfiguration.sharedOLHttpConfiguration
self.manager = AFHTTPSessionManager(baseURL: nil)
//给定一个默认的解析方式
self.manager.responseSerializer = AFHTTPResponseSerializer()
self.manager.responseSerializer.acceptableContentTypes = Set( ["application/json", "text/json", "text/javascript","text/html", "application/x-javascript"])
self.requestRecord = [:]
}
//添加请求到缓存池
private func addRequestToPool(request: OLHttpRequest) {
if request.requestTask != nil {
self.requestRecord[NSNumber(integerLiteral: request.requestTask!.taskIdentifier)] = request
}
}
//移除请求出缓存池
private func removeRequestFromPool(request: OLHttpRequest) {
self.requestRecord.removeValue(forKey: NSNumber(integerLiteral: request.requestTask!.taskIdentifier))
}
//请求状态码校验
private func ol_validateResult(request: OLHttpRequest) -> (Bool, NSError?) {
var result = OLHttpUtils.ol_statusCodeValidator(statusCode: request.statusCode!)
if !result {
return (result, NSError(domain: OLHttpRequestValidationErrorDomain, code: OLHttpRequestValidationError.InvalidStatusCode.rawValue, userInfo: [NSLocalizedDescriptionKey: OL_NetworkError]))
}
result = request.ol_requestCustomJSONValidator()
if !result {
return (result, NSError(domain: OLHttpRequestValidationErrorDomain, code: request.errorCode!, userInfo: [NSLocalizedDescriptionKey: request.errorMsg == nil ? OL_ServerError : request.errorMsg!]))
}
return (true, nil)
}
//HTTPStatusCode异常处理
private func handleResponseErrorCode(errorCode: Int) -> NSError {
var responseError: NSError?
if errorCode == NSURLErrorNotConnectedToInternet {
//网络不可用
responseError = NSError(domain: OLHttpRequestValidationErrorDomain, code: NSURLErrorNotConnectedToInternet, userInfo: [NSLocalizedDescriptionKey: OL_NetworkErrorNotConnectedToInternet])
}else if errorCode == NSURLErrorTimedOut {
//网络请求超时
responseError = NSError(domain: OLHttpRequestValidationErrorDomain, code: NSURLErrorTimedOut, userInfo: [NSLocalizedDescriptionKey: OL_NetworkErrorTimedOut])
}else {
//其他错误
responseError = NSError(domain: OLHttpRequestValidationErrorDomain, code: OLHttpRequestValidationError.InvalidStatusCode.rawValue, userInfo: [NSLocalizedDescriptionKey: OL_NetworkError])
}
return responseError!
}
//MARK: 请求发起相关
private func sendHttpRequest(request: OLHttpRequest, uploadProgressBlock: ((Progress) -> Void)?, downloadProgressBlock: ((Progress) -> Void)?) {
var requestSerializationError: NSError?
request.requestTask = self.sessionTaskForRequest(request: request, uploadProgressBlock: uploadProgressBlock, downloadProgressBlock: downloadProgressBlock ,error: &requestSerializationError)
if requestSerializationError != nil {
//请求失败
return
}
print("\n========\n========开始请求: url = \(request.requestUrl!)\n========请求模式: \(OLHttpConfiguration.sharedOLHttpConfiguration.requestMode!)\n========接口号: \(request.requestCode!.rawValue)\n========请求参数: \(String(describing: request.requestArgument))\n========")
//添加请求到缓存池
self.addRequestToPool(request: request)
request.requestTask?.resume()
}
//创建URLSessionTask会话
private func sessionTaskForRequest(request: OLHttpRequest, uploadProgressBlock: ((Progress) -> Void)?, downloadProgressBlock: ((Progress) -> Void)?, error: NSErrorPointer) -> URLSessionTask {
let url = request.requestUrl!
let method = request.requestMethod!
let requestSerializer = self.requestSerializerForRequest(request: request)
let param = request.requestArgument
switch method {
case .GET:
return self.dataTaskWithHTTPMethod(method: "GET", requestSerializer: requestSerializer, URLString: url, parameters: param, error: error)
case .POST:
return self.dataTaskWithHTTPMethod(method: "POST", requestSerializer: requestSerializer, URLString: url, parameters: param, error: error)
case .UPLOAD:
return self.dataTaskWithHTTPMethod(method: "POST", requestSerializer: requestSerializer, URLString: url, parameters: param, constructingBodyBlock: request.constructingBlock, uploadProgress: uploadProgressBlock, error: error)
case .DOWNLOAD:
return self.downloadTaskWithDownloadPath(downloadPath: request.resumableDownloadPath!, requestSerializer: requestSerializer, URLString: url, parameters: param, downloadProgressBlock: downloadProgressBlock, error: error)
}
}
//MARK: -
//NSURLSessionDataTask 普通请求
private func dataTaskWithHTTPMethod(method: String,
requestSerializer: AFHTTPRequestSerializer,
URLString: String,
parameters: [String: Any]?,
error: NSErrorPointer) -> URLSessionDataTask {
return self.dataTaskWithHTTPMethod(method: method, requestSerializer: requestSerializer, URLString: URLString, parameters: parameters, constructingBodyBlock: nil, uploadProgress: nil, error: error)
}
//NSURLSessionUploadTask 上传请求
private func dataTaskWithHTTPMethod(method: String,
requestSerializer: AFHTTPRequestSerializer,
URLString: String,
parameters: [String: Any]?,
constructingBodyBlock: ((AFMultipartFormData) -> Void)?,
uploadProgress: ((Progress) -> Void)?,
error: NSErrorPointer) -> URLSessionDataTask {
var request: NSURLRequest?
if constructingBodyBlock != nil {
request = requestSerializer.multipartFormRequest(withMethod: method, urlString: URLString, parameters: parameters, constructingBodyWith: constructingBodyBlock, error: error)
}else {
request = requestSerializer.request(withMethod: method, urlString: URLString, parameters: parameters, error: error)
}
var dataTask: URLSessionDataTask?
dataTask = manager.dataTask(with: request! as URLRequest, uploadProgress: uploadProgress, downloadProgress: nil) { (response, responseObject, error) in
self.handleRequestResult(task: dataTask!, responseObject: responseObject as AnyObject, error: error as NSError?)
}
return dataTask!
}
//NSURLSessionDownloadTask 下载请求
private func downloadTaskWithDownloadPath(downloadPath: String,
requestSerializer: AFHTTPRequestSerializer,
URLString: String,
parameters: [String: Any]?,
downloadProgressBlock: ((Progress) -> Void)?,
error: NSErrorPointer) -> URLSessionDownloadTask {
var downloadTargetPath: String?
let request = requestSerializer.request(withMethod: "GET", urlString: URLString, parameters: parameters, error: error)
var isDirectory: ObjCBool = false
if FileManager.default.fileExists(atPath: downloadPath, isDirectory: &isDirectory) == false {
isDirectory = false
}
//如果目标下载路径是一个文件夹 使用从url中获取到的最后路径名
//确保下载的目标路径是一个文件 而不是一个文件夹
if isDirectory.boolValue == true {
let fileName = request.url!.lastPathComponent as String
downloadTargetPath = NSString.path(withComponents: [downloadPath, fileName]) as String
}else {
downloadTargetPath = downloadPath
}
//判断本地是否有已下载的原始数据
var resumeDataFileExists: Bool = false
var data: Data?
let filePath = OLHttpUtils.incompletedDownloadTempPathForDownloadPath(downloadPath: downloadPath)
if filePath != nil {
resumeDataFileExists = FileManager.default.fileExists(atPath: filePath!.path)
try? data = Data(contentsOf: filePath!)
}
//判断已下载原始数据是否失效
let resumeDataIsValid = OLHttpUtils.validateResumeData(data: data)
//判断此下载任务是否可以被重新唤起
let canBeResumed: Bool = resumeDataFileExists && resumeDataIsValid
var downloadTask: URLSessionDownloadTask?
if canBeResumed {
downloadTask = manager.downloadTask(withResumeData: data!, progress: downloadProgressBlock, destination: { (targetPathURL, response) -> URL in
return URL(fileURLWithPath: downloadTargetPath!, isDirectory: false)
}, completionHandler: { (response, filePathURL, error) in
self.handleRequestResult(task: downloadTask!, responseObject: filePathURL as AnyObject, error: error as NSError?)
})
}else {
downloadTask = manager.downloadTask(with: request as URLRequest, progress: downloadProgressBlock, destination: { (targetPathURL, response) -> URL in
return URL(fileURLWithPath: downloadTargetPath!, isDirectory: false)
}, completionHandler: { (response, filePathURL, error) in
self.handleRequestResult(task: downloadTask!, responseObject: filePathURL as AnyObject, error: error as NSError?)
})
}
return downloadTask!
}
//获取请求的序列化方式
private func requestSerializerForRequest(request: OLHttpRequest) -> AFHTTPRequestSerializer {
var requestSerializer: AFHTTPRequestSerializer?
switch request.requestSerializerType! {
case .HTTP:
requestSerializer = AFHTTPRequestSerializer()
case .JSON:
requestSerializer = AFJSONRequestSerializer()
}
requestSerializer!.timeoutInterval = request.requestTimeoutInterval
//如果服务器请求需要用户名和密码进行认证操作
let authorizationHeaderFieldArray = request.requestAuthorizationHeaderFieldArray
if authorizationHeaderFieldArray != nil && authorizationHeaderFieldArray!.count > 2 {
requestSerializer?.setAuthorizationHeaderFieldWithUsername(authorizationHeaderFieldArray!.first!, password: authorizationHeaderFieldArray!.last!)
}
//如果服务器请求需要自定义HTTPHeaderField
let headerFieldValueDictionary = request.requestHeaders
if headerFieldValueDictionary != nil {
for httpHeaderFieldKey in headerFieldValueDictionary!.keys {
let httpHeaderFieldValue = headerFieldValueDictionary![httpHeaderFieldKey] as? String
requestSerializer?.setValue(httpHeaderFieldValue, forHTTPHeaderField: httpHeaderFieldKey)
}
}
return requestSerializer!
}
//处理请求回调
private func handleRequestResult(task: URLSessionTask, responseObject: AnyObject?, error: NSError?) {
let request = requestRecord[NSNumber(integerLiteral: task.taskIdentifier)]
if request == nil {
return
}
request!.responseObject = responseObject
if error != nil {
let responseError = self.handleResponseErrorCode(errorCode: error!.code)
self.requestDidFailWithRequest(request: request!, error: responseError)
self.removeRequestFromPool(request: request!)
return
}
if request?.responseObject == nil {
self.requestDidFailWithRequest(request: request!, error: NSError(domain: OLHttpRequestValidationErrorDomain, code: OLHttpRequestValidationError.InvalidJSONFormat.rawValue, userInfo: [NSLocalizedDescriptionKey: OL_ServerError]))
self.removeRequestFromPool(request: request!)
return
}
//请求错误信息
var requestError: NSError?
//JSON序列化错误信息
var serializationError: NSError?
//请求成功还是失败
var succees: Bool = false
switch request!.responseSerializerType! {
case .HTTP:
//默认方式
break
case .JSON:
request?.responseObject = self.jsonResponseSerializer.responseObject(for: task.response, data: request!.responseObject as? Data, error: &serializationError) as AnyObject
break
case .XML:
request?.responseObject = self.xmlResponseSerializer.responseObject(for: task.response, data: request!.responseObject as? Data, error: &serializationError) as AnyObject
break
}
if serializationError != nil {
succees = false
requestError = NSError(domain: OLHttpRequestValidationErrorDomain, code: OLHttpRequestValidationError.InvalidJSONFormat.rawValue, userInfo: [NSLocalizedDescriptionKey: OL_ServerError])
}else {
let validateResult = self.ol_validateResult(request: request!)
succees = validateResult.0
requestError = validateResult.1
}
if succees {
self.requestDidSucceedWithRequest(request: request!)
} else {
self.requestDidFailWithRequest(request: request!, error: requestError!)
}
self.removeRequestFromPool(request: request!)
}
//MARK: - 请求回调
private func requestDidFailWithRequest(request: OLHttpRequest, error: NSError) {
request.errorCode = error.code
request.errorMsg = error.userInfo[NSLocalizedDescriptionKey] as? String
print("\n========\n========请求失败: url = \(request.requestUrl!)\n========请求模式: \(OLHttpConfiguration.sharedOLHttpConfiguration.requestMode!)\n========接口号: \(request.requestCode!.rawValue)\n========请求参数: \(String(describing: request.requestArgument))\n========错误信息: \(String(describing: request.errorMsg))\n========错误码: \(String(describing: request.errorCode))\n========URLResponseStatusCode状态码: \(String(describing: request.statusCode))\n========")
let incompleteDownloadData = error.userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
if incompleteDownloadData != nil && request.resumableDownloadPath != nil {
let path = OLHttpUtils.incompletedDownloadTempPathForDownloadPath(downloadPath: request.resumableDownloadPath!)
if path != nil {
incompleteDownloadData?.write(to: path! as URL, atomically: true)
}
}
request.delegate?.ol_requestFailed(request: request)
}
private func requestDidSucceedWithRequest(request: OLHttpRequest) {
print("\n========\n========请求成功: url = \(request.requestUrl!)\n========请求模式: \(OLHttpConfiguration.sharedOLHttpConfiguration.requestMode!)\n========接口号: \(request.requestCode!.rawValue)\n========请求参数: \(String(describing: request.requestArgument))\n========返回JSON: \n\(String(describing: request.responseObject!.modelToJSONString()))\n========错误码: \(String(describing: request.errorCode))\n========URLResponseStatusCode状态码: \(String(describing: request.statusCode))\n========")
request.delegate?.ol_requestFinished(request: request)
}
}
| mit | 7ae89afcaa596ac30be29bd42f9f15fd | 47.856764 | 485 | 0.650144 | 5.331114 | false | false | false | false |
vicentesuarez/AlertHubController | AlertHubController/AlertHubController/AlertHubSize.swift | 1 | 468 | //
// AlertHubSize.swift
// AlertHubControllerDemo
//
// Created by Vicente Suarez on 2/1/17.
// Copyright © 2017 Vicente Suarez. All rights reserved.
//
import UIKit
struct AlertHubSize {
static let loadingLength: CGFloat = 100.0
static let alertBottom: CGFloat = -8.0
static let alertTop: CGFloat = 28.0
static let alertWidth: CGFloat = 304.0
static let alertSideInset: CGFloat = 16.0
static let alertWidthMultiplier: CGFloat = 0.75
}
| mit | 298196ef39afc7f2d59bbc5ff54c1467 | 24.944444 | 57 | 0.706638 | 3.592308 | false | false | false | false |
adrfer/swift | test/IRGen/Inputs/ObjectiveC.swift | 12 | 1186 | // This is an overlay Swift module.
@_exported import ObjectiveC
public struct ObjCBool : CustomStringConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
private var value: Int8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
return value != 0
}
#else
// Everywhere else it is C/C++'s "Bool"
private var value: Bool
public init(_ value: Bool) {
self.value = value
}
public var boolValue: Bool {
return value
}
#endif
public var description: String {
// Dispatch to Bool.
return self.boolValue.description
}
}
public struct Selector {
private var ptr : COpaquePointer
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
public func _convertBoolToObjCBool(x: Bool) -> ObjCBool {
return ObjCBool(x)
}
public func _convertObjCBoolToBool(x: ObjCBool) -> Bool {
return x.boolValue
}
extension NSObject : Hashable {
public var hashValue: Int { return 0 }
}
public func ==(x: NSObject, y: NSObject) -> Bool { return x === y }
| apache-2.0 | 5a70405891d1e9dd4f8ce3c609b26a45 | 21.377358 | 75 | 0.669477 | 3.753165 | false | false | false | false |
elationfoundation/Reporta-iOS | IWMF/TableViewCell/FreelancerTableViewCell.swift | 1 | 1555 | //
// FreelancerTableViewCell.swift
// IWMF
//
//
//
//
import UIKit
protocol FreelancerBtProtocol{
func freelancerButtonClicked(isSelected : NSNumber)
}
class FreelancerTableViewCell: UITableViewCell {
@IBOutlet weak var okImage: UIImageView!
@IBOutlet weak var freelancerBtn: UIButton!
var delegate : FreelancerBtProtocol!
var isSelectedValue : Bool!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func freelancerBtnClicked(sender: AnyObject) {
if(isSelectedValue == true){
isSelectedValue = false
self.okImage.image = UIImage(named: "Uncheck")
}else{
isSelectedValue = true
self.okImage.image = UIImage(named: "ok")
}
delegate?.freelancerButtonClicked(NSNumber(bool: isSelectedValue))
}
func initialize(){
freelancerBtn.setTitle(NSLocalizedString(Utility.getKey("Freelancer"),comment:""), forState: .Normal)
self.freelancerBtn.titleLabel?.font = Utility.setFont()
self.okImage.hidden = false
if(isSelectedValue == true)
{
self.okImage.image = UIImage(named: "ok")
}
else
{
self.okImage.image = UIImage(named: "Uncheck")
}
}
}
| gpl-3.0 | dababc33a2dc881bd0605768ac285b75 | 24.080645 | 109 | 0.610289 | 4.655689 | false | false | false | false |
manGoweb/S3 | Tests/S3Tests/S3Tests.swift | 1 | 10017 | @testable import S3Signer
import XCTest
class S3Tests: BaseTestCase {
static var allTests = [
("test_Get_Object", test_Get_Object),
("test_Put_Object", test_Put_Object),
("test_Get_bucket_lifecycle", test_Get_bucket_lifecycle),
("test_Get_bucket_list_object", test_Get_bucket_list_object),
("test_Presigned_URL_V4", test_Presigned_URL_V4)
]
// S3 example signature calcuations
// https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html#example-signature-calculations
func test_Get_Object() {
let requestURL = URL(string: "https://examplebucket.s3.amazonaws.com/test.txt")!
let updatedHeaders = signer.update(
headers: ["Range": "bytes=0-9"],
url: requestURL,
longDate: overridenDate.long,
bodyDigest: Payload.none.hashed(),
region: region
)
let expectedCanonRequest = [
"GET",
"/test.txt",
"",
"host:examplebucket.s3.amazonaws.com",
"range:bytes=0-9",
"x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"x-amz-date:20130524T000000Z",
"",
"host;range;x-amz-content-sha256;x-amz-date",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
].joined(separator: "\n")
let canonRequest = try! signer.createCanonicalRequest(.GET, url: requestURL, headers: updatedHeaders, bodyDigest: Payload.none.hashed())
XCTAssertEqual(expectedCanonRequest, canonRequest)
let expectedStringToSign = [
"AWS4-HMAC-SHA256",
"20130524T000000Z",
"20130524/us-east-1/s3/aws4_request",
"7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972"
].joined(separator: "\n")
let stringToSign = try! signer.createStringToSign(canonRequest, dates: overridenDate, region: region)
XCTAssertEqual(expectedStringToSign, stringToSign)
let expectedSignature = "f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
let signature = try! signer.createSignature(stringToSign, timeStampShort: overridenDate.short, region: region)
XCTAssertEqual(expectedSignature, signature)
let expectedAuthHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
let authHeader = try! signer.generateAuthHeader(.GET, url: requestURL, headers: updatedHeaders, bodyDigest: Payload.none.hashed(), dates: overridenDate, region: region)
XCTAssertEqual(expectedAuthHeader, authHeader)
}
func test_Put_Object() {
guard let requestURL = URL(string: "https://examplebucket.s3.amazonaws.com/test$file.text"),
let bytes = "Welcome to Amazon S3.".data(using: .utf8) else {
XCTFail("Could not intialize request/data")
return
}
let payload = Payload.bytes(bytes).hashed()
let updatedHeaders = signer.update(headers: ["x-amz-storage-class": "REDUCED_REDUNDANCY", "Date": "Fri, 24 May 2013 00:00:00 GMT"], url: requestURL, longDate: overridenDate.long, bodyDigest: payload, region: region)
let expectedCanonRequest = [
"PUT",
"/test%24file.text",
"",
"date:Fri, 24 May 2013 00:00:00 GMT",
"host:examplebucket.s3.amazonaws.com",
"x-amz-content-sha256:44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072",
"x-amz-date:20130524T000000Z",
"x-amz-storage-class:REDUCED_REDUNDANCY",
"",
"date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class",
"44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072"
].joined(separator: "\n")
let canonRequest = try! signer.createCanonicalRequest(.PUT, url: requestURL, headers: updatedHeaders, bodyDigest: payload)
XCTAssertEqual(expectedCanonRequest, canonRequest)
let expectedStringToSign = [
"AWS4-HMAC-SHA256",
"20130524T000000Z",
"20130524/us-east-1/s3/aws4_request",
"9e0e90d9c76de8fa5b200d8c849cd5b8dc7a3be3951ddb7f6a76b4158342019d"
].joined(separator: "\n")
let stringToSign = try! signer.createStringToSign(canonRequest, dates: overridenDate, region: region)
XCTAssertEqual(expectedStringToSign, stringToSign)
let expectedSignature = "98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"
let signature = try! signer.createSignature(stringToSign, timeStampShort: overridenDate.short, region: region)
XCTAssertEqual(expectedSignature, signature)
let expectedAuthHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class, Signature=98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"
let authHeader = try! signer.generateAuthHeader(.PUT, url: requestURL, headers: updatedHeaders, bodyDigest: payload, dates: overridenDate, region: region)
XCTAssertEqual(expectedAuthHeader, authHeader)
}
func test_Get_bucket_lifecycle() {
let requestURL = URL(string: "https://examplebucket.s3.amazonaws.com?lifecycle")!
let payload = Payload.none.hashed()
let updatedHeaders = signer.update(headers: [:], url: requestURL, longDate: overridenDate.long, bodyDigest: payload, region: region)
let expectedCanonRequest = [
"GET",
"/",
"lifecycle=",
"host:examplebucket.s3.amazonaws.com",
"x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"x-amz-date:20130524T000000Z",
"",
"host;x-amz-content-sha256;x-amz-date",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
].joined(separator: "\n")
let canonRequest = try! signer.createCanonicalRequest(.GET, url: requestURL, headers: updatedHeaders, bodyDigest: payload)
XCTAssertEqual(expectedCanonRequest, canonRequest)
let expectedAuthHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=fea454ca298b7da1c68078a5d1bdbfbbe0d65c699e0f91ac7a200a0136783543"
let authHeader = try! signer.generateAuthHeader(.GET, url: requestURL, headers: updatedHeaders, bodyDigest: payload, dates: overridenDate, region: region)
XCTAssertEqual(expectedAuthHeader, authHeader)
}
func test_Get_bucket_list_object() {
let requestURL = URL(string: "https://examplebucket.s3.amazonaws.com/?max-keys=2&prefix=J")!
let payload = Payload.none.hashed()
let updatedHeaders = signer.update(headers: [:], url: requestURL, longDate: overridenDate.long, bodyDigest: payload, region: region)
let expectedCanonRequest = [
"GET",
"/",
"max-keys=2&prefix=J",
"host:examplebucket.s3.amazonaws.com",
"x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"x-amz-date:20130524T000000Z",
"",
"host;x-amz-content-sha256;x-amz-date",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
].joined(separator: "\n")
let canonRequest = try! signer.createCanonicalRequest(.GET, url: requestURL, headers: updatedHeaders, bodyDigest: payload)
XCTAssertEqual(expectedCanonRequest, canonRequest)
let expectedAuthHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"
let authHeader = try! signer.generateAuthHeader(.GET, url: requestURL, headers: updatedHeaders, bodyDigest: payload, dates: overridenDate, region: region)
XCTAssertEqual(expectedAuthHeader, authHeader)
}
// Taken from https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
func test_Presigned_URL_V4() {
let requestURL = URL(string: "https://examplebucket.s3.amazonaws.com/test.txt")!
let expectedCanonRequest = [
"GET",
"/test.txt",
"X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20130524T000000Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host",
"host:examplebucket.s3.amazonaws.com",
"",
"host",
"UNSIGNED-PAYLOAD"
].joined(separator: "\n")
let (canonRequest, _) = try! signer.presignedURLCanonRequest(.GET, dates: overridenDate, expiration: Expiration.custom(86400), url: requestURL, region: region, headers: ["Host": requestURL.host ?? Region.usEast1.host])
XCTAssertEqual(expectedCanonRequest, canonRequest)
let expectedStringToSign = [
"AWS4-HMAC-SHA256",
"20130524T000000Z",
"20130524/us-east-1/s3/aws4_request",
"3bfa292879f6447bbcda7001decf97f4a54dc650c8942174ae0a9121cf58ad04"
// "414cf5ed57126f2233fac1f7b5e5e4b8dcf58040010cb69d21f126d353d13df7"
].joined(separator: "\n")
let stringToSign = try! signer.createStringToSign(canonRequest, dates: overridenDate, region: region)
NSLog("expectedStringToSign: \(expectedStringToSign)")
NSLog("stringToSign: \(stringToSign)")
XCTAssertEqual(expectedStringToSign, stringToSign)
// let expectedSignature = "17594f59285415a5be4debfcf5227a2d78b7c2634442b7ab816cace9333ec989"
let expectedSignature = "aeeed9bbccd4d02ee5c0109b86d86835f995330da4c265957d157751f604d404"
let signature = try! signer.createSignature(stringToSign, timeStampShort: overridenDate.short, region: region)
XCTAssertEqual(expectedSignature, signature)
let expectedURLString = "https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20130524T000000Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=17594f59285415a5be4debfcf5227a2d78b7c2634442b7ab816cace9333ec989"
let presignedURL = try! signer.presignedURL(for: .GET, url: requestURL, expiration: Expiration.custom(86400), region: region, headers: [:], dates: overridenDate)
XCTAssertEqual(expectedURLString, presignedURL?.absoluteString)
}
}
| mit | 57aa440db1672d8c4b25f6d8eaf0d20e | 43.919283 | 343 | 0.756214 | 2.938398 | false | true | false | false |
macostea/appcluj-expenses-ios | Alamofire-master/Source/Alamofire.swift | 1 | 66064 | // Alamofire.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Alamofire errors
public let AlamofireErrorDomain = "com.alamofire.error"
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)
}
}
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
*/
public protocol URLStringConvertible {
/// The URL string.
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString!
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest {
return self
}
}
// MARK: -
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
*/
public class var sharedInstance: Manager {
struct Singleton {
static var configuration: NSURLSessionConfiguration = {
var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = {
// Accept-Encoding HTTP Header; see http://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return join(",", components)
}()
// User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}()
return configuration
}()
static let instance = Manager(configuration: configuration)
}
return Singleton.instance
}
private let delegate: SessionDelegate
private let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
:param: configuration The configuration used to construct the managed session.
*/
required public init(configuration: NSURLSessionConfiguration? = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}
deinit {
self.session.invalidateAndCancel()
}
// MARK: -
/**
Creates a request for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask?
dispatch_sync(queue) {
dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
}
let request = Request(session: session, task: dataTask!)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) {
subdelegate = self.subdelegates[task.taskIdentifier]
}
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if sessionDidReceiveChallenge != nil {
completionHandler(sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
private let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress? { return delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
/**
Associates an HTTP Basic credential with the request.
:param: user The user.
:param: password The password.
:returns: The request.
*/
public func authenticate(#user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
:param: credential The credential.
:returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
/**
A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
*/
public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public class func responseDataSerializer() -> Serializer {
return { (request, response, data) in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(Request.responseDataSerializer(), completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: serializer The closure responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(delegate.queue) {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
}
}
return self
}
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t
let progress: NSProgress
var data: NSData? { return nil }
private(set) var error: NSError?
var credential: NSURLCredential?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
return queue
}()
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if taskDidReceiveChallenge != nil {
(disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
switch challenge.protectionSpace.authenticationMethod! {
case NSURLAuthenticationMethodServerTrust:
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
default:
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
}
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if taskNeedNewBodyStream != nil {
bodyStream = taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if error != nil {
self.error = error
}
dispatch_resume(queue)
}
}
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData? {
return mutableData
}
private var expectedContentLength: Int64?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
dataTaskDidReceiveData?(session, dataTask, data)
mutableData.appendData(data)
if let expectedContentLength = dataTask?.response?.expectedContentLength {
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
}
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Validation
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
dispatch_async(delegate.queue) {
if self.response != nil && self.delegate.error == nil {
if !validation(self.request, self.response!) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
}
return self
}
// MARK: Status Code
private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
return contains(statusCodes, response.statusCode)
}
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate(statusCode range: Range<Int>) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
}
}
/**
Validates that the response has a status code in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: array The acceptable status codes.
:returns: The request.
*/
public func validate(statusCode array: [Int]) -> Self {
return validate { (_, response) in
return Request.response(response, hasAcceptableStatusCode: array)
}
}
// MARK: Content-Type
private struct MIMEType {
let type: String
let subtype: String
init(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
self.type = components.first!
self.subtype = components.last!
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case ("*", "*"), ("*", MIME.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
return true
default:
return false
}
}
}
private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
if response.MIMEType != nil {
let responseMIMEType = MIMEType(response.MIMEType!)
for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
if acceptableMIMEType.matches(responseMIMEType) {
return true
}
}
}
return false
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate(contentType array: [String]) -> Self {
return validate {(_, response) in
return Request.response(response, hasAcceptableContentType: array)
}
}
// MARK: Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
// MARK: - Upload
extension Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Request {
var uploadTask: NSURLSessionUploadTask!
var HTTPBodyStream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = session.uploadTaskWithStreamedRequest(request)
HTTPBodyStream = stream
}
let request = Request(session: session, task: uploadTask)
if HTTPBodyStream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return HTTPBodyStream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: file The file to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return upload(.File(URLRequest.URLRequest, file))
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: data The data to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return upload(.Data(URLRequest.URLRequest, data))
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: stream The stream to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return upload(.Stream(URLRequest.URLRequest, stream))
}
}
extension Request {
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if uploadProgress != nil {
uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
}
}
}
// MARK: - Download
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = session.downloadTaskWithResumeData(resumeData)
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if downloadTaskDidFinishDownloadingToURL != nil {
let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: - Printable
extension Request: Printable {
/// The textual representation used when written to an `OutputStreamType`, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if request.HTTPMethod != nil {
components.append(request.HTTPMethod!)
}
components.append(request.URL.absoluteString!)
if response != nil {
components.append("(\(response!.statusCode))")
}
return join(" ", components)
}
}
extension Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
components.append("-X \(request.HTTPMethod!)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port?.integerValue ?? 0, `protocol`: URL.scheme!, realm: URL.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
if let cookieStorage = session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
if request.allHTTPHeaderFields != nil {
for (field, value) in request.allHTTPHeaderFields! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if session.configuration.HTTPAdditionalHeaders != nil {
for (field, value) in session.configuration.HTTPAdditionalHeaders! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let HTTPBody = request.HTTPBody {
if let escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") {
components.append("-d \"\(escapedBody)\"")
}
}
components.append("\"\(URL.absoluteString!)\"")
return join(" \\\n\t", components)
}
/// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:returns: A string response serializer.
*/
public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
return { (_, _, data) in
let string = NSString(data: data!, encoding: encoding)
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
return { (request, response, data) in
if data == nil {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
return { (request, response, data) in
if data == nil {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience -
private func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
// MARK: - Request
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
:param: URLRequest The URL request.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
:param: URLRequest The URL request.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
:param: URLRequest The URL request.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: - Download
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
:param: URLRequest The URL request.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
}
| mit | 349ea2ea47498094116291256dac4d95 | 39.98263 | 555 | 0.664053 | 5.724287 | false | false | false | false |
duliodenis/benji | benji/benji/ViewController.swift | 1 | 2058 | //
// ViewController.swift
// benji
//
// Created by Dulio Denis on 2/4/15.
// Copyright (c) 2015 ddApps. All rights reserved.
//
import UIKit
class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {
@IBOutlet weak var welcomeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Savings"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if PFUser.currentUser() == nil {
let login = PFLogInViewController()
let signup = PFSignUpViewController()
login.fields = PFLogInFields.UsernameAndPassword | PFLogInFields.SignUpButton | PFLogInFields.LogInButton |
PFLogInFields.PasswordForgotten
login.delegate = self
signup.delegate = self
login.signUpController = signup
self.presentViewController(login, animated: true, completion: nil)
} else {
var username = PFUser.currentUser().username
welcomeLabel.text = username
}
}
func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
var account = PFObject(className: "transactions")
account["accountholder"] = PFUser.currentUser()
user.saveInBackgroundWithBlock{(success:Bool!, error:NSError!) -> Void in
if success != nil {
NSLog("Success")
self.dismissViewControllerAnimated(true, completion: nil)
} else {
NSLog("%@", error)
}
}
}
func logInViewController(logInController: PFLogInViewController!, didLogInUser user: PFUser!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewControllerDidCancelSignUp(signUpController: PFSignUpViewController!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | ead100782faf6f654815751f14999c8a | 31.15625 | 119 | 0.62828 | 5.700831 | false | false | false | false |
brentsimmons/Evergreen | Mac/Preferences/Accounts/AccountCell.swift | 1 | 940 | //
// AccountCell.swift
// NetNewsWire
//
// Created by Maurice Parker on 11/19/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import AppKit
class AccountCell: NSTableCellView {
private var originalImage: NSImage?
var isImageTemplateCapable = true
override func prepareForReuse() {
originalImage = nil
}
override var backgroundStyle: NSView.BackgroundStyle {
didSet {
updateImage()
}
}
}
private extension AccountCell {
func updateImage() {
guard isImageTemplateCapable else { return }
if backgroundStyle != .normal {
guard !(imageView?.image?.isTemplate ?? false) else { return }
originalImage = imageView?.image
let templateImage = imageView?.image?.copy() as? NSImage
templateImage?.isTemplate = true
imageView?.image = templateImage
} else {
guard let originalImage = originalImage else { return }
imageView?.image = originalImage
}
}
}
| mit | 5140176adf4537f5fbead9914d3f778e | 18.5625 | 65 | 0.699681 | 4.064935 | false | false | false | false |
robpeach/test | SwiftPages/AboutVC.swift | 1 | 3351 | //
// AboutVC.swift
// Britannia v2
//
// Created by Rob Mellor on 10/08/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import Foundation
import MessageUI
class AboutVC: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func findusButton(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/?address=198,HighStreet,Scunthorpe.DN156EA")!)
}
@IBAction func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.view.window!.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil)
})
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("")
mailComposerVC.setMessageBody("Sent from The Britannia App - We aim to reply within 24 hours.", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func movetoChatBtn(sender: AnyObject) {
print("button pressed")
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : ChatVC = storyboard.instantiateViewControllerWithIdentifier("ChatView") as! ChatVC
// vc.teststring = "hello"
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 7a77630c8dbfefc34728554464215797 | 33.183673 | 213 | 0.676119 | 5.564784 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Tests/EurofurenceKitTests/Model Ingestion/WellKnownTagTests.swift | 1 | 4002 | import CoreData
@testable import EurofurenceKit
import XCTest
class WellKnownTagTests: EurofurenceKitTestCase {
func testSponsorOnly() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "sponsors_only", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.sponsorOnly))
}
func testSuperSponsorOnly() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "supersponsors_only", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.superSponsorOnly))
}
func testArtShow() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "art_show", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.artShow))
}
func testKage() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "kage", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.kage))
}
func testDealersDen() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "dealers_den", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.dealersDen))
}
func testMainStage() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "main_stage", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.mainStage))
}
func testPhotoshoot() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "photoshoot", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.photoshoot))
}
func testFaceMaskRequired() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let eventWithTag = try self.eventWithTag(named: "mask_required", in: scenario.viewContext)
XCTAssertTrue(eventWithTag.canonicalTags.contains(.faceMaskRequired))
}
func testTagsReturnedInAlphabeticalOrder() async throws {
let scenario = await EurofurenceModelTestBuilder().build()
try await scenario.updateLocalStore(using: .ef26)
let dealersDenID = "18ab1606-506e-4b7c-b1db-4d3dad0e7c20"
let dealersDen = try scenario.model.event(identifiedBy: dealersDenID)
let expected: [CanonicalTag] = [.sponsorOnly, .superSponsorOnly, .faceMaskRequired]
XCTAssertEqual(expected, dealersDen.canonicalTags, "Expected tags to be ordered alphabetically")
}
private func eventWithTag(named name: String, in managedObjectContext: NSManagedObjectContext) throws -> Event {
let fetchRequest: NSFetchRequest<Event> = Event.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "SELF.tags.name CONTAINS %@", name)
fetchRequest.fetchLimit = 1
let matches = try managedObjectContext.fetch(fetchRequest)
let eventWithTag = try XCTUnwrap(matches.first)
return eventWithTag
}
}
| mit | 17985bc3ad13d8bab4d4b047a1db42e2 | 42.5 | 116 | 0.695902 | 4.959108 | false | true | false | false |
edjiang/forward-swift-workshop | SwiftNotesIOS/Pods/Stormpath/Stormpath/Core/Stormpath.swift | 1 | 8003 | //
// Stormpath.swift
// Stormpath
//
// Created by Adis on 16/11/15.
// Copyright © 2015 Stormpath. All rights reserved.
//
import Foundation
/// Callback for Stormpath API responses that respond with a success/fail.
public typealias StormpathSuccessCallback = (Bool, NSError?) -> Void
/// Callback for Stormpath API responses that respond with an account object.
public typealias StormpathAccountCallback = (Account?, NSError?) -> Void
/**
Stormpath represents the state of the application's connection to the Stormpath
Framework server. It allows you to connect to the Stormpath Framework
Integration API, register, login, and stores the current account's access and
refresh tokens securely. All callbacks to the application are handled on the
main thread.
*/
public final class Stormpath: NSObject {
/// Singleton representing the primary Stormpath instance using the default configuration.
public static let sharedSession = Stormpath(identifier: "default")
/// Configuration parameter for the Stormpath object. Can be changed.
public var configuration = StormpathConfiguration.defaultConfiguration
/// Reference to the API Service.
var apiService: APIService!
/// Reference to the Social Login Service.
var socialLoginService: SocialLoginService!
/// Reference to the Keychain Service.
var keychain: KeychainService!
/**
Initializes the Stormpath object with a default configuration. The
identifier is used to namespace the current state of the object, so that on
future loads we can find the saved credentials from the right location. The
default identifier is "default".
*/
public init(identifier: String) {
super.init()
apiService = APIService(withStormpath: self)
keychain = KeychainService(withIdentifier: identifier)
socialLoginService = SocialLoginService(withStormpath: self)
}
/**
This method registers an account from the data provided.
- parameters:
- account: A Registration Model object with the account data you want to
register.
- completionHandler: The completion block to be invoked after the API
request is finished. It returns an account object.
*/
public func register(account: RegistrationModel, completionHandler: StormpathAccountCallback? = nil) {
apiService.register(newAccount: account, completionHandler: completionHandler)
}
/**
Logs in an account and assumes that the login path is behind the /login
relative path. This method also stores the account session tokens for later
use.
- parameters:
- username: Account's email or username.
- password: Account password.
- completionHandler: The completion block to be invoked after the API
request is finished. If the method fails, the error will be passed in
the completion.
*/
public func login(username: String, password: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.login(username, password: password, completionHandler: completionHandler)
}
/**
Begins a login flow with a social provider, presenting or opening up Safari
(iOS8) to handle login. This WILL NOT call back if the user clicks "cancel"
on the login screen, as they never began the login process in the first
place.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you
have an access token
- completionHandler: Callback on success or failure
*/
public func login(socialProvider provider: StormpathSocialProvider, completionHandler: StormpathSuccessCallback? = nil) {
socialLoginService.beginLoginFlow(provider, completionHandler: completionHandler)
}
/**
Logs in an account if you have an access token from a social provider.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you
have an access token
- accessToken: String containing the access token
- completionHandler: A block of code that is called back on success or
failure.
*/
public func login(socialProvider provider: StormpathSocialProvider, accessToken: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.login(socialProvider: provider, accessToken: accessToken, completionHandler: completionHandler)
}
/**
Logs in an account if you have an authorization code from a social provider.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you have
an access token
- authorizationCode: String containing the authorization code
- completionHandler: A block of code that is called back on success or
failure.
*/
// Making this internal for now, since we don't support auth codes for FB /
// Google
func login(socialProvider provider: StormpathSocialProvider, authorizationCode: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.login(socialProvider: provider, authorizationCode: authorizationCode, completionHandler: completionHandler)
}
/**
Fetches the account data, and returns it in the form of a dictionary.
- parameters:
- completionHandler: Completion block invoked
*/
public func me(completionHandler: StormpathAccountCallback? = nil) {
apiService.me(completionHandler)
}
/**
Logs out the account and clears the sessions tokens.
*/
public func logout() {
apiService.logout()
}
// MARK: Account password reset
/**
Generates an account password reset token and sends an email to the user,
if such email exists.
- parameters:
- email: Account email. Usually from an input.
- completionHandler: The completion block to be invoked after the API
request is finished. This will always succeed if the API call is
successful.
*/
public func resetPassword(email: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.resetPassword(email, completionHandler: completionHandler)
}
/// Deep link handler (iOS9)
public func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
return socialLoginService.handleCallbackURL(url)
}
/// Deep link handler (<iOS9)
public func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return self.application(application, openURL: url, options: [String: AnyObject]())
}
/**
Provides the last access token fetched by either login or
refreshAccessToken functions. The validity of the token is not verified
upon fetching!
- returns: Access token for your API calls.
*/
internal(set) public var accessToken: String? {
get {
return keychain.accessToken
}
set {
keychain.accessToken = newValue
}
}
/// Refresh token for the current account.
internal(set) public var refreshToken: String? {
get {
return keychain.refreshToken
}
set {
keychain.refreshToken = newValue
}
}
/**
Refreshes the access token and stores it to be available via accessToken
var. Call this function if your token expires.
- parameters:
- completionHandler: Block invoked on function completion. It will have
either a new access token passed as a string, or an error if one
occurred.
*/
public func refreshAccessToken(completionHandler: StormpathSuccessCallback? = nil) {
apiService.refreshAccessToken(completionHandler)
}
} | apache-2.0 | 7ca58dc222991d83db50bfdf6f2b775f | 36.92891 | 146 | 0.684829 | 5.309887 | false | false | false | false |
tingkerians/master | doharmony/SaveProjectController.swift | 1 | 3007 | //
// SaveProjectController.swift
// doharmony
//
// Created by Daryl Super Duper Handsum on 08/03/2016.
// Copyright © 2016 Eleazer Toluan. All rights reserved.
//
import UIKit
import AVFoundation
class SaveProjectController: UIViewController, mergeDelegate, cropDelegate {
//title description thumbnail collab
@IBOutlet weak var projectTitle: UITextField!
@IBOutlet weak var projectDescription: UITextField!
@IBOutlet weak var contributors: UITextField!
var db = RecordingData()
var Layout:UIView!
var croppedAssets:[AVAsset] = []
var duration:CMTime = kCMTimeZero
var cropProgress:[Bool] = []
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var progressLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func save(sender: AnyObject) {
cropProgress = []
for frame in Layout.subviews{
let tag = frame.tag
let record = db.fetch("Recordings", predicate: NSPredicate(format: "tag == %ld", NSInteger(tag)))
if record.count>0 {
let filename = record[0].valueForKey("record") as! String
let filePath = env.documentFolder.stringByAppendingPathComponent("\(filename)")
let fileURL = NSURL(fileURLWithPath: filePath)
let Cropper = Crop()
Cropper.delegate = self
Cropper.crop(fileURL, frame: frame, filename: filename)
cropProgress.append(false)
}
}
}
@IBAction func closeWindow(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func didFinishCropping(frameTag: Int, cropOutputFileURL: NSURL) {
cropProgress[frameTag] = true
croppedAssets.append(AVAsset(URL: cropOutputFileURL))
var alldone:Bool = true
for var index = 0; index < cropProgress.count; index++ {
if cropProgress[index] == false {
alldone = false
}
}
if alldone == true{
print(Layout.subviews.count, croppedAssets.count, cropProgress.count)
for asset in self.croppedAssets{
if CMTimeCompare(asset.duration, self.duration) == 1{
self.duration = asset.duration
}
}
Merge().exportSingleVideo(self.Layout, assets: self.croppedAssets, duration: self.duration)
}
}
func mergeSuccess(outputFileURL: NSURL) {
let title = NSString(string: projectTitle.text!)
let trackPath = NSString(string: outputFileURL.absoluteString)
let insert = ["title":title,"trackPath":trackPath]
RecordingData().insert("Tracks", values: insert)
}
}
| unlicense | 28d432537c43e6abc63dad0e763a5df4 | 33.551724 | 109 | 0.620093 | 4.801917 | false | false | false | false |
aaronraimist/firefox-ios | XCUITests/ThirdPartySearchTest.swift | 1 | 4705 | /* 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 XCTest
class ThirdPartySearchTest: BaseTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testCustomSearchEngines() {
let app = XCUIApplication()
// Visit MDN to add a custom search engine
loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true)
app.webViews.textFields.elementBoundByIndex(0).tap()
app.buttons["AddSearch"].tap()
app.alerts["Add Search Provider?"].collectionViews.buttons["OK"].tap()
XCTAssertFalse(app.buttons["AddSearch"].enabled)
app.buttons["Done"].tap()
// Perform a search using a custom search engine
app.buttons["URLBarView.tabsButton"].tap()
app.buttons["TabTrayController.addTabButton"].tap()
app.textFields["url"].tap()
app.typeText("window")
app.scrollViews.otherElements.buttons["developer.mozilla.org search"].tap()
// Ensure that the search is done on MDN
let url = app.textFields["url"].value as! String
XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default")
}
func testCustomSearchEngineAsDefault() {
let app = XCUIApplication()
// Visit MDN to add a custom search engine
loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true)
app.webViews.textFields.elementBoundByIndex(0).tap()
app.buttons["AddSearch"].tap()
app.alerts["Add Search Provider?"].collectionViews.buttons["OK"].tap()
XCTAssertFalse(app.buttons["AddSearch"].enabled)
app.buttons["Done"].tap()
// Go to settings and set MDN as the default
app.buttons["URLBarView.tabsButton"].tap()
app.buttons["TabTrayController.menuButton"].tap()
app.collectionViews.cells["Settings"].tap()
let tablesQuery = app.tables
tablesQuery.cells["Search"].tap()
tablesQuery.cells.elementBoundByIndex(0).tap()
tablesQuery.staticTexts["developer.mozilla.org"].tap()
app.navigationBars["Search"].buttons["Settings"].tap()
app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap()
// Perform a search to check
app.buttons["TabTrayController.addTabButton"].tap()
app.textFields["url"].tap()
app.typeText("window\r")
// Ensure that the default search is MDN
let url = app.textFields["url"].value as! String
XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default")
}
func testCustomSearchEngineDeletion() {
let app = XCUIApplication()
// Visit MDN to add a custom search engine
loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true)
app.webViews.textFields.elementBoundByIndex(0).tap()
app.buttons["AddSearch"].tap()
app.alerts["Add Search Provider?"].collectionViews.buttons["OK"].tap()
XCTAssertFalse(app.buttons["AddSearch"].enabled)
app.buttons["Done"].tap()
app.buttons["URLBarView.tabsButton"].tap()
app.buttons["TabTrayController.addTabButton"].tap()
app.textFields["url"].tap()
app.typeText("window")
XCTAssert(app.scrollViews.otherElements.buttons["developer.mozilla.org search"].exists)
app.typeText("\r")
// Go to settings and set MDN as the default
app.buttons["URLBarView.tabsButton"].tap()
app.buttons["TabTrayController.menuButton"].tap()
app.collectionViews.cells["Settings"].tap()
let tablesQuery = app.tables
tablesQuery.cells["Search"].tap()
app.navigationBars["Search"].buttons["Edit"].tap()
tablesQuery.buttons["Delete developer.mozilla.org"].tap()
tablesQuery.buttons["Delete"].tap()
app.navigationBars["Search"].buttons["Settings"].tap()
app.navigationBars["Settings"].buttons["AppSettingsTableViewController.navigationItem.leftBarButtonItem"].tap()
restart(app, reset: false)
// Perform a search to check
app.textFields["url"].tap()
app.typeText("window")
XCTAssertFalse(app.scrollViews.otherElements.buttons["developer.mozilla.org search"].exists)
}
}
| mpl-2.0 | ddc4b0e3c73671d68229371bddeccd3d | 39.560345 | 162 | 0.663337 | 4.723896 | false | true | false | false |
wyp767363905/TestKitchen_1606 | TestKitchen/TestKitchen/classes/common/MainTabBarController.swift | 1 | 7904 | //
// MainTabBarController.swift
// TestKitchen
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 1606. All rights reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
//tabbar背景视图
private var bgView: UIView?
//json文件对应的数组
private var array: Array<Dictionary<String,String>>? {
get {
//读文件
let path = NSBundle.mainBundle().pathForResource("Ctrl.json", ofType: nil)
var myArray: Array<Dictionary<String,String>>? = nil
if let filePath = path {
let data = NSData(contentsOfFile: filePath)
if let jsonData = data {
do {
let jsonValue = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers)
if jsonValue.isKindOfClass(NSArray.self) {
myArray = jsonValue as? Array<Dictionary<String,String>>
}
}catch {
//程序出现异常
print(error)
return nil
}
}
}
return myArray
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//创建视图控制器
//Swift里面,一般在类的内部调用属性和方法的时候,可以不写self
createViewControllers()
}
//创建视图控制器
func createViewControllers(){
var ctrlNames = [String]()
var imageNames = [String]()
var titleNames = [String]()
if let tmpArray = self.array {
//json文件的数据解析成功
//并且数组里面有数据
for dict in tmpArray {
let name = dict["ctrlName"]
let titleName = dict["titleName"]
let imageName = dict["imageName"]
ctrlNames.append(name!)
titleNames.append(titleName!)
imageNames.append(imageName!)
}
}else{
ctrlNames = ["CookbookViewController","CommunityViewController","MallViewController","FoodClassViewController","ProfileViewController"]
titleNames = ["食材","社区","商城","食课","我的"]
imageNames = ["home","community","shop","shike","mine"]
}
var vCtrlArray = Array<UINavigationController>()
for i in 0..<ctrlNames.count {
//创建视图控制器
let ctrlName = "TestKitchen." + ctrlNames[i]
let cls = NSClassFromString(ctrlName) as! UIViewController.Type
let ctrl = cls.init()
//导航
let navCtrl = UINavigationController(rootViewController: ctrl)
vCtrlArray.append(navCtrl)
}
self.viewControllers = vCtrlArray
//隐藏系统的tabbar
tabBar.hidden = true
//自定制tabbar
createCustomTabbar(titleNames, imageNames: imageNames)
}
//自定制tabbar
func createCustomTabbar(titleNames: [String], imageNames: [String]) {
//1.创建背景视图
bgView = UIView.createView()
bgView?.backgroundColor = UIColor.whiteColor()
bgView?.layer.borderWidth = 1
bgView?.layer.borderColor = UIColor.grayColor().CGColor
view.addSubview(bgView!)
//2.添加约束
bgView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.left.right.equalTo(self!.view)
make.bottom.equalTo(self!.view)
make.top.equalTo(self!.view.snp_bottom).offset(-49)
})
//2.循环添加按钮
//按钮的宽度
let width = kScreenWidth/5.0
for i in 0..<imageNames.count {
//图片
let imageName = imageNames[i]
let titleName = titleNames[i]
//2.1 按钮
let bgImageName = imageName + "_normal"
let selectBgImageName = imageName + "_select"
let btn = UIButton.createBtn(nil, bgImageName: bgImageName, selectBgImageName: selectBgImageName, target: self, action: #selector(clickBtn(_:)))
bgView?.addSubview(btn)
//添加约束
btn.snp_makeConstraints(closure: {
[weak self]
(make) in
make.top.bottom.equalTo(self!.bgView!)
make.width.equalTo(width)
make.left.equalTo(width*CGFloat(i))
})
//2.2 文字
let label = UILabel.createLabel(titleName, font: UIFont.systemFontOfSize(8), textAlignment: .Center, textColor: UIColor.grayColor())
btn.addSubview(label)
//约束
label.snp_makeConstraints(closure: { (make) in
make.left.right.equalTo(btn)
make.top.equalTo(btn).offset(32)
make.height.equalTo(12)
})
//设置tag值
btn.tag = 300+i
label.tag = 400
//默认选中第一个按钮
if i == 0 {
btn.selected = true
label.textColor = UIColor.orangeColor()
}
}
}
func clickBtn(curBtn: UIButton) {
//1.取消之前选中按钮的状态
let lastBtnVeiw = bgView!.viewWithTag(300+selectedIndex)
if let tmpBtn = lastBtnVeiw {
let lastBtn = tmpBtn as! UIButton
let lastView = tmpBtn.viewWithTag(400)
if let tmpLabel = lastView {
let lastLabel = tmpLabel as! UILabel
lastBtn.selected = false
lastLabel.textColor = UIColor.grayColor()
}
}
//2.设置当前选中按钮的状态
let curLabelView = curBtn.viewWithTag(400)
if let tmpLabel = curLabelView {
let curLabel = tmpLabel as! UILabel
curBtn.selected = true
curLabel.textColor = UIColor.orangeColor()
}
//3.选中视图控制器
selectedIndex = curBtn.tag - 300
}
//显示tabbar
func showTabbar(){
UIView.animateWithDuration(0.05) {
[weak self] in
self!.bgView?.hidden = false
}
}
//隐藏tabbar
func hideTabbar(){
UIView.animateWithDuration(0.05) {
[weak self] in
self!.bgView?.hidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 029ec521a32d0a7dce58b577f6625110 | 27.869732 | 156 | 0.486264 | 5.520147 | false | false | false | false |
lovemo/MVVMFramework-Swift | SwiftMVVMKitDemo/SwiftMVVMKitDemo/SwiftMVVMKit/Base/SMKBaseTableViewManger.swift | 2 | 3628 | //
// SMKBaseTableViewManger.swift
// MVVMFramework-Swift
//
// Created by momo on 15/12/29.
// Copyright © 2015年 momo. All rights reserved.
//
import UIKit
import UITableView_FDTemplateLayoutCell
/// 选中UITableViewCell的Block
typealias didSelectTableCellBlock = (NSIndexPath, AnyObject) -> Void
// - - - - - -- - - - - - - - -- - - - 创建类 - -- - - - - -- -- - - - - -- - - -//
class SMKBaseTableViewManger: NSObject, UITableViewDelegate, UITableViewDataSource {
lazy var myCellIdentifiers = [String]()
lazy var smk_dataArrayList = []
var didSelectCellBlock: didSelectTableCellBlock?
/**
初始化方法
- parameter aCellIdentifier: aCellIdentifier
- parameter didselectBlock: didselectBlock
- returns: return value description
*/
init(cellIdentifiers: [String], didSelectBlock: didSelectTableCellBlock) {
super.init()
self.myCellIdentifiers = cellIdentifiers
self.didSelectCellBlock = didSelectBlock
}
/**
设置UITableView的Datasource和Delegate为self
- parameter table: UITableView
*/
func handleTableViewDatasourceAndDelegate(table: UITableView) {
table.dataSource = self
table.delegate = self
}
/**
获取模型数组
- parameter modelArrayBlock: 返回模型数组Block
- parameter completion: 获取数据完成时
*/
func getItemsWithModelArray(modelArrayBlock:( () -> [AnyObject] )?, completion: (() -> ())?) -> Void {
if let _ = modelArrayBlock {
smk_dataArrayList = modelArrayBlock!()
if let _ = completion {
completion!()
}
}
}
/**
获取UITableView中Item所在的indexPath
- parameter indexPath: indexPath
- returns: return value description
*/
func itemAtIndexPath(indexPath: NSIndexPath) -> AnyObject {
return smk_dataArrayList[indexPath.row];
}
// MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return smk_dataArrayList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item: AnyObject? = itemAtIndexPath(indexPath)
let cell = tableView.dequeueReusableCellWithIdentifier(myCellIdentifiers.first!)
if cell == nil {
UITableViewCell .registerTable(tableView, nibIdentifier: myCellIdentifiers.first!)
}
cell?.configure(cell!, customObj: item!, indexPath: indexPath)
return cell!
}
// MARK: - UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
UITableViewCell.registerTable(tableView, nibIdentifier: self.myCellIdentifiers.first!)
let item: AnyObject? = self.itemAtIndexPath(indexPath)
return tableView.fd_heightForCellWithIdentifier(self.myCellIdentifiers.first!, configuration: { (cell: AnyObject?) -> Void in
cell?.configure(cell! as! UITableViewCell, customObj: item!, indexPath: indexPath)
})
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let item: AnyObject? = self.itemAtIndexPath(indexPath)
self.didSelectCellBlock?(indexPath, item!)
}
}
| mit | 1e07affbf43cea77e21312befefecfdd | 30.353982 | 133 | 0.650579 | 5.018414 | false | false | false | false |
UofACSProjectsClub/Uchat-iOS | Uchat/Model/User.swift | 1 | 1297 | //
// User.swift
// Uchat
//
// Created by Fraser Bulbuc on 2017-10-15.
// Copyright © 2017 UofACSProjectsClub. All rights reserved.
//
import Foundation
public struct User {
private var _UID: String
private var _email: String
private var _messages: [String] // array of message IDs
private var _chats: [String] // array of chat IDs
public var UID: String {
get { return self._UID }
set (UID) { self._UID = UID }
}
public var email: String {
get { return self._email }
set (email) { self._email = email }
}
public var messages: [String] {
get { return self._messages }
set (messages) { self._messages = messages }
}
public var chats: [String] {
get { return self._chats }
set (chats) { self._chats = chats }
}
init(UID: String, email: String, messages: [String]?, chats: [String]?) {
self._UID = UID
self._email = email
if let chats = chats { self._chats = chats }
else { self._chats = [String]() }
if let messages = messages { self._messages = messages }
else { self._messages = [String]() }
}
}
| mit | d1aae6f6604da0eaf620cea233b90330 | 24.92 | 77 | 0.516975 | 4.012384 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.