repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AboutObjectsTraining/Swift4Examples | Model/Garment.swift | 1 | 1247 | //
// Copyright (C) 2017 About Objects, Inc. All Rights Reserved.
// See LICENSE.txt for this example's licensing information.
//
import Foundation
public enum Garment {
case tie
case shirt(size: String)
case pants(waist: Int, inseam: Int)
}
extension Garment: CustomStringConvertible {
public var description: String {
switch self {
case .tie: return "tie"
case let .shirt(s): return "shirt: \(s)"
case let .pants(w, i): return "pants: \(w) X \(i)"
}
}
}
extension Garment: Equatable {
public static func ==(lhs: Garment, rhs: Garment) -> Bool {
switch (lhs, rhs) {
case (.tie, .tie): return true
case let (.shirt(s1), .shirt(s2)):
return s1 == s2
case let (.pants(w1, i1), .pants(w2, i2)):
return w1 == w2 && i1 == i2
default: return false
}
}
}
func show(item: Garment)
{
switch item {
case .tie: print("tie")
case .shirt(let s): print("shirt, \(s)")
case .pants(let w, let i): print("pants, \(w)X\(i)")
}
switch item {
case .tie: print("tie")
case let .shirt(s): print("shirt, \(s)")
case let .pants(w, i): print("pants, \(w)X\(i)")
}
}
| mit | 53c6c9cf3dd720ccc4141cc073c661a8 | 23.45098 | 63 | 0.546913 | 3.272966 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift | 1 | 2092 | //
// DistinctUntilChanged.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class DistinctUntilChangedSink<O: ObserverType, Key>: Sink<O>, ObserverType {
typealias E = O.E
private let _parent: DistinctUntilChanged<E, Key>
private var _currentKey: Key?
init(parent: DistinctUntilChanged<E, Key>, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case let .next(value):
do {
let key = try _parent._selector(value)
var areEqual = false
if let currentKey = _currentKey {
areEqual = try _parent._comparer(currentKey, key)
}
if areEqual {
return
}
_currentKey = key
forwardOn(event)
} catch let error {
forwardOn(.error(error))
dispose()
}
case .error, .completed:
forwardOn(event)
dispose()
}
}
}
final class DistinctUntilChanged<Element, Key>: Producer<Element> {
typealias KeySelector = (Element) throws -> Key
typealias EqualityComparer = (Key, Key) throws -> Bool
fileprivate let _source: Observable<Element>
fileprivate let _selector: KeySelector
fileprivate let _comparer: EqualityComparer
init(source: Observable<Element>, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) {
_source = source
_selector = selector
_comparer = comparer
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | 29f97662e38c8aa0cf4723cf63cf0676 | 30.208955 | 144 | 0.594931 | 4.773973 | false | false | false | false |
neonichu/Azkaban | Sources/azkaban/ATZPackage+Azkaban.swift | 1 | 1432 | import Foundation
extension ATZPackage {
private func synchronousAction(action: ((String?, CGFloat) -> (), (NSError?) -> ()) -> ()) -> NSError? {
var error: NSError?
makeSynchronous { semaphore in
action({ _, _ in print("") }) { err in
error = err
dispatch_semaphore_signal(semaphore)
}
}
return error
}
private func install() -> NSError? {
return synchronousAction(self.installWithProgress)
}
func installAndReport() -> Bool {
if isInstalled {
print("\(name) is already installed")
} else {
if let error = install() {
print("Failed to install \(name): \(error)")
return false
} else {
print("Installed \(name)")
}
}
return true
}
private func remove() -> NSError? {
var error: NSError?
makeSynchronous { semaphore in
self.removeWithCompletion { err in
error = err
dispatch_semaphore_signal(semaphore)
}
}
return error
}
func removeAndReport() {
if let error = remove() {
print("Failed to uninstall \(name): \(error)")
} else {
print("Uninstalled \(name)")
}
}
private func update() -> NSError? {
return synchronousAction(self.updateWithProgress)
}
func updateAndReport() {
if let error = update() {
print("Failed to update \(name): \(error)")
} else {
print("Updated \(name)")
}
}
}
| mit | 66e14064fe67d9b95e7470d305ce53d5 | 20.058824 | 106 | 0.573324 | 4.313253 | false | false | false | false |
OpenTimeApp/OpenTimeIOSSDK | OpenTimeSDK/Classes/OTAPIRawResponse.swift | 1 | 3941 | //
// APIRawResponse.swift
// OpenTime
//
// Created by Josh Woodcock on 5/10/15.
// Copyright (c) 2015 Connecting Open Time, LLC. All rights reserved.
//
public class OTAPIRawResponse {
// Whether or not the request logically succeeded or logically failed.
// @SerializedName("success")
private var _success: Bool;
// The message associated with the success or failed response.
// @SerializedName("message")
private var _message: String;
// String representation of data object.
// @SerializedName("data")
private var _rawData: AnyObject?;
/**
Designated constructor.
*/
public init() {
self._success = false;
self._message = "Error: Message not parsed from server response";
}
/**
Gets the success or failure from the response body from the server.
- returns: Whether or not the request to the server succeeded.
*/
public func isSuccessful() -> Bool {
return self._success;
}
/**
Gets the message about why the response failed or succeeded.
- returns: A message explaining why the request to the server failed or succeeded.
*/
public func getMessage() -> String {
return self._message;
}
/**
Gets a parsed object usually a dictionairy or an array.
- returns: nil, an array of dictionaries, or a dictionary with data in it.
*/
public func getRawData() -> AnyObject? {
return self._rawData;
}
/**
Tries to parse data elements from the first level of JSON elements.
- parameter responseObject: The object given by AFNetworking by parsing a JSON string.
- returns: A raw response object with the values of the first level of the JSON object.
*/
public static func deserialize(_ responseObject: AnyObject!) -> OTAPIRawResponse {
// Setup the raw response object.
let rawResponse: OTAPIRawResponse = OTAPIRawResponse();
if(responseObject != nil)
{
// Try to get the success from the response object.
if(OTSerialHelper.keyExists(responseObject, key: "success") == true) {
rawResponse._success = responseObject.object(forKey: "success") as! Bool;
}
// Try to get the message from the response object.
if(OTSerialHelper.keyExists(responseObject, key: "message") == true) {
rawResponse._message = responseObject.object(forKey: "message") as! String;
}
// Try to get the data from the response object.
if (rawResponse._success == true && OTSerialHelper.keyExists(responseObject, key: "data") == true) {
rawResponse._rawData = self._getData(responseObject);
}
}
if(responseObject != nil && rawResponse._success == false) {
// Print the response object.
print(responseObject, terminator: "");
}
return rawResponse;
}
/**
Gets the data element from the response object.
- returns: The data element of the response object.
*/
private static func _getData(_ responseObject: AnyObject) -> AnyObject!
{
// Try to get the data object.
let data: AnyObject! = responseObject["data"]! as AnyObject!;
// Set data property of the OTAPIResponse as a typed object.
if(data is NSDictionary)
{
// Its a dictionary. Cast it as a dictionary.
return data as! NSDictionary;
}else if(data is NSArray){
// Its an array. Cast it as an array.
return data as! NSArray;
}else{
// Its either empty or something besides an array or dictionary.
return data;
}
}
}
| mit | db58042066c9a44846d34e85a776981f | 31.841667 | 112 | 0.587922 | 4.982301 | false | false | false | false |
Harry-L/5-3-1 | ios-charts-master/Charts/Classes/Renderers/ChartXAxisRendererRadarChart.swift | 4 | 2971 | //
// ChartXAxisRendererRadarChart.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/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ChartXAxisRendererRadarChart: ChartXAxisRenderer
{
public weak var chart: RadarChartView?
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, chart: RadarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil)
self.chart = chart
}
public override func renderAxisLabels(context context: CGContext)
{
guard let
xAxis = xAxis,
chart = chart
else { return }
if (!xAxis.isEnabled || !xAxis.isDrawLabelsEnabled)
{
return
}
let labelFont = xAxis.labelFont
let labelTextColor = xAxis.labelTextColor
let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
let drawLabelAnchor = CGPoint(x: 0.5, y: 0.0)
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let modulus = xAxis.axisLabelModulus
for var i = 0, count = xAxis.values.count; i < count; i += modulus
{
let label = xAxis.values[i]
if (label == nil)
{
continue
}
let angle = (sliceangle * CGFloat(i) + chart.rotationAngle) % 360.0
let p = ChartUtils.getPosition(center: center, dist: CGFloat(chart.yRange) * factor + xAxis.labelRotatedWidth / 2.0, angle: angle)
drawLabel(context: context, label: label!, xIndex: i, x: p.x, y: p.y - xAxis.labelRotatedHeight / 2.0, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor], anchor: drawLabelAnchor, 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)
}
public override func renderLimitLines(context context: CGContext)
{
/// XAxis LimitLines on RadarChart not yet supported.
}
} | mit | 95c0dfce45503caae7ae26bcb0943fc1 | 34.807229 | 274 | 0.636823 | 5.018581 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Core/Extensions/UIBarButtonItem.swift | 1 | 978 | //
// UIBarButtonItem.swift
// HTWDD
//
// Created by Chris Herlemann on 03.01.21.
// Copyright © 2021 HTW Dresden. All rights reserved.
//
extension UIBarButtonItem {
static func menuButton(_ target: Any?, action: Selector, imageName: String, insets: Bool = true) -> UIBarButtonItem {
let button = UIButton(type: .system)
button.setImage(UIImage(named: imageName), for: .normal)
button.addTarget(target, action: action, for: .touchUpInside)
if insets {
button.imageEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
}
let menuBarItem = UIBarButtonItem(customView: button)
menuBarItem.customView?.translatesAutoresizingMaskIntoConstraints = false
menuBarItem.customView?.heightAnchor.constraint(equalToConstant: 24).isActive = true
menuBarItem.customView?.widthAnchor.constraint(equalToConstant: 24).isActive = true
return menuBarItem
}
}
| gpl-2.0 | 330fd3c8208a2897ac460ba6c88daad3 | 35.185185 | 121 | 0.677584 | 4.652381 | false | false | false | false |
Adorkable/Eunomia | Source/Core/UtilityExtensions/UIFont+Utility.swift | 1 | 2922 | //
// UIFont+Utility.swift
// Eunomia
//
// Created by Ian on 5/8/15.
// Copyright (c) 2015 Eunomia. All rights reserved.
//
#if os(iOS)
import UIKit
extension UIFont {
public class func supportedFonts() -> [String : [String]]? {
var result : [String : [String]]?
for familyName in UIFont.familyNames {
let fonts = fontNames(forFamilyName: familyName)
if fonts.count > 0 {
if result == nil {
result = [String : [String]]()
}
if result != nil {
result![familyName] = fonts
} else {
// TODO: log
}
}
}
return result
}
public func fontWithTrait(_ trait : UIFontDescriptor.SymbolicTraits) -> UIFont {
let fontDescriptor = self.fontDescriptor.withSymbolicTraits(trait)
return UIFont(descriptor: fontDescriptor!, size: self.pointSize)
}
public func regularFont() -> UIFont? {
return UIFont(name: self.fontName, size: self.pointSize)
}
public func italicFont() -> UIFont {
return self.fontWithTrait(.traitItalic)
}
public func boldFont() -> UIFont {
return self.fontWithTrait(.traitBold)
}
public func expandedFont() -> UIFont {
return self.fontWithTrait(.traitExpanded)
}
public func condensedFont() -> UIFont {
return self.fontWithTrait(.traitCondensed)
}
public func monospaceFont() -> UIFont {
return self.fontWithTrait(.traitMonoSpace)
}
public func verticalFont() -> UIFont {
return self.fontWithTrait(.traitVertical)
}
public func uiOptimizedFont() -> UIFont {
return self.fontWithTrait(.traitUIOptimized)
}
public func tightLeadingFont() -> UIFont {
return self.fontWithTrait(.traitTightLeading)
}
public func looseLeadingFont() -> UIFont {
return self.fontWithTrait(.traitLooseLeading)
}
}
extension UIFont {
// https://stackoverflow.com/a/30450559
public func width(withConstrainedHeight height: CGFloat, string: String) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = string.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: self], context: nil)
return ceil(boundingBox.width)
}
public func height(withConstrainedWidth width: CGFloat, string: String) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = string.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: self], context: nil)
return ceil(boundingBox.height)
}
}
#endif
| mit | 2e6cc7f98f51d9bf67757a0d58e9f9d3 | 29.123711 | 142 | 0.601985 | 4.813839 | false | false | false | false |
candyan/RepairMan | RepairMan/controllers/HomeViewController.swift | 1 | 9732 | //
// HomeViewController.swift
//
//
// Created by cherry on 9/1/15.
//
//
import UIKit
class HomeViewController: YATableViewController {
var header: ABRSProfileHeader?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupNavigator()
self.loadSubviews()
self.registerDataSourceClass(HomeDataSource.self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
weak var weakSelf = self
let orderQuery: AVQuery! = ABRSRepairOrder.query()
orderQuery.cachePolicy = AVCachePolicy.NetworkElseCache
orderQuery.limit = 1000
if AVUser.currentUser().role() == .Normal {
orderQuery.whereKey("poster", equalTo: AVUser.currentUser())
orderQuery.orderByDescending("createdAt")
} else {
orderQuery.whereKey("serviceman", equalTo: AVUser.currentUser())
orderQuery.whereKey("repairStatus", equalTo: ABRSRepairStatus.Repairing.rawValue)
orderQuery.orderByDescending("updatedAt")
}
orderQuery.findObjectsInBackgroundWithBlock { (results, error) -> Void in
if results != nil {
weakSelf!.dataSource.setAllSectionObjects([results])
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension HomeViewController {
private func loadSubviews() {
header = ABRSProfileHeader(frame: CGRectMake(0, 0, self.view.bounds.width, 279))
self.tableView?.tableHeaderView = header
let currentUser: AVUser = AVUser.currentUser()
header?.avatarImageView?.image = UIImage(named: currentUser.role() == .Normal ? "NormalAvatar" : "RepairManAvatar")
header?.titleLabel?.text = currentUser.username
header?.subtitleLabel?.text = currentUser.department()
header?.segmentLabel?.text = (AVUser.currentUser().role() == .Normal) ? "我的报修" : "我的维修"
header?.operationButton?.setTitle(currentUser.homeOperationButtonTitle, forState: .Normal)
header?.operationButton?.addTarget(self, action: "publishRepairButtonTouchUpInsideHandler:", forControlEvents: .TouchUpInside)
}
func setupNavigator() {
self.title = "维修"
weak var weakSelf = self
let logoutBarButtonItems = UIBarButtonItem.barButtonItemsWithTitle("退出", actionBlock: { () -> Void in
let alert = YAAlertView(title: "退出登录", message: nil)
alert.setCancelButtonWithTitle("取消", block: nil)
alert.addButtonWithTitle("退出", block: { () -> Void in
AVUser.logOut()
AppManager.sharedManager.rootNavigator.setViewControllers([LaunchViewController()],
animated: false)
AppManager.sharedManager.rootNavigator.navigationBarHidden = true
})
alert.show()
})
self.navigationItem.rightBarButtonItems = logoutBarButtonItems as? [UIBarButtonItem]
}
}
extension HomeViewController {
internal func publishRepairButtonTouchUpInsideHandler(sender: AnyObject?) {
if AVUser.currentUser().role() == .Normal {
let publishRepairVC = PublishRepairViewController()
publishRepairVC.title = "我要报修"
publishRepairVC.delegate = self
self.presentViewController(UINavigationController(rootViewController: publishRepairVC), animated: true, completion: nil)
} else {
let pickerController = RepairOrderPickerController()
pickerController.title = "我要维修"
self.presentViewController(UINavigationController(rootViewController: pickerController), animated: true, completion: nil)
}
}
}
extension HomeViewController: PublishRepairViewControllerDelegate {
func publishRepairViewController(publishRepairVC: PublishRepairViewController,
didFinishPublishWithInfo info: [String : AnyObject!]) {
publishRepairVC.dismissViewControllerAnimated(true, completion: nil)
}
}
class HomeDataSource: YATableDataSource {
override init() {
super.init()
}
override init!(tableView: UITableView!) {
super.init(tableView: tableView)
tableView.registerReuseCellClass(RepairOrderCell.self)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let repairOrderForRow = self.objectAtIndexPath(indexPath) as? ABRSRepairOrder
let repairOrderDescription = repairOrderForRow?.troubleDescription()
return RepairOrderCell.heightForContent(repairOrderDescription!,
limitedSize: CGSize(width: tableView.bounds.width, height: CGFloat(FLT_MAX)))
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithClass(RepairOrderCell.self) as! RepairOrderCell
cell.selectionStyle = .None
let repairOrder = self.objectAtIndexPath(indexPath) as? ABRSRepairOrder
let firstImage = repairOrder!.troubleImageFiles()?.first
if firstImage != nil {
AVFile.getFileWithObjectId(firstImage?.objectId, withBlock: { (file, error) -> Void in
file?.getThumbnail(true, width: 180, height: 180, withBlock: { (image, error) -> Void in
cell.avatarImageView?.image = image
})
})
}
if repairOrder != nil {
if AVUser.currentUser().role() == .Normal {
cell.titleLabel!.text = repairOrder!.repairType().stringValue
cell.contentLabel!.text = repairOrder!.troubleDescription()
cell.statusLabel!.text = repairOrder!.repairStatus().stringValue
switch repairOrder!.repairStatus() {
case .Waiting:
cell.statusLabel!.backgroundColor = UIColor(hex: 0x4A90E2)
case .Repairing:
cell.statusLabel!.backgroundColor = UIColor(hex: 0x31CCAA)
case .Finished:
cell.statusLabel!.backgroundColor = UIColor(hex: 0x666666)
}
} else {
cell.titleLabel!.text = "报修人:\(repairOrder!.poster().username)"
cell.subTitleLabel!.text = "地点:\(repairOrder!.address())"
cell.contentLabel!.text = repairOrder!.troubleDescription()
cell.statusLabel!.text = repairOrder!.troubleLevel().stringValue
switch repairOrder!.troubleLevel() {
case .NotUrgent:
cell.statusLabel!.backgroundColor = UIColor(hex: 0x31CCAA)
case .Urgent:
cell.statusLabel!.backgroundColor = UIColor(hex: 0xF5A623)
case .VeryUrgent:
cell.statusLabel!.backgroundColor = UIColor(hex: 0xFF2D0C)
}
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
super.tableView(tableView, didSelectRowAtIndexPath: indexPath)
if AVUser.currentUser().role() != .Normal {
weak var repairOrder = self.objectAtIndexPath(indexPath) as? ABRSRepairOrder
weak var weakSelf = self
if repairOrder?.repairStatus() == .Repairing {
let sheet = YAActionSheet(title: "操作")
sheet.addButtonWithTitle("联系报修人", block: { () -> Void in
let phoneURL = NSURL(string: "tel://\(repairOrder?.poster().mobilePhoneNumber)")
UIApplication.sharedApplication().openURL(phoneURL!)
})
sheet.addButtonWithTitle("维修完成", block: { () -> Void in
weakSelf?.finishRepairOrder(repairOrder!)
})
sheet.setCancelButtonWithTitle("取消", block: nil)
sheet.showInView(UIApplication.sharedApplication().keyboardWindow())
}
}
}
private func finishRepairOrder(repairOrder: ABRSRepairOrder) {
let alert = YAAlertView(title: "维修完成了?", message: "这个东西已经修完了?")
weak var weakSelf = self
alert.setCancelButtonWithTitle("还没有", block: nil)
alert.addButtonWithTitle("修完了", block: { () -> Void in
repairOrder.setRepairStatus(.Finished)
MBProgressHUD.showProgressHUDWithText("请求中...")
repairOrder.saveInBackgroundWithBlock({ (success, error) -> Void in
MBProgressHUD.hideHUDForView(UIApplication.sharedApplication().keyboardWindow(),
animated: false)
if success == true {
weakSelf?.removeObject(repairOrder, atSection: 0)
} else {
MBProgressHUD.showHUDWithText("请求失败", complete: nil)
}
})
})
alert.show()
}
}
extension AVUser {
private var homeOperationButtonTitle: String! {
switch self.role() {
case .Normal:
return "我要报修"
default:
return "我要维修"
}
}
}
| mit | c5b27f2d72ade99ca323de7daa4714cf | 38.512397 | 134 | 0.61096 | 5.210899 | false | false | false | false |
Polidea/RxBluetoothKit | Source/CentralManager.swift | 1 | 18056 | import Foundation
import RxSwift
import CoreBluetooth
/// Error received when device disconnection event occurs
public typealias DisconnectionReason = Error
/// CentralManager is a class implementing ReactiveX API which wraps all Core Bluetooth Manager's functions allowing to
/// discover, connect to remote peripheral devices and more.
/// You can start using this class by discovering available services of nearby peripherals. Before calling any
/// public `CentralManager`'s functions you should make sure that Bluetooth is turned on and powered on.
/// It can be done by calling and observing returned value of `observeStateWithInitialValue()` and then
/// chaining it with `scanForPeripherals(_:options:)`:
/// ```
/// let disposable = centralManager.observeStateWithInitialValue()
/// .filter { $0 == .poweredOn }
/// .take(1)
/// .flatMap { centralManager.scanForPeripherals(nil) }
/// ```
/// As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and
/// peripheral's RSSI registered during discovery. You can then `establishConnection(_:options:)` and do other operations.
/// You can also simply stop scanning with just disposing it:
/// ```
/// disposable.dispose()
/// ```
/// - seealso: `Peripheral`
public class CentralManager: ManagerType {
/// Implementation of CBCentralManager
public let manager: CBCentralManager
@available(*, deprecated, renamed: "CentralManager.manager")
public var centralManager: CBCentralManager { return manager }
let peripheralProvider: PeripheralProvider
let delegateWrapper: CBCentralManagerDelegateWrapper
/// Lock which should be used before accessing any internal structures
private let lock = NSLock()
/// Ongoing scan disposable
private var scanDisposable: Disposable?
/// Connector instance is used for establishing connection with peripherals
private let connector: Connector
// MARK: Initialization
/// Creates new `CentralManager`
/// - parameter centralManager: Central instance which is used to perform all of the necessary operations
/// - parameter delegateWrapper: Wrapper on CoreBluetooth's central manager callbacks.
/// - parameter peripheralProvider: Provider for providing peripherals and peripheral wrappers
/// - parameter connector: Connector instance which is used for establishing connection with peripherals.
init(
centralManager: CBCentralManager,
delegateWrapper: CBCentralManagerDelegateWrapper,
peripheralProvider: PeripheralProvider,
connector: Connector
) {
self.manager = centralManager
self.delegateWrapper = delegateWrapper
self.peripheralProvider = peripheralProvider
self.connector = connector
centralManager.delegate = delegateWrapper
}
/// Creates new `CentralManager` instance. By default all operations and events are executed and received on main thread.
/// - warning: If you pass background queue to the method make sure to observe results on main thread for UI related code.
/// - parameter queue: Queue on which bluetooth callbacks are received. By default main thread is used.
/// - parameter options: An optional dictionary containing initialization options for a central manager.
/// For more info about it please refer to [Central Manager initialization options](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/index.html)
/// - parameter cbCentralManager: Optional instance of `CBCentralManager` to be used as a `manager`. If you
/// skip this parameter, there will be created an instance of `CBCentralManager` using given queue and options.
public convenience init(queue: DispatchQueue = .main,
options: [String: AnyObject]? = nil,
cbCentralManager: CBCentralManager? = nil) {
let delegateWrapper = CBCentralManagerDelegateWrapper()
let centralManager = cbCentralManager ??
CBCentralManager(delegate: delegateWrapper, queue: queue, options: options)
self.init(
centralManager: centralManager,
delegateWrapper: delegateWrapper,
peripheralProvider: PeripheralProvider(),
connector: Connector(centralManager: centralManager, delegateWrapper: delegateWrapper)
)
}
/// Attaches RxBluetoothKit delegate to CBCentralManager.
/// This method is useful in cases when delegate of CBCentralManager was reassigned outside of
/// RxBluetoothKit library (e.g. CBCentralManager was used in some other library or used in non-reactive way)
public func attach() {
manager.delegate = delegateWrapper
}
// MARK: State
public var state: BluetoothState {
return BluetoothState(rawValue: manager.state.rawValue) ?? .unknown
}
public func observeState() -> Observable<BluetoothState> {
return self.delegateWrapper.didUpdateState.asObservable()
}
public func observeStateWithInitialValue() -> Observable<BluetoothState> {
return Observable.deferred { [weak self] in
guard let self = self else {
RxBluetoothKitLog.w("observeState - CentralManager deallocated")
return .never()
}
return self.delegateWrapper.didUpdateState.asObservable()
.startWith(self.state)
}
}
// MARK: Scanning
/// Value indicating if manager is currently scanning.
public var isScanInProgress: Bool {
lock.lock(); defer { lock.unlock() }
return scanDisposable != nil
}
/// Scans for `Peripheral`s after subscription to returned observable. First parameter `serviceUUIDs` is
/// an array of `Service` UUIDs which needs to be implemented by a peripheral to be discovered. If user don't want to
/// filter any peripherals, `nil` can be used instead. Additionally dictionary of
/// [CBCentralManager specific options](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Scanning_Options)
/// can be passed to allow further customisation.
/// Scans by default are infinite streams of `ScannedPeripheral` structures which need to be stopped by the user. For
/// example this can be done by limiting scanning to certain number of peripherals or time:
/// ```
/// centralManager.scanForPeripherals(withServices: nil)
/// .timeout(3.0, timeoutScheduler)
/// .take(2)
/// ```
///
/// There can be only one ongoing scanning. It will return `BluetoothError.scanInProgress` error if
/// this method will be called when there is already ongoing scan.
/// As a result you will receive `ScannedPeripheral` which contains `Peripheral` object, `AdvertisementData` and
/// peripheral's RSSI registered during discovery. You can then `establishConnection(_:options:)` and do other
/// operations.
///
/// - seealso: `Peripheral`
///
/// - parameter serviceUUIDs: Services of peripherals to search for. Nil value will accept all peripherals.
/// - parameter options: Optional scanning options.
/// - returns: Infinite stream of scanned peripherals.
///
/// Observable can ends with following errors:
/// * `BluetoothError.scanInProgress`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String: Any]? = nil)
-> Observable<ScannedPeripheral> {
let observable: Observable<ScannedPeripheral> = Observable.create { [weak self] observer in
guard let strongSelf = self else {
observer.onError(BluetoothError.destroyed)
return Disposables.create()
}
strongSelf.lock.lock(); defer { strongSelf.lock.unlock() }
if strongSelf.scanDisposable != nil {
observer.onError(BluetoothError.scanInProgress)
return Disposables.create()
}
strongSelf.scanDisposable = strongSelf.delegateWrapper.didDiscoverPeripheral
.flatMap { [weak self] (cbPeripheral, advertisment, rssi) -> Observable<ScannedPeripheral> in
guard let strongSelf = self else {
throw BluetoothError.destroyed
}
let peripheral = strongSelf.retrievePeripheral(for: cbPeripheral)
let advertismentData = AdvertisementData(advertisementData: advertisment)
return .just(ScannedPeripheral(peripheral: peripheral,
advertisementData: advertismentData, rssi: rssi))
}
.subscribe(observer)
strongSelf.manager.scanForPeripherals(withServices: serviceUUIDs, options: options)
return Disposables.create { [weak self] in
guard let strongSelf = self else { return }
// When disposed, stop scan and dispose scanning
if strongSelf.state == .poweredOn {
strongSelf.manager.stopScan()
}
do { strongSelf.lock.lock(); defer { strongSelf.lock.unlock() }
strongSelf.scanDisposable?.dispose()
strongSelf.scanDisposable = nil
}
}
}
return ensure(.poweredOn, observable: observable)
}
// MARK: Peripheral's Connection Management
/// Establishes connection with a given `Peripheral`.
/// When connection did succeded it sends event with `Peripheral` - from now on it is possible to call all other methods that require connection.
/// The connection is automatically disconnected when resulting Observable is unsubscribed.
/// On the other hand when the connection is interrupted or failed by the device or the system, the Observable will be unsubscribed as well
/// following `BluetoothError.peripheralConnectionFailed` or `BluetoothError.peripheralDisconnected` emission.
/// Additionally you can pass optional [dictionary](https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCentralManager_Class/#//apple_ref/doc/constant_group/Peripheral_Connection_Options)
/// to customise the behaviour of connection.
///
/// - parameter peripheral: The `Peripheral` to which `CentralManager` is attempting to establish connection.
/// - parameter options: Dictionary to customise the behaviour of connection.
/// - returns: `Observable` which emits next event after connection is established.
///
/// Observable can ends with following errors:
/// * `BluetoothError.peripheralIsAlreadyObservingConnection`
/// * `BluetoothError.peripheralConnectionFailed`
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func establishConnection(_ peripheral: Peripheral, options: [String: Any]? = nil) -> Observable<Peripheral> {
let observable = connector.establishConnection(with: peripheral, options: options)
return ensure(.poweredOn, observable: observable)
}
// MARK: Retrieving Lists of Peripherals
/// Returns list of the `Peripheral`s which are currently connected to the `CentralManager` and contain
/// all of the specified `Service`'s UUIDs.
///
/// - parameter serviceUUIDs: A list of `Service` UUIDs
/// - returns: Retrieved `Peripheral`s. They are in connected state and contain all of the
/// `Service`s with UUIDs specified in the `serviceUUIDs` parameter.
public func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [Peripheral] {
return manager.retrieveConnectedPeripherals(withServices: serviceUUIDs)
.map { self.retrievePeripheral(for: $0) }
}
/// Returns list of `Peripheral`s by their identifiers which are known to `CentralManager`.
///
/// - parameter identifiers: List of `Peripheral`'s identifiers which should be retrieved.
/// - returns: Retrieved `Peripheral`s.
public func retrievePeripherals(withIdentifiers identifiers: [UUID]) -> [Peripheral] {
return manager.retrievePeripherals(withIdentifiers: identifiers)
.map { self.retrievePeripheral(for: $0) }
}
// MARK: Connection and disconnection observing
/// Emits `Peripheral` instance when it's connected.
///
/// - parameter peripheral: Optional `Peripheral` which is observed for connection. When not specified it will observe fo any `Peripheral`.
/// - returns: Observable which emits next events when `peripheral` was connected.
///
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func observeConnect(for peripheral: Peripheral? = nil) -> Observable<Peripheral> {
let observable = delegateWrapper.didConnectPeripheral
.filter { peripheral != nil ? ($0 == peripheral!.peripheral) : true }
.map { [weak self] (cbPeripheral: CBPeripheral) -> Peripheral in
guard let strongSelf = self else { throw BluetoothError.destroyed }
return peripheral ?? strongSelf.retrievePeripheral(for: cbPeripheral)
}
return ensure(.poweredOn, observable: observable)
}
/// Emits `Peripheral` instance when it's disconnected.
/// - parameter peripheral: Optional `Peripheral` which is observed for disconnection. When not specified it will observe for any `Peripheral`.
/// - returns: Observable which emits next events when `Peripheral` instance was disconnected.
/// It provides optional error which may contain more information about the cause of the disconnection
/// if it wasn't the `cancelPeripheralConnection` call.
///
/// It's **infinite** stream, so `.complete` is never called.
///
/// Observable can ends with following errors:
/// * `BluetoothError.destroyed`
/// * `BluetoothError.bluetoothUnsupported`
/// * `BluetoothError.bluetoothUnauthorized`
/// * `BluetoothError.bluetoothPoweredOff`
/// * `BluetoothError.bluetoothInUnknownState`
/// * `BluetoothError.bluetoothResetting`
public func observeDisconnect(for peripheral: Peripheral? = nil) -> Observable<(Peripheral, DisconnectionReason?)> {
let observable = delegateWrapper.didDisconnectPeripheral
.filter { peripheral != nil ? ($0.0 == peripheral!.peripheral) : true }
.map { [weak self] (cbPeripheral, error) -> (Peripheral, DisconnectionReason?) in
guard let strongSelf = self else { throw BluetoothError.destroyed }
let peripheral = peripheral ?? strongSelf.retrievePeripheral(for: cbPeripheral)
return (peripheral, error)
}
return ensure(.poweredOn, observable: observable)
.catchError { error in
if error is BluetoothError, let peripheral = peripheral {
return .concat(.just((peripheral, error)), .error(error))
} else {
return .error(error)
}
}
}
// MARK: ANCS
/// Emits boolean values according to ancsAuthorized property on a CBPeripheral.
///
/// - parameter peripheral: `Peripheral` which is observed for ancsAuthorized chances.
/// - returns: Observable which emits next events when `ancsAuthorized` property changes on a peripheral.
#if !os(macOS)
@available(iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func observeANCSAuthorized(for peripheral: Peripheral) -> Observable<Bool> {
let observable = delegateWrapper.didUpdateANCSAuthorizationForPeripheral
.asObservable()
.filter { $0 == peripheral.peripheral }
// ancsAuthorized is a Bool by default, but the testing framework
// will use Bool! instead. In order to support that we are converting
// to optional and unwrapping the value.
.map { ($0.ancsAuthorized as Bool?)! }
return ensure(.poweredOn, observable: observable)
}
#endif
// MARK: Internal functions
/// Ensure that specified `peripheral` is connected during subscription.
/// - parameter peripheral: `Peripheral` which should be connected during subscription.
/// - returns: Observable which emits error when `peripheral` is disconnected during subscription.
func ensurePeripheralIsConnected<T>(_ peripheral: Peripheral) -> Observable<T> {
return .deferred {
if !peripheral.isConnected {
throw BluetoothError.peripheralDisconnected(peripheral, nil)
}
return self.delegateWrapper.didDisconnectPeripheral
.filter { $0.0 == peripheral.peripheral }
.map { (_, error) -> T in
throw BluetoothError.peripheralDisconnected(peripheral, error)
}
}
}
func retrievePeripheral(for cbPeripheral: CBPeripheral) -> Peripheral {
return peripheralProvider.provide(for: cbPeripheral, centralManager: self)
}
}
| apache-2.0 | 39098bfbca11dfee8f163cb63075291b | 50.295455 | 219 | 0.679442 | 5.440193 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/Resources/NutshellUILabel.swift | 1 | 1282 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
// This intermediate class is used to enable UITextField views in storyboards to have fonts and backgrounds determined by NutshellStyles data.
@IBDesignable class NutshellUILabel: UILabel {
@IBInspectable var usage: String = "" {
didSet {
updateStyling()
}
}
fileprivate func updateStyling() {
if let backColor = Styles.usageToBackgroundColor[usage] {
self.backgroundColor = backColor
}
if let (font, textColor) = Styles.usageToFontWithColor[usage] {
self.font = font
self.textColor = textColor
}
}
}
| bsd-2-clause | 10ba4388bd2694383c3d539c8d4c4f1d | 33.648649 | 142 | 0.699688 | 4.678832 | false | true | false | false |
superk589/DereGuide | DereGuide/LiveSimulator/LSScoreBonusGroup.swift | 2 | 1227 | //
// LSScoreBonusGroup.swift
// DereGuide
//
// Created by zzk on 2017/5/19.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
struct LSScoreBonusGroup {
var basePerfectBonus: Int
var baseComboBonus: Int
var skillBoost: Int
static let basic = LSScoreBonusGroup(basePerfectBonus: 100, baseComboBonus: 100, skillBoost: 1000)
var bonusValue: Int {
if skillBoost > 1000 {
let p = add(skillBoost, to: basePerfectBonus)
let c = add(skillBoost, to: baseComboBonus)
return p * c
} else {
return basePerfectBonus * baseComboBonus
}
}
var comboBonus: Int {
if skillBoost > 1000 {
let c = add(skillBoost, to: baseComboBonus)
return c
} else {
return baseComboBonus
}
}
var perfectBonus: Int {
if skillBoost > 1000 {
let p = add(skillBoost, to: basePerfectBonus)
return p
} else {
return basePerfectBonus
}
}
private func add(_ skillBoost: Int, to bonus: Int) -> Int {
return 100 + Int(ceil(Double((bonus - 100) * skillBoost) * 0.001))
}
}
| mit | f3f32d67b72e42592859cd4469ca34c5 | 23.039216 | 102 | 0.561175 | 3.980519 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Models/Device.swift | 1 | 1666 | //
// Device.swift
// Webretail
//
// Created by Gerardo Grisolini on 11/04/17.
//
//
import StORM
import PerfectLogger
class Device: PostgresSqlORM, Codable {
public var deviceId : Int = 0
public var storeId : Int = 0
public var deviceName : String = ""
public var deviceToken : String = ""
public var deviceCreated : Int = Int.now()
public var deviceUpdated : Int = Int.now()
public var _store: Store = Store()
private enum CodingKeys: String, CodingKey {
case deviceId
case deviceName
case deviceToken
case _store = "store"
case deviceUpdated = "updatedAt"
}
open override func table() -> String { return "devices" }
open override func tableIndexes() -> [String] { return ["deviceId", "deviceName"] }
open override func to(_ this: StORMRow) {
deviceId = this.data["deviceid"] as? Int ?? 0
storeId = this.data["storeid"] as? Int ?? 0
deviceName = this.data["devicename"] as? String ?? ""
deviceToken = this.data["devicetoken"] as? String ?? ""
deviceCreated = this.data["devicecreated"] as? Int ?? 0
deviceUpdated = this.data["deviceupdated"] as? Int ?? 0
_store.to(this)
}
func rows() -> [Device] {
var rows = [Device]()
for i in 0..<self.results.rows.count {
let row = Device()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
/// Performs a find on supplied deviceToken
func get(deviceToken: String, deviceName: String) {
do {
try query(whereclause: "deviceToken = $1 AND deviceName = $2", params: [deviceToken, deviceName], cursor: StORMCursor(limit: 1, offset: 0))
} catch {
LogFile.error("\(error)")
}
}
}
| apache-2.0 | b6cb629723e7b16e21c573746f8612fc | 25.870968 | 142 | 0.642857 | 3.456432 | false | false | false | false |
feiin/VPNOn | VPNOn/VPNTableViewController.swift | 2 | 14375 | //
// VPNTableViewController.swift
// VPN On
//
// Created by Lex Tang on 12/4/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import UIKit
import CoreData
import NetworkExtension
import VPNOnKit
let kVPNIDKey = "VPNID"
let kVPNConnectionSection = 0
let kVPNOnDemandSection = 1
let kVPNListSectionIndex = 2
let kVPNAddSection = 3
let kConnectionCellID = "ConnectionCell"
let kAddCellID = "AddCell"
let kVPNCellID = "VPNCell"
let kOnDemandCellID = "OnDemandCell"
let kDomainsCellID = "DomainsCell"
class VPNTableViewController: UITableViewController, SimplePingDelegate, VPNDomainsViewControllerDelegate
{
var vpns = [VPN]()
var activatedVPNID: String? = nil
var connectionStatus = NSLocalizedString("Not Connected", comment: "VPN Table - Connection Status")
var connectionOn = false
@IBOutlet weak var restartPingButton: UIBarButtonItem!
override func loadView() {
super.loadView()
let backgroundView = LTViewControllerBackground()
tableView.backgroundView = backgroundView
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kVPNDidCreate, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kVPNDidUpdate, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kVPNDidRemove, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kVPNDidDuplicate, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pingDidUpdate:"), name: "kPingDidUpdate", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pingDidComplete:"), name: "kPingDidComplete", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("geoDidUpdate:"), name: "kGeoDidUpdate", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("selectionDidChange:"), name: "kSelectionDidChange", object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: Selector("VPNStatusDidChange:"),
name: NEVPNStatusDidChangeNotification,
object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: kVPNDidCreate, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: kVPNDidUpdate, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: kVPNDidRemove, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: kVPNDidDuplicate, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "kPingDidUpdate", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "kPingDidComplete", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "kGeoDidUpdate", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "kSelectionDidChange", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(
self,
name: NEVPNStatusDidChangeNotification,
object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadVPNs()
}
func reloadVPNs() {
vpns = VPNDataManager.sharedManager.allVPN()
if let selectedID = VPNDataManager.sharedManager.selectedVPNID {
if selectedID != activatedVPNID {
activatedVPNID = selectedID.URIRepresentation().absoluteString
tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section
{
case kVPNOnDemandSection:
if VPNManager.sharedManager.onDemand {
return 2
}
return 1
case kVPNListSectionIndex:
return vpns.count
default:
return 1
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section
{
case kVPNConnectionSection:
let cell = tableView.dequeueReusableCellWithIdentifier(kConnectionCellID, forIndexPath: indexPath) as! VPNSwitchCell
cell.titleLabel!.text = connectionStatus
cell.switchButton.on = connectionOn
cell.switchButton.enabled = vpns.count != 0
return cell
case kVPNOnDemandSection:
if indexPath.row == 0 {
let switchCell = tableView.dequeueReusableCellWithIdentifier(kOnDemandCellID) as! VPNSwitchCell
switchCell.switchButton.on = VPNManager.sharedManager.onDemand
return switchCell
} else {
let domainsCell = tableView.dequeueReusableCellWithIdentifier(kDomainsCellID) as! VPNTableViewCell
var domainsCount = 0
for domain in VPNManager.sharedManager.onDemandDomainsArray as [String] {
if domain.rangeOfString("*.") == nil {
domainsCount++
}
}
let domainsCountFormat = NSLocalizedString("%d Domains", comment: "VPN Table - Domains count")
domainsCell.detailTextLabel!.text = String(format: domainsCountFormat, domainsCount)
return domainsCell
}
case kVPNListSectionIndex:
let cell = tableView.dequeueReusableCellWithIdentifier(kVPNCellID, forIndexPath: indexPath) as! VPNTableViewCell
let vpn = vpns[indexPath.row]
cell.textLabel?.attributedText = cellTitleForIndexPath(indexPath)
cell.detailTextLabel?.text = vpn.server
cell.IKEv2 = vpn.ikev2
cell.imageView!.image = nil
if let cc = vpn.countryCode {
if let image = UIImage(named: cc) {
cell.imageView!.image = image
}
}
cell.current = Bool(activatedVPNID == vpns[indexPath.row].ID)
return cell
default:
return tableView.dequeueReusableCellWithIdentifier(kAddCellID, forIndexPath: indexPath) as! UITableViewCell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section
{
case kVPNAddSection:
VPNDataManager.sharedManager.selectedVPNID = nil
let detailNavigationController = splitViewController!.viewControllers.last! as! UINavigationController
detailNavigationController.popToRootViewControllerAnimated(false)
splitViewController!.viewControllers.last!.performSegueWithIdentifier("config", sender: nil)
break
case kVPNOnDemandSection:
if indexPath.row == 1 {
let detailNavigationController = splitViewController!.viewControllers.last! as! UINavigationController
detailNavigationController.popToRootViewControllerAnimated(false)
splitViewController!.viewControllers.last!.performSegueWithIdentifier("domains", sender: nil)
}
break
case kVPNListSectionIndex:
activatedVPNID = vpns[indexPath.row].ID
VPNManager.sharedManager.activatedVPNID = activatedVPNID
tableView.reloadData()
break
default:
()
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
switch indexPath.section
{
case kVPNListSectionIndex:
return 60
default:
return 44
}
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == kVPNListSectionIndex {
return 20
}
return 0
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == kVPNListSectionIndex && vpns.count > 0 {
return NSLocalizedString("VPN CONFIGURATIONS", comment: "VPN Table - List Section Header")
}
return .None
}
// MARK: - Notifications
func reloadDataAndPopDetail(notification: NSNotification) {
vpns = VPNDataManager.sharedManager.allVPN()
tableView.reloadData()
if let vpn = notification.object as! VPN? {
NSNotificationCenter.defaultCenter().postNotificationName("kGeoDidUpdate", object: vpn)
}
popDetailViewController()
VPNManager.sharedManager.seeYaInAnothaLifeBrotha()
}
func selectionDidChange(notification: NSNotification) {
reloadVPNs()
}
// MARK: - Navigation
func popDetailViewController() {
let topNavigationController = splitViewController!.viewControllers.last! as! UINavigationController
topNavigationController.popViewControllerAnimated(true)
}
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
if indexPath.section == kVPNListSectionIndex {
let VPNID = vpns[indexPath.row].objectID
VPNDataManager.sharedManager.selectedVPNID = VPNID
let detailNavigationController = splitViewController!.viewControllers.last! as! UINavigationController
detailNavigationController.popToRootViewControllerAnimated(false)
detailNavigationController.performSegueWithIdentifier("config", sender: self)
}
}
// MARK: - Cell title
func cellTitleForIndexPath(indexPath: NSIndexPath) -> NSAttributedString {
let vpn = vpns[indexPath.row]
let latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server)
let titleAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
]
var attributedTitle = NSMutableAttributedString(string: vpn.title, attributes: titleAttributes)
if latency != -1 {
var latencyColor = UIColor(red:0.39, green:0.68, blue:0.19, alpha:1)
if latency > 200 {
latencyColor = UIColor(red:0.73, green:0.54, blue:0.21, alpha:1)
} else if latency > 500 {
latencyColor = UIColor(red:0.9 , green:0.11, blue:0.34, alpha:1)
}
let latencyAttributes = [
NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote),
NSForegroundColorAttributeName: latencyColor
]
var attributedLatency = NSMutableAttributedString(string: " \(latency)ms", attributes: latencyAttributes)
attributedTitle.appendAttributedString(attributedLatency)
}
return attributedTitle
}
// MARK: - Ping
@IBAction func pingServers() {
restartPingButton.enabled = false
LTPingQueue.sharedQueue.restartPing()
}
func pingDidUpdate(notification: NSNotification) {
tableView.reloadData()
}
func pingDidComplete(notification: NSNotification) {
restartPingButton.enabled = true
}
// MARK: - Connection
@IBAction func toggleVPN(sender: UISwitch) {
if sender.on {
if let vpn = VPNDataManager.sharedManager.activatedVPN {
let passwordRef = VPNKeychainWrapper.passwordForVPNID(vpn.ID)
let secretRef = VPNKeychainWrapper.secretForVPNID(vpn.ID)
let certificate = VPNKeychainWrapper.certificateForVPNID(vpn.ID)
if vpn.ikev2 {
VPNManager.sharedManager.connectIKEv2(vpn.title, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate)
} else {
VPNManager.sharedManager.connectIPSec(vpn.title, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate)
}
}
} else {
VPNManager.sharedManager.disconnect()
}
}
func VPNStatusDidChange(notification: NSNotification?) {
switch VPNManager.sharedManager.status
{
case NEVPNStatus.Connecting:
connectionStatus = NSLocalizedString("Connecting...", comment: "VPN Table - Connection Status")
connectionOn = true
break
case NEVPNStatus.Connected:
connectionStatus = NSLocalizedString("Connected", comment: "VPN Table - Connection Status")
connectionOn = true
break
case NEVPNStatus.Disconnecting:
connectionStatus = NSLocalizedString("Disconnecting...", comment: "VPN Table - Connection Status")
connectionOn = false
break
default:
connectionStatus = NSLocalizedString("Not Connected", comment: "VPN Table - Connection Status")
connectionOn = false
}
if vpns.count > 0 {
let connectionIndexPath = NSIndexPath(forRow: 0, inSection: kVPNConnectionSection)
tableView.reloadRowsAtIndexPaths([connectionIndexPath], withRowAnimation: .None)
}
}
}
| mit | a0779b555de9d910636a29167cf37dab | 39.153631 | 226 | 0.641809 | 5.697582 | false | false | false | false |
mownier/photostream | Photostream/Modules/Single Post/Presenter/SinglePostPresenter.swift | 1 | 2427 | //
// SinglePostPresenter.swift
// Photostream
//
// Created by Mounir Ybanez on 19/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
protocol SinglePostPresenterInterface: BaseModulePresenter, BaseModuleInteractable {
var postId: String { set get }
var postData: SinglePostData? { set get }
}
class SinglePostPresenter: SinglePostPresenterInterface {
typealias ModuleView = SinglePostScene
typealias ModuleInteractor = SinglePostInteractorInput
typealias ModuleWireframe = SinglePostWireframeInterface
weak var view: ModuleView!
var interactor: ModuleInteractor!
var wireframe: ModuleWireframe!
var postId: String = ""
var postData: SinglePostData?
}
extension SinglePostPresenter: SinglePostModuleInterface {
func exit() {
var property = WireframeExitProperty()
property.controller = view.controller
wireframe.exit(with: property)
}
func viewDidLoad() {
view.isLoadingViewHidden = false
fetchPost()
}
func fetchPost() {
interactor.fetchPost(id: postId)
}
func likePost() {
guard postData != nil else {
return
}
postData!.isLiked = true
postData!.likes += 1
view.reload()
interactor.likePost(id: postId)
}
func unlikePost() {
guard postData != nil else {
return
}
postData!.isLiked = false
if postData!.likes > 0 {
postData!.likes -= 1
}
view.reload()
interactor.unlikePost(id: postId)
}
func toggleLike() {
guard postData != nil else {
return
}
if postData!.isLiked {
unlikePost()
} else {
likePost()
}
}
}
extension SinglePostPresenter: SinglePostInteractorOutput {
func didFetchPost(data: SinglePostData) {
postData = data
view.isLoadingViewHidden = true
view.reload()
}
func didFetchPost(error: PostServiceError) {
view.isLoadingViewHidden = true
view.didFetch(error: error.message)
}
func didLike(error: PostServiceError?) {
view.didLike(error: error?.message)
}
func didUnlike(error: PostServiceError?) {
view.didUnlike(error: error?.message)
}
}
| mit | 449e505d786e332903b57b2fed89c49b | 22.326923 | 84 | 0.598516 | 4.852 | false | false | false | false |
tinrobots/CoreDataPlus | Sources/NSAttributeDescription+Utils.swift | 1 | 8567 | // CoreDataPlus
// https://developer.apple.com/documentation/coredata/nsattributetype
//
// About the NSAttributeDescription isOptional property:
//
// The underlying SQLite database has the is_nullable value always set to TRUE for every table's column.
// So, it seems that the isOptional is evaluated only at runtime (like probably many other CoreData properties, i.e. uniquenessConstraints)
//
// This can be verified easily if during a save we set not optional values to nil through their primitive values; the save will succeed.
//
// public override func willSave() {
// setPrimitiveValue(nil, forKey: MY_KEY)
// }
import CoreData
extension NSEntityDescription {
/// Creates a new NSEntityDescription instance.
/// - Parameters:
/// - aClass: The class that represents the entity.
/// - name: The entity name (defaults to the class name).
public convenience init<T: NSManagedObject>(for aClass: T.Type, withName name: String? = .none) {
self.init()
self.managedObjectClassName = String(describing: aClass.self)
// unless specified otherwise the entity name is equal to the class name
self.name = (name == nil) ? String(describing: T.self) : name
self.isAbstract = false
self.subentities = []
}
/// Adds a property description
public func add(_ property: NSPropertyDescription) {
properties.append(property)
}
}
extension NSAttributeDescription {
/// - Parameters:
/// - name: The name of the attribute.
/// - defaultValue: The default value of the attribute.
/// - Returns: Returns a *Int16* attribute description.
public static func int16(name: String, defaultValue: Int16? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .integer16AttributeType)
attributes.defaultValue = defaultValue.map { NSNumber(value: $0) }
return attributes
}
public static func int32(name: String, defaultValue: Int32? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .integer32AttributeType)
attributes.defaultValue = defaultValue.map { NSNumber(value: $0) }
return attributes
}
public static func int64(name: String, defaultValue: Int64? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .integer64AttributeType)
attributes.defaultValue = defaultValue.map { NSNumber(value: $0) }
return attributes
}
public static func decimal(name: String, defaultValue: Decimal? = nil) -> NSAttributeDescription {
// https://stackoverflow.com/questions/2376853/core-data-decimal-type-for-currency
let attributes = NSAttributeDescription(name: name, type: .decimalAttributeType)
attributes.defaultValue = defaultValue.map { NSDecimalNumber(decimal: $0) }
return attributes
}
public static func float(name: String, defaultValue: Float? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .floatAttributeType)
attributes.defaultValue = defaultValue.map { NSNumber(value: $0) }
return attributes
}
public static func double(name: String, defaultValue: Double? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .doubleAttributeType)
attributes.defaultValue = defaultValue.map { NSNumber(value: $0) }
return attributes
}
public static func string(name: String, defaultValue: String? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .stringAttributeType)
attributes.defaultValue = defaultValue
return attributes
}
public static func bool(name: String, defaultValue: Bool? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .booleanAttributeType)
attributes.defaultValue = defaultValue.map { NSNumber(value: $0) }
return attributes
}
public static func date(name: String, defaultValue: Date? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .dateAttributeType)
attributes.defaultValue = defaultValue
return attributes
}
public static func uuid(name: String, defaultValue: UUID? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .UUIDAttributeType)
attributes.defaultValue = defaultValue
return attributes
}
public static func uri(name: String, defaultValue: URL? = nil) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .URIAttributeType)
attributes.defaultValue = defaultValue
return attributes
}
public static func binaryData(name: String, defaultValue: Data? = nil, allowsExternalBinaryDataStorage: Bool = false) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .binaryDataAttributeType)
attributes.defaultValue = defaultValue
attributes.allowsExternalBinaryDataStorage = allowsExternalBinaryDataStorage
return attributes
}
// transformerName needs to be unique
private static func transformable<T: NSObject & NSSecureCoding>(for aClass: T.Type,
name: String,
defaultValue: T? = nil,
valueTransformerName: String) -> NSAttributeDescription {
let attributes = NSAttributeDescription(name: name, type: .transformableAttributeType)
attributes.defaultValue = defaultValue
attributes.attributeValueClassName = "\(T.self.classForCoder())"
attributes.valueTransformerName = valueTransformerName
return attributes
}
public static func customTransformable<T: NSObject & NSSecureCoding>(for aClass: T.Type,
name: String,
defaultValue: T? = nil,
transform: @escaping CustomTransformer<T>.Transform,
reverse: @escaping CustomTransformer<T>.ReverseTransform) -> NSAttributeDescription {
CustomTransformer<T>.register(transform: transform, reverseTransform: reverse)
let attributes = NSAttributeDescription.transformable(for: T.self,
name: name,
defaultValue: defaultValue,
valueTransformerName: CustomTransformer<T>.transformerName.rawValue)
return attributes
}
public static func transformable<T: NSObject & NSSecureCoding>(for aClass: T.Type,
name: String,
defaultValue: T? = nil) -> NSAttributeDescription {
Transformer<T>.register()
let attributes = NSAttributeDescription.transformable(for: T.self,
name: name,
defaultValue: defaultValue,
valueTransformerName: Transformer<T>.transformerName.rawValue)
return attributes
}
/// Creates a new `NSAttributeDescription` instance.
/// - Parameters:
/// - name: The name of the attribute.
/// - type: The type of the attribute.
public convenience init(name: String, type: NSAttributeType) {
self.init()
self.name = name
self.attributeType = type
}
}
// Decimal, Double, and Float data types are for storing fractional numbers.
//
// The Double data type uses 64 bits to store a value while the Float data type uses 32 bits for storing a value.
// The only limitation with these two data types is that they round off the values.
// To avoid any rounding of values, the Decimal data type is preferred. The Decimal type uses fixed point numbers for storing values, so the numerical value stored in it is not rounded of
// "Optional" means something different to Core Data than it does to Swift.
//
// If a Core Data attribute is not optional, it must have a non-nil value when you save changes. At other times Core Data doesn't care if the attribute is nil.
// If a Swift property is not optional, it must have a non-nil value at all times after initialization is complete.
| mit | f242ef050ec9327964a8de62ee64afd0 | 48.520231 | 187 | 0.66371 | 5.252606 | false | false | false | false |
firebase/firebase-ios-sdk | FirebaseStorage/Sources/StorageTaskSnapshot.swift | 1 | 2755 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/**
* `StorageTaskSnapshot` represents an immutable view of a task.
* A snapshot contains a task, storage reference, metadata (if it exists),
* progress, and an error (if one occurred).
*/
@objc(FIRStorageTaskSnapshot) open class StorageTaskSnapshot: NSObject {
/**
* The task this snapshot represents.
*/
@objc public let task: StorageTask
/**
* Metadata returned by the task, or `nil` if no metadata returned.
*/
@objc public let metadata: StorageMetadata?
/**
* The `StorageReference` this task operates on.
*/
@objc public let reference: StorageReference
/**
* An object which tracks the progress of an upload or download.
*/
@objc public let progress: Progress?
/**
* An error raised during task execution, or `nil` if no error occurred.
*/
@objc public let error: Error?
/**
* The status of the task.
*/
@objc public let status: StorageTaskStatus
// MARK: NSObject overrides
@objc override public var description: String {
switch status {
case .resume: return "<State: Resume>"
case .progress: return "<State: Progress, Progress: \(String(describing: progress))>"
case .pause: return "<State: Paused>"
case .success: return "<State: Success>"
case .failure: return "<State: Failed, Error: \(String(describing: error))"
case .unknown: return "<State: Unknown>"
}
}
internal init(task: StorageTask,
state: StorageTaskState,
reference: StorageReference,
progress: Progress,
metadata: StorageMetadata? = nil,
error: NSError? = nil) {
self.task = task
self.reference = reference
self.progress = progress
self.error = error
self.metadata = metadata
switch state {
case .queueing, .running, .resuming: status = StorageTaskStatus.resume
case .progress: status = StorageTaskStatus.progress
case .paused, .pausing: status = StorageTaskStatus.pause
case .success, .completing: status = StorageTaskStatus.success
case .cancelled, .failed, .failing: status = .failure
case .unknown: status = .unknown
}
}
}
| apache-2.0 | 844888a59a98fa08b1fc71b1070bd828 | 30.666667 | 89 | 0.67804 | 4.291277 | false | false | false | false |
iHunterX/SocketIODemo | DemoSocketIO/Utils/Validator/Rules/ValidationRulePattern.swift | 1 | 2379 | /*
ValidationRulePattern.swift
Validator
Created by @adamwaite.
Copyright (c) 2015 Adam Waite. 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
public enum ValidationPattern: String {
case UserName = "^[a-zA-Z0-9_.-]*$"
case EmailAddress = "^[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-+]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$"
case ContainsNumber = ".*\\d.*"
case ContainsCapital = "^.*?[A-Z].*?$"
case ContainsLowercase = "^.*?[a-z].*?$"
case UKPostcode = "(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY]))))[ ]?[0-9][A-Z-[CIKMOV]]{2})"
}
public struct ValidationRulePattern: ValidationRule {
public typealias InputType = String
public let pattern: String
public let failureError: ValidationErrorType
public init(pattern: String, failureError: ValidationErrorType) {
self.pattern = pattern
self.failureError = failureError
}
public init(pattern: ValidationPattern, failureError: ValidationErrorType) {
self.init(pattern: pattern.rawValue, failureError: failureError)
}
public func validateInput(input: String?) -> Bool {
return NSPredicate(format: "SELF MATCHES %@", pattern).evaluate(with: input)
}
}
| gpl-3.0 | d398b156087139fe41a59210820bbe96 | 37.934426 | 203 | 0.691368 | 3.757911 | false | false | false | false |
Lclmyname/BookReader_Swift | Pods/SnapKit/Source/Constraint.swift | 1 | 11145 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
open class Constraint {
internal let sourceLocation: (String, UInt)
internal let label: String?
fileprivate let from: ConstraintItem
fileprivate let to: ConstraintItem
fileprivate let relation: ConstraintRelation
fileprivate let multiplier: ConstraintMultiplierTarget
fileprivate var constant: ConstraintConstantTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
fileprivate var priority: ConstraintPriorityTarget {
didSet {
self.updateConstantAndPriorityIfNeeded()
}
}
fileprivate var layoutConstraints: [LayoutConstraint]
// MARK: Initialization
internal init(from: ConstraintItem,
to: ConstraintItem,
relation: ConstraintRelation,
sourceLocation: (String, UInt),
label: String?,
multiplier: ConstraintMultiplierTarget,
constant: ConstraintConstantTarget,
priority: ConstraintPriorityTarget) {
self.from = from
self.to = to
self.relation = relation
self.sourceLocation = sourceLocation
self.label = label
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.layoutConstraints = []
// get attributes
let layoutFromAttributes = self.from.attributes.layoutAttributes
let layoutToAttributes = self.to.attributes.layoutAttributes
// get layout from
let layoutFrom: ConstraintView = self.from.view!
// get relation
let layoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute: NSLayoutAttribute
#if os(iOS) || os(tvOS)
if layoutToAttributes.count > 0 {
if self.from.attributes == .edges && self.to.attributes == .margins {
switch layoutFromAttribute {
case .left:
layoutToAttribute = .leftMargin
case .right:
layoutToAttribute = .rightMargin
case .top:
layoutToAttribute = .topMargin
case .bottom:
layoutToAttribute = .bottomMargin
default:
fatalError()
}
} else if self.from.attributes == .margins && self.to.attributes == .edges {
switch layoutFromAttribute {
case .leftMargin:
layoutToAttribute = .left
case .rightMargin:
layoutToAttribute = .right
case .topMargin:
layoutToAttribute = .top
case .bottomMargin:
layoutToAttribute = .bottom
default:
fatalError()
}
} else if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else {
layoutToAttribute = layoutToAttributes[0]
}
} else {
layoutToAttribute = layoutFromAttribute
}
#else
if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else if layoutToAttributes.count > 0 {
layoutToAttribute = layoutToAttributes[0]
} else {
layoutToAttribute = layoutFromAttribute
}
#endif
// get layout constant
let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutToAttribute)
// get layout to
var layoutTo: AnyObject? = self.to.target
// use superview if possible
if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
layoutTo = layoutFrom.superview
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: self.multiplier.constraintMultiplierTargetValue,
constant: layoutConstant
)
// set label
layoutConstraint.label = self.label
// set priority
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
// set constraint
layoutConstraint.constraint = self
// append
self.layoutConstraints.append(layoutConstraint)
}
}
// MARK: Public
@available(*, deprecated:3.0, message:"Use activate().")
open func install() {
self.activate()
}
@available(*, deprecated:3.0, message:"Use deactivate().")
open func uninstall() {
self.deactivate()
}
open func activate() {
self.activateIfNeeded()
}
open func deactivate() {
self.deactivateIfNeeded()
}
@discardableResult
open func update(_ offset: ConstraintOffsetTarget) -> Constraint {
self.constant = offset.constraintOffsetTargetValue
return self
}
@discardableResult
open func update(_ inset: ConstraintInsetTarget) -> Constraint {
self.constant = inset.constraintInsetTargetValue
return self
}
@discardableResult
open func update(_ priority: ConstraintPriorityTarget) -> Constraint {
self.priority = priority.constraintPriorityTargetValue
return self
}
@available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.")
open func updateOffset(_ amount: ConstraintOffsetTarget) -> Void {
// self.update(offset: amount)
}
@available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.")
open func updateInsets(_ amount: ConstraintInsetTarget) -> Void {
// self.update(inset: amount)
}
@available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
open func updatePriority(_ amount: ConstraintPriorityTarget) -> Void {
// self.update(priority: amount)
}
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
open func updatePriorityRequired() -> Void {}
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
open func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
open func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
@available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
open func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
// MARK: Internal
internal func updateConstantAndPriorityIfNeeded() {
for layoutConstraint in self.layoutConstraints {
let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(attribute)
layoutConstraint.priority = self.priority.constraintPriorityTargetValue
}
}
internal func activateIfNeeded(_ updatingExisting: Bool = false) {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 }
if updatingExisting {
for layoutConstraint in layoutConstraints {
let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
guard let updateLayoutConstraint = existingLayoutConstraint else {
fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
}
let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(updateLayoutAttribute)
}
} else {
NSLayoutConstraint.activate(layoutConstraints)
view.snp.add([self])
}
}
internal func deactivateIfNeeded() {
guard let view = self.from.view else {
print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
NSLayoutConstraint.deactivate(layoutConstraints)
view.snp.remove([self])
}
}
| mit | 88508766d3407ed2e23042d2fc7ed71b | 39.675182 | 184 | 0.602871 | 6.027582 | false | false | false | false |
leo-lp/LPIM | LPIM+UIKit/SessionList/LPKSessionListViewController.swift | 1 | 13801 | //
// LPKSessionListViewController.swift
// LPIM
//
// Created by lipeng on 2017/6/19.
// Copyright © 2017年 lipeng. All rights reserved.
//
import UIKit
import NIMSDK
import Kingfisher
private let kCellID = "LPKSessionListCell"
class LPKSessionListViewController: UIViewController {
/// 会话列表tableView
lazy var tableView: UITableView = {
let tableView = UITableView(frame: self.view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
return tableView
}()
/// 最近会话集合
lazy var recentSessions: [NIMRecentSession] = []
/// 删除会话时是不是也同时删除服务器会话 (防止漫游)
lazy var autoRemoveRemoteSession = true
deinit {
NIMSDK.shared().conversationManager.remove(self)
NIMSDK.shared().loginManager.remove(self)
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.addSubview(tableView)
if let recents = NIMSDK.shared().conversationManager.allRecentSessions() {
recentSessions = recents
}
NIMSDK.shared().conversationManager.add(self)
NIMSDK.shared().loginManager.add(self)
NotificationCenter.default.addObserver(self,
selector: #selector(teamInfoHasUpdatedNotification),
name: LPKTeamInfoHasUpdatedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(teamMembersHasUpdatedNotification),
name: LPKTeamMembersHasUpdatedNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(userInfoHasUpdatedNotification),
name: LPKUserInfoHasUpdatedNotification,
object: nil)
}
/// 选中某一条最近会话时触发的事件回调
/// discussion: 默认将进入会话界面
///
/// - Parameters:
/// - recent: 最近会话
/// - indexPath: 最近会话cell所在的位置
func selectedRecent(at indexPath: IndexPath, recent: NIMRecentSession) {
// NIMSessionViewController *vc = [[NIMSessionViewController alloc] initWithSession:recentSession.session];
// [self.navigationController pushViewController:vc animated:YES];
}
/// 选中某一条最近会话的头像控件,触发的事件回调
/// discussion: 默认将进入会话界面
///
/// - Parameters:
/// - recent: 最近会话
/// - at: 最近会话cell所在的位置
func selectedAvatar(at indexPath: IndexPath, recent: NIMRecentSession) {
}
/// 删除某一条最近会话时触发的事件回调
/// discussion: 默认将删除会话,并检查是否需要删除服务器的会话(防止漫游)
///
/// - Parameters:
/// - indexPath: 最近会话cell所在的位置
/// - recent: 最近会话
func deleteRecent(at indexPath: IndexPath, recent: NIMRecentSession) {
let manager = NIMSDK.shared().conversationManager
manager.delete(recent)
}
/// cell显示的会话名
/// discussion: 默认实现为:点对点会话,显示聊天对象的昵称(没有昵称则显示账号);群聊会话,显示群名称。
///
/// - Parameter recent: 最近会话
/// - Returns: 会话名
func nameForRecentSession(_ recent: NIMRecentSession) -> String? {
guard let session = recent.session else { return "" }
if session.sessionType == .P2P {
return LPKUtil.showNick(uid: session.sessionId, in: recent.session)
} else {
let team = NIMSDK.shared().teamManager.team(byId: session.sessionId)
return team?.teamName
}
}
/// cell显示的最近会话具体内容
/// discussion: 默认实现为:显示最近一条消息的内容,文本消息则显示文本信息,其他类型消息详见本类中 func messageContent(_:NIMMessage) -> String 方法的实现。
///
/// - Parameter recent: 最近会话
/// - Returns: 具体内容名
func contentForRecentSession(_ recent: NIMRecentSession) -> NSAttributedString {
if let lastmessage = recent.lastMessage {
let content = messageContent(lastmessage)
return NSAttributedString(string: content)
}
return NSAttributedString(string: "")
}
/// cell显示的最近会话时间戳
/// DISCUSSION: 默认实现为:最后一条消息的时间戳,具体时间戳消息格式详见LPKUtil中,class func showTime(:TimeInterval,:Bool) -> String 方法的实现。
///
/// - Parameter recent: 最近会话
/// - Returns: 时间戳格式化后的字符串
func timestampDescription(for recent: NIMRecentSession) -> String {
if let lastMessage = recent.lastMessage {
return LPKUtil.showTime(msglastTime: lastMessage.timestamp, showDetail: false)
}
return ""
}
/// 重新加载所有数据,调用时必须先调用父类方法
///
/// - Parameter reload: 是否刷新列表
func refresh(_ reload: Bool) {
if recentSessions.count > 0 {
tableView.isHidden = false
} else {
tableView.isHidden = true
}
if reload {
tableView.reloadData()
}
}
}
// MARK: - Private / Misc
extension LPKSessionListViewController {
func findInsertPlace(_ recentSession: NIMRecentSession) -> Int {
for (idx, item) in recentSessions.enumerated() {
if let lastmessage = recentSession.lastMessage, let itemLastmessage = item.lastMessage {
if itemLastmessage.timestamp <= lastmessage.timestamp {
return idx
}
}
}
return recentSessions.count
}
func sort() {
recentSessions.sort { (item1, item2) -> Bool in
if let lastmsg1 = item1.lastMessage, let lastmsg2 = item2.lastMessage {
return lastmsg1.timestamp < lastmsg2.timestamp
}
return false
}
}
func messageContent(_ lastMessage: NIMMessage) -> String {
var text: String
switch lastMessage.messageType {
case .text: text = lastMessage.text ?? ""
case .audio: text = "[语音]"
case .image: text = "[图片]"
case .video: text = "[视频]"
case .location: text = "[位置]"
case .notification:
return notificationMessageContent(lastMessage)
case .file: text = "[文件]"
case .tip: text = lastMessage.text ?? ""
default: text = "[未知消息]"
}
if lastMessage.messageType == .tip {
return text
}
if let session = lastMessage.session, session.sessionType == .P2P {
return text
}
if let nickName = LPKUtil.showNick(uid: lastMessage.from, in: lastMessage.session), nickName.characters.count > 0 {
return "\(nickName) : \(text)"
}
return ""
}
func avatarClicked(_ sender: UIButton) {
var view = sender.superview
while !(view is UITableViewCell) {
view = view?.superview
}
if let cell = view as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) {
if recentSessions.count > indexPath.row {
let recent = recentSessions[indexPath.row]
selectedAvatar(at: indexPath, recent: recent)
}
}
}
}
// MARK: -
// MARK: - Delegate / Notification
extension LPKSessionListViewController: UITableViewDataSource, UITableViewDelegate, NIMLoginManagerDelegate, NIMConversationManagerDelegate {
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recentSessions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
func lp_cell(with tableView: UITableView) -> LPKSessionListCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: kCellID) {
return cell as! LPKSessionListCell
}
let cell = LPKSessionListCell(style: .default, reuseIdentifier: kCellID)
cell.avatarButton.addTarget(self, action: #selector(avatarClicked), for: .touchUpInside)
return cell
}
let cell = lp_cell(with: tableView)
let recent = recentSessions[indexPath.row]
cell.nameLabel.text = nameForRecentSession(recent)
cell.avatarButton.setAvatar(bySession: recent.session)
cell.nameLabel.sizeToFit()
cell.messageLabel.attributedText = contentForRecentSession(recent)
cell.messageLabel.sizeToFit()
cell.timeLabel.text = timestampDescription(for: recent)
cell.timeLabel.sizeToFit()
cell.refresh(with: recent)
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let recentSession = recentSessions[indexPath.row]
selectedRecent(at: indexPath, recent: recentSession)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70.0
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let recentSession = recentSessions[indexPath.row]
deleteRecent(at: indexPath, recent: recentSession)
}
}
// MARK: - NIMConversationManagerDelegate
func didAdd(_ recentSession: NIMRecentSession, totalUnreadCount: Int) {
recentSessions.append(recentSession)
sort()
refresh(true)
}
func didUpdate(_ recentSession: NIMRecentSession, totalUnreadCount: Int) {
for (idx, recent) in recentSessions.enumerated() {
if recentSession.session?.sessionId == recent.session?.sessionId {
recentSessions.remove(at: idx)
break
}
}
let insert = findInsertPlace(recentSession)
recentSessions.insert(recentSession, at: insert)
refresh(true)
}
func didRemove(_ recentSession: NIMRecentSession, totalUnreadCount: Int) {
//清理本地数据
if let index = recentSessions.index(of: recentSession) {
recentSessions.remove(at: index)
let indexPath = IndexPath(row: index, section: 0)
tableView.deleteRows(at: [indexPath], with: .fade)
//如果删除本地会话后就不允许漫游当前会话,则需要进行一次删除服务器会话的操作
if autoRemoveRemoteSession, let session = recentSession.session {
NIMSDK.shared().conversationManager.deleteRemoteSessions([session], completion: nil)
}
}
refresh(false)
}
func messagesDeleted(in session: NIMSession) {
allMessagesDeleted()
}
func allMessagesDeleted() {
if let recents = NIMSDK.shared().conversationManager.allRecentSessions() {
recentSessions = recents
} else {
recentSessions.removeAll()
}
refresh(true)
}
// MARK: - NIMLoginManagerDelegate
func onLogin(_ step: NIMLoginStep) {
if step == .syncOK {
refresh(true)
}
}
func onMultiLoginClientsChanged() {
}
func notificationMessageContent(_ lastMessage: NIMMessage) -> String {
if let object = lastMessage.messageObject as? NIMNotificationObject {
if object.notificationType == .netCall, let content = object.content as? NIMNetCallNotificationContent {
if content.callType == .audio {
return "[网络通话]"
}
return "[视频聊天]"
}
if object.notificationType == .team, let sessionId = lastMessage.session?.sessionId {
if let team = NIMSDK.shared().teamManager.team(byId: sessionId), team.type == .normal {
return "[讨论组信息更新]"
} else {
return "[群信息更新]"
}
}
}
return "[未知消息]"
}
// MARK: - Notification
func userInfoHasUpdatedNotification(_ notification: Notification) {
refresh(true)
}
func teamInfoHasUpdatedNotification(_ notification: Notification) {
refresh(true)
}
func teamMembersHasUpdatedNotification(_ notification: Notification) {
refresh(true)
}
}
| mit | 860a45a2195dc31754a39c4f4e92dc5b | 33.314667 | 141 | 0.590457 | 4.751846 | false | false | false | false |
KinveyClientServices/training-app-ios | TrainingApp/Partner.swift | 1 | 1072 | //
// Partner.swift
// TrainingApp
//
// Created by Victor Barros on 2016-02-08.
// Copyright © 2016 Kinvey. All rights reserved.
//
import Foundation
import Kinvey
class Partner: Entity {
dynamic var name: String?
dynamic var company: String?
dynamic var email: String?
class func build(name: String? = nil, company: String? = nil, email: String? = nil) -> Partner {
let partner = Partner()
if let name = name {
partner.name = name
}
if let company = company {
partner.company = company
}
if let email = email {
partner.email = email
}
return partner
}
override class func collectionName() -> String {
return "Partner"
}
override func propertyMapping(map: Map) {
super.propertyMapping(map)
//TODO: LAB: map the entity properties
name <- ("partnername", map["partnername"])
company <- ("partnercompany", map["partnercompany"])
email <- ("email", map["email"])
}
}
| apache-2.0 | 9513c191db31f84fa6c714c643b22dbb | 23.340909 | 100 | 0.573296 | 4.336032 | false | false | false | false |
PureSwift/Predicate | Sources/Predicate.swift | 1 | 2552 | //
// Predicate.swift
// Predicate
//
// Created by Alsey Coleman Miller on 4/2/17.
// Copyright © 2017 PureSwift. All rights reserved.
//
/// You use predicates to represent logical conditions,
/// used for describing objects in persistent stores and in-memory filtering of objects.
public enum Predicate: Equatable, Hashable {
case comparison(Comparison)
case compound(Compound)
case value(Bool)
}
/// Predicate Type
public enum PredicateType: String, Codable {
case comparison
case compound
case value
}
public extension Predicate {
/// Predicate Type
var type: PredicateType {
switch self {
case .comparison: return .comparison
case .compound: return .compound
case .value: return .value
}
}
}
// MARK: - CustomStringConvertible
extension Predicate: CustomStringConvertible {
public var description: String {
switch self {
case let .comparison(value): return value.description
case let .compound(value): return value.description
case let .value(value): return value.description
}
}
}
// MARK: - Codable
extension Predicate: Codable {
internal enum CodingKeys: String, CodingKey {
case type
case predicate
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(PredicateType.self, forKey: .type)
switch type {
case .comparison:
let predicate = try container.decode(Comparison.self, forKey: .predicate)
self = .comparison(predicate)
case .compound:
let predicate = try container.decode(Compound.self, forKey: .predicate)
self = .compound(predicate)
case .value:
let value = try container.decode(Bool.self, forKey: .predicate)
self = .value(value)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(type, forKey: .type)
switch self {
case let .comparison(predicate):
try container.encode(predicate, forKey: .predicate)
case let .compound(predicate):
try container.encode(predicate, forKey: .predicate)
case let .value(value):
try container.encode(value, forKey: .predicate)
}
}
}
| mit | a736de4d137eb3b008bdb468fe6d1e4a | 26.138298 | 88 | 0.618189 | 4.759328 | false | false | false | false |
diegocavalca/Studies | programming/Swift/NavigationControllerClientes/NavigationControllerClientes/DCRequest.swift | 1 | 1615 | //
// DCRequest.swift
// iTunesList
//
// Created by Diego Cavalca on 02/05/15.
// Copyright (c) 2015 Diego Cavalca. All rights reserved.
//
import UIKit
class DCRequest {
internal func getData(url: String, completionHandler: ((NSData!, NSError!) -> Void)!) -> Void
{
let httpMethod = "GET"
let timeout = 15
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if (error != nil) {
return completionHandler(nil, error)
}
if data.length >= 0 && error == nil{
//let json = NSString(data: data, encoding: NSASCIIStringEncoding)
// Retornar resultado...
return completionHandler(data, nil)
} else {
return completionHandler(nil, error)
}
}
)
}
internal func parseJSON(data:NSData)->AnyObject
{
var parseError: NSError?
let parsedObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.AllowFragments,
error:&parseError)
return parsedObject!
}
} | cc0-1.0 | 5780c7c591f76407f4ac1c1f403fbac9 | 31.32 | 97 | 0.543653 | 5.456081 | false | false | false | false |
dangquochoi2007/cleancodeswift | CleanStore/CleanStore/App/Scenes/TVShows/View/TVShowsViewController.swift | 1 | 6819 | //
// TVShowsViewController.swift
// CleanStore
//
// Created by hoi on 27/6/17.
// Copyright (c) 2017 hoi. All rights reserved.
//
import UIKit
protocol TVShowsViewControllerInput: TVShowsPresenterOutput {
}
protocol TVShowsViewControllerOutput {
func doSomething()
}
final class TVShowsViewController: UIViewController {
var output: TVShowsViewControllerOutput!
var router: TVShowsRouterProtocol!
var tvShowsBackgrounColor: UIColor = UIColor(red: 22.0/255.0, green: 23.0/255.0, blue: 27.0/255.0, alpha: 0.95)
var tvShowsForegroundColor: UIColor = UIColor(red: 26.0/255.0, green: 206.0/255.0, blue: 239.0/255.0, alpha: 1)
var liveTvList: [LiveTV] = LiveTVStore.shareInstance.items()
lazy var tvShowsTableView: UITableView = { [unowned self] in
var tableView = UITableView()
tableView.register(TVShowsTableViewCell.nib, forCellReuseIdentifier: TVShowsTableViewCell.nibName)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
tableView.estimatedRowHeight = 80
tableView.delegate = self
tableView.dataSource = self
tableView.showsHorizontalScrollIndicator = false
tableView.showsVerticalScrollIndicator = false
tableView.backgroundColor = self.tvShowsBackgrounColor
tableView.tableHeaderView = self.segmentControl
return tableView
}()
lazy var segmentControl: TZSegmentedControl = { [unowned self] in
let titleCont = TZSegmentedControl(sectionTitles: ["", "FOR YOU", "TOP","ACTION", "COMEDY", "FAMILY" , "ENGLISH", "VIDEO EPIC"])
titleCont.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 50)
titleCont.indicatorWidthPercent = 1.5
titleCont.backgroundColor = self.tvShowsBackgrounColor
titleCont.borderType = .none
titleCont.borderColor = self.tvShowsBackgrounColor
titleCont.borderWidth = 2.0
titleCont.segmentWidthStyle = .dynamic
titleCont.verticalDividerEnabled = false
titleCont.verticalDividerWidth = 0
titleCont.verticalDividerColor = self.tvShowsBackgrounColor
titleCont.selectionStyle = .fullWidth
titleCont.selectionIndicatorLocation = .down
titleCont.selectionIndicatorColor = self.tvShowsForegroundColor
titleCont.selectionIndicatorHeight = 4.0
titleCont.edgeInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
titleCont.selectedTitleTextAttributes = [NSForegroundColorAttributeName: self.tvShowsForegroundColor]
titleCont.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white,
NSFontAttributeName:UIFont(name: "Lato-Bold", size: 11.0) ?? UIFont.systemFont(ofSize: 11)]
return titleCont
}()
// MARK: - Initializers
init(configurator: TVShowsConfigurator = TVShowsConfigurator.sharedInstance) {
super.init(nibName: nil, bundle: nil)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
// MARK: - Configurator
private func configure(configurator: TVShowsConfigurator = TVShowsConfigurator.sharedInstance) {
configurator.configure(viewController: self)
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "TV SHOWS"
configureControllerWhenLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
configureControllerWhenAppear()
}
// MARK: - Load data
func doSomethingOnLoad() {
// TODO: Ask the Interactor to do some work
output.doSomething()
}
func configureControllerWhenLoad() {
constraintsLayoutTableView()
configureRightMenuBarButton()
}
func configureControllerWhenAppear() {
navigationController?.navigationBar.barTintColor = tvShowsBackgrounColor
navigationController?.navigationBar.tintColor = tvShowsForegroundColor
navigationController?.navigationBar.isTranslucent = false
tabBarController?.tabBar.barTintColor = tvShowsBackgrounColor
tabBarController?.tabBar.tintColor = tvShowsForegroundColor
title = "TV SHOWS"
guard let latoBoldFont = UIFont(name: "Lato-Bold", size: 15) else {
return
}
navigationController?.navigationBar.titleTextAttributes = [
NSFontAttributeName : latoBoldFont,
NSForegroundColorAttributeName: tvShowsForegroundColor
]
}
func configureRightMenuBarButton() {
if self.revealViewController() != nil {
let mainMenuImage = UIImage(named: "artboard_ico")
let mainMenuBarButton = UIBarButtonItem(image: mainMenuImage, style: .plain, target: self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:)))
self.navigationItem.leftBarButtonItem = mainMenuBarButton
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
}
// MARK: - TVShowsPresenterOutput
extension TVShowsViewController: TVShowsViewControllerInput {
// MARK: - Display logic
func displaySomething(viewModel: TVShowsViewModel) {
// TODO: Update UI
}
}
extension TVShowsViewController: UITableViewDelegate, UITableViewDataSource {
func constraintsLayoutTableView() {
[tvShowsTableView].forEach {
self.view.addSubview($0)
}
let attributes: [NSLayoutAttribute] = [.top, .left, .bottom, .right]
for attribute in attributes {
view.addConstraint(NSLayoutConstraint(item: self.tvShowsTableView, attribute: attribute, relatedBy: .equal, toItem: view, attribute: attribute, multiplier: 1, constant: 0))
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return liveTvList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TVShowsTableViewCell.nibName, for: indexPath) as! TVShowsTableViewCell
cell.liveTv = liveTvList[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
router.navigateToTouchTVShowsViewController()
}
}
| mit | faa58b96d0dba3bf7c40fabb771d0597 | 32.263415 | 185 | 0.680305 | 5.119369 | false | true | false | false |
LDlalala/LDZBLiving | LDZBLiving/LDZBLiving/Classes/Main/Extension/UIColor-extension.swift | 1 | 1926 | //
// UIColor-extension.swift
// LDZBLiving
//
// Created by 李丹 on 17/8/2.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
extension UIColor{
// 在extentsion中给系统类扩充构造函数,只能构造'便利构造函数'
convenience init(r : CGFloat , g : CGFloat ,b : CGFloat , alpha : CGFloat = 1.0) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
}
// 便利构造函数
convenience init?(hex : String , alpha : CGFloat) {
// 1. 判断传进入的字符串是否是符合要求的
guard hex.characters.count >= 6 else {
return nil
}
// 2. 将字母转化为大写
var tmpHex = hex.uppercased()
// 3. 判断开头是 #/ 0x / ##
if tmpHex.hasPrefix("#") {
tmpHex = (tmpHex as NSString).substring(from: 1)
}
if tmpHex.hasPrefix("0x") || tmpHex.hasPrefix("##")
{
tmpHex = (tmpHex as NSString).substring(from: 2)
}
// 4. 分别取出RGB 使用Scanner
var range = NSRange(location:0 ,length:2)
let rHex = (tmpHex as NSString).substring(with: range)
range.location = 2;
let gHex = (tmpHex as NSString).substring(with: range)
range.location = 4
let bHex = (tmpHex as NSString).substring(with: range)
var r : Int32 = 0 , g : Int32 = 0, b : Int32 = 0
Scanner(string: rHex).scanInt32(&r)
Scanner(string: gHex).scanInt32(&g)
Scanner(string: bHex).scanInt32(&b)
self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b), alpha: alpha)
}
// 随机颜色
class func randomColor() -> UIColor {
return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}
}
| mit | 8cc6dfe9eda8b2b822a534481d407306 | 28.716667 | 133 | 0.54627 | 3.616633 | false | false | false | false |
LDlalala/LDZBLiving | LDZBLiving/LDZBLiving/Classes/Live/ChatView/LDEmoticonView.swift | 1 | 2883 | //
// LDEmoticonView.swift
// LDZBLiving
//
// Created by 李丹 on 17/8/21.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
class LDEmoticonView: UIView {
// 定义一个闭包在点击cell时将emoticon传递出去
var emoticonClickCallBlock : ((LDEmoticon) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
// 添加UI
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 添加UI
extension LDEmoticonView {
func setupUI() {
let frame = CGRect(x: 0, y: 0, width: KScreenW, height: bounds.height)
let layout = LDPageCollectionViewLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.cols = 7
layout.row = 3
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let style = LDPageStyle()
let pageCollectionView = LDPageCollectionView(frame: frame, titles: ["普通","粉丝专属"], isTitleInTop: false, layout: layout, style: style)
pageCollectionView.dataSource = self
pageCollectionView.delegate = self
addSubview(pageCollectionView)
pageCollectionView.register(nib: UINib(nibName: "LDEmoticonViewCell", bundle: nil), identifier: "LDEmoticonViewCell")
}
}
// MARK:- 实现代理方法LDPageCollectionViewDataSource
extension LDEmoticonView : LDPageCollectionViewDataSource{
func numberOfSections(in pageCollectionView: LDPageCollectionView) -> Int {
return EmoticonViewModel.shareEmoticonModel.packages.count
}
func collectionView(_ pageCollectionView: LDPageCollectionView, numberOfItemsInSection section: Int) -> Int
{
return EmoticonViewModel.shareEmoticonModel.packages[section].emoticons.count
}
func collectionView(_ pageCollectionView: LDPageCollectionView, _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LDEmoticonViewCell", for: indexPath) as! LDEmoticonViewCell
cell.emoticon = EmoticonViewModel.shareEmoticonModel.packages[indexPath.section].emoticons[indexPath.item]
return cell
}
}
// MARK:- 实现代理方法LDPageCollectionViewDelegate
extension LDEmoticonView : LDPageCollectionViewDelegate{
func collectionView(_ pageCollectionView: LDPageCollectionView, _ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let emoticon = EmoticonViewModel.shareEmoticonModel.packages[indexPath.section].emoticons[indexPath.item]
if let emoticonClickCallBlock = emoticonClickCallBlock {
emoticonClickCallBlock(emoticon)
}
}
}
| mit | ae23b277a15c9c1ad688331758a696de | 34.025 | 165 | 0.703426 | 4.773424 | false | false | false | false |
lyle-luan/firefox-ios | Client/Frontend/Browser/LongPressGestureRecognizer.swift | 2 | 4055 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import UIKit
enum LongPressElementType {
case Image
case Link
}
protocol LongPressGestureDelegate: class {
func longPressRecognizer(longPressRecognizer: LongPressGestureRecognizer, didLongPressElements elements: [LongPressElementType: NSURL])
}
class LongPressGestureRecognizer: UILongPressGestureRecognizer, UIGestureRecognizerDelegate {
private weak var webView: WKWebView!
weak var longPressGestureDelegate: LongPressGestureDelegate?
override init(target: AnyObject, action: Selector) {
super.init(target: target, action: action)
}
required init?(webView: WKWebView) {
super.init()
self.webView = webView
delegate = self
self.addTarget(self, action: "SELdidLongPress:")
if let path = NSBundle.mainBundle().pathForResource("LongPress", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: false)
self.webView.configuration.userContentController.addUserScript(userScript)
}
}
}
// MARK: - Gesture Recognizer Delegate Methods
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailByGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// Hack to detect the built-in context menu gesture recognizer.
return otherGestureRecognizer is UILongPressGestureRecognizer && otherGestureRecognizer.delegate?.description.rangeOfString("WKContentView") != nil
}
// MARK: - Long Press Gesture Handling
func SELdidLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began {
//Finding actual touch location in webView
var touchLocation = gestureRecognizer.locationInView(self.webView)
touchLocation.x -= self.webView.scrollView.contentInset.left
touchLocation.y -= self.webView.scrollView.contentInset.top
touchLocation.x /= self.webView.scrollView.zoomScale
touchLocation.y /= self.webView.scrollView.zoomScale
self.webView.evaluateJavaScript("__firefox__.LongPress.findElementsAtPoint(\(touchLocation.x),\(touchLocation.y))") { (response: AnyObject!, error: NSError!) in
if error != nil {
println("Long press gesture recognizer error: \(error.description)")
} else {
self.handleTouchResult(response as [String: AnyObject])
}
}
}
}
private func handleTouchResult(elementsDict: [String: AnyObject]) {
var elements = [LongPressElementType: NSURL]()
if let hrefElement = elementsDict["hrefElement"] as? [String: String] {
if let hrefStr: String = hrefElement["hrefLink"] {
if let linkURL = NSURL(string: hrefStr) {
elements[LongPressElementType.Link] = linkURL
}
}
}
if let imageElement = elementsDict["imageElement"] as? [String: String] {
if let imageSrcStr: String = imageElement["imageSrc"] {
if let imageURL = NSURL(string: imageSrcStr) {
elements[LongPressElementType.Image] = imageURL
}
}
}
if !elements.isEmpty {
self.longPressGestureDelegate?.longPressRecognizer(self, didLongPressElements: elements)
}
}
} | mpl-2.0 | 06b2993094a706036547019a0da109b3 | 43.571429 | 172 | 0.677189 | 5.570055 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/OldModels/Discover/DiscoverTVMDB.swift | 1 | 1964 | //
// DiscoverTV.swift
// TheMovieDBWrapperSwift
//
// Created by George Kye on 2016-02-05.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public enum TVGenres: String {
case Action_Adventure = "10759"
case Animation = "16"
case Comedy = "35"
case Crime = "80"
case Documentary = "99"
case Drama = "18"
case Education = "10761"
case Family = "10751"
case Kids = "10762"
case Mystery = "9648"
case News = "10763"
case Reality = "10764"
case ScifiFantasy = "10765"
case Soap = "10766"
case Talk = "10767"
case WarPolitics = "10768"
case Western = "37"
}
public enum DiscoverSortByTV: String {
case popularity_asc = "popularity.asc"
case popularity_desc = "popularity_desc"
case vote_average_asc = "vote_average.asc"
case vote_average_desc = "vote_average.desc"
case first_air_date_desc = "first_air_date.desc"
case first_air_date_asc = "first_air_date.asc"
}
public class DiscoverTVMDB: DiscoverMDB {
public var name: String!
public var origin_country: [String]?
public var original_name: String?
public var first_air_date: String?
public var genreIds: [Int]?
enum CodingKeys: String, CodingKey {
case name
case origin_country
case original_name
case first_air_date
case genreIds = "genre_ids"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try? container.decode(String?.self, forKey: .name)
origin_country = try? container.decode([String]?.self, forKey: .origin_country)
original_name = try? container.decode(String?.self, forKey: .original_name)
first_air_date = try? container.decode(String?.self, forKey: .first_air_date)
genreIds = try? container.decode([Int]?.self, forKey: .genreIds)
try super.init(from: decoder)
}
}
| mit | 80ec3effc7212e6047ffec01292b94f4 | 29.671875 | 87 | 0.651044 | 3.517921 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Models/PXCard+Business.swift | 1 | 2261 | import Foundation
/// :nodoc:
extension PXCard: PXCardInformation {
func getIssuer() -> PXIssuer? {
return issuer
}
func isSecurityCodeRequired() -> Bool {
if securityCode != nil {
if securityCode!.length != 0 {
return true
} else {
return false
}
} else {
return false
}
}
func getFirstSixDigits() -> String {
return firstSixDigits ?? ""
}
func getCardDescription() -> String {
return "terminada en".localized + " " + lastFourDigits!
}
func getPaymentMethod() -> PXPaymentMethod? {
return self.paymentMethod
}
func getCardId() -> String {
return id ?? ""
}
func getPaymentMethodId() -> String {
return self.paymentMethod?.id ?? ""
}
func getPaymentTypeId() -> String {
return self.paymentMethod?.paymentTypeId ?? ""
}
func getCardSecurityCode() -> PXSecurityCode? {
return self.securityCode
}
func getCardBin() -> String? {
return self.firstSixDigits
}
func getCardLastForDigits() -> String {
return self.lastFourDigits ?? ""
}
func setupPaymentMethodSettings(_ settings: [PXSetting]) {
self.paymentMethod?.settings = settings
}
func setupPaymentMethod(_ paymentMethod: PXPaymentMethod) {
self.paymentMethod = paymentMethod
}
func isIssuerRequired() -> Bool {
return self.issuer == nil
}
func canBeClone() -> Bool {
return false
}
}
/// :nodoc:
extension PXCard: PaymentOptionDrawable {
func isDisabled() -> Bool {
return false
}
func getTitle() -> String {
return getCardDescription()
}
}
/// :nodoc:
extension PXCard: PaymentMethodOption {
func getPaymentType() -> String {
return paymentMethod?.paymentTypeId ?? ""
}
func getId() -> String {
return String(describing: id)
}
func getChildren() -> [PaymentMethodOption]? {
return nil
}
func hasChildren() -> Bool {
return false
}
func isCard() -> Bool {
return true
}
func isCustomerPaymentMethod() -> Bool {
return true
}
}
| mit | 2ff9ac827f71a8c6e7cee999e4da0a47 | 20.130841 | 63 | 0.567006 | 4.740042 | false | false | false | false |
grandiere/box | box/View/Landing/VLandingCell.swift | 1 | 2233 | import UIKit
class VLandingCell:UICollectionViewCell
{
private weak var icon:UIImageView!
private weak var label:UILabel!
private let kLabelHeight:CGFloat = 90
private let kAlphaSelected:CGFloat = 0.4
private let kAlphaNotSelected:CGFloat = 1
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let icon:UIImageView = UIImageView()
icon.isUserInteractionEnabled = false
icon.translatesAutoresizingMaskIntoConstraints = false
icon.contentMode = UIViewContentMode.center
icon.clipsToBounds = true
self.icon = icon
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor.clear
label.font = UIFont.bold(size:14)
label.textAlignment = NSTextAlignment.center
self.label = label
addSubview(icon)
addSubview(label)
NSLayoutConstraint.equals(
view:icon,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:label,
toView:self)
NSLayoutConstraint.height(
view:label,
constant:kLabelHeight)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
icon.alpha = kAlphaSelected
label.textColor = UIColor.gridOrange
}
else
{
icon.alpha = kAlphaNotSelected
label.textColor = UIColor.white
}
}
//MARK: public
func config(model:MLandingItem)
{
icon.image = model.icon
label.text = model.title
hover()
}
}
| mit | b438c533ae88d743fc44cbeba899fe52 | 22.505263 | 63 | 0.566502 | 5.446341 | false | false | false | false |
trentrand/WWDC-2015-Scholarship | Trent Rand/PortfolioChildViewController.swift | 1 | 2529 | //
// PortfolioChildViewController.swift
// Trent Rand
//
// Created by Trent Rand on 4/26/15.
// Copyright (c) 2015 Trent Rand. All rights reserved.
//
import Foundation
class PortfolioChildViewController: UIViewController {
var index: NSInteger!
@IBOutlet var portfolioDescription: UITextView!
@IBOutlet var portfolioTitle: UILabel!
@IBOutlet var portfolioLogo: UILabel!
let githubBase = "http://www.GitHub.com/TrentRand/"
var githubProject: String = ""
override func viewDidLoad() {
super.viewDidLoad()
switch index {
case 0:
portfolioTitle.text = "iTunes Radio Unlimited"
githubProject = "iTunesRadioUnlimited"
portfolioLogo.text = ""
portfolioDescription.text = "With over 500k downloads, iTunes Radio Unlimited is a jailbreak tweak to get rid of the ads and skip limits of iTunes Radio for iOS. Don't hate me, Apple :("
case 1:
portfolioTitle.text = "Karma Infinity"
githubProject = "KarmaInfinity"
portfolioLogo.text = ""
portfolioDescription.text = "The original reddit upvote bot. With human-like activity running on a one-to-one proxy, KarmaInfinity is great at bypassing the auto-bot detection implemented by reddit."
case 2:
portfolioTitle.text = "Patient Care"
githubProject = "Patient-Care"
portfolioLogo.text = ""
portfolioDescription.text = "Patient Care allows patients, doctors, and healthcare professionals to enter the 21st century by introducing a smart phone powered waiting room queue system. It's has a great deal of networking practices and software engineering architchecture to demonstrate."
case 3:
portfolioTitle.text = "Want to see more?"
githubProject = "#"
portfolioLogo.text = ""
portfolioDescription.text = "More portfolio content coming soon... If you're eager to see right now, view my GitHub."
default:
portfolioTitle.text = "Error"
githubProject = "404"
portfolioLogo.text = ""
portfolioDescription.text = "This shouldn't have shown up. Oops!"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func clickedViewGithub(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: githubBase + githubProject)!)
}
} | mit | 34060f8604a4e6218d94a343ea7f47ec | 41 | 302 | 0.654625 | 4.596715 | false | false | false | false |
JudoPay/JudoKit | Source/FloatingTextField.swift | 1 | 7253 | //
// FloatingTextField.swift
// JudoKit
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class FloatingTextField: UITextField {
let animationDuration = 0.3
var title = UILabel()
let theme: Theme
// MARK: - Properties
override var accessibilityLabel: String! {
get {
if text!.isEmpty {
return title.text
} else {
return text
}
}
set {
self.accessibilityLabel = newValue
}
}
override var placeholder: String? {
didSet {
title.text = placeholder
title.sizeToFit()
}
}
override var attributedPlaceholder: NSAttributedString? {
didSet {
title.text = attributedPlaceholder?.string
title.sizeToFit()
}
}
var titleFont: UIFont = .systemFont(ofSize: 12.0) {
didSet {
title.font = titleFont
title.sizeToFit()
}
}
var keepBaseline = false
var hintYPadding: CGFloat = 0.0
var titleYPadding: CGFloat = 6.0 {
didSet {
var r = title.frame
r.origin.y = titleYPadding
title.frame = r
}
}
var titleTextColour: UIColor = .gray {
didSet {
if !isFirstResponder {
title.textColor = titleTextColour
}
}
}
var titleActiveTextColour: UIColor! {
didSet {
if isFirstResponder {
title.textColor = titleActiveTextColour
}
}
}
// MARK: - Init
init(currentTheme: Theme) {
self.theme = currentTheme
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
self.theme = Theme()
super.init(coder:aDecoder)
setup()
}
override init(frame: CGRect) {
self.theme = Theme()
super.init(frame: frame)
setup()
}
// MARK: - Overrides
override func layoutSubviews() {
super.layoutSubviews()
setTitlePositionForTextAlignment()
let isResp = isFirstResponder
if isResp && !text!.isEmpty {
title.textColor = titleActiveTextColour
} else {
title.textColor = titleTextColour
}
// Should we show or hide the title label?
if text!.isEmpty {
// Hide
hideTitle(isResp)
} else {
// Show
showTitle(isResp)
}
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
var r = super.textRect(forBounds: bounds)
if !text!.isEmpty || self.keepBaseline {
var top = ceil(title.font.lineHeight + hintYPadding)
top = min(top, maxTopInset())
r = r.inset(by: UIEdgeInsets(top: top, left: 0.0, bottom: 0.0, right: 0.0))
}
return r.integral
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
var r = super.editingRect(forBounds: bounds)
if !text!.isEmpty || self.keepBaseline {
var top = ceil(title.font.lineHeight + hintYPadding)
top = min(top, maxTopInset())
r = r.inset(by: UIEdgeInsets(top: top, left: 0.0, bottom: 0.0, right: 0.0))
}
return r.integral
}
override func clearButtonRect(forBounds bounds: CGRect) -> CGRect {
var r = super.clearButtonRect(forBounds: bounds)
if !text!.isEmpty || self.keepBaseline {
var top = ceil(title.font.lineHeight + hintYPadding)
top = min(top, maxTopInset())
r = CGRect(x:r.origin.x, y:r.origin.y + (top * 0.5), width:r.size.width, height:r.size.height)
}
return r.integral
}
// MARK: - Private Methods
fileprivate func setup() {
borderStyle = UITextField.BorderStyle.none
titleActiveTextColour = self.theme.getButtonColor()
// Set up title label
title.alpha = 0.0
title.font = titleFont
title.textColor = titleTextColour
if let str = placeholder {
if !str.isEmpty {
title.text = str
title.sizeToFit()
}
}
self.addSubview(title)
}
fileprivate func maxTopInset() -> CGFloat {
return max(0, floor(bounds.size.height - font!.lineHeight - 4.0))
}
fileprivate func setTitlePositionForTextAlignment() {
let r = textRect(forBounds: bounds)
var x = r.origin.x
if textAlignment == NSTextAlignment.center {
x = r.origin.x + (r.size.width * 0.5) - title.frame.size.width
} else if textAlignment == NSTextAlignment.right {
x = r.origin.x + r.size.width - title.frame.size.width
}
title.frame = CGRect(x:x, y:title.frame.origin.y, width:title.frame.size.width, height:title.frame.size.height)
}
fileprivate func showTitle(_ animated: Bool) {
if self.title.alpha == 0.0 {
let dur = animated ? animationDuration : 0
UIView.animate(withDuration: dur, delay:0, options: UIView.AnimationOptions.beginFromCurrentState.union(UIView.AnimationOptions.curveEaseOut), animations:{
// Animation
self.title.alpha = 1.0
var r = self.title.frame
r.origin.y = self.titleYPadding
self.title.frame = r
}, completion:nil)
}
}
fileprivate func hideTitle(_ animated: Bool) {
if self.title.alpha == 1.0 {
let dur = animated ? animationDuration : 0
UIView.animate(withDuration: dur, delay:0, options: UIView.AnimationOptions.beginFromCurrentState.union(UIView.AnimationOptions.curveEaseIn), animations:{
// Animation
self.title.alpha = 0.0
var r = self.title.frame
r.origin.y = self.title.font.lineHeight + self.hintYPadding
self.title.frame = r
}, completion:nil)
}
}
}
| mit | 280da31d5fa718daf8549d4f02edcda4 | 31.671171 | 167 | 0.57976 | 4.533125 | false | false | false | false |
yahua/YAHCharts | Source/Charts/Highlight/Highlight.swift | 1 | 7530 | //
// Highlight.swift
// Charts
//
// 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
@objc(ChartHighlight)
open class Highlight: NSObject
{
/// the x-value of the highlighted value
fileprivate var _x = Double.nan
/// the y-value of the highlighted value
fileprivate var _y = Double.nan
/// the x-pixel of the highlight
fileprivate var _xPx = CGFloat.nan
/// the y-pixel of the highlight
fileprivate var _yPx = CGFloat.nan
/// the index of the data object - in case it refers to more than one
open var dataIndex = Int(-1)
/// the index of the dataset the highlighted value is in
fileprivate var _dataSetIndex = Int(0)
/// index which value of a stacked bar entry is highlighted
///
/// **default**: -1
fileprivate var _stackIndex = Int(-1)
/// the axis the highlighted value belongs to
fileprivate var _axis: YAxis.AxisDependency = YAxis.AxisDependency.left
/// the x-position (pixels) on which this highlight object was last drawn
open var drawX: CGFloat = 0.0
/// the y-position (pixels) on which this highlight object was last drawn
open var drawY: CGFloat = 0.0
// 新增对于pie high的半径
open var selectionShift: CGFloat = 18.0
public override init()
{
super.init()
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter xPx: the x-pixel of the highlighted value
/// - parameter yPx: the y-pixel of the highlighted value
/// - parameter dataIndex: the index of the Data the highlighted value belongs to
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataIndex: Int,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency)
{
super.init()
_x = x
_y = y
_xPx = xPx
_yPx = yPx
self.dataIndex = dataIndex
_dataSetIndex = dataSetIndex
_stackIndex = stackIndex
_axis = axis
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter xPx: the x-pixel of the highlighted value
/// - parameter yPx: the y-pixel of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter axis: the axis the highlighted value belongs to
public convenience init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency)
{
self.init(x: x, y: y, xPx: xPx, yPx: yPx,
dataIndex: 0,
dataSetIndex: dataSetIndex,
stackIndex: stackIndex,
axis: axis)
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter xPx: the x-pixel of the highlighted value
/// - parameter yPx: the y-pixel of the highlighted value
/// - parameter dataIndex: the index of the Data the highlighted value belongs to
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
/// - parameter axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
axis: YAxis.AxisDependency)
{
super.init()
_x = x
_y = y
_xPx = xPx
_yPx = yPx
_dataSetIndex = dataSetIndex
_axis = axis
}
/// - parameter x: the x-value of the highlighted value
/// - parameter y: the y-value of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
public init(x: Double, y: Double, dataSetIndex: Int)
{
_x = x
_y = y
_dataSetIndex = dataSetIndex
}
/// - parameter x: the x-value of the highlighted value
/// - parameter dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - parameter stackIndex: references which value of a stacked-bar entry has been selected
public convenience init(x: Double, dataSetIndex: Int, stackIndex: Int)
{
self.init(x: x, y: Double.nan, dataSetIndex: dataSetIndex)
_stackIndex = stackIndex
}
open var x: Double { return _x }
open var y: Double { return _y }
open var xPx: CGFloat { return _xPx }
open var yPx: CGFloat { return _yPx }
open var dataSetIndex: Int { return _dataSetIndex }
open var stackIndex: Int { return _stackIndex }
open var axis: YAxis.AxisDependency { return _axis }
open var isStacked: Bool { return _stackIndex >= 0 }
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(x: CGFloat, y: CGFloat)
{
self.drawX = x
self.drawY = y
}
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(pt: CGPoint)
{
self.drawX = pt.x
self.drawY = pt.y
}
// MARK: NSObject
open override var description: String
{
return "Highlight, x: \(_x), y: \(_y), dataIndex (combined charts): \(dataIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)"
}
open override func isEqual(_ object: Any?) -> Bool
{
if object == nil
{
return false
}
if !(object! as AnyObject).isKind(of: type(of: self))
{
return false
}
if (object! as AnyObject).x != _x
{
return false
}
if (object! as AnyObject).y != _y
{
return false
}
if (object! as AnyObject).dataIndex != dataIndex
{
return false
}
if (object! as AnyObject).dataSetIndex != _dataSetIndex
{
return false
}
if (object! as AnyObject).stackIndex != _stackIndex
{
return false
}
return true
}
}
func ==(lhs: Highlight, rhs: Highlight) -> Bool
{
if lhs === rhs
{
return true
}
if !lhs.isKind(of: type(of: rhs))
{
return false
}
if lhs._x != rhs._x
{
return false
}
if lhs._y != rhs._y
{
return false
}
if lhs.dataIndex != rhs.dataIndex
{
return false
}
if lhs._dataSetIndex != rhs._dataSetIndex
{
return false
}
if lhs._stackIndex != rhs._stackIndex
{
return false
}
return true
}
| mit | 7e7ffcd3ff2a3bbf2ed29b97adb01a2a | 28.019305 | 173 | 0.585817 | 4.47381 | false | false | false | false |
humeng12/DouYuZB | DouYuZB/DouYuZB/Classes/Main/Model/AnchorModel.swift | 1 | 807 | //
// AnchorModel.swift
// DouYuZB
//
// Created by 胡猛 on 2016/11/30.
// Copyright © 2016年 HuMeng. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
/// 房间ID
var room_id : Int = 0
/// 房间图片对应的URLString
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
// 0 : 电脑直播 1 : 手机直播
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | 2f479c99cc09d41a9d6c9f448123767e | 19.228571 | 73 | 0.549435 | 3.593909 | false | false | false | false |
zavsby/ProjectHelpersSwift | Classes/Categories/UIViewController+Extensions.swift | 1 | 2188 | //
// UIViewController+Extensions.swift
// ProjectHelpers-Swift
//
// Created by Sergey on 01.11.15.
// Copyright © 2015 Sergey Plotkin. All rights reserved.
//
import Foundation
import UIKit
public typealias KeyboardObserverBlock = (keyboardHeight: Double) -> ()
public extension UIViewController {
public func addChildViewController(vc: UIViewController, onView view: UIView) {
view.addSubview(vc.view)
self.addChildViewController(vc)
vc.didMoveToParentViewController(self)
}
public func removeChildViewControllerFromParent(vc: UIViewController) {
if vc.parentViewController != nil {
vc.willMoveToParentViewController(nil)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
}
}
// MARK:- Keyboard observing
public func addKeyboardObserverWithShownBlock(shownBlock: KeyboardObserverBlock, dismissBlock: KeyboardObserverBlock) -> NSObjectProtocol {
return NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil) { (note) -> Void in
if let userInfo = note.userInfo {
let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let animationType = UIViewAnimationOptions(rawValue: (userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt) << 16)
let keyboardHeight = Double(keyboardFrame.size.height)
UIView.animateWithDuration(duration, delay: 0, options:animationType , animations: { () -> Void in
if CGRectIntersectsRect(self.view.frame, keyboardFrame) {
shownBlock(keyboardHeight: keyboardHeight)
} else {
dismissBlock(keyboardHeight: keyboardHeight)
}
}, completion: nil)
}
}
}
public func removeKeyboardObserver(observer: NSObjectProtocol) {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
} | mit | 66cdb244fd849d302e8c958bd11f646f | 40.283019 | 154 | 0.662551 | 5.910811 | false | false | false | false |
PlutoMa/SwiftProjects | 025.CustomTransition/CustomTransition/CustomTransition/Transition/CustomPushTransition.swift | 1 | 1840 | //
// CustomPushTransition.swift
// CustomTransition
//
// Created by Dareway on 2017/11/6.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
class CustomPushTransition: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromVC = transitionContext.viewController(forKey: .from) as! ViewController
let toVC = transitionContext.viewController(forKey: .to) as! DetailViewController
let container = transitionContext.containerView
let snapshotView = fromVC.selectedCell.imageView.snapshotView(afterScreenUpdates: false)
snapshotView?.frame = container.convert(fromVC.selectedCell.imageView.frame, from: fromVC.selectedCell)
fromVC.selectedCell.imageView.isHidden = true
toVC.view.frame = transitionContext.finalFrame(for: toVC)
toVC.view.alpha = 0.0
container.addSubview(toVC.view)
container.addSubview(snapshotView!)
toVC.bannerImageView.layoutIfNeeded()
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: UIViewAnimationOptions(), animations: {
snapshotView?.frame = toVC.bannerImageView.frame
fromVC.view.alpha = 0.0
toVC.view.alpha = 1.0
}) { (finish) in
snapshotView?.frame = toVC.bannerImageView.frame
fromVC.selectedCell.imageView.isHidden = false
toVC.bannerImageView.image = toVC.image
snapshotView?.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
}
| mit | 6a197df79afb2be614a2c4167e11869c | 38.934783 | 141 | 0.6908 | 5.434911 | false | false | false | false |
ljshj/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/AAConversationContentController.swift | 1 | 19663 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import UIKit
import MediaPlayer
import AVKit
import AVFoundation
public class AAConversationContentController: SLKTextViewController, ARDisplayList_AppleChangeListener {
public let peer: ACPeer
private let delayLoad = false
private let binder = AABinder()
private var displayList: ARBindedDisplayList!
private var isStarted: Bool = AADevice.isiPad
private var isVisible: Bool = false
private var isLoaded: Bool = false
private var isLoadedAfter: Bool = false
private var unreadIndex: Int? = nil
private let collectionViewLayout = AAMessagesFlowLayout()
private var prevCount: Int = 0
private var unreadMessageId: jlong = 0
private var isUpdating: Bool = false
private var isBinded: Bool = false
private var pendingUpdates = [ARAppleListUpdate]()
private var readDate: jlong = 0
private var receiveDate: jlong = 0
// Audio notes
public var voicePlayer : AAModernConversationAudioPlayer!
public var voiceContext : AAModernViewInlineMediaContext!
public var currentAudioFileId: jlong = 0
public var voicesCache: Dictionary<jlong,Float> = Dictionary<jlong,Float>()
public init(peer: ACPeer) {
self.peer = peer
super.init(collectionViewLayout: collectionViewLayout)
self.collectionView.backgroundColor = UIColor.clearColor()
self.collectionView.alwaysBounceVertical = true
for layout in AABubbles.layouters {
self.collectionView.registerClass(layout.cellClass(), forCellWithReuseIdentifier: layout.cellReuseId())
}
}
public required init!(coder decoder: NSCoder!) {
fatalError("Not implemented");
}
// Controller and UI lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
if (self.displayList == nil) {
self.displayList = displayListForController()
}
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
isVisible = true
// Hack for delaying collection view init from first animation frame
// This dramatically speed up controller opening
if delayLoad {
if (isStarted) {
tryBind()
return
} else {
self.collectionView.alpha = 0
}
dispatch_async(dispatch_get_main_queue(),{
// What if controller is already closed?
if (!self.isVisible) {
return
}
self.isStarted = true
UIView.animateWithDuration(0.6, animations: { () -> Void in self.collectionView.alpha = 1 }, completion: { (comp) -> Void in })
self.tryBind()
})
} else {
self.isStarted = true
UIView.animateWithDuration(0.6, animations: { () -> Void in self.collectionView.alpha = 1 }, completion: { (comp) -> Void in })
tryBind()
}
}
private func tryBind() {
if !self.isBinded {
self.binder.bind(Actor.getConversationVMWithACPeer(peer).getReadDate()) { (val: JavaLangLong!) in
let nReadDate = val!.longLongValue()
let oReadDate = self.readDate
self.readDate = nReadDate
if self.isBinded && nReadDate != oReadDate {
self.messageStatesUpdated(oReadDate, end: nReadDate)
}
}
self.binder.bind(Actor.getConversationVMWithACPeer(peer).getReceiveDate()) { (val: JavaLangLong!) in
let nReceiveDate = val!.longLongValue()
let oReceiveDate = self.receiveDate
self.receiveDate = nReceiveDate
if self.isBinded && nReceiveDate != oReceiveDate {
self.messageStatesUpdated(oReceiveDate, end: nReceiveDate)
}
}
self.isBinded = true
self.willUpdate()
self.collectionViewLayout.beginUpdates(false, list: self.displayList.getProcessedList() as? AAPreprocessedList, unread: self.unreadMessageId)
self.collectionView.reloadData()
self.prevCount = self.getCount()
self.displayList.addAppleListener(self)
self.didUpdate()
}
}
public func buildCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let list = getProcessedList()
let layout = list!.layouts[indexPath.row]
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(layout.layouter.cellReuseId(), forIndexPath: indexPath)
(cell as! AABubbleCell).setConfig(peer, controller: self)
return cell
}
public func bindCell(collectionView: UICollectionView, cellForRowAtIndexPath indexPath: NSIndexPath, cell: UICollectionViewCell) {
let list = getProcessedList()
let message = list!.items[indexPath.row]
let setting = list!.cellSettings[indexPath.row]
let layout = list!.layouts[indexPath.row]
let bubbleCell = (cell as! AABubbleCell)
let isShowNewMessages = message.rid == unreadMessageId
bubbleCell.performBind(message, receiveDate: receiveDate, readDate: readDate, setting: setting, isShowNewMessages: isShowNewMessages, layout: layout)
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(6, 0, 100, 0)
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
public override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) -> Bool {
return true
}
public override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
public override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) {
}
func getProcessedList() -> AAPreprocessedList? {
if self.displayList == nil {
return nil
}
if !isStarted {
return nil
}
return self.displayList.getProcessedList() as? AAPreprocessedList
}
public override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return isStarted ? getCount() : 0
}
public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = buildCell(collectionView, cellForRowAtIndexPath: indexPath)
bindCell(collectionView, cellForRowAtIndexPath: indexPath, cell: cell)
displayList.touchWithIndex(jint(indexPath.row))
return cell
}
public override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! AABubbleCell
cell.updateView()
}
public override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! AABubbleCell
cell.updateView()
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
isVisible = false
if isBinded {
isBinded = false
// Remove listener on exit
self.displayList.removeAppleListener(self)
// Unbinding read/receive states
self.binder.unbindAll()
}
}
// Model updates
func displayListForController() -> ARBindedDisplayList {
let res = Actor.getMessageDisplayList(peer)
if (res.getListProcessor() == nil) {
res.setListProcessor(AAListProcessor(peer: peer))
}
return res
}
public func objectAtIndexPath(indexPath: NSIndexPath) -> AnyObject? {
return objectAtIndex(indexPath.row)
}
public func objectAtIndex(index: Int) -> AnyObject? {
return displayList.itemWithIndex(jint(index))
}
public func getCount() -> Int {
if (isUpdating) {
return self.prevCount
}
return Int(displayList.size())
}
public func onCollectionChangedWithChanges(modification: ARAppleListUpdate!) {
// if isUpdating {
// pendingUpdates.append(modification)
// return
// }
if modification.isLoadMore {
UIView.setAnimationsEnabled(false)
}
// NSLog("👮🏻 onCollectionChanged called was: \(prevCount)")
self.willUpdate()
// NSLog("👮🏻 willUpdate called")
let list = self.displayList.getProcessedList() as? AAPreprocessedList
var isAppliedList = false
if modification.nonUpdateCount() > 0 {
isUpdating = true
// NSLog("👮🏻 batch updates")
self.collectionView.performBatchUpdates({ () -> Void in
// NSLog("👮🏻 batch started")
// Removed rows
if modification.removedCount() > 0 {
var rows = [NSIndexPath]()
for i in 0..<modification.removedCount() {
let removedRow = Int(modification.getRemoved(jint(i)))
rows.append(NSIndexPath(forRow: removedRow, inSection: 0))
// NSLog("👮🏻 removed \(removedRow)")
}
self.collectionView.deleteItemsAtIndexPaths(rows)
}
// Added rows
if modification.addedCount() > 0 {
var rows = [NSIndexPath]()
for i in 0..<modification.addedCount() {
let insertedRow = Int(modification.getAdded(jint(i)))
rows.append(NSIndexPath(forRow: insertedRow, inSection: 0))
// print("👮🏻 inserted \(insertedRow)")
}
self.collectionView.insertItemsAtIndexPaths(rows)
}
// Moved rows
if modification.movedCount() > 0 {
for i in 0..<modification.movedCount() {
let mov = modification.getMoved(jint(i))
let sourceRow = Int(mov.getSourceIndex())
let destRow = Int(mov.getDestIndex())
self.collectionView.moveItemAtIndexPath(NSIndexPath(forRow: sourceRow, inSection: 0), toIndexPath: NSIndexPath(forRow: destRow, inSection: 0))
// NSLog("👮🏻 moved \(sourceRow) -> \(destRow)")
}
}
self.isUpdating = false
self.prevCount = self.getCount()
self.collectionViewLayout.beginUpdates(modification.isLoadMore, list: list, unread: self.unreadMessageId)
isAppliedList = true
// NSLog("👮🏻 batch updates:end \(self.prevCount)")
}, completion: { (b) -> Void in
// NSLog("👮🏻 batch updates:completion")
})
// NSLog("👮🏻 batch updates:after")
}
if !isAppliedList {
self.collectionViewLayout.beginUpdates(modification.isLoadMore, list: list, unread: self.unreadMessageId)
isAppliedList = true
}
var updated = [Int]()
var updatedForce = [Int]()
if modification.updatedCount() > 0 {
for i in 0..<modification.updatedCount() {
let updIndex = Int(modification.getUpdated(i))
// Is forced update not marking as required for soft update
if (list!.forceUpdated[updIndex]) {
continue
}
updated.append(updIndex)
}
}
if list != nil {
for i in 0..<list!.forceUpdated.count {
if list!.forceUpdated[i] {
updatedForce.append(i)
}
}
for i in 0..<list!.updated.count {
if list!.updated[i] {
// If already in list
if updated.contains(i) {
continue
}
updated.append(i)
}
}
}
var forcedRows = [NSIndexPath]()
let visibleIndexes = self.collectionView.indexPathsForVisibleItems()
for ind in updated {
let indexPath = NSIndexPath(forRow: ind, inSection: 0)
if visibleIndexes.contains(indexPath) {
let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
self.bindCell(self.collectionView, cellForRowAtIndexPath: indexPath, cell: cell!)
}
}
for ind in updatedForce {
let indexPath = NSIndexPath(forRow: ind, inSection: 0)
forcedRows.append(indexPath)
}
if (forcedRows.count > 0) {
self.collectionViewLayout.beginUpdates(false, list: list, unread: unreadMessageId)
self.collectionView.performBatchUpdates({ () -> Void in
self.collectionView.reloadItemsAtIndexPaths(forcedRows)
}, completion: nil)
}
self.didUpdate()
// NSLog("👮🏻 didUpdate Called")
if modification.isLoadMore {
UIView.setAnimationsEnabled(true)
}
}
private func completeUpdates(modification: ARAppleListUpdate!) {
}
private func messageStatesUpdated(start: jlong, end: jlong) {
let visibleIndexes = self.collectionView.indexPathsForVisibleItems()
for ind in visibleIndexes {
if let obj = objectAtIndex(ind.row) {
if obj.senderId == Actor.myUid() && obj.sortDate >= start && obj.sortDate <= end {
let cell = self.collectionView.cellForItemAtIndexPath(ind)
self.bindCell(self.collectionView, cellForRowAtIndexPath: ind, cell: cell!)
}
}
}
}
public func willUpdate() {
isLoadedAfter = false
if getCount() > 0 && !isLoaded {
isLoaded = true
isLoadedAfter = true
let readState = Actor.loadFirstUnread(peer)
if readState > 0 {
for i in 0..<getCount() {
let ind = getCount() - 1 - i
let item = objectAtIndex(ind) as! ACMessage
if item.senderId != Actor.myUid() {
if readState < item.sortDate {
unreadIndex = ind
unreadMessageId = item.rid
break
}
}
}
}
}
}
public func didUpdate() {
if isLoadedAfter {
if unreadIndex != nil {
self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: unreadIndex!, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: false)
unreadIndex = nil
}
}
}
public func onBubbleAvatarTap(view: UIView, uid: jint) {
var controller: AAViewController! = ActorSDK.sharedActor().delegate.actorControllerForUser(Int(uid))
if controller == nil {
controller = AAUserViewController(uid: Int(uid))
}
if (AADevice.isiPad) {
let navigation = AANavigationController()
navigation.viewControllers = [controller]
let popover = UIPopoverController(contentViewController: navigation)
controller.popover = popover
popover.presentPopoverFromRect(view.bounds, inView: view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
} else {
navigateNext(controller, removeCurrent: false)
}
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.performBatchUpdates(nil, completion: nil)
})
}
///////////////////////
// MARK: - audio play
///////////////////////
func playVoiceFromPath(path:String,fileId:jlong,position:Float) {
if (self.currentAudioFileId != fileId) {
self.voicePlayer?.stop()
self.voicePlayer?.audioPlayerStopAndFinish()
self.voicesCache[self.currentAudioFileId] = 0.0
self.voicePlayer = AAModernConversationAudioPlayer(filePath:path)
self.voiceContext = self.voicePlayer.inlineMediaContext()
self.voicePlayer?.play()
self.currentAudioFileId = fileId
} else {
if (position == 0.0 || position == 0) {
self.voicePlayer = AAModernConversationAudioPlayer(filePath:path)
self.voiceContext = self.voicePlayer.inlineMediaContext()
self.voicePlayer?.play()
} else {
if self.voicePlayer?.isPaused() == false {
self.voicePlayer?.pause()
} else {
self.voicePlayer?.play()
}
}
}
}
func playVideoFromPath(path:String) {
let player = AVPlayer(URL: NSURL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
self.presentViewController(playerController, animated: true) {
player.play()
}
}
} | mit | 8ff7756355b60162c79c2deacec3a197 | 36.187856 | 192 | 0.570495 | 5.610364 | false | false | false | false |
AnirudhDas/AniruddhaDas.github.io | WikipediaSearch/WikipediaSearch/Common/SessionManager.swift | 1 | 1458 | //
// SessionManager.swift
// WikipediaSearch
//
// Created by Anirudh Das on 8/11/18.
// Copyright © 2018 Aniruddha Das. All rights reserved.
//
import Foundation
public protocol SessionManaging {
static func addRecentSearch(searchResult: WikiResult)
static func getRecentSearch() -> [WikiResult]
}
open class SessionManager: NSObject, SessionManaging {
open static func addRecentSearch(searchResult: WikiResult) {
var recentResults: [WikiResult] = getRecentSearch()
if (!recentResults.contains(where: { result in result == searchResult })) {
if(recentResults.count >= 4) {
recentResults.removeLast()
}
recentResults.insert(searchResult, at: 0)
}
saveRecentResults(recentResults: recentResults)
}
open static func getRecentSearch() -> [WikiResult] {
guard let data = UserDefaults.standard.data(forKey: Constants.KEY_RECENT_SEARCH), let recentResultsArray = NSKeyedUnarchiver.unarchiveObject(with: data) as? [WikiResult], !recentResultsArray.isEmpty else {
return []
}
return recentResultsArray
}
fileprivate static func saveRecentResults(recentResults: [WikiResult]) {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: recentResults)
UserDefaults.standard.set(encodedData, forKey: Constants.KEY_RECENT_SEARCH)
UserDefaults.standard.synchronize()
}
}
| apache-2.0 | 80683d9259b698515021c890fa83beb2 | 35.425 | 213 | 0.688401 | 4.553125 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document8.playgroundchapter/Pages/Exercise1.playgroundpage/Sources/SetUp.swift | 1 | 3143 | //
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
//let world = GridWorld(columns: 10, rows: 7)
let world = loadGridWorld(named: "8.1")
public let actor = Actor()
let wallLength: Int = 5
public func playgroundPrologue() {
placeItems()
addRandomElementPlaceholders()
world.place(actor, facing: north, at: Coordinate(column: 0, row: 0))
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world) {
realizeRandomElements()
}
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func addRandomElementPlaceholders() {
let block = Block()
let height = wallLength
let rects = [
world.coordinates(inColumns: [1], intersectingRows: 0..<height),
world.coordinates(inColumns: [3], intersectingRows: 0..<height),
world.coordinates(inColumns: 5...6, intersectingRows: 0..<height),
world.coordinates(inColumns: [8], intersectingRows: 0..<height)
]
for rect in rects {
for coord in rect {
world.place(RandomNode(resembling: block), at: coord)
}
}
}
func placeItems() {
let items = [
Coordinate(column: 2, row: 0),
Coordinate(column: 7, row: 0),
Coordinate(column: 4, row: 0),
]
world.placeGems(at: items)
world.place(Switch(), at: Coordinate(column: 9, row: 0))
}
func addStaticElements() {
let tiers = [
Coordinate(column: 1, row: 0),
Coordinate(column: 3, row: 0),
Coordinate(column: 5, row: 0),
Coordinate(column: 6, row: 0),
Coordinate(column: 8, row: 0),
]
world.placeBlocks(at: tiers)
let row7 = world.coordinates(inRows:[6])
world.removeNodes(at: row7)
world.placeWater(at: row7)
}
func realizeRandomElements() {
let randomMax = UInt32(wallLength + 1)
let randomHeight1 = Int(arc4random_uniform(randomMax))
let randomHeight2 = Int(arc4random_uniform(randomMax))
let randomHeight3 = Int(arc4random_uniform(randomMax))
let randomHeight4 = Int(arc4random_uniform(randomMax))
let rect1 = world.coordinates(inColumns: [1], intersectingRows: 0..<randomHeight1)
world.placeBlocks(at: rect1)
let rect2 = world.coordinates(inColumns: [3], intersectingRows: 0..<randomHeight2)
world.placeBlocks(at: rect2)
let rect3 = world.coordinates(inColumns: 5...6, intersectingRows: 0..<randomHeight3)
world.placeBlocks(at: rect3)
let rect4 = world.coordinates(inColumns: [8], intersectingRows: 0..<randomHeight4)
world.placeBlocks(at: rect4)
}
| mit | 8743f5a395d3521978d3c1a7bc8cf18e | 27.315315 | 89 | 0.61979 | 3.914072 | false | false | false | false |
pierrewehbe/MyVoice | MyVoice/Constants.swift | 1 | 1722 | //
// Constants.swift
// MyVoice
//
// Created by Pierre on 11/12/16.
// Copyright © 2016 Pierre. All rights reserved.
//
import Foundation
import AVFoundation
import CoreData
import UIKit
//MARK: File Manager
let myFileManager = FileManager.default
let dirPaths = myFileManager.urls(for: .documentDirectory, in: .userDomainMask)
let appDocumentDirectory = dirPaths[0]
let appTemporaryFilesDirectory = NSTemporaryDirectory()
let screenSize: CGRect = UIScreen.main.bounds
//MARK: User Defaults
let myUserDefaults = UserDefaults.standard
//MARK: CoreData
//Storing CoreData
let appDelegate = UIApplication.shared.delegate as! AppDelegate // Since if we go to AppDelegate.swift, we want to user persistant Container and saveContext ...
let context = appDelegate.managedObjectContext // this is the key that lets us have access to the CoreData
//MARK: Alert Meassages
// Delete
let Message_Delete_LastRecorded : String = "Are you sure you want to delete your last voice memo ?"
let Message_Delete_CurrentlySelected : String = "Are you sure you want to delete this file ?"
let Message_Delete_Success: String = "Deletion has been sucessful"
//MARK: Variables
let defaultTime = "00:00"
let CREATENEWDIRECTORY = "Create new Directory"
//MARK: Segues
var changingDirectory = false
var currentlySaving = false
let RtoF : String = "SEGUE_FILES_FROM_RECORDS"
let RtoS : String = "SEGUE_SETTINGS_FROM_RECORDS"
let FtoR : String = "SEGUE_RECORDS_FROM_FILES"
let FtoS : String = "SEGUE_SETTINGS_FROM_FILES"
let StoR : String = "SEGUE_RECORDS_FROM_SETTINGS"
let StoF : String = "SEGUE_FILES_FROM_SETTINGS"
let FtoAP : String = "SEGUE_AUDIOPLAYER_FROM_FILES"
let APtoF : String = "SEGUE_FILES_FROM_AUDIOPLAYER"
| mit | c80eedec94adc578c66f8e404418d869 | 25.890625 | 160 | 0.759442 | 3.67735 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/DiffContainerViewController.swift | 2 | 46908 |
import UIKit
struct StubRevisionModel {
let revisionId: Int
let summary: String
let username: String
let timestamp: Date
}
protocol DiffRevisionRetrieving: class {
func retrievePreviousRevision(with sourceRevision: WMFPageHistoryRevision) -> WMFPageHistoryRevision?
func retrieveNextRevision(with sourceRevision: WMFPageHistoryRevision) -> WMFPageHistoryRevision?
}
class DiffContainerViewController: ViewController, HintPresenting {
struct NextPrevModel {
let from: WMFPageHistoryRevision
let to: WMFPageHistoryRevision
}
private var containerViewModel: DiffContainerViewModel
private var headerExtendedView: DiffHeaderExtendedView?
private var headerTitleView: DiffHeaderTitleView?
private var scrollingEmptyViewController: EmptyViewController?
private var diffListViewController: DiffListViewController?
private var diffToolbarView: DiffToolbarView?
private let diffController: DiffController
private var fromModel: WMFPageHistoryRevision?
private var fromModelRevisionID: Int?
private var toModel: WMFPageHistoryRevision?
private let toModelRevisionID: Int?
private let siteURL: URL
private var articleTitle: String?
private let safeAreaBottomAlignView = UIView()
private let type: DiffContainerViewModel.DiffType
private let revisionRetrievingDelegate: DiffRevisionRetrieving?
private var firstRevision: WMFPageHistoryRevision?
var animateDirection: DiffRevisionTransition.Direction?
private var hidesHistoryBackTitle: Bool = false
lazy private(set) var fakeProgressController: FakeProgressController = {
let progressController = FakeProgressController(progress: navigationBar, delegate: navigationBar)
progressController.delay = 0.0
return progressController
}()
var hintController: HintController?
private var prevModel: NextPrevModel? {
didSet {
diffToolbarView?.setPreviousButtonState(isEnabled: prevModel != nil)
}
}
private var nextModel: NextPrevModel? {
didSet {
diffToolbarView?.setNextButtonState(isEnabled: nextModel != nil)
}
}
private var isOnFirstRevisionInHistory: Bool {
if type == .single,
let toModel = toModel,
let firstRevision = firstRevision,
fromModel == nil,
toModel.revisionID == firstRevision.revisionID {
return true
}
return false
}
private var isOnSecondRevisionInHistory: Bool {
if type == .single,
let _ = toModel,
let fromModel = fromModel,
let firstRevision = firstRevision,
fromModel.revisionID == firstRevision.revisionID {
return true
}
return false
}
private var byteDifference: Int? {
guard let toModel = toModel,
type == .single else {
return nil
}
if toModel.revisionSize == 0 { //indication that this has not been calculated yet from Page History, need fromModel for calculation
guard let fromModel = fromModel else {
return isOnFirstRevisionInHistory ? toModel.articleSizeAtRevision : nil
}
return toModel.articleSizeAtRevision - fromModel.articleSizeAtRevision
} else {
return toModel.revisionSize
}
}
init(siteURL: URL, theme: Theme, fromRevisionID: Int?, toRevisionID: Int?, type: DiffContainerViewModel.DiffType, articleTitle: String?, hidesHistoryBackTitle: Bool = false) {
self.siteURL = siteURL
self.type = type
self.articleTitle = articleTitle
self.toModelRevisionID = toRevisionID
self.fromModelRevisionID = fromRevisionID
self.hidesHistoryBackTitle = hidesHistoryBackTitle
self.diffController = DiffController(siteURL: siteURL, pageHistoryFetcher: nil, revisionRetrievingDelegate: nil, type: type)
self.containerViewModel = DiffContainerViewModel(type: type, fromModel: nil, toModel: nil, listViewModel: nil, articleTitle: articleTitle, byteDifference: nil, theme: theme)
self.firstRevision = nil
self.revisionRetrievingDelegate = nil
self.toModel = nil
self.fromModel = nil
super.init()
self.theme = theme
self.containerViewModel.stateHandler = { [weak self] oldState in
self?.evaluateState(oldState: oldState)
}
}
init(articleTitle: String, siteURL: URL, type: DiffContainerViewModel.DiffType, fromModel: WMFPageHistoryRevision?, toModel: WMFPageHistoryRevision, pageHistoryFetcher: PageHistoryFetcher? = nil, theme: Theme, revisionRetrievingDelegate: DiffRevisionRetrieving?, firstRevision: WMFPageHistoryRevision?) {
self.type = type
self.fromModel = fromModel
self.toModel = toModel
self.toModelRevisionID = toModel.revisionID
self.articleTitle = articleTitle
self.revisionRetrievingDelegate = revisionRetrievingDelegate
self.siteURL = siteURL
self.firstRevision = firstRevision
self.diffController = DiffController(siteURL: siteURL, pageHistoryFetcher: pageHistoryFetcher, revisionRetrievingDelegate: revisionRetrievingDelegate, type: type)
self.containerViewModel = DiffContainerViewModel(type: type, fromModel: fromModel, toModel: toModel, listViewModel: nil, articleTitle: articleTitle, byteDifference: nil, theme: theme)
super.init()
self.theme = theme
self.containerViewModel.stateHandler = { [weak self] oldState in
self?.evaluateState(oldState: oldState)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if !hidesHistoryBackTitle {
navigationItem.backBarButtonItem = UIBarButtonItem(title: CommonStrings.historyTabTitle, style: .plain, target: nil, action: nil)
}
let onLoad = { [weak self] in
guard let self = self else { return }
if self.fromModel == nil {
self.fetchFromModelAndFinishSetup()
} else if self.toModel == nil {
self.fetchToModelAndFinishSetup()
} else {
self.midSetup()
self.completeSetup()
}
}
startSetup()
if toModel == nil {
populateModelsFromDeepLink { [weak self] (error) in
guard let self = self else { return }
if let error = error {
self.containerViewModel.state = .error(error: error)
return
}
onLoad()
}
} else {
onLoad()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let toolbarView = diffToolbarView {
view.bringSubviewToFront(toolbarView)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
switch type {
case .compare:
self.showDiffPanelOnce()
case .single:
break
}
resetPrevNextAnimateState()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let scrollView = diffListViewController?.scrollView {
configureExtendedViewSquishing(scrollView: scrollView)
}
if let emptyViewController = scrollingEmptyViewController {
navigationBar.setNeedsLayout()
navigationBar.layoutSubviews()
let bottomSafeAreaHeight = safeAreaBottomAlignView.frame.height
let bottomHeight = bottomSafeAreaHeight
let targetRect = CGRect(x: 0, y: navigationBar.visibleHeight, width: emptyViewController.view.frame.width, height: emptyViewController.view.frame.height - navigationBar.visibleHeight - bottomHeight)
let convertedTargetRect = view.convert(targetRect, to: emptyViewController.view)
emptyViewController.centerEmptyView(within: convertedTargetRect)
}
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard isViewLoaded else {
return
}
switch containerViewModel.state {
case .empty, .error:
view.backgroundColor = theme.colors.midBackground
default:
view.backgroundColor = theme.colors.paperBackground
}
headerTitleView?.apply(theme: theme)
headerExtendedView?.apply(theme: theme)
diffListViewController?.apply(theme: theme)
scrollingEmptyViewController?.apply(theme: theme)
diffToolbarView?.apply(theme: theme)
}
}
//MARK: Private
private extension DiffContainerViewController {
func populateNewHeaderViewModel() {
guard let toModel = toModel,
let articleTitle = articleTitle else {
assertionFailure("tomModel and articleTitle need to be in place for generating header.")
return
}
self.containerViewModel.headerViewModel = DiffHeaderViewModel(diffType: type, fromModel: self.fromModel, toModel: toModel, articleTitle: articleTitle, byteDifference: byteDifference, theme: self.theme)
}
func resetPrevNextAnimateState() {
animateDirection = nil
}
func populateModelsFromDeepLink(completion: @escaping (_ error: Error?) -> Void) {
guard toModel == nil else {
assertionFailure("Why are you calling this if you already have toModel?")
return
}
diffController.populateModelsFromDeepLink(fromRevisionID: fromModelRevisionID, toRevisionID: toModelRevisionID, articleTitle: articleTitle) { (result) in
switch result {
case .success(let response):
DispatchQueue.main.async {
self.fromModel = response.from
self.toModel = response.to
self.firstRevision = response.first
self.articleTitle = response.articleTitle
completion(nil)
}
case .failure(let error):
DispatchQueue.main.async {
completion(error)
}
}
}
}
func fetchToModelAndFinishSetup() {
guard let fromModel = fromModel,
let articleTitle = articleTitle else {
assertionFailure("fromModel and articleTitle must be populated for fetching toModel")
return
}
diffController.fetchAdjacentRevisionModel(sourceRevision: fromModel, direction: .next, articleTitle: articleTitle) { (result) in
switch result {
case .success(let revision):
DispatchQueue.main.async {
self.toModel = revision
self.midSetup()
self.completeSetup()
}
case .failure(let error):
DispatchQueue.main.async {
self.containerViewModel.state = .error(error: error)
}
}
}
}
func fetchFromModelAndFinishSetup() {
guard let toModel = toModel,
let articleTitle = articleTitle else {
assertionFailure("toModel and articleTitle must be populated for fetching fromModel")
return
}
//early exit for first revision
//there is no previous revision from toModel in this case
if isOnFirstRevisionInHistory {
midSetup()
completeSetup()
return
}
diffController.fetchAdjacentRevisionModel(sourceRevision: toModel, direction: .previous, articleTitle: articleTitle) { (result) in
switch result {
case .success(let revision):
DispatchQueue.main.async {
self.fromModel = revision
self.midSetup()
self.completeSetup()
}
case .failure(let error):
DispatchQueue.main.async {
self.containerViewModel.state = .error(error: error)
}
}
}
}
func startSetup() {
setupToolbarIfNeeded()
containerViewModel.state = .loading
}
func midSetup() {
guard let _ = toModel else {
assertionFailure("Expecting at least toModel to be populated for this method.")
return
}
populateNewHeaderViewModel()
setupHeaderViewIfNeeded()
setupDiffListViewControllerIfNeeded()
fetchIntermediateCountIfNeeded()
fetchEditCountIfNeeded()
apply(theme: theme)
}
func completeSetup() {
guard let _ = toModel,
(fromModel != nil || isOnFirstRevisionInHistory) else {
assertionFailure("Both models must be populated at this point or needs to be on the first revision.")
return
}
if isOnFirstRevisionInHistory {
fetchFirstDiff()
} else {
fetchDiff()
}
//Still need models for enabling/disabling prev/next buttons
populatePrevNextModelsForToolbar()
}
func setThankAndShareState(isEnabled: Bool) {
diffToolbarView?.setThankButtonState(isEnabled: isEnabled)
diffToolbarView?.setShareButtonState(isEnabled: isEnabled)
diffToolbarView?.apply(theme: theme)
}
func populatePrevNextModelsForToolbar() {
guard let toModel = toModel,
let articleTitle = articleTitle,
(fromModel != nil || isOnFirstRevisionInHistory) else {
assertionFailure("Both models and articleTitle must be populated at this point or needs to be on the first revision.")
return
}
//populate nextModel for enabling previous/next button
let nextFromModel = toModel
var nextToModel: WMFPageHistoryRevision?
diffController.fetchAdjacentRevisionModel(sourceRevision: nextFromModel, direction: .next, articleTitle: articleTitle) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let revision):
DispatchQueue.main.async {
nextToModel = revision
if let nextToModel = nextToModel {
self.nextModel = NextPrevModel(from: nextFromModel, to: nextToModel)
}
}
case .failure:
break
}
}
//if on first or second revision, fromModel will be nil and attempting to fetch previous revision will fail.
if isOnFirstRevisionInHistory {
diffToolbarView?.setNextButtonState(isEnabled: true)
return
}
if isOnSecondRevisionInHistory {
diffToolbarView?.setPreviousButtonState(isEnabled: true)
return
}
guard let fromModel = fromModel else {
return
}
//populate prevModel for enabling previous/next button
var prevFromModel: WMFPageHistoryRevision?
let prevToModel = fromModel
diffController.fetchAdjacentRevisionModel(sourceRevision: prevToModel, direction: .previous, articleTitle: articleTitle) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let revision):
DispatchQueue.main.async {
prevFromModel = revision
if let prevFromModel = prevFromModel {
self.prevModel = NextPrevModel(from: prevFromModel, to: prevToModel)
}
}
case .failure(let error):
DDLogError("error fetching revision: \(error)")
break
}
}
}
func fullRevisionDiffURL() -> URL? {
guard let toModel = toModel else {
return nil
}
var components = URLComponents(url: siteURL, resolvingAgainstBaseURL: false)
components?.path = "/w/index.php"
components?.queryItems = [
URLQueryItem(name: "title", value: articleTitle),
URLQueryItem(name: "diff", value: String(toModel.revisionID)),
URLQueryItem(name: "oldid", value: String(toModel.parentID))
]
return components?.url
}
func evaluateState(oldState: DiffContainerViewModel.State) {
//need up update background color if state is error/empty or not
switch containerViewModel.state {
case .error, .empty:
switch oldState {
case .error, .empty:
break
default:
apply(theme: theme)
diffToolbarView?.parentViewState = containerViewModel.state
}
default:
switch oldState {
case .error, .empty:
apply(theme: theme)
diffToolbarView?.parentViewState = containerViewModel.state
default:
break
}
}
switch containerViewModel.state {
case .loading:
fakeProgressController.start()
scrollingEmptyViewController?.view.isHidden = true
diffListViewController?.view.isHidden = true
setThankAndShareState(isEnabled: false)
case .empty:
fakeProgressController.stop()
setupScrollingEmptyViewControllerIfNeeded()
switch type {
case .compare:
scrollingEmptyViewController?.type = .diffCompare
case .single:
scrollingEmptyViewController?.type = .diffSingle
}
if let direction = animateDirection {
animateInOut(viewController: scrollingEmptyViewController, direction: direction)
} else {
scrollingEmptyViewController?.view.isHidden = false
}
diffListViewController?.view.isHidden = true
setThankAndShareState(isEnabled: true)
case .error(let error):
fakeProgressController.stop()
showNoInternetConnectionAlertOrOtherWarning(from: error)
setupScrollingEmptyViewControllerIfNeeded()
switch type {
case .compare:
scrollingEmptyViewController?.type = .diffErrorCompare
case .single:
scrollingEmptyViewController?.type = .diffErrorSingle
}
scrollingEmptyViewController?.view.isHidden = false
diffListViewController?.view.isHidden = true
setThankAndShareState(isEnabled: false)
case .data:
fakeProgressController.stop()
scrollingEmptyViewController?.view.isHidden = true
if let direction = animateDirection {
animateInOut(viewController: diffListViewController, direction: direction)
} else {
diffListViewController?.view.isHidden = false
}
setThankAndShareState(isEnabled: true)
}
}
func animateInOut(viewController: UIViewController?, direction: DiffRevisionTransition.Direction) {
viewController?.view.alpha = 0
viewController?.view.isHidden = false
if let oldFrame = viewController?.view.frame {
let newY = direction == .down ? oldFrame.maxY : oldFrame.minY - oldFrame.height
let newFrame = CGRect(x: oldFrame.minX, y: newY, width: oldFrame.width, height: oldFrame.height)
viewController?.view.frame = newFrame
UIView.animate(withDuration: DiffRevisionTransition.duration, delay: 0.0, options: .curveEaseInOut, animations: {
viewController?.view.alpha = 1
viewController?.view.frame = oldFrame
}, completion: nil)
}
}
func fetchEditCountIfNeeded() {
guard let toModel = toModel else {
return
}
switch type {
case .single:
if let username = toModel.user {
diffController.fetchEditCount(guiUser: username) { [weak self] (result) in
guard let self = self else {
return
}
DispatchQueue.main.async {
switch result {
case .success(let editCount):
self.updateHeaderWithEditCount(editCount)
case .failure:
break
}
}
}
}
case .compare:
break
}
}
private func show(hintViewController: HintViewController){
guard let toolbarView = diffToolbarView else {
return
}
let showHint = {
self.hintController = HintController(hintViewController: hintViewController)
self.hintController?.toggle(presenter: self, context: nil, theme: self.theme, additionalBottomSpacing: toolbarView.toolbarHeight)
self.hintController?.setHintHidden(false)
}
if let hintController = self.hintController {
hintController.setHintHidden(true) {
showHint()
}
} else {
showHint()
}
}
private func thankRevisionAuthor(completion: @escaping ((Error?) -> Void)) {
guard let toModel = toModel else {
return
}
switch type {
case .single:
diffController.thankRevisionAuthor(toRevisionId: toModel.revisionID) { [weak self] (result) in
guard let self = self else {
return
}
DispatchQueue.main.async {
switch result {
case .success(let result):
self.show(hintViewController: RevisionAuthorThankedHintVC(recipient: result.recipient))
completion(nil)
case .failure(let error as NSError):
self.show(hintViewController: RevisionAuthorThanksErrorHintVC(error: error))
completion(error)
}
}
}
case .compare:
break
}
}
func fetchIntermediateCountIfNeeded() {
guard let toModel = toModel,
let articleTitle = articleTitle else {
return
}
switch type {
case .compare:
if let fromModel = fromModel {
let fromID = fromModel.revisionID
let toID = toModel.revisionID
diffController.fetchIntermediateCounts(for: articleTitle, pageURL: siteURL, from: fromID, to: toID) { [weak self] (result) in
switch result {
case .success(let editCounts):
guard let self = self else {
return
}
DispatchQueue.main.async {
self.updateHeaderWithIntermediateCounts(editCounts)
self.diffListViewController?.updateScrollViewInsets()
}
default:
break
}
}
} else {
assertionFailure("Expect compare type to have fromModel for fetching intermediate count")
}
case .single:
break
}
}
func updateHeaderWithIntermediateCounts(_ editCounts: EditCountsGroupedByType) {
switch type {
case .compare:
guard let headerViewModel = containerViewModel.headerViewModel,
let articleTitle = articleTitle else {
return
}
let newTitleViewModel = DiffHeaderViewModel.generateTitleViewModelForCompare(articleTitle: articleTitle, editCounts: editCounts)
headerViewModel.title = newTitleViewModel
headerTitleView?.update(newTitleViewModel)
case .single:
assertionFailure("Should not call this method for the compare type.")
}
}
func updateHeaderWithEditCount(_ editCount: Int) {
//update view model
guard let headerViewModel = containerViewModel.headerViewModel else {
return
}
switch headerViewModel.headerType {
case .single(let editorViewModel, _):
editorViewModel.numberOfEdits = editCount
case .compare:
assertionFailure("Should not call this method for the compare type.")
return
}
//update view
headerExtendedView?.update(headerViewModel)
}
func fetchFirstDiff() {
guard let toModel = toModel,
isOnFirstRevisionInHistory else {
return
}
view.setNeedsLayout()
view.layoutIfNeeded()
let width = diffListViewController?.collectionView.frame.width
diffController.fetchFirstRevisionDiff(revisionId: toModel.revisionID, siteURL: siteURL, theme: theme, traitCollection: traitCollection) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let listViewModel):
self.updateListViewController(with: listViewModel, collectionViewWidth: width)
case .failure(let error):
DispatchQueue.main.async {
self.containerViewModel.state = .error(error: error)
}
}
}
}
func updateListViewController(with listViewModels: [DiffListGroupViewModel], collectionViewWidth: CGFloat?) {
assert(!Thread.isMainThread, "diffListViewController.updateListViewModels could take a while, would be better from a background thread.")
self.containerViewModel.listViewModel = listViewModels
self.diffListViewController?.updateListViewModels(listViewModel: listViewModels, updateType: .initialLoad(width: collectionViewWidth ?? 0))
DispatchQueue.main.async {
self.diffListViewController?.applyListViewModelChanges(updateType: .initialLoad(width: collectionViewWidth ?? 0))
self.diffListViewController?.updateScrollViewInsets()
self.containerViewModel.state = listViewModels.count == 0 ? .empty : .data
}
}
func fetchDiff() {
guard let toModel = toModel,
let fromModel = fromModel else {
return
}
view.setNeedsLayout()
view.layoutIfNeeded()
let width = diffListViewController?.collectionView.frame.width
diffController.fetchDiff(fromRevisionId: fromModel.revisionID, toRevisionId: toModel.revisionID, theme: theme, traitCollection: traitCollection) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let listViewModel):
self.updateListViewController(with: listViewModel, collectionViewWidth: width)
case .failure(let error):
DispatchQueue.main.async {
self.containerViewModel.state = .error(error: error)
}
}
}
}
func configureExtendedViewSquishing(scrollView: UIScrollView) {
guard let headerTitleView = headerTitleView,
let headerExtendedView = headerExtendedView else {
return
}
let beginSquishYOffset = headerTitleView.frame.height
let scrollYOffset = scrollView.contentOffset.y + scrollView.adjustedContentInset.top
headerExtendedView.configureHeight(beginSquishYOffset: beginSquishYOffset, scrollYOffset: scrollYOffset)
}
func setupHeaderViewIfNeeded() {
guard let headerViewModel = containerViewModel.headerViewModel else {
return
}
if self.headerTitleView == nil {
let headerTitleView = DiffHeaderTitleView(frame: .zero)
headerTitleView.translatesAutoresizingMaskIntoConstraints = false
navigationBar.isUnderBarViewHidingEnabled = true
navigationBar.allowsUnderbarHitsFallThrough = true
navigationBar.addUnderNavigationBarView(headerTitleView)
navigationBar.underBarViewPercentHiddenForShowingTitle = 0.6
navigationBar.isShadowShowing = false
self.headerTitleView = headerTitleView
}
if self.headerExtendedView == nil {
let headerExtendedView = DiffHeaderExtendedView(frame: .zero)
headerExtendedView.translatesAutoresizingMaskIntoConstraints = false
navigationBar.allowsUnderbarHitsFallThrough = true
navigationBar.allowsExtendedHitsFallThrough = true
navigationBar.addExtendedNavigationBarView(headerExtendedView)
headerExtendedView.delegate = self
self.headerExtendedView = headerExtendedView
}
navigationBar.isBarHidingEnabled = false
useNavigationBarVisibleHeightForScrollViewInsets = true
switch headerViewModel.headerType {
case .compare(_, let navBarTitle):
navigationBar.title = navBarTitle
default:
break
}
headerTitleView?.update(headerViewModel.title)
headerExtendedView?.update(headerViewModel)
navigationBar.isExtendedViewHidingEnabled = headerViewModel.isExtendedViewHidingEnabled
}
func setupScrollingEmptyViewControllerIfNeeded() {
guard scrollingEmptyViewController == nil else {
return
}
scrollingEmptyViewController = EmptyViewController(nibName: "EmptyViewController", bundle: nil)
if let emptyViewController = scrollingEmptyViewController,
let emptyView = emptyViewController.view {
emptyViewController.canRefresh = false
emptyViewController.theme = theme
setupSafeAreaBottomAlignView()
addChild(emptyViewController)
emptyView.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(emptyView, belowSubview: navigationBar)
let bottomAnchor = diffToolbarView?.topAnchor ?? safeAreaBottomAlignView.bottomAnchor
let bottom = emptyView.bottomAnchor.constraint(equalTo: bottomAnchor)
let leading = view.leadingAnchor.constraint(equalTo: emptyView.leadingAnchor)
let trailing = view.trailingAnchor.constraint(equalTo: emptyView.trailingAnchor)
let top = view.topAnchor.constraint(equalTo: emptyView.topAnchor)
NSLayoutConstraint.activate([top, leading, trailing, bottom])
emptyViewController.didMove(toParent: self)
emptyViewController.view.isHidden = true
emptyViewController.delegate = self
}
}
func setupSafeAreaBottomAlignView() {
//add alignment view view
safeAreaBottomAlignView.translatesAutoresizingMaskIntoConstraints = false
safeAreaBottomAlignView.isHidden = true
view.addSubview(safeAreaBottomAlignView)
let leadingConstraint = view.leadingAnchor.constraint(equalTo: safeAreaBottomAlignView.leadingAnchor)
let bottomAnchor = diffToolbarView?.topAnchor ?? view.safeAreaLayoutGuide.bottomAnchor
let bottomConstraint = safeAreaBottomAlignView.bottomAnchor.constraint(equalTo: bottomAnchor)
let widthAnchor = safeAreaBottomAlignView.widthAnchor.constraint(equalToConstant: 1)
let heightAnchor = safeAreaBottomAlignView.heightAnchor.constraint(equalToConstant: 1)
NSLayoutConstraint.activate([leadingConstraint, bottomConstraint, widthAnchor, heightAnchor])
}
func setupToolbarIfNeeded() {
switch type {
case .single:
if diffToolbarView == nil {
let toolbarView = DiffToolbarView(frame: .zero)
self.diffToolbarView = toolbarView
toolbarView.delegate = self
toolbarView.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(toolbarView, aboveSubview: navigationBar)
let bottom = view.bottomAnchor.constraint(equalTo: toolbarView.bottomAnchor)
let leading = view.leadingAnchor.constraint(equalTo: toolbarView.leadingAnchor)
let trailing = view.trailingAnchor.constraint(equalTo: toolbarView.trailingAnchor)
NSLayoutConstraint.activate([bottom, leading, trailing])
toolbarView.apply(theme: theme)
toolbarView.setPreviousButtonState(isEnabled: false)
toolbarView.setNextButtonState(isEnabled: false)
}
default:
break
}
}
func setupDiffListViewControllerIfNeeded() {
if diffListViewController == nil {
let diffListViewController = DiffListViewController(theme: theme, delegate: self, type: type)
self.diffListViewController = diffListViewController
switch type {
case .single:
if let listView = diffListViewController.view,
let toolbarView = diffToolbarView {
addChild(diffListViewController)
listView.translatesAutoresizingMaskIntoConstraints = false
view.insertSubview(listView, belowSubview: navigationBar)
let bottom = toolbarView.topAnchor.constraint(equalTo: listView.bottomAnchor)
let leading = view.leadingAnchor.constraint(equalTo: listView.leadingAnchor)
let trailing = view.trailingAnchor.constraint(equalTo: listView.trailingAnchor)
let top = view.topAnchor.constraint(equalTo: listView.topAnchor)
NSLayoutConstraint.activate([top, leading, trailing, bottom])
diffListViewController.didMove(toParent: self)
}
case .compare:
wmf_add(childController: diffListViewController, andConstrainToEdgesOfContainerView: view, belowSubview: navigationBar)
}
}
}
func showDiffPanelOnce() {
let key = "didShowDiffPanel"
if (UserDefaults.wmf.bool(forKey: key)) {
return
}
let panelVC = DiffEducationalPanelViewController(showCloseButton: false, primaryButtonTapHandler: { [weak self] (action) in
self?.presentedViewController?.dismiss(animated: true)
}, secondaryButtonTapHandler: nil, dismissHandler: nil, discardDismissHandlerOnPrimaryButtonTap: true, theme: theme)
present(panelVC, animated: true)
UserDefaults.wmf.set(true, forKey: key)
}
func showNoInternetConnectionAlertOrOtherWarning(from error: Error, noInternetConnectionAlertMessage: String = CommonStrings.noInternetConnection) {
if (error as NSError).wmf_isNetworkConnectionError() {
if UIAccessibility.isVoiceOverRunning {
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: noInternetConnectionAlertMessage)
} else {
WMFAlertManager.sharedInstance.showErrorAlertWithMessage(noInternetConnectionAlertMessage, sticky: true, dismissPreviousAlerts: true)
}
} else if let diffError = error as? DiffError {
if UIAccessibility.isVoiceOverRunning {
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: diffError.localizedDescription)
} else {
WMFAlertManager.sharedInstance.showWarningAlert(diffError.localizedDescription, sticky: true, dismissPreviousAlerts: true)
}
} else {
if UIAccessibility.isVoiceOverRunning {
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: error.localizedDescription)
} else {
WMFAlertManager.sharedInstance.showErrorAlertWithMessage(error.localizedDescription, sticky: true, dismissPreviousAlerts: true)
}
}
}
}
extension DiffContainerViewController: DiffListDelegate {
func diffListScrollViewDidScroll(_ scrollView: UIScrollView) {
self.scrollViewDidScroll(scrollView)
configureExtendedViewSquishing(scrollView: scrollView)
}
}
extension DiffContainerViewController: EmptyViewControllerDelegate {
func triggeredRefresh(refreshCompletion: @escaping () -> Void) {
//no refreshing
}
func emptyViewScrollViewDidScroll(_ scrollView: UIScrollView) {
self.scrollViewDidScroll(scrollView)
}
}
extension DiffContainerViewController: DiffHeaderActionDelegate {
func tappedUsername(username: String) {
if let username = (username as NSString).wmf_normalizedPageTitle() {
let userPageURL = siteURL.wmf_URL(withPath: "/wiki/User:\(username)", isMobile: true)
navigate(to: userPageURL)
}
}
func tappedRevision(revisionID: Int) {
guard let fromModel = fromModel,
let toModel = toModel,
let articleTitle = articleTitle else {
assertionFailure("Revision tapping is not supported on a page without models or articleTitle.")
return
}
let revision: WMFPageHistoryRevision
if revisionID == fromModel.revisionID {
revision = fromModel
} else if revisionID == toModel.revisionID {
revision = toModel
} else {
assertionFailure("Trouble determining revision model to push on next")
return
}
let singleDiffVC = DiffContainerViewController(articleTitle: articleTitle, siteURL: siteURL, type: .single, fromModel: nil, toModel: revision, theme: theme, revisionRetrievingDelegate: revisionRetrievingDelegate, firstRevision: firstRevision)
wmf_push(singleDiffVC, animated: true)
}
}
class AuthorAlreadyThankedHintVC: HintViewController {
override func configureSubviews() {
viewType = .warning
warningLabel.text = WMFLocalizedString("diff-thanks-sent-already", value: "You’ve already sent a ‘Thanks’ for this edit", comment: "Message indicating thanks was already sent")
warningSubtitleLabel.text = WMFLocalizedString("diff-thanks-sent-cannot-unsend", value: "Thanks cannot be unsent", comment: "Message indicating thanks cannot be unsent")
}
}
class AnonymousUsersCannotBeThankedHintVC: HintViewController {
override func configureSubviews() {
viewType = .warning
warningLabel.text = WMFLocalizedString("diff-thanks-anonymous-no-thanks", value: "Anonymous users cannot be thanked", comment: "Message indicating anonymous users cannot be thanked")
warningSubtitleLabel.text = nil
}
}
class RevisionAuthorThankedHintVC: HintViewController {
var recipient: String
init(recipient: String) {
self.recipient = recipient
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configureSubviews() {
viewType = .default
let thanksMessage = WMFLocalizedString("diff-thanks-sent", value: "Your 'Thanks' was sent to %1$@", comment: "Message indicating thanks was sent. Parameters:\n* %1$@ - name of user who was thanked")
let thanksMessageWithRecipient = String.localizedStringWithFormat(thanksMessage, recipient)
defaultImageView.image = UIImage(named: "selected")
defaultLabel.text = thanksMessageWithRecipient
}
}
class RevisionAuthorThanksErrorHintVC: HintViewController {
var error: Error
init(error: Error) {
self.error = error
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configureSubviews() {
viewType = .warning
warningLabel.text = (error as NSError).alertMessage()
warningSubtitleLabel.text = nil
}
}
extension DiffContainerViewController: DiffToolbarViewDelegate {
private func replaceLastAndPush(with viewController: UIViewController) {
if var newViewControllers = navigationController?.viewControllers {
newViewControllers.removeLast()
newViewControllers.append(viewController)
navigationController?.setViewControllers(newViewControllers, animated: true)
}
}
func tappedPrevious() {
animateDirection = .down
guard prevModel != nil ||
isOnSecondRevisionInHistory else {
assertionFailure("Expecting either a prevModel populated to push or a firstRevision to push.")
return
}
let fromModel = prevModel?.from
let maybeToModel = prevModel?.to ?? firstRevision
guard let toModel = maybeToModel,
let articleTitle = articleTitle else {
assertionFailure("toModel and articleTitle before pushing on new DiffContainerVC")
return
}
let singleDiffVC = DiffContainerViewController(articleTitle: articleTitle, siteURL: siteURL, type: .single, fromModel: fromModel, toModel: toModel, theme: theme, revisionRetrievingDelegate: revisionRetrievingDelegate, firstRevision: firstRevision)
replaceLastAndPush(with: singleDiffVC)
}
func tappedNext() {
animateDirection = .up
guard let nextModel = nextModel,
let articleTitle = articleTitle else {
assertionFailure("Expecting nextModel and articleTitle to be populated. Next button should have been disabled if there's no model.")
return
}
let singleDiffVC = DiffContainerViewController(articleTitle: articleTitle, siteURL: siteURL, type: .single, fromModel: nextModel.from, toModel: nextModel.to, theme: theme, revisionRetrievingDelegate: revisionRetrievingDelegate, firstRevision: firstRevision)
replaceLastAndPush(with: singleDiffVC)
}
func tappedShare(_ sender: UIBarButtonItem) {
guard let diffURL = fullRevisionDiffURL() else {
assertionFailure("Couldn't get full revision diff URL")
return
}
let activityViewController = UIActivityViewController(activityItems: [diffURL], applicationActivities: [TUSafariActivity()])
activityViewController.popoverPresentationController?.barButtonItem = sender
present(activityViewController, animated: true)
}
func tappedThank(isAlreadySelected: Bool) {
guard let toModel = toModel else {
return
}
guard !isAlreadySelected else {
self.show(hintViewController: AuthorAlreadyThankedHintVC())
return
}
guard !toModel.isAnon else {
self.show(hintViewController: AnonymousUsersCannotBeThankedHintVC())
return
}
guard isLoggedIn else {
wmf_showLoginOrCreateAccountToThankRevisionAuthorPanel(theme: theme, dismissHandler: nil, loginSuccessCompletion: {
self.apply(theme: self.theme)
}, loginDismissedCompletion: nil)
return
}
guard !UserDefaults.wmf.wmf_didShowThankRevisionAuthorEducationPanel() else {
thankRevisionAuthor { (error) in
if error == nil {
self.diffToolbarView?.isThankSelected = true
}
}
return
}
wmf_showThankRevisionAuthorEducationPanel(theme: theme, sendThanksHandler: {_ in
UserDefaults.wmf.wmf_setDidShowThankRevisionAuthorEducationPanel(true)
self.dismiss(animated: true, completion: {
self.thankRevisionAuthor { (error) in
if error == nil {
self.diffToolbarView?.isThankSelected = true
}
}
})
})
}
var isLoggedIn: Bool {
return WMFAuthenticationManager.sharedInstance.isLoggedIn
}
}
extension DiffContainerViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let direction = animateDirection {
return DiffRevisionTransition(direction: direction)
}
return nil
}
}
extension DiffContainerViewController: DiffRevisionAnimating {
var embeddedViewController: UIViewController? {
switch containerViewModel.state {
case .data, .loading:
return diffListViewController
case .empty, .error:
return scrollingEmptyViewController
}
}
}
| mit | f075c9574a19cf13ab0824462befeb86 | 37.318627 | 308 | 0.612533 | 5.809017 | false | false | false | false |
opalorange/OpalImagePicker | OpalImagePicker/Source/UIViewController+OpalImagePicker.swift | 1 | 5221 | //
// UIViewController+OpalImagePicker.swift
// OpalImagePicker
//
// Created by Kris Katsanevas on 1/15/17.
// Copyright © 2017 Opal Orange LLC. All rights reserved.
//
import UIKit
import Photos
public extension UIViewController {
/// Present Image Picker using closures rather than delegation.
///
/// - Parameters:
/// - imagePicker: the `OpalImagePickerController`
/// - animated: is presentation animated
/// - select: notifies when selection of `[PHAsset]` has been made
/// - cancel: notifies when Image Picker has been cancelled by user
/// - completion: notifies when the Image Picker finished presenting
func presentOpalImagePickerController(_ imagePicker: OpalImagePickerController, animated: Bool, select: @escaping (([PHAsset]) -> Void), cancel: @escaping (() -> Void), completion: (() -> Void)? = nil) {
let manager = OpalImagePickerManager.shared
manager.selectAssets = select
manager.cancel = cancel
imagePicker.imagePickerDelegate = manager
present(imagePicker, animated: animated, completion: completion)
}
/// Present Image Picker with External Images using closures rather than delegation.
///
/// - Parameters:
/// - imagePicker: the `OpalImagePickerController`
/// - animated: is presentation animated
/// - maximumSelectionsAllowed: the maximum number of image selections allowed for the user. Defaults to 10. This is advised to limit the amount of memory to store all the images.
/// - numberOfExternalItems: the number of external items
/// - externalItemsTitle: the localized title for display in the `UISegmentedControl`
/// - externalURLForIndex: the `URL` for an external item at the given index.
/// - selectImages: notifies that image selections have completed with an array of `UIImage`
/// - selectAssets: notifies that image selections have completed with an array of `PHAsset`
/// - selectExternalURLs: notifies that image selections have completed with an array of `URL`
/// - cancel: notifies when Image Picker has been cancelled by user
/// - completion: notifies when the Image Picker finished presenting
func presentOpalImagePickerController(_ imagePicker: OpalImagePickerController, animated: Bool, maximumSelectionsAllowed: Int = 10, numberOfExternalItems: Int, externalItemsTitle: String, externalURLForIndex: @escaping (Int) -> URL?, selectImages: (([UIImage]) -> Void)? = nil, selectAssets: (([PHAsset]) -> Void)? = nil, selectExternalURLs: (([URL]) -> Void)? = nil, cancel: @escaping () -> Void, completion: (() -> Void)? = nil) {
let manager = OpalImagePickerWithExternalItemsManager.sharedWithExternalItems
if selectImages != nil {
print("The `selectImages` parameter will be removed in future versions. Please switch to using `selectAssets`, and download `UIImage` using the `PHAsset` APIs.")
}
manager.selectImages = selectImages
manager.selectAssets = selectAssets
manager.selectURLs = selectExternalURLs
manager.cancel = cancel
manager.numberOfExternalItems = numberOfExternalItems
manager.externalItemsTitle = externalItemsTitle
manager.externalURLForIndex = externalURLForIndex
imagePicker.imagePickerDelegate = manager
imagePicker.maximumSelectionsAllowed = maximumSelectionsAllowed
present(imagePicker, animated: animated, completion: completion)
}
}
class OpalImagePickerWithExternalItemsManager: OpalImagePickerManager {
var selectImages: (([UIImage]) -> Void)?
var selectURLs: (([URL]) -> Void)?
var externalURLForIndex: ((Int) -> URL?)?
var numberOfExternalItems = 0
var externalItemsTitle = NSLocalizedString("External", comment: "External (Segmented Control Title)")
static let sharedWithExternalItems = OpalImagePickerWithExternalItemsManager()
override init() { }
func imagePickerNumberOfExternalItems(_ picker: OpalImagePickerController) -> Int {
return numberOfExternalItems
}
func imagePickerTitleForExternalItems(_ picker: OpalImagePickerController) -> String {
return externalItemsTitle
}
func imagePicker(_ picker: OpalImagePickerController, imageURLforExternalItemAtIndex index: Int) -> URL? {
return externalURLForIndex?(index)
}
func imagePicker(_ picker: OpalImagePickerController, didFinishPickingExternalURLs urls: [URL]) {
selectURLs?(urls)
}
func imagePickerDidFinishPickingImages(_ picker: OpalImagePickerController, images: [UIImage]) {
selectImages?(images)
}
}
class OpalImagePickerManager: NSObject {
var selectAssets: (([PHAsset]) -> Void)?
var cancel: (() -> Void)?
static var shared = OpalImagePickerManager()
override init() { }
}
extension OpalImagePickerManager: OpalImagePickerControllerDelegate {
func imagePicker(_ picker: OpalImagePickerController, didFinishPickingAssets assets: [PHAsset]) {
selectAssets?(assets)
}
func imagePickerDidCancel(_ picker: OpalImagePickerController) {
cancel?()
}
}
| mit | df2164cfea99f50a69c63c1f459564ef | 45.607143 | 436 | 0.702874 | 5.173439 | false | false | false | false |
ColinConduff/BlocFit | BlocFit/Supporting Files/Generic UI/FRCTableViewDataSource.swift | 1 | 4216 | //
// FRCTableViewDataSource.swift
// BlocFit
//
// Created by Colin Conduff on 12/24/16.
// Copyright © 2016 Colin Conduff. All rights reserved.
//
import UIKit
import CoreData
// Rename BFFetchedResultsController
class BFFetchedResultsController: NSObject, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
// MARK: Properties
private unowned var tableView: UITableView
var fetchedResultsController: NSFetchedResultsController<NSManagedObject>? {
didSet {
do {
if let frc = fetchedResultsController {
frc.delegate = self
try frc.performFetch()
}
tableView.reloadData()
} catch let error {
print("NSFetechResultsController.performFetch() failed: \(error)")
}
}
}
init(tableView: UITableView) {
self.tableView = tableView
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return fetchedResultsController?.sections?.count ?? 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let sections = fetchedResultsController?.sections, sections.count > 0 {
return sections[section].numberOfObjects
} else {
return 0
}
}
func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
if let sections = fetchedResultsController?.sections, sections.count > 0 {
return sections[section].name
} else {
return nil
}
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return fetchedResultsController?.sectionIndexTitles
}
func tableView(_ tableView: UITableView,
sectionForSectionIndexTitle title: String,
at index: Int) -> Int {
return fetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
}
// must be overridden
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
fatalError("Must Override")
}
//
// Override to support conditional editing of the table view.
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// MARK: NSFetchedResultsControllerDelegate
func controllerWillChangeContent(
_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange sectionInfo: NSFetchedResultsSectionInfo,
atSectionIndex sectionIndex: Int,
for type: NSFetchedResultsChangeType) {
switch type {
case .insert: tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
case .delete: tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
default: break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any, at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
func controllerDidChangeContent(
_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| mit | 43e3defff447a1ede14959feffb4835d | 34.125 | 124 | 0.615896 | 5.870474 | false | false | false | false |
leacode/LCYCoreDataHelper | LCYCoreDataHelper/LCYCoreDataHelper/LCYCoreDataCVC.swift | 1 | 3503 | //
// LCYCoreDataCVC.swift
// GlobalAlarm2
//
// Created by leacode on 15/1/17.
// Copyright (c) 2015年 leacode. All rights reserved.
//
import UIKit
import CoreData
let reuseIdentifier = "Cell"
open class LCYCoreDataCVC: UICollectionViewController, NSFetchedResultsControllerDelegate {
open var frc:NSFetchedResultsController<NSFetchRequestResult>!
//MARK: - FETCHING
open func performFetch() throws {
frc.managedObjectContext.performAndWait { () -> Void in
do {
try self.frc.performFetch()
} catch {
print("Failed to perform fetch")
}
self.collectionView?.reloadData()
}
}
// MARK: UICollectionViewDataSource
override open func numberOfSections(in collectionView: UICollectionView) -> Int {
var numberOfSections: Int = 0
if let sections = self.frc.sections {
numberOfSections = sections.count
}
return numberOfSections
}
override open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numberOfRow: Int = 0
if let sections = self.frc.sections {
numberOfRow = sections[section].numberOfObjects
}
return numberOfRow
}
//MARK: - DELEGATE: NSFetchedResultsController
open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case NSFetchedResultsChangeType.insert:
self.collectionView?.insertSections(IndexSet(integer: sectionIndex))
break;
case NSFetchedResultsChangeType.delete:
self.collectionView?.deleteSections(IndexSet(integer: sectionIndex))
break;
default:
break;
}
}
open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case NSFetchedResultsChangeType.insert:
if let newPath = newIndexPath {
self.collectionView?.insertItems(at: [newPath])
}
break
case NSFetchedResultsChangeType.delete:
if let idxPath = indexPath {
self.collectionView?.deleteItems(at: [idxPath])
}
break
case NSFetchedResultsChangeType.update:
if let newPath = newIndexPath {
if let idxPath = indexPath {
self.collectionView?.deleteItems(at: [idxPath])
self.collectionView?.insertItems(at: [newPath])
}
} else {
if let idxPath = indexPath {
self.collectionView?.reloadItems(at: [idxPath])
}
}
break
case NSFetchedResultsChangeType.move:
if let newPath = newIndexPath {
if let idxPath = indexPath {
self.collectionView?.deleteItems(at: [idxPath])
self.collectionView?.insertItems(at: [newPath])
}
}
break
@unknown default:
break
}
}
}
| mit | b7e41fc77070dd1b48daf3d25343ed67 | 30.540541 | 214 | 0.590688 | 5.994863 | false | false | false | false |
adrfer/swift | test/SILGen/metatypes.swift | 11 | 4237 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s
import Swift
protocol SomeProtocol {
func method()
func static_method()
}
protocol Any {}
struct SomeStruct : Any {}
class SomeClass : SomeProtocol {
func method() {}
func static_method() {}
}
class SomeSubclass : SomeClass {}
// CHECK-LABEL: sil hidden @_TF9metatypes16static_metatypes
func static_metatypes()
-> (SomeStruct.Type, SomeClass.Type, SomeClass.Type)
{
// CHECK: [[STRUCT:%[0-9]+]] = metatype $@thin SomeStruct.Type
// CHECK: [[CLASS:%[0-9]+]] = metatype $@thick SomeClass.Type
// CHECK: [[SUBCLASS:%[0-9]+]] = metatype $@thick SomeSubclass.Type
// CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type
// CHECK: tuple ([[STRUCT]] : {{.*}}, [[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}})
return (SomeStruct.self, SomeClass.self, SomeSubclass.self)
}
// CHECK-LABEL: sil hidden @_TF9metatypes16struct_metatypes
func struct_metatypes(s: SomeStruct)
-> (SomeStruct.Type, SomeStruct.Type)
{
// CHECK: [[STRUCT1:%[0-9]+]] = metatype $@thin SomeStruct.Type
// CHECK: [[STRUCT2:%[0-9]+]] = metatype $@thin SomeStruct.Type
// CHECK: tuple ([[STRUCT1]] : {{.*}}, [[STRUCT2]] : {{.*}})
return (s.dynamicType, SomeStruct.self)
}
// CHECK-LABEL: sil hidden @_TF9metatypes15class_metatypes
func class_metatypes(c: SomeClass, s: SomeSubclass)
-> (SomeClass.Type, SomeClass.Type)
{
// CHECK: [[CLASS:%[0-9]+]] = value_metatype $@thick SomeClass.Type,
// CHECK: [[SUBCLASS:%[0-9]+]] = value_metatype $@thick SomeSubclass.Type,
// CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type
// CHECK: tuple ([[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}})
return (c.dynamicType, s.dynamicType)
}
// CHECK-LABEL: sil hidden @_TF9metatypes19archetype_metatypes
// CHECK: bb0(%0 : $*T):
func archetype_metatypes<T>(t: T) -> (T.Type, T.Type) {
// CHECK: [[STATIC_T:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[DYN_T:%[0-9]+]] = value_metatype $@thick T.Type, %0
// CHECK: tuple ([[STATIC_T]] : {{.*}}, [[DYN_T]] : {{.*}})
return (T.self, t.dynamicType)
}
// CHECK-LABEL: sil hidden @_TF9metatypes21existential_metatypes
func existential_metatypes(p: SomeProtocol) -> SomeProtocol.Type {
// CHECK: existential_metatype $@thick SomeProtocol.Type
return p.dynamicType
}
struct SomeGenericStruct<T> {}
func generic_metatypes<T>(x: T)
-> (SomeGenericStruct<T>.Type, SomeGenericStruct<SomeStruct>.Type)
{
// CHECK: metatype $@thin SomeGenericStruct<T>
// CHECK: metatype $@thin SomeGenericStruct<SomeStruct>
return (SomeGenericStruct<T>.self, SomeGenericStruct<SomeStruct>.self)
}
// rdar://16610078
// CHECK-LABEL: sil hidden @_TF9metatypes30existential_metatype_from_thinFT_PMPS_3Any_ : $@convention(thin) () -> @thick Any.Type
// CHECK: [[T0:%.*]] = metatype $@thin SomeStruct.Type
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type
// CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type
// CHECK-NEXT: return [[T2]] : $@thick Any.Type
func existential_metatype_from_thin() -> Any.Type {
return SomeStruct.self
}
// CHECK-LABEL: sil hidden @_TF9metatypes36existential_metatype_from_thin_valueFT_PMPS_3Any_ : $@convention(thin) () -> @thick Any.Type
// CHECK: [[T0:%.*]] = function_ref @_TFV9metatypes10SomeStructC
// CHECK-NEXT: [[T1:%.*]] = metatype $@thin SomeStruct.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: debug_value [[T2]] : $SomeStruct, let, name "s"
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin SomeStruct.Type
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type
// CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type
// CHECK-NEXT: return [[T2]] : $@thick Any.Type
func existential_metatype_from_thin_value() -> Any.Type {
let s = SomeStruct()
return s.dynamicType
}
// CHECK-LABEL: sil hidden @_TF9metatypes20specialized_metatypeFT_GVs10DictionarySSSi_
// CHECK: metatype $@thin Dictionary<String, Int>.Type
func specialized_metatype() -> Dictionary<String, Int> {
let dict = Swift.Dictionary<Swift.String, Int>()
return dict
}
| apache-2.0 | 36bf144a5c666167a6071d8317d3379e | 38.231481 | 135 | 0.656833 | 3.487243 | false | false | false | false |
ephread/Instructions | Examples/Example/Sources/Core/View Controllers/ProfileViewController.swift | 1 | 4591 | // Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
import Instructions
/// This class serves as a base for all the other examples
internal class ProfileViewController: UIViewController,
CoachMarksControllerDelegate {
// MARK: - IBOutlet
@IBOutlet weak var handleLabel: UILabel?
@IBOutlet weak var emailLabel: UILabel?
@IBOutlet weak var postsLabel: UILabel?
@IBOutlet weak var reputationLabel: UILabel?
@IBOutlet weak var avatar: UIImageView?
// MARK: - Public properties
var coachMarksController = CoachMarksController()
let avatarText = "That's your profile picture. You look gorgeous!"
let profileSectionText = """
You are in the profile section, where you can review \
all your informations.
"""
let handleText = "That, here, is your name. Sounds a bit generic, don't you think?"
let emailText = "This is your email address. Nothing too fancy."
let postsText = "Here, is the number of posts you made. You are just starting up!"
let reputationText = "That's your reputation around here, that's actually quite good."
let nextButtonText = "Ok!"
// Used for Snapshot testing (i. e. has nothing to do with the example)
weak var snapshotDelegate: CoachMarksControllerDelegate?
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
coachMarksController.overlay.isUserInteractionEnabled = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
startInstructions()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
coachMarksController.stop(immediately: true)
}
func startInstructions() {
coachMarksController.start(in: .window(over: self))
}
// MARK: Protocol Conformance | CoachMarksControllerDelegate
// Used for Snapshot testing (i. e. has nothing to do with the example)
func coachMarksController(_ coachMarksController: CoachMarksController,
configureOrnamentsOfOverlay overlay: UIView) {
snapshotDelegate?.coachMarksController(coachMarksController,
configureOrnamentsOfOverlay: overlay)
}
func coachMarksController(_ coachMarksController: CoachMarksController,
willShow coachMark: inout CoachMark,
beforeChanging change: ConfigurationChange,
at index: Int) {
snapshotDelegate?.coachMarksController(coachMarksController, willShow: &coachMark,
beforeChanging: change,
at: index)
}
func coachMarksController(_ coachMarksController: CoachMarksController,
didShow coachMark: CoachMark,
afterChanging change: ConfigurationChange,
at index: Int) {
snapshotDelegate?.coachMarksController(coachMarksController, didShow: coachMark,
afterChanging: change,
at: index)
}
func coachMarksController(_ coachMarksController: CoachMarksController,
willHide coachMark: CoachMark,
at index: Int) {
snapshotDelegate?.coachMarksController(coachMarksController, willHide: coachMark,
at: index)
}
func coachMarksController(_ coachMarksController: CoachMarksController,
didHide coachMark: CoachMark,
at index: Int) {
snapshotDelegate?.coachMarksController(coachMarksController, didHide: coachMark,
at: index)
}
func coachMarksController(_ coachMarksController: CoachMarksController,
didEndShowingBySkipping skipped: Bool) {
snapshotDelegate?.coachMarksController(coachMarksController,
didEndShowingBySkipping: skipped)
}
func shouldHandleOverlayTap(in coachMarksController: CoachMarksController,
at index: Int) -> Bool {
return true
}
}
| mit | ebedb2cb41972832ad78368d77104f9c | 41.88785 | 90 | 0.601002 | 6.427171 | false | false | false | false |
khizkhiz/swift | test/DebugInfo/closure-multivalue.swift | 2 | 2155 | // rdar://problem/23727705:
// RUN-DISABLED: %target-swift-frontend -O %s -disable-llvm-optzns -emit-ir -g -o - | FileCheck %s
import StdlibUnittest
// CHECK: define {{.*}}i1 {{.*}}4main4sort
// CHECK: call void @llvm.dbg.value(metadata i8*{{.*}}, metadata ![[A:.*]], metadata ![[P1:.*]])
// CHECK: call void @llvm.dbg.value(metadata i{{[0-9]+}} {{.*}}, metadata ![[A]], metadata ![[P2:.*]])
// CHECK: call void @llvm.dbg.value(metadata i{{[0-9]+}} {{.*}}, metadata ![[A]], metadata ![[P3:.*]])
// CHECK: call void @llvm.dbg.value(metadata i8*{{.*}}, metadata ![[B:.*]], metadata ![[P1]])
// CHECK: call void @llvm.dbg.value(metadata i{{[0-9]+}} {{.*}}, metadata ![[B]], metadata ![[P2]])
// CHECK: call void @llvm.dbg.value(metadata i{{[0-9]+}} {{.*}}, metadata ![[B]], metadata ![[P3]])
// CHECK-DAG: ![[A]] = !DILocalVariable(name: "a",{{.*}} line: 17
// CHECK-DAG: ![[B]] = !DILocalVariable(name: "b",{{.*}} line: 17
// CHECK-DAG: ![[P1]] = !DIExpression(DW_OP_bit_piece, 0, {{(32|64)}})
// CHECK-DAG: ![[P2]] = !DIExpression(DW_OP_bit_piece, {{(32, 32|64, 64)}})
// CHECK-DAG: ![[P3]] = !DIExpression(DW_OP_bit_piece, {{(64, 32|128, 64)}})
public func sort(a: String, b: String) -> Bool {
_blackHole("Sorting..\(a) & \(b)")
return (a < b)
}
public func demo() {
var names = ["Sean", "Barry", "Kate"]
var sortedNames = names.sorted(isOrderedBefore: sort)
var sortedNamesAsString : String = String()
for name in sortedNames {
sortedNamesAsString += ("\(name), ")
}
_blackHole(sortedNamesAsString)
}
demo()
// At -O0, we should have a single aggregate argument.
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s --check-prefix=CHECK-O0
// Verify that a reabstraction thunk does not have a line number.
// CHECK-O0-NOT: DW_OP_bit_piece
// CHECK-O0: !DISubprogram(linkageName: "_TTRXFo_oSSoSS_dSb_XFo_iSSiSS_dSb_", scope: !{{[0-9]+}}, file: !{{[0-9]+}}, type: !{{[0-9]+}},
// CHECK-O0-NOT: DW_OP_bit_piece
// CHECK-O0: !DILocalVariable(name: "a", arg: 1{{.*}} line: 17,
// CHECK-O0-NOT: DW_OP_bit_piece
// CHECK-O0: !DILocalVariable(name: "b", arg: 2{{.*}} line: 17,
// CHECK-O0-NOT: DW_OP_bit_piece
| apache-2.0 | d4b439e1e4748ce9663621323eb18e92 | 50.309524 | 135 | 0.596288 | 3.048091 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/WorkMail/WorkMail_Shapes.swift | 1 | 126917 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension WorkMail {
// MARK: Enums
public enum AccessControlRuleEffect: String, CustomStringConvertible, Codable {
case allow = "ALLOW"
case deny = "DENY"
public var description: String { return self.rawValue }
}
public enum EntityState: String, CustomStringConvertible, Codable {
case deleted = "DELETED"
case disabled = "DISABLED"
case enabled = "ENABLED"
public var description: String { return self.rawValue }
}
public enum FolderName: String, CustomStringConvertible, Codable {
case deletedItems = "DELETED_ITEMS"
case drafts = "DRAFTS"
case inbox = "INBOX"
case junkEmail = "JUNK_EMAIL"
case sentItems = "SENT_ITEMS"
public var description: String { return self.rawValue }
}
public enum MailboxExportJobState: String, CustomStringConvertible, Codable {
case cancelled = "CANCELLED"
case completed = "COMPLETED"
case failed = "FAILED"
case running = "RUNNING"
public var description: String { return self.rawValue }
}
public enum MemberType: String, CustomStringConvertible, Codable {
case group = "GROUP"
case user = "USER"
public var description: String { return self.rawValue }
}
public enum PermissionType: String, CustomStringConvertible, Codable {
case fullAccess = "FULL_ACCESS"
case sendAs = "SEND_AS"
case sendOnBehalf = "SEND_ON_BEHALF"
public var description: String { return self.rawValue }
}
public enum ResourceType: String, CustomStringConvertible, Codable {
case equipment = "EQUIPMENT"
case room = "ROOM"
public var description: String { return self.rawValue }
}
public enum RetentionAction: String, CustomStringConvertible, Codable {
case delete = "DELETE"
case none = "NONE"
case permanentlyDelete = "PERMANENTLY_DELETE"
public var description: String { return self.rawValue }
}
public enum UserRole: String, CustomStringConvertible, Codable {
case resource = "RESOURCE"
case systemUser = "SYSTEM_USER"
case user = "USER"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AccessControlRule: AWSDecodableShape {
/// Access protocol actions to include in the rule. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail.
public let actions: [String]?
/// The date that the rule was created.
public let dateCreated: Date?
/// The date that the rule was modified.
public let dateModified: Date?
/// The rule description.
public let description: String?
/// The rule effect.
public let effect: AccessControlRuleEffect?
/// IPv4 CIDR ranges to include in the rule.
public let ipRanges: [String]?
/// The rule name.
public let name: String?
/// Access protocol actions to exclude from the rule. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail.
public let notActions: [String]?
/// IPv4 CIDR ranges to exclude from the rule.
public let notIpRanges: [String]?
/// User IDs to exclude from the rule.
public let notUserIds: [String]?
/// User IDs to include in the rule.
public let userIds: [String]?
public init(actions: [String]? = nil, dateCreated: Date? = nil, dateModified: Date? = nil, description: String? = nil, effect: AccessControlRuleEffect? = nil, ipRanges: [String]? = nil, name: String? = nil, notActions: [String]? = nil, notIpRanges: [String]? = nil, notUserIds: [String]? = nil, userIds: [String]? = nil) {
self.actions = actions
self.dateCreated = dateCreated
self.dateModified = dateModified
self.description = description
self.effect = effect
self.ipRanges = ipRanges
self.name = name
self.notActions = notActions
self.notIpRanges = notIpRanges
self.notUserIds = notUserIds
self.userIds = userIds
}
private enum CodingKeys: String, CodingKey {
case actions = "Actions"
case dateCreated = "DateCreated"
case dateModified = "DateModified"
case description = "Description"
case effect = "Effect"
case ipRanges = "IpRanges"
case name = "Name"
case notActions = "NotActions"
case notIpRanges = "NotIpRanges"
case notUserIds = "NotUserIds"
case userIds = "UserIds"
}
}
public struct AssociateDelegateToResourceRequest: AWSEncodableShape {
/// The member (user or group) to associate to the resource.
public let entityId: String
/// The organization under which the resource exists.
public let organizationId: String
/// The resource for which members (users or groups) are associated.
public let resourceId: String
public init(entityId: String, organizationId: String, resourceId: String) {
self.entityId = entityId
self.organizationId = organizationId
self.resourceId = resourceId
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.resourceId, name: "resourceId", parent: name, max: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, min: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, pattern: "^r-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case organizationId = "OrganizationId"
case resourceId = "ResourceId"
}
}
public struct AssociateDelegateToResourceResponse: AWSDecodableShape {
public init() {}
}
public struct AssociateMemberToGroupRequest: AWSEncodableShape {
/// The group to which the member (user or group) is associated.
public let groupId: String
/// The member (user or group) to associate to the group.
public let memberId: String
/// The organization under which the group exists.
public let organizationId: String
public init(groupId: String, memberId: String, organizationId: String) {
self.groupId = groupId
self.memberId = memberId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.groupId, name: "groupId", parent: name, max: 256)
try self.validate(self.groupId, name: "groupId", parent: name, min: 12)
try self.validate(self.memberId, name: "memberId", parent: name, max: 256)
try self.validate(self.memberId, name: "memberId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case groupId = "GroupId"
case memberId = "MemberId"
case organizationId = "OrganizationId"
}
}
public struct AssociateMemberToGroupResponse: AWSDecodableShape {
public init() {}
}
public struct BookingOptions: AWSEncodableShape & AWSDecodableShape {
/// The resource's ability to automatically reply to requests. If disabled, delegates must be associated to the resource.
public let autoAcceptRequests: Bool?
/// The resource's ability to automatically decline any conflicting requests.
public let autoDeclineConflictingRequests: Bool?
/// The resource's ability to automatically decline any recurring requests.
public let autoDeclineRecurringRequests: Bool?
public init(autoAcceptRequests: Bool? = nil, autoDeclineConflictingRequests: Bool? = nil, autoDeclineRecurringRequests: Bool? = nil) {
self.autoAcceptRequests = autoAcceptRequests
self.autoDeclineConflictingRequests = autoDeclineConflictingRequests
self.autoDeclineRecurringRequests = autoDeclineRecurringRequests
}
private enum CodingKeys: String, CodingKey {
case autoAcceptRequests = "AutoAcceptRequests"
case autoDeclineConflictingRequests = "AutoDeclineConflictingRequests"
case autoDeclineRecurringRequests = "AutoDeclineRecurringRequests"
}
}
public struct CancelMailboxExportJobRequest: AWSEncodableShape {
/// The idempotency token for the client request.
public let clientToken: String
/// The job ID.
public let jobId: String
/// The organization ID.
public let organizationId: String
public init(clientToken: String = CancelMailboxExportJobRequest.idempotencyToken(), jobId: String, organizationId: String) {
self.clientToken = clientToken
self.jobId = jobId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[\\x21-\\x7e]+")
try self.validate(self.jobId, name: "jobId", parent: name, max: 63)
try self.validate(self.jobId, name: "jobId", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[A-Za-z0-9-]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case jobId = "JobId"
case organizationId = "OrganizationId"
}
}
public struct CancelMailboxExportJobResponse: AWSDecodableShape {
public init() {}
}
public struct CreateAliasRequest: AWSEncodableShape {
/// The alias to add to the member set.
public let alias: String
/// The member (user or group) to which this alias is added.
public let entityId: String
/// The organization under which the member (user or group) exists.
public let organizationId: String
public init(alias: String, entityId: String, organizationId: String) {
self.alias = alias
self.entityId = entityId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.alias, name: "alias", parent: name, max: 254)
try self.validate(self.alias, name: "alias", parent: name, min: 1)
try self.validate(self.alias, name: "alias", parent: name, pattern: "[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]+\\.[a-zA-Z-]{2,}")
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case alias = "Alias"
case entityId = "EntityId"
case organizationId = "OrganizationId"
}
}
public struct CreateAliasResponse: AWSDecodableShape {
public init() {}
}
public struct CreateGroupRequest: AWSEncodableShape {
/// The name of the group.
public let name: String
/// The organization under which the group is to be created.
public let organizationId: String
public init(name: String, organizationId: String) {
self.name = name
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 256)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[\\u0020-\\u00FF]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case organizationId = "OrganizationId"
}
}
public struct CreateGroupResponse: AWSDecodableShape {
/// The identifier of the group.
public let groupId: String?
public init(groupId: String? = nil) {
self.groupId = groupId
}
private enum CodingKeys: String, CodingKey {
case groupId = "GroupId"
}
}
public struct CreateOrganizationRequest: AWSEncodableShape {
/// The organization alias.
public let alias: String
/// The idempotency token associated with the request.
public let clientToken: String?
/// The AWS Directory Service directory ID.
public let directoryId: String?
/// The email domains to associate with the organization.
public let domains: [Domain]?
/// When true, allows organization interoperability between Amazon WorkMail and Microsoft Exchange. Can only be set to true if an AD Connector directory ID is included in the request.
public let enableInteroperability: Bool?
/// The Amazon Resource Name (ARN) of a customer managed master key from AWS KMS.
public let kmsKeyArn: String?
public init(alias: String, clientToken: String? = CreateOrganizationRequest.idempotencyToken(), directoryId: String? = nil, domains: [Domain]? = nil, enableInteroperability: Bool? = nil, kmsKeyArn: String? = nil) {
self.alias = alias
self.clientToken = clientToken
self.directoryId = directoryId
self.domains = domains
self.enableInteroperability = enableInteroperability
self.kmsKeyArn = kmsKeyArn
}
public func validate(name: String) throws {
try self.validate(self.alias, name: "alias", parent: name, max: 62)
try self.validate(self.alias, name: "alias", parent: name, min: 1)
try self.validate(self.alias, name: "alias", parent: name, pattern: "^(?!d-)([\\da-zA-Z]+)([-][\\da-zA-Z]+)*")
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[\\x21-\\x7e]+")
try self.validate(self.directoryId, name: "directoryId", parent: name, max: 12)
try self.validate(self.directoryId, name: "directoryId", parent: name, min: 12)
try self.validate(self.directoryId, name: "directoryId", parent: name, pattern: "^d-[0-9a-f]{10}$")
try self.domains?.forEach {
try $0.validate(name: "\(name).domains[]")
}
try self.validate(self.domains, name: "domains", parent: name, max: 5)
try self.validate(self.domains, name: "domains", parent: name, min: 0)
try self.validate(self.kmsKeyArn, name: "kmsKeyArn", parent: name, max: 2048)
try self.validate(self.kmsKeyArn, name: "kmsKeyArn", parent: name, min: 20)
try self.validate(self.kmsKeyArn, name: "kmsKeyArn", parent: name, pattern: "arn:aws:kms:[a-z0-9-]*:[a-z0-9-]+:[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,1023}")
}
private enum CodingKeys: String, CodingKey {
case alias = "Alias"
case clientToken = "ClientToken"
case directoryId = "DirectoryId"
case domains = "Domains"
case enableInteroperability = "EnableInteroperability"
case kmsKeyArn = "KmsKeyArn"
}
}
public struct CreateOrganizationResponse: AWSDecodableShape {
/// The organization ID.
public let organizationId: String?
public init(organizationId: String? = nil) {
self.organizationId = organizationId
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
}
}
public struct CreateResourceRequest: AWSEncodableShape {
/// The name of the new resource.
public let name: String
/// The identifier associated with the organization for which the resource is created.
public let organizationId: String
/// The type of the new resource. The available types are equipment and room.
public let type: ResourceType
public init(name: String, organizationId: String, type: ResourceType) {
self.name = name
self.organizationId = organizationId
self.type = type
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 20)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[\\w\\-.]+(@[a-zA-Z0-9.\\-]+\\.[a-zA-Z0-9-]{2,})?")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case organizationId = "OrganizationId"
case type = "Type"
}
}
public struct CreateResourceResponse: AWSDecodableShape {
/// The identifier of the new resource.
public let resourceId: String?
public init(resourceId: String? = nil) {
self.resourceId = resourceId
}
private enum CodingKeys: String, CodingKey {
case resourceId = "ResourceId"
}
}
public struct CreateUserRequest: AWSEncodableShape {
/// The display name for the new user.
public let displayName: String
/// The name for the new user. Simple AD or AD Connector user names have a maximum length of 20. All others have a maximum length of 64.
public let name: String
/// The identifier of the organization for which the user is created.
public let organizationId: String
/// The password for the new user.
public let password: String
public init(displayName: String, name: String, organizationId: String, password: String) {
self.displayName = displayName
self.name = name
self.organizationId = organizationId
self.password = password
}
public func validate(name: String) throws {
try self.validate(self.displayName, name: "displayName", parent: name, max: 256)
try self.validate(self.name, name: "name", parent: name, max: 64)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[\\w\\-.]+(@[a-zA-Z0-9.\\-]+\\.[a-zA-Z0-9-]{2,})?")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.password, name: "password", parent: name, max: 256)
try self.validate(self.password, name: "password", parent: name, pattern: "[\\u0020-\\u00FF]+")
}
private enum CodingKeys: String, CodingKey {
case displayName = "DisplayName"
case name = "Name"
case organizationId = "OrganizationId"
case password = "Password"
}
}
public struct CreateUserResponse: AWSDecodableShape {
/// The identifier for the new user.
public let userId: String?
public init(userId: String? = nil) {
self.userId = userId
}
private enum CodingKeys: String, CodingKey {
case userId = "UserId"
}
}
public struct Delegate: AWSDecodableShape {
/// The identifier for the user or group associated as the resource's delegate.
public let id: String
/// The type of the delegate: user or group.
public let type: MemberType
public init(id: String, type: MemberType) {
self.id = id
self.type = type
}
private enum CodingKeys: String, CodingKey {
case id = "Id"
case type = "Type"
}
}
public struct DeleteAccessControlRuleRequest: AWSEncodableShape {
/// The name of the access control rule.
public let name: String
/// The identifier for the organization.
public let organizationId: String
public init(name: String, organizationId: String) {
self.name = name
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 64)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_-]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case name = "Name"
case organizationId = "OrganizationId"
}
}
public struct DeleteAccessControlRuleResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteAliasRequest: AWSEncodableShape {
/// The aliases to be removed from the user's set of aliases. Duplicate entries in the list are collapsed into single entries (the list is transformed into a set).
public let alias: String
/// The identifier for the member (user or group) from which to have the aliases removed.
public let entityId: String
/// The identifier for the organization under which the user exists.
public let organizationId: String
public init(alias: String, entityId: String, organizationId: String) {
self.alias = alias
self.entityId = entityId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.alias, name: "alias", parent: name, max: 254)
try self.validate(self.alias, name: "alias", parent: name, min: 1)
try self.validate(self.alias, name: "alias", parent: name, pattern: "[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]+\\.[a-zA-Z-]{2,}")
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case alias = "Alias"
case entityId = "EntityId"
case organizationId = "OrganizationId"
}
}
public struct DeleteAliasResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteGroupRequest: AWSEncodableShape {
/// The identifier of the group to be deleted.
public let groupId: String
/// The organization that contains the group.
public let organizationId: String
public init(groupId: String, organizationId: String) {
self.groupId = groupId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.groupId, name: "groupId", parent: name, max: 256)
try self.validate(self.groupId, name: "groupId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case groupId = "GroupId"
case organizationId = "OrganizationId"
}
}
public struct DeleteGroupResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteMailboxPermissionsRequest: AWSEncodableShape {
/// The identifier of the member (user or group) that owns the mailbox.
public let entityId: String
/// The identifier of the member (user or group) for which to delete granted permissions.
public let granteeId: String
/// The identifier of the organization under which the member (user or group) exists.
public let organizationId: String
public init(entityId: String, granteeId: String, organizationId: String) {
self.entityId = entityId
self.granteeId = granteeId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.granteeId, name: "granteeId", parent: name, max: 256)
try self.validate(self.granteeId, name: "granteeId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case granteeId = "GranteeId"
case organizationId = "OrganizationId"
}
}
public struct DeleteMailboxPermissionsResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteOrganizationRequest: AWSEncodableShape {
/// The idempotency token associated with the request.
public let clientToken: String?
/// If true, deletes the AWS Directory Service directory associated with the organization.
public let deleteDirectory: Bool
/// The organization ID.
public let organizationId: String
public init(clientToken: String? = DeleteOrganizationRequest.idempotencyToken(), deleteDirectory: Bool, organizationId: String) {
self.clientToken = clientToken
self.deleteDirectory = deleteDirectory
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[\\x21-\\x7e]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case deleteDirectory = "DeleteDirectory"
case organizationId = "OrganizationId"
}
}
public struct DeleteOrganizationResponse: AWSDecodableShape {
/// The organization ID.
public let organizationId: String?
/// The state of the organization.
public let state: String?
public init(organizationId: String? = nil, state: String? = nil) {
self.organizationId = organizationId
self.state = state
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case state = "State"
}
}
public struct DeleteResourceRequest: AWSEncodableShape {
/// The identifier associated with the organization from which the resource is deleted.
public let organizationId: String
/// The identifier of the resource to be deleted.
public let resourceId: String
public init(organizationId: String, resourceId: String) {
self.organizationId = organizationId
self.resourceId = resourceId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.resourceId, name: "resourceId", parent: name, max: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, min: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, pattern: "^r-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case resourceId = "ResourceId"
}
}
public struct DeleteResourceResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteRetentionPolicyRequest: AWSEncodableShape {
/// The retention policy ID.
public let id: String
/// The organization ID.
public let organizationId: String
public init(id: String, organizationId: String) {
self.id = id
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.id, name: "id", parent: name, max: 64)
try self.validate(self.id, name: "id", parent: name, min: 1)
try self.validate(self.id, name: "id", parent: name, pattern: "[a-zA-Z0-9_-]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case id = "Id"
case organizationId = "OrganizationId"
}
}
public struct DeleteRetentionPolicyResponse: AWSDecodableShape {
public init() {}
}
public struct DeleteUserRequest: AWSEncodableShape {
/// The organization that contains the user to be deleted.
public let organizationId: String
/// The identifier of the user to be deleted.
public let userId: String
public init(organizationId: String, userId: String) {
self.organizationId = organizationId
self.userId = userId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.userId, name: "userId", parent: name, max: 256)
try self.validate(self.userId, name: "userId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case userId = "UserId"
}
}
public struct DeleteUserResponse: AWSDecodableShape {
public init() {}
}
public struct DeregisterFromWorkMailRequest: AWSEncodableShape {
/// The identifier for the member (user or group) to be updated.
public let entityId: String
/// The identifier for the organization under which the Amazon WorkMail entity exists.
public let organizationId: String
public init(entityId: String, organizationId: String) {
self.entityId = entityId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case organizationId = "OrganizationId"
}
}
public struct DeregisterFromWorkMailResponse: AWSDecodableShape {
public init() {}
}
public struct DescribeGroupRequest: AWSEncodableShape {
/// The identifier for the group to be described.
public let groupId: String
/// The identifier for the organization under which the group exists.
public let organizationId: String
public init(groupId: String, organizationId: String) {
self.groupId = groupId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.groupId, name: "groupId", parent: name, max: 256)
try self.validate(self.groupId, name: "groupId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case groupId = "GroupId"
case organizationId = "OrganizationId"
}
}
public struct DescribeGroupResponse: AWSDecodableShape {
/// The date and time when a user was deregistered from WorkMail, in UNIX epoch time format.
public let disabledDate: Date?
/// The email of the described group.
public let email: String?
/// The date and time when a user was registered to WorkMail, in UNIX epoch time format.
public let enabledDate: Date?
/// The identifier of the described group.
public let groupId: String?
/// The name of the described group.
public let name: String?
/// The state of the user: enabled (registered to Amazon WorkMail) or disabled (deregistered or never registered to WorkMail).
public let state: EntityState?
public init(disabledDate: Date? = nil, email: String? = nil, enabledDate: Date? = nil, groupId: String? = nil, name: String? = nil, state: EntityState? = nil) {
self.disabledDate = disabledDate
self.email = email
self.enabledDate = enabledDate
self.groupId = groupId
self.name = name
self.state = state
}
private enum CodingKeys: String, CodingKey {
case disabledDate = "DisabledDate"
case email = "Email"
case enabledDate = "EnabledDate"
case groupId = "GroupId"
case name = "Name"
case state = "State"
}
}
public struct DescribeMailboxExportJobRequest: AWSEncodableShape {
/// The mailbox export job ID.
public let jobId: String
/// The organization ID.
public let organizationId: String
public init(jobId: String, organizationId: String) {
self.jobId = jobId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.jobId, name: "jobId", parent: name, max: 63)
try self.validate(self.jobId, name: "jobId", parent: name, min: 1)
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "[A-Za-z0-9-]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case jobId = "JobId"
case organizationId = "OrganizationId"
}
}
public struct DescribeMailboxExportJobResponse: AWSDecodableShape {
/// The mailbox export job description.
public let description: String?
/// The mailbox export job end timestamp.
public let endTime: Date?
/// The identifier of the user or resource associated with the mailbox.
public let entityId: String?
/// Error information for failed mailbox export jobs.
public let errorInfo: String?
/// The estimated progress of the mailbox export job, in percentage points.
public let estimatedProgress: Int?
/// The Amazon Resource Name (ARN) of the symmetric AWS Key Management Service (AWS KMS) key that encrypts the exported mailbox content.
public let kmsKeyArn: String?
/// The ARN of the AWS Identity and Access Management (IAM) role that grants write permission to the Amazon Simple Storage Service (Amazon S3) bucket.
public let roleArn: String?
/// The name of the S3 bucket.
public let s3BucketName: String?
/// The path to the S3 bucket and file that the mailbox export job is exporting to.
public let s3Path: String?
/// The S3 bucket prefix.
public let s3Prefix: String?
/// The mailbox export job start timestamp.
public let startTime: Date?
/// The state of the mailbox export job.
public let state: MailboxExportJobState?
public init(description: String? = nil, endTime: Date? = nil, entityId: String? = nil, errorInfo: String? = nil, estimatedProgress: Int? = nil, kmsKeyArn: String? = nil, roleArn: String? = nil, s3BucketName: String? = nil, s3Path: String? = nil, s3Prefix: String? = nil, startTime: Date? = nil, state: MailboxExportJobState? = nil) {
self.description = description
self.endTime = endTime
self.entityId = entityId
self.errorInfo = errorInfo
self.estimatedProgress = estimatedProgress
self.kmsKeyArn = kmsKeyArn
self.roleArn = roleArn
self.s3BucketName = s3BucketName
self.s3Path = s3Path
self.s3Prefix = s3Prefix
self.startTime = startTime
self.state = state
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case endTime = "EndTime"
case entityId = "EntityId"
case errorInfo = "ErrorInfo"
case estimatedProgress = "EstimatedProgress"
case kmsKeyArn = "KmsKeyArn"
case roleArn = "RoleArn"
case s3BucketName = "S3BucketName"
case s3Path = "S3Path"
case s3Prefix = "S3Prefix"
case startTime = "StartTime"
case state = "State"
}
}
public struct DescribeOrganizationRequest: AWSEncodableShape {
/// The identifier for the organization to be described.
public let organizationId: String
public init(organizationId: String) {
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
}
}
public struct DescribeOrganizationResponse: AWSDecodableShape {
/// The alias for an organization.
public let alias: String?
/// The Amazon Resource Name (ARN) of the organization.
public let arn: String?
/// The date at which the organization became usable in the WorkMail context, in UNIX epoch time format.
public let completedDate: Date?
/// The default mail domain associated with the organization.
public let defaultMailDomain: String?
/// The identifier for the directory associated with an Amazon WorkMail organization.
public let directoryId: String?
/// The type of directory associated with the WorkMail organization.
public let directoryType: String?
/// (Optional) The error message indicating if unexpected behavior was encountered with regards to the organization.
public let errorMessage: String?
/// The identifier of an organization.
public let organizationId: String?
/// The state of an organization.
public let state: String?
public init(alias: String? = nil, arn: String? = nil, completedDate: Date? = nil, defaultMailDomain: String? = nil, directoryId: String? = nil, directoryType: String? = nil, errorMessage: String? = nil, organizationId: String? = nil, state: String? = nil) {
self.alias = alias
self.arn = arn
self.completedDate = completedDate
self.defaultMailDomain = defaultMailDomain
self.directoryId = directoryId
self.directoryType = directoryType
self.errorMessage = errorMessage
self.organizationId = organizationId
self.state = state
}
private enum CodingKeys: String, CodingKey {
case alias = "Alias"
case arn = "ARN"
case completedDate = "CompletedDate"
case defaultMailDomain = "DefaultMailDomain"
case directoryId = "DirectoryId"
case directoryType = "DirectoryType"
case errorMessage = "ErrorMessage"
case organizationId = "OrganizationId"
case state = "State"
}
}
public struct DescribeResourceRequest: AWSEncodableShape {
/// The identifier associated with the organization for which the resource is described.
public let organizationId: String
/// The identifier of the resource to be described.
public let resourceId: String
public init(organizationId: String, resourceId: String) {
self.organizationId = organizationId
self.resourceId = resourceId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.resourceId, name: "resourceId", parent: name, max: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, min: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, pattern: "^r-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case resourceId = "ResourceId"
}
}
public struct DescribeResourceResponse: AWSDecodableShape {
/// The booking options for the described resource.
public let bookingOptions: BookingOptions?
/// The date and time when a resource was disabled from WorkMail, in UNIX epoch time format.
public let disabledDate: Date?
/// The email of the described resource.
public let email: String?
/// The date and time when a resource was enabled for WorkMail, in UNIX epoch time format.
public let enabledDate: Date?
/// The name of the described resource.
public let name: String?
/// The identifier of the described resource.
public let resourceId: String?
/// The state of the resource: enabled (registered to Amazon WorkMail), disabled (deregistered or never registered to WorkMail), or deleted.
public let state: EntityState?
/// The type of the described resource.
public let type: ResourceType?
public init(bookingOptions: BookingOptions? = nil, disabledDate: Date? = nil, email: String? = nil, enabledDate: Date? = nil, name: String? = nil, resourceId: String? = nil, state: EntityState? = nil, type: ResourceType? = nil) {
self.bookingOptions = bookingOptions
self.disabledDate = disabledDate
self.email = email
self.enabledDate = enabledDate
self.name = name
self.resourceId = resourceId
self.state = state
self.type = type
}
private enum CodingKeys: String, CodingKey {
case bookingOptions = "BookingOptions"
case disabledDate = "DisabledDate"
case email = "Email"
case enabledDate = "EnabledDate"
case name = "Name"
case resourceId = "ResourceId"
case state = "State"
case type = "Type"
}
}
public struct DescribeUserRequest: AWSEncodableShape {
/// The identifier for the organization under which the user exists.
public let organizationId: String
/// The identifier for the user to be described.
public let userId: String
public init(organizationId: String, userId: String) {
self.organizationId = organizationId
self.userId = userId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.userId, name: "userId", parent: name, max: 256)
try self.validate(self.userId, name: "userId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case userId = "UserId"
}
}
public struct DescribeUserResponse: AWSDecodableShape {
/// The date and time at which the user was disabled for Amazon WorkMail usage, in UNIX epoch time format.
public let disabledDate: Date?
/// The display name of the user.
public let displayName: String?
/// The email of the user.
public let email: String?
/// The date and time at which the user was enabled for Amazon WorkMail usage, in UNIX epoch time format.
public let enabledDate: Date?
/// The name for the user.
public let name: String?
/// The state of a user: enabled (registered to Amazon WorkMail) or disabled (deregistered or never registered to WorkMail).
public let state: EntityState?
/// The identifier for the described user.
public let userId: String?
/// In certain cases, other entities are modeled as users. If interoperability is enabled, resources are imported into Amazon WorkMail as users. Because different WorkMail organizations rely on different directory types, administrators can distinguish between an unregistered user (account is disabled and has a user role) and the directory administrators. The values are USER, RESOURCE, and SYSTEM_USER.
public let userRole: UserRole?
public init(disabledDate: Date? = nil, displayName: String? = nil, email: String? = nil, enabledDate: Date? = nil, name: String? = nil, state: EntityState? = nil, userId: String? = nil, userRole: UserRole? = nil) {
self.disabledDate = disabledDate
self.displayName = displayName
self.email = email
self.enabledDate = enabledDate
self.name = name
self.state = state
self.userId = userId
self.userRole = userRole
}
private enum CodingKeys: String, CodingKey {
case disabledDate = "DisabledDate"
case displayName = "DisplayName"
case email = "Email"
case enabledDate = "EnabledDate"
case name = "Name"
case state = "State"
case userId = "UserId"
case userRole = "UserRole"
}
}
public struct DisassociateDelegateFromResourceRequest: AWSEncodableShape {
/// The identifier for the member (user, group) to be removed from the resource's delegates.
public let entityId: String
/// The identifier for the organization under which the resource exists.
public let organizationId: String
/// The identifier of the resource from which delegates' set members are removed.
public let resourceId: String
public init(entityId: String, organizationId: String, resourceId: String) {
self.entityId = entityId
self.organizationId = organizationId
self.resourceId = resourceId
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.resourceId, name: "resourceId", parent: name, max: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, min: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, pattern: "^r-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case organizationId = "OrganizationId"
case resourceId = "ResourceId"
}
}
public struct DisassociateDelegateFromResourceResponse: AWSDecodableShape {
public init() {}
}
public struct DisassociateMemberFromGroupRequest: AWSEncodableShape {
/// The identifier for the group from which members are removed.
public let groupId: String
/// The identifier for the member to be removed to the group.
public let memberId: String
/// The identifier for the organization under which the group exists.
public let organizationId: String
public init(groupId: String, memberId: String, organizationId: String) {
self.groupId = groupId
self.memberId = memberId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.groupId, name: "groupId", parent: name, max: 256)
try self.validate(self.groupId, name: "groupId", parent: name, min: 12)
try self.validate(self.memberId, name: "memberId", parent: name, max: 256)
try self.validate(self.memberId, name: "memberId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case groupId = "GroupId"
case memberId = "MemberId"
case organizationId = "OrganizationId"
}
}
public struct DisassociateMemberFromGroupResponse: AWSDecodableShape {
public init() {}
}
public struct Domain: AWSEncodableShape {
/// The fully qualified domain name.
public let domainName: String?
/// The hosted zone ID for a domain hosted in Route 53. Required when configuring a domain hosted in Route 53.
public let hostedZoneId: String?
public init(domainName: String? = nil, hostedZoneId: String? = nil) {
self.domainName = domainName
self.hostedZoneId = hostedZoneId
}
public func validate(name: String) throws {
try self.validate(self.domainName, name: "domainName", parent: name, max: 255)
try self.validate(self.domainName, name: "domainName", parent: name, min: 3)
try self.validate(self.domainName, name: "domainName", parent: name, pattern: "[a-zA-Z0-9.-]+\\.[a-zA-Z-]{2,}")
try self.validate(self.hostedZoneId, name: "hostedZoneId", parent: name, max: 32)
try self.validate(self.hostedZoneId, name: "hostedZoneId", parent: name, min: 1)
try self.validate(self.hostedZoneId, name: "hostedZoneId", parent: name, pattern: "[\\S\\s]*")
}
private enum CodingKeys: String, CodingKey {
case domainName = "DomainName"
case hostedZoneId = "HostedZoneId"
}
}
public struct FolderConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The action to take on the folder contents at the end of the folder configuration period.
public let action: RetentionAction
/// The folder name.
public let name: FolderName
/// The period of time at which the folder configuration action is applied.
public let period: Int?
public init(action: RetentionAction, name: FolderName, period: Int? = nil) {
self.action = action
self.name = name
self.period = period
}
public func validate(name: String) throws {
try self.validate(self.period, name: "period", parent: name, max: 730)
try self.validate(self.period, name: "period", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case action = "Action"
case name = "Name"
case period = "Period"
}
}
public struct GetAccessControlEffectRequest: AWSEncodableShape {
/// The access protocol action. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail.
public let action: String
/// The IPv4 address.
public let ipAddress: String
/// The identifier for the organization.
public let organizationId: String
/// The user ID.
public let userId: String
public init(action: String, ipAddress: String, organizationId: String, userId: String) {
self.action = action
self.ipAddress = ipAddress
self.organizationId = organizationId
self.userId = userId
}
public func validate(name: String) throws {
try self.validate(self.action, name: "action", parent: name, max: 64)
try self.validate(self.action, name: "action", parent: name, min: 1)
try self.validate(self.action, name: "action", parent: name, pattern: "[a-zA-Z]+")
try self.validate(self.ipAddress, name: "ipAddress", parent: name, max: 15)
try self.validate(self.ipAddress, name: "ipAddress", parent: name, min: 1)
try self.validate(self.ipAddress, name: "ipAddress", parent: name, pattern: "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.userId, name: "userId", parent: name, max: 256)
try self.validate(self.userId, name: "userId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case action = "Action"
case ipAddress = "IpAddress"
case organizationId = "OrganizationId"
case userId = "UserId"
}
}
public struct GetAccessControlEffectResponse: AWSDecodableShape {
/// The rule effect.
public let effect: AccessControlRuleEffect?
/// The rules that match the given parameters, resulting in an effect.
public let matchedRules: [String]?
public init(effect: AccessControlRuleEffect? = nil, matchedRules: [String]? = nil) {
self.effect = effect
self.matchedRules = matchedRules
}
private enum CodingKeys: String, CodingKey {
case effect = "Effect"
case matchedRules = "MatchedRules"
}
}
public struct GetDefaultRetentionPolicyRequest: AWSEncodableShape {
/// The organization ID.
public let organizationId: String
public init(organizationId: String) {
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
}
}
public struct GetDefaultRetentionPolicyResponse: AWSDecodableShape {
/// The retention policy description.
public let description: String?
/// The retention policy folder configurations.
public let folderConfigurations: [FolderConfiguration]?
/// The retention policy ID.
public let id: String?
/// The retention policy name.
public let name: String?
public init(description: String? = nil, folderConfigurations: [FolderConfiguration]? = nil, id: String? = nil, name: String? = nil) {
self.description = description
self.folderConfigurations = folderConfigurations
self.id = id
self.name = name
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case folderConfigurations = "FolderConfigurations"
case id = "Id"
case name = "Name"
}
}
public struct GetMailboxDetailsRequest: AWSEncodableShape {
/// The identifier for the organization that contains the user whose mailbox details are being requested.
public let organizationId: String
/// The identifier for the user whose mailbox details are being requested.
public let userId: String
public init(organizationId: String, userId: String) {
self.organizationId = organizationId
self.userId = userId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.userId, name: "userId", parent: name, max: 256)
try self.validate(self.userId, name: "userId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case userId = "UserId"
}
}
public struct GetMailboxDetailsResponse: AWSDecodableShape {
/// The maximum allowed mailbox size, in MB, for the specified user.
public let mailboxQuota: Int?
/// The current mailbox size, in MB, for the specified user.
public let mailboxSize: Double?
public init(mailboxQuota: Int? = nil, mailboxSize: Double? = nil) {
self.mailboxQuota = mailboxQuota
self.mailboxSize = mailboxSize
}
private enum CodingKeys: String, CodingKey {
case mailboxQuota = "MailboxQuota"
case mailboxSize = "MailboxSize"
}
}
public struct Group: AWSDecodableShape {
/// The date indicating when the group was disabled from Amazon WorkMail use.
public let disabledDate: Date?
/// The email of the group.
public let email: String?
/// The date indicating when the group was enabled for Amazon WorkMail use.
public let enabledDate: Date?
/// The identifier of the group.
public let id: String?
/// The name of the group.
public let name: String?
/// The state of the group, which can be ENABLED, DISABLED, or DELETED.
public let state: EntityState?
public init(disabledDate: Date? = nil, email: String? = nil, enabledDate: Date? = nil, id: String? = nil, name: String? = nil, state: EntityState? = nil) {
self.disabledDate = disabledDate
self.email = email
self.enabledDate = enabledDate
self.id = id
self.name = name
self.state = state
}
private enum CodingKeys: String, CodingKey {
case disabledDate = "DisabledDate"
case email = "Email"
case enabledDate = "EnabledDate"
case id = "Id"
case name = "Name"
case state = "State"
}
}
public struct ListAccessControlRulesRequest: AWSEncodableShape {
/// The identifier for the organization.
public let organizationId: String
public init(organizationId: String) {
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
}
}
public struct ListAccessControlRulesResponse: AWSDecodableShape {
/// The access control rules.
public let rules: [AccessControlRule]?
public init(rules: [AccessControlRule]? = nil) {
self.rules = rules
}
private enum CodingKeys: String, CodingKey {
case rules = "Rules"
}
}
public struct ListAliasesRequest: AWSEncodableShape {
/// The identifier for the entity for which to list the aliases.
public let entityId: String
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
/// The identifier for the organization under which the entity exists.
public let organizationId: String
public init(entityId: String, maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.entityId = entityId
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListAliasesResponse: AWSDecodableShape {
/// The entity's paginated aliases.
public let aliases: [String]?
/// The token to use to retrieve the next page of results. The value is "null" when there are no more results to return.
public let nextToken: String?
public init(aliases: [String]? = nil, nextToken: String? = nil) {
self.aliases = aliases
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case aliases = "Aliases"
case nextToken = "NextToken"
}
}
public struct ListGroupMembersRequest: AWSEncodableShape {
/// The identifier for the group to which the members (users or groups) are associated.
public let groupId: String
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
/// The identifier for the organization under which the group exists.
public let organizationId: String
public init(groupId: String, maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.groupId = groupId
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.groupId, name: "groupId", parent: name, max: 256)
try self.validate(self.groupId, name: "groupId", parent: name, min: 12)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case groupId = "GroupId"
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListGroupMembersResponse: AWSDecodableShape {
/// The members associated to the group.
public let members: [Member]?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
public init(members: [Member]? = nil, nextToken: String? = nil) {
self.members = members
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case members = "Members"
case nextToken = "NextToken"
}
}
public struct ListGroupsRequest: AWSEncodableShape {
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
/// The identifier for the organization under which the groups exist.
public let organizationId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListGroupsResponse: AWSDecodableShape {
/// The overview of groups for an organization.
public let groups: [Group]?
/// The token to use to retrieve the next page of results. The value is "null" when there are no more results to return.
public let nextToken: String?
public init(groups: [Group]? = nil, nextToken: String? = nil) {
self.groups = groups
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case groups = "Groups"
case nextToken = "NextToken"
}
}
public struct ListMailboxExportJobsRequest: AWSEncodableShape {
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results.
public let nextToken: String?
/// The organization ID.
public let organizationId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListMailboxExportJobsResponse: AWSDecodableShape {
/// The mailbox export job details.
public let jobs: [MailboxExportJob]?
/// The token to use to retrieve the next page of results.
public let nextToken: String?
public init(jobs: [MailboxExportJob]? = nil, nextToken: String? = nil) {
self.jobs = jobs
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case jobs = "Jobs"
case nextToken = "NextToken"
}
}
public struct ListMailboxPermissionsRequest: AWSEncodableShape {
/// The identifier of the user, group, or resource for which to list mailbox permissions.
public let entityId: String
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
/// The identifier of the organization under which the user, group, or resource exists.
public let organizationId: String
public init(entityId: String, maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.entityId = entityId
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListMailboxPermissionsResponse: AWSDecodableShape {
/// The token to use to retrieve the next page of results. The value is "null" when there are no more results to return.
public let nextToken: String?
/// One page of the user, group, or resource mailbox permissions.
public let permissions: [Permission]?
public init(nextToken: String? = nil, permissions: [Permission]? = nil) {
self.nextToken = nextToken
self.permissions = permissions
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case permissions = "Permissions"
}
}
public struct ListOrganizationsRequest: AWSEncodableShape {
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListOrganizationsResponse: AWSDecodableShape {
/// The token to use to retrieve the next page of results. The value is "null" when there are no more results to return.
public let nextToken: String?
/// The overview of owned organizations presented as a list of organization summaries.
public let organizationSummaries: [OrganizationSummary]?
public init(nextToken: String? = nil, organizationSummaries: [OrganizationSummary]? = nil) {
self.nextToken = nextToken
self.organizationSummaries = organizationSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case organizationSummaries = "OrganizationSummaries"
}
}
public struct ListResourceDelegatesRequest: AWSEncodableShape {
/// The number of maximum results in a page.
public let maxResults: Int?
/// The token used to paginate through the delegates associated with a resource.
public let nextToken: String?
/// The identifier for the organization that contains the resource for which delegates are listed.
public let organizationId: String
/// The identifier for the resource whose delegates are listed.
public let resourceId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, organizationId: String, resourceId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
self.resourceId = resourceId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.resourceId, name: "resourceId", parent: name, max: 256)
try self.validate(self.resourceId, name: "resourceId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
case resourceId = "ResourceId"
}
}
public struct ListResourceDelegatesResponse: AWSDecodableShape {
/// One page of the resource's delegates.
public let delegates: [Delegate]?
/// The token used to paginate through the delegates associated with a resource. While results are still available, it has an associated value. When the last page is reached, the token is empty.
public let nextToken: String?
public init(delegates: [Delegate]? = nil, nextToken: String? = nil) {
self.delegates = delegates
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case delegates = "Delegates"
case nextToken = "NextToken"
}
}
public struct ListResourcesRequest: AWSEncodableShape {
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
/// The identifier for the organization under which the resources exist.
public let organizationId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListResourcesResponse: AWSDecodableShape {
/// The token used to paginate through all the organization's resources. While results are still available, it has an associated value. When the last page is reached, the token is empty.
public let nextToken: String?
/// One page of the organization's resource representation.
public let resources: [Resource]?
public init(nextToken: String? = nil, resources: [Resource]? = nil) {
self.nextToken = nextToken
self.resources = resources
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case resources = "Resources"
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
/// The resource ARN.
public let resourceARN: String
public init(resourceARN: String) {
self.resourceARN = resourceARN
}
public func validate(name: String) throws {
try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011)
try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case resourceARN = "ResourceARN"
}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
/// A list of tag key-value pairs.
public let tags: [Tag]?
public init(tags: [Tag]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct ListUsersRequest: AWSEncodableShape {
/// The maximum number of results to return in a single call.
public let maxResults: Int?
/// The token to use to retrieve the next page of results. The first call does not contain any tokens.
public let nextToken: String?
/// The identifier for the organization under which the users exist.
public let organizationId: String
public init(maxResults: Int? = nil, nextToken: String? = nil, organizationId: String) {
self.maxResults = maxResults
self.nextToken = nextToken
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 100)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 1024)
try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "[\\S\\s]*|[a-zA-Z0-9/+=]{1,1024}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case maxResults = "MaxResults"
case nextToken = "NextToken"
case organizationId = "OrganizationId"
}
}
public struct ListUsersResponse: AWSDecodableShape {
/// The token to use to retrieve the next page of results. This value is `null` when there are no more results to return.
public let nextToken: String?
/// The overview of users for an organization.
public let users: [User]?
public init(nextToken: String? = nil, users: [User]? = nil) {
self.nextToken = nextToken
self.users = users
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case users = "Users"
}
}
public struct MailboxExportJob: AWSDecodableShape {
/// The mailbox export job description.
public let description: String?
/// The mailbox export job end timestamp.
public let endTime: Date?
/// The identifier of the user or resource associated with the mailbox.
public let entityId: String?
/// The estimated progress of the mailbox export job, in percentage points.
public let estimatedProgress: Int?
/// The identifier of the mailbox export job.
public let jobId: String?
/// The name of the S3 bucket.
public let s3BucketName: String?
/// The path to the S3 bucket and file that the mailbox export job exports to.
public let s3Path: String?
/// The mailbox export job start timestamp.
public let startTime: Date?
/// The state of the mailbox export job.
public let state: MailboxExportJobState?
public init(description: String? = nil, endTime: Date? = nil, entityId: String? = nil, estimatedProgress: Int? = nil, jobId: String? = nil, s3BucketName: String? = nil, s3Path: String? = nil, startTime: Date? = nil, state: MailboxExportJobState? = nil) {
self.description = description
self.endTime = endTime
self.entityId = entityId
self.estimatedProgress = estimatedProgress
self.jobId = jobId
self.s3BucketName = s3BucketName
self.s3Path = s3Path
self.startTime = startTime
self.state = state
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case endTime = "EndTime"
case entityId = "EntityId"
case estimatedProgress = "EstimatedProgress"
case jobId = "JobId"
case s3BucketName = "S3BucketName"
case s3Path = "S3Path"
case startTime = "StartTime"
case state = "State"
}
}
public struct Member: AWSDecodableShape {
/// The date indicating when the member was disabled from Amazon WorkMail use.
public let disabledDate: Date?
/// The date indicating when the member was enabled for Amazon WorkMail use.
public let enabledDate: Date?
/// The identifier of the member.
public let id: String?
/// The name of the member.
public let name: String?
/// The state of the member, which can be ENABLED, DISABLED, or DELETED.
public let state: EntityState?
/// A member can be a user or group.
public let type: MemberType?
public init(disabledDate: Date? = nil, enabledDate: Date? = nil, id: String? = nil, name: String? = nil, state: EntityState? = nil, type: MemberType? = nil) {
self.disabledDate = disabledDate
self.enabledDate = enabledDate
self.id = id
self.name = name
self.state = state
self.type = type
}
private enum CodingKeys: String, CodingKey {
case disabledDate = "DisabledDate"
case enabledDate = "EnabledDate"
case id = "Id"
case name = "Name"
case state = "State"
case type = "Type"
}
}
public struct OrganizationSummary: AWSDecodableShape {
/// The alias associated with the organization.
public let alias: String?
/// The default email domain associated with the organization.
public let defaultMailDomain: String?
/// The error message associated with the organization. It is only present if unexpected behavior has occurred with regards to the organization. It provides insight or solutions regarding unexpected behavior.
public let errorMessage: String?
/// The identifier associated with the organization.
public let organizationId: String?
/// The state associated with the organization.
public let state: String?
public init(alias: String? = nil, defaultMailDomain: String? = nil, errorMessage: String? = nil, organizationId: String? = nil, state: String? = nil) {
self.alias = alias
self.defaultMailDomain = defaultMailDomain
self.errorMessage = errorMessage
self.organizationId = organizationId
self.state = state
}
private enum CodingKeys: String, CodingKey {
case alias = "Alias"
case defaultMailDomain = "DefaultMailDomain"
case errorMessage = "ErrorMessage"
case organizationId = "OrganizationId"
case state = "State"
}
}
public struct Permission: AWSDecodableShape {
/// The identifier of the user, group, or resource to which the permissions are granted.
public let granteeId: String
/// The type of user, group, or resource referred to in GranteeId.
public let granteeType: MemberType
/// The permissions granted to the grantee. SEND_AS allows the grantee to send email as the owner of the mailbox (the grantee is not mentioned on these emails). SEND_ON_BEHALF allows the grantee to send email on behalf of the owner of the mailbox (the grantee is not mentioned as the physical sender of these emails). FULL_ACCESS allows the grantee full access to the mailbox, irrespective of other folder-level permissions set on the mailbox.
public let permissionValues: [PermissionType]
public init(granteeId: String, granteeType: MemberType, permissionValues: [PermissionType]) {
self.granteeId = granteeId
self.granteeType = granteeType
self.permissionValues = permissionValues
}
private enum CodingKeys: String, CodingKey {
case granteeId = "GranteeId"
case granteeType = "GranteeType"
case permissionValues = "PermissionValues"
}
}
public struct PutAccessControlRuleRequest: AWSEncodableShape {
/// Access protocol actions to include in the rule. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail.
public let actions: [String]?
/// The rule description.
public let description: String
/// The rule effect.
public let effect: AccessControlRuleEffect
/// IPv4 CIDR ranges to include in the rule.
public let ipRanges: [String]?
/// The rule name.
public let name: String
/// Access protocol actions to exclude from the rule. Valid values include ActiveSync, AutoDiscover, EWS, IMAP, SMTP, WindowsOutlook, and WebMail.
public let notActions: [String]?
/// IPv4 CIDR ranges to exclude from the rule.
public let notIpRanges: [String]?
/// User IDs to exclude from the rule.
public let notUserIds: [String]?
/// The identifier of the organization.
public let organizationId: String
/// User IDs to include in the rule.
public let userIds: [String]?
public init(actions: [String]? = nil, description: String, effect: AccessControlRuleEffect, ipRanges: [String]? = nil, name: String, notActions: [String]? = nil, notIpRanges: [String]? = nil, notUserIds: [String]? = nil, organizationId: String, userIds: [String]? = nil) {
self.actions = actions
self.description = description
self.effect = effect
self.ipRanges = ipRanges
self.name = name
self.notActions = notActions
self.notIpRanges = notIpRanges
self.notUserIds = notUserIds
self.organizationId = organizationId
self.userIds = userIds
}
public func validate(name: String) throws {
try self.actions?.forEach {
try validate($0, name: "actions[]", parent: name, max: 64)
try validate($0, name: "actions[]", parent: name, min: 1)
try validate($0, name: "actions[]", parent: name, pattern: "[a-zA-Z]+")
}
try self.validate(self.actions, name: "actions", parent: name, max: 10)
try self.validate(self.actions, name: "actions", parent: name, min: 0)
try self.validate(self.description, name: "description", parent: name, max: 255)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.validate(self.description, name: "description", parent: name, pattern: "[\\u0020-\\u00FF]+")
try self.ipRanges?.forEach {
try validate($0, name: "ipRanges[]", parent: name, max: 18)
try validate($0, name: "ipRanges[]", parent: name, min: 1)
try validate($0, name: "ipRanges[]", parent: name, pattern: "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/([0-9]|[12][0-9]|3[0-2])$")
}
try self.validate(self.ipRanges, name: "ipRanges", parent: name, max: 10)
try self.validate(self.ipRanges, name: "ipRanges", parent: name, min: 0)
try self.validate(self.name, name: "name", parent: name, max: 64)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_-]+")
try self.notActions?.forEach {
try validate($0, name: "notActions[]", parent: name, max: 64)
try validate($0, name: "notActions[]", parent: name, min: 1)
try validate($0, name: "notActions[]", parent: name, pattern: "[a-zA-Z]+")
}
try self.validate(self.notActions, name: "notActions", parent: name, max: 10)
try self.validate(self.notActions, name: "notActions", parent: name, min: 0)
try self.notIpRanges?.forEach {
try validate($0, name: "notIpRanges[]", parent: name, max: 18)
try validate($0, name: "notIpRanges[]", parent: name, min: 1)
try validate($0, name: "notIpRanges[]", parent: name, pattern: "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/([0-9]|[12][0-9]|3[0-2])$")
}
try self.validate(self.notIpRanges, name: "notIpRanges", parent: name, max: 10)
try self.validate(self.notIpRanges, name: "notIpRanges", parent: name, min: 0)
try self.notUserIds?.forEach {
try validate($0, name: "notUserIds[]", parent: name, max: 256)
try validate($0, name: "notUserIds[]", parent: name, min: 12)
}
try self.validate(self.notUserIds, name: "notUserIds", parent: name, max: 10)
try self.validate(self.notUserIds, name: "notUserIds", parent: name, min: 0)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.userIds?.forEach {
try validate($0, name: "userIds[]", parent: name, max: 256)
try validate($0, name: "userIds[]", parent: name, min: 12)
}
try self.validate(self.userIds, name: "userIds", parent: name, max: 10)
try self.validate(self.userIds, name: "userIds", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case actions = "Actions"
case description = "Description"
case effect = "Effect"
case ipRanges = "IpRanges"
case name = "Name"
case notActions = "NotActions"
case notIpRanges = "NotIpRanges"
case notUserIds = "NotUserIds"
case organizationId = "OrganizationId"
case userIds = "UserIds"
}
}
public struct PutAccessControlRuleResponse: AWSDecodableShape {
public init() {}
}
public struct PutMailboxPermissionsRequest: AWSEncodableShape {
/// The identifier of the user, group, or resource for which to update mailbox permissions.
public let entityId: String
/// The identifier of the user, group, or resource to which to grant the permissions.
public let granteeId: String
/// The identifier of the organization under which the user, group, or resource exists.
public let organizationId: String
/// The permissions granted to the grantee. SEND_AS allows the grantee to send email as the owner of the mailbox (the grantee is not mentioned on these emails). SEND_ON_BEHALF allows the grantee to send email on behalf of the owner of the mailbox (the grantee is not mentioned as the physical sender of these emails). FULL_ACCESS allows the grantee full access to the mailbox, irrespective of other folder-level permissions set on the mailbox.
public let permissionValues: [PermissionType]
public init(entityId: String, granteeId: String, organizationId: String, permissionValues: [PermissionType]) {
self.entityId = entityId
self.granteeId = granteeId
self.organizationId = organizationId
self.permissionValues = permissionValues
}
public func validate(name: String) throws {
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.granteeId, name: "granteeId", parent: name, max: 256)
try self.validate(self.granteeId, name: "granteeId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case entityId = "EntityId"
case granteeId = "GranteeId"
case organizationId = "OrganizationId"
case permissionValues = "PermissionValues"
}
}
public struct PutMailboxPermissionsResponse: AWSDecodableShape {
public init() {}
}
public struct PutRetentionPolicyRequest: AWSEncodableShape {
/// The retention policy description.
public let description: String?
/// The retention policy folder configurations.
public let folderConfigurations: [FolderConfiguration]
/// The retention policy ID.
public let id: String?
/// The retention policy name.
public let name: String
/// The organization ID.
public let organizationId: String
public init(description: String? = nil, folderConfigurations: [FolderConfiguration], id: String? = nil, name: String, organizationId: String) {
self.description = description
self.folderConfigurations = folderConfigurations
self.id = id
self.name = name
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, pattern: "[\\w\\d\\s\\S\\-!?=,.;:'_]+")
try self.folderConfigurations.forEach {
try $0.validate(name: "\(name).folderConfigurations[]")
}
try self.validate(self.id, name: "id", parent: name, max: 64)
try self.validate(self.id, name: "id", parent: name, min: 1)
try self.validate(self.id, name: "id", parent: name, pattern: "[a-zA-Z0-9_-]+")
try self.validate(self.name, name: "name", parent: name, max: 64)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[a-zA-Z0-9_-]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case folderConfigurations = "FolderConfigurations"
case id = "Id"
case name = "Name"
case organizationId = "OrganizationId"
}
}
public struct PutRetentionPolicyResponse: AWSDecodableShape {
public init() {}
}
public struct RegisterToWorkMailRequest: AWSEncodableShape {
/// The email for the user, group, or resource to be updated.
public let email: String
/// The identifier for the user, group, or resource to be updated.
public let entityId: String
/// The identifier for the organization under which the user, group, or resource exists.
public let organizationId: String
public init(email: String, entityId: String, organizationId: String) {
self.email = email
self.entityId = entityId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.email, name: "email", parent: name, max: 254)
try self.validate(self.email, name: "email", parent: name, min: 1)
try self.validate(self.email, name: "email", parent: name, pattern: "[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]+\\.[a-zA-Z-]{2,}")
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case email = "Email"
case entityId = "EntityId"
case organizationId = "OrganizationId"
}
}
public struct RegisterToWorkMailResponse: AWSDecodableShape {
public init() {}
}
public struct ResetPasswordRequest: AWSEncodableShape {
/// The identifier of the organization that contains the user for which the password is reset.
public let organizationId: String
/// The new password for the user.
public let password: String
/// The identifier of the user for whom the password is reset.
public let userId: String
public init(organizationId: String, password: String, userId: String) {
self.organizationId = organizationId
self.password = password
self.userId = userId
}
public func validate(name: String) throws {
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.password, name: "password", parent: name, max: 256)
try self.validate(self.password, name: "password", parent: name, pattern: "[\\u0020-\\u00FF]+")
try self.validate(self.userId, name: "userId", parent: name, max: 256)
try self.validate(self.userId, name: "userId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case organizationId = "OrganizationId"
case password = "Password"
case userId = "UserId"
}
}
public struct ResetPasswordResponse: AWSDecodableShape {
public init() {}
}
public struct Resource: AWSDecodableShape {
/// The date indicating when the resource was disabled from Amazon WorkMail use.
public let disabledDate: Date?
/// The email of the resource.
public let email: String?
/// The date indicating when the resource was enabled for Amazon WorkMail use.
public let enabledDate: Date?
/// The identifier of the resource.
public let id: String?
/// The name of the resource.
public let name: String?
/// The state of the resource, which can be ENABLED, DISABLED, or DELETED.
public let state: EntityState?
/// The type of the resource: equipment or room.
public let type: ResourceType?
public init(disabledDate: Date? = nil, email: String? = nil, enabledDate: Date? = nil, id: String? = nil, name: String? = nil, state: EntityState? = nil, type: ResourceType? = nil) {
self.disabledDate = disabledDate
self.email = email
self.enabledDate = enabledDate
self.id = id
self.name = name
self.state = state
self.type = type
}
private enum CodingKeys: String, CodingKey {
case disabledDate = "DisabledDate"
case email = "Email"
case enabledDate = "EnabledDate"
case id = "Id"
case name = "Name"
case state = "State"
case type = "Type"
}
}
public struct StartMailboxExportJobRequest: AWSEncodableShape {
/// The idempotency token for the client request.
public let clientToken: String
/// The mailbox export job description.
public let description: String?
/// The identifier of the user or resource associated with the mailbox.
public let entityId: String
/// The Amazon Resource Name (ARN) of the symmetric AWS Key Management Service (AWS KMS) key that encrypts the exported mailbox content.
public let kmsKeyArn: String
/// The identifier associated with the organization.
public let organizationId: String
/// The ARN of the AWS Identity and Access Management (IAM) role that grants write permission to the S3 bucket.
public let roleArn: String
/// The name of the S3 bucket.
public let s3BucketName: String
/// The S3 bucket prefix.
public let s3Prefix: String
public init(clientToken: String = StartMailboxExportJobRequest.idempotencyToken(), description: String? = nil, entityId: String, kmsKeyArn: String, organizationId: String, roleArn: String, s3BucketName: String, s3Prefix: String) {
self.clientToken = clientToken
self.description = description
self.entityId = entityId
self.kmsKeyArn = kmsKeyArn
self.organizationId = organizationId
self.roleArn = roleArn
self.s3BucketName = s3BucketName
self.s3Prefix = s3Prefix
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 128)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "[\\x21-\\x7e]+")
try self.validate(self.description, name: "description", parent: name, max: 1023)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.validate(self.description, name: "description", parent: name, pattern: "[\\S\\s]*")
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.kmsKeyArn, name: "kmsKeyArn", parent: name, max: 2048)
try self.validate(self.kmsKeyArn, name: "kmsKeyArn", parent: name, min: 20)
try self.validate(self.kmsKeyArn, name: "kmsKeyArn", parent: name, pattern: "arn:aws:kms:[a-z0-9-]*:[a-z0-9-]+:[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,1023}")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048)
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20)
try self.validate(self.s3BucketName, name: "s3BucketName", parent: name, max: 63)
try self.validate(self.s3BucketName, name: "s3BucketName", parent: name, min: 1)
try self.validate(self.s3BucketName, name: "s3BucketName", parent: name, pattern: "[A-Za-z0-9.-]+")
try self.validate(self.s3Prefix, name: "s3Prefix", parent: name, max: 1023)
try self.validate(self.s3Prefix, name: "s3Prefix", parent: name, min: 1)
try self.validate(self.s3Prefix, name: "s3Prefix", parent: name, pattern: "[A-Za-z0-9!_.*'()/-]+")
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case description = "Description"
case entityId = "EntityId"
case kmsKeyArn = "KmsKeyArn"
case organizationId = "OrganizationId"
case roleArn = "RoleArn"
case s3BucketName = "S3BucketName"
case s3Prefix = "S3Prefix"
}
}
public struct StartMailboxExportJobResponse: AWSDecodableShape {
/// The job ID.
public let jobId: String?
public init(jobId: String? = nil) {
self.jobId = jobId
}
private enum CodingKeys: String, CodingKey {
case jobId = "JobId"
}
}
public struct Tag: AWSEncodableShape & AWSDecodableShape {
/// The key of the tag.
public let key: String
/// The value of the tag.
public let value: String
public init(key: String, value: String) {
self.key = key
self.value = value
}
public func validate(name: String) throws {
try self.validate(self.key, name: "key", parent: name, max: 128)
try self.validate(self.key, name: "key", parent: name, min: 1)
try self.validate(self.value, name: "value", parent: name, max: 256)
try self.validate(self.value, name: "value", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case key = "Key"
case value = "Value"
}
}
public struct TagResourceRequest: AWSEncodableShape {
/// The resource ARN.
public let resourceARN: String
/// The tag key-value pairs.
public let tags: [Tag]
public init(resourceARN: String, tags: [Tag]) {
self.resourceARN = resourceARN
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011)
try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1)
try self.tags.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 50)
try self.validate(self.tags, name: "tags", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case resourceARN = "ResourceARN"
case tags = "Tags"
}
}
public struct TagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UntagResourceRequest: AWSEncodableShape {
/// The resource ARN.
public let resourceARN: String
/// The tag keys.
public let tagKeys: [String]
public init(resourceARN: String, tagKeys: [String]) {
self.resourceARN = resourceARN
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resourceARN, name: "resourceARN", parent: name, max: 1011)
try self.validate(self.resourceARN, name: "resourceARN", parent: name, min: 1)
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
}
try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 50)
try self.validate(self.tagKeys, name: "tagKeys", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case resourceARN = "ResourceARN"
case tagKeys = "TagKeys"
}
}
public struct UntagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UpdateMailboxQuotaRequest: AWSEncodableShape {
/// The updated mailbox quota, in MB, for the specified user.
public let mailboxQuota: Int
/// The identifier for the organization that contains the user for whom to update the mailbox quota.
public let organizationId: String
/// The identifer for the user for whom to update the mailbox quota.
public let userId: String
public init(mailboxQuota: Int, organizationId: String, userId: String) {
self.mailboxQuota = mailboxQuota
self.organizationId = organizationId
self.userId = userId
}
public func validate(name: String) throws {
try self.validate(self.mailboxQuota, name: "mailboxQuota", parent: name, min: 1)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.userId, name: "userId", parent: name, max: 256)
try self.validate(self.userId, name: "userId", parent: name, min: 12)
}
private enum CodingKeys: String, CodingKey {
case mailboxQuota = "MailboxQuota"
case organizationId = "OrganizationId"
case userId = "UserId"
}
}
public struct UpdateMailboxQuotaResponse: AWSDecodableShape {
public init() {}
}
public struct UpdatePrimaryEmailAddressRequest: AWSEncodableShape {
/// The value of the email to be updated as primary.
public let email: String
/// The user, group, or resource to update.
public let entityId: String
/// The organization that contains the user, group, or resource to update.
public let organizationId: String
public init(email: String, entityId: String, organizationId: String) {
self.email = email
self.entityId = entityId
self.organizationId = organizationId
}
public func validate(name: String) throws {
try self.validate(self.email, name: "email", parent: name, max: 254)
try self.validate(self.email, name: "email", parent: name, min: 1)
try self.validate(self.email, name: "email", parent: name, pattern: "[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]+\\.[a-zA-Z-]{2,}")
try self.validate(self.entityId, name: "entityId", parent: name, max: 256)
try self.validate(self.entityId, name: "entityId", parent: name, min: 12)
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case email = "Email"
case entityId = "EntityId"
case organizationId = "OrganizationId"
}
}
public struct UpdatePrimaryEmailAddressResponse: AWSDecodableShape {
public init() {}
}
public struct UpdateResourceRequest: AWSEncodableShape {
/// The resource's booking options to be updated.
public let bookingOptions: BookingOptions?
/// The name of the resource to be updated.
public let name: String?
/// The identifier associated with the organization for which the resource is updated.
public let organizationId: String
/// The identifier of the resource to be updated.
public let resourceId: String
public init(bookingOptions: BookingOptions? = nil, name: String? = nil, organizationId: String, resourceId: String) {
self.bookingOptions = bookingOptions
self.name = name
self.organizationId = organizationId
self.resourceId = resourceId
}
public func validate(name: String) throws {
try self.validate(self.name, name: "name", parent: name, max: 20)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "[\\w\\-.]+(@[a-zA-Z0-9.\\-]+\\.[a-zA-Z0-9-]{2,})?")
try self.validate(self.organizationId, name: "organizationId", parent: name, max: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, min: 34)
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "^m-[0-9a-f]{32}$")
try self.validate(self.resourceId, name: "resourceId", parent: name, max: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, min: 34)
try self.validate(self.resourceId, name: "resourceId", parent: name, pattern: "^r-[0-9a-f]{32}$")
}
private enum CodingKeys: String, CodingKey {
case bookingOptions = "BookingOptions"
case name = "Name"
case organizationId = "OrganizationId"
case resourceId = "ResourceId"
}
}
public struct UpdateResourceResponse: AWSDecodableShape {
public init() {}
}
public struct User: AWSDecodableShape {
/// The date indicating when the user was disabled from Amazon WorkMail use.
public let disabledDate: Date?
/// The display name of the user.
public let displayName: String?
/// The email of the user.
public let email: String?
/// The date indicating when the user was enabled for Amazon WorkMail use.
public let enabledDate: Date?
/// The identifier of the user.
public let id: String?
/// The name of the user.
public let name: String?
/// The state of the user, which can be ENABLED, DISABLED, or DELETED.
public let state: EntityState?
/// The role of the user.
public let userRole: UserRole?
public init(disabledDate: Date? = nil, displayName: String? = nil, email: String? = nil, enabledDate: Date? = nil, id: String? = nil, name: String? = nil, state: EntityState? = nil, userRole: UserRole? = nil) {
self.disabledDate = disabledDate
self.displayName = displayName
self.email = email
self.enabledDate = enabledDate
self.id = id
self.name = name
self.state = state
self.userRole = userRole
}
private enum CodingKeys: String, CodingKey {
case disabledDate = "DisabledDate"
case displayName = "DisplayName"
case email = "Email"
case enabledDate = "EnabledDate"
case id = "Id"
case name = "Name"
case state = "State"
case userRole = "UserRole"
}
}
}
| apache-2.0 | 4e66f46fb713ecfa98ffaddcbfb0973e | 45.660662 | 451 | 0.621879 | 4.559292 | false | false | false | false |
zerovagner/iOS-Studies | PageTheScroll/PageTheScroll/ViewController.swift | 1 | 1765 | //
// ViewController.swift
// PageTheScroll
//
// Created by Vagner Oliveira on 4/28/17.
// Copyright © 2017 Vagner Oliveira. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var images = [UIImageView]()
@IBOutlet weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
let scrollWidth = scrollView.frame.width
var contentWidth: CGFloat = 0.0
for x in 0..<3 {
let image = UIImage(named: "icon\(x).png")
let imageView = UIImageView(image: image)
images.append(imageView)
let newX = scrollWidth / 2 + scrollWidth * CGFloat(x)
contentWidth += scrollWidth
scrollView.addSubview(imageView)
imageView.frame = CGRect(x: newX - 75, y: (view.frame.size.height / 2) - 75, width: 150, height: 150)
}
scrollView.contentSize = (CGSize(width: contentWidth, height: view.frame.size.height))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func swipeLeft(_ sender: UISwipeGestureRecognizer) {
processSwipe(sender)
}
@IBAction func swipeRight(_ sender: UISwipeGestureRecognizer) {
processSwipe(sender)
}
func processSwipe(_ sender: UISwipeGestureRecognizer) {
var newX = CGFloat(0.0)
if sender.direction == UISwipeGestureRecognizerDirection.left {
newX = scrollView.contentOffset.x + scrollView.frame.width
if newX >= scrollView.contentSize.width {
newX = scrollView.contentSize.width
}
}
if sender.direction == UISwipeGestureRecognizerDirection.right {
newX = scrollView.contentOffset.x - scrollView.frame.width
if newX < 0 {
newX = 0
}
}
scrollView.setContentOffset(CGPoint(x: newX, y: 0), animated: true)
}
}
| gpl-3.0 | f15a688bcc978772d75aae6661896f11 | 25.328358 | 104 | 0.710884 | 3.761194 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.CurrentHeaterCoolerState.swift | 1 | 2211 | import Foundation
public extension AnyCharacteristic {
static func currentHeaterCoolerState(
_ value: Enums.CurrentHeaterCoolerState = .heating,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Current Heater-Cooler State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 3,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.currentHeaterCoolerState(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func currentHeaterCoolerState(
_ value: Enums.CurrentHeaterCoolerState = .heating,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Current Heater-Cooler State",
format: CharacteristicFormat? = .uint8,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = 3,
minValue: Double? = 0,
minStep: Double? = 1,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Enums.CurrentHeaterCoolerState> {
GenericCharacteristic<Enums.CurrentHeaterCoolerState>(
type: .currentHeaterCoolerState,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 82ba4dbf2c6f54331f6d25ec54fbc5f7 | 35.245902 | 67 | 0.605156 | 5.118056 | false | false | false | false |
qutheory/vapor | Sources/Vapor/HTTP/Headers/HTTPHeaderExpires.swift | 1 | 2021 | import NIO
extension HTTPHeaders {
public struct Expires {
/// The date represented by the header.
public let expires: Date
internal static func parse(_ dateString: String) -> Expires? {
// https://tools.ietf.org/html/rfc7231#section-7.1.1.1
let fmt = DateFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(secondsFromGMT: 0)
fmt.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zzz"
if let date = fmt.date(from: dateString) {
return .init(expires: date)
}
// Obsolete RFC 850 format
fmt.dateFormat = "EEEE, dd-MMM-yy hh:mm:ss zzz"
if let date = fmt.date(from: dateString) {
return .init(expires: date)
}
// Obsolete ANSI C asctime() format
fmt.dateFormat = "EEE MMM d hh:mm:s yyyy"
if let date = fmt.date(from: dateString) {
return .init(expires: date)
}
return nil
}
init(expires: Date) {
self.expires = expires
}
/// Generates the header string for this instance.
public func serialize() -> String {
let fmt = DateFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.timeZone = TimeZone(secondsFromGMT: 0)
fmt.dateFormat = "EEE, dd MMM yyyy hh:mm:ss zzz"
return fmt.string(from: expires)
}
}
/// Gets the value of the `Expires` header, if present.
/// ### Note ###
/// `Expires` is legacy and you should switch to using `CacheControl` if possible.
public var expires: Expires? {
get { self.first(name: .expires).flatMap(Expires.parse) }
set {
if let new = newValue?.serialize() {
self.replaceOrAdd(name: .expires, value: new)
} else {
self.remove(name: .expires)
}
}
}
}
| mit | 1f0504a9bac534feac3e6dba41dcb2d6 | 31.596774 | 86 | 0.531915 | 4.318376 | false | true | false | false |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/People/WPStyleGuide+People.swift | 1 | 905 | import Foundation
import WordPressShared
extension WPStyleGuide {
public struct People {
public struct RoleBadge {
// MARK: Metrics
public static let padding = CGFloat(4)
public static let borderWidth = CGFloat(1)
public static let cornerRadius = CGFloat(2)
// MARK: Typography
public static let font = WPFontManager.systemRegularFontOfSize(11)
// MARK: Colors
public static let textColor = UIColor.whiteColor()
}
// MARK: Colors
public static let superAdminColor = WPStyleGuide.fireOrange()
public static let adminColor = WPStyleGuide.darkGrey()
public static let editorColor = WPStyleGuide.darkBlue()
public static let authorColor = WPStyleGuide.wordPressBlue()
public static let contributorColor = WPStyleGuide.wordPressBlue()
}
} | gpl-2.0 | c5840362e7dffcbb5e3fafe282f45941 | 33.846154 | 78 | 0.650829 | 5.764331 | false | false | false | false |
ashetty1/kedge | vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-generator/Sources/gnostic-swift-generator/main.swift | 89 | 1700 | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
func Log(_ message : String) {
FileHandle.standardError.write((message + "\n").data(using:.utf8)!)
}
func main() throws {
// read the OpenAPI document
let rawRequest = try Stdin.readall()
let request = try Openapi_Plugin_V1_Request(serializedData:rawRequest)
let wrapper = request.wrapper
let document = try Openapi_V2_Document(serializedData:wrapper.value)
// build the service renderer
let renderer = ServiceRenderer(document:document)
// generate the desired files
var response = Openapi_Plugin_V1_Response()
var filenames : [String]
switch CommandLine.arguments[0] {
case "openapi_swift_client":
filenames = ["client.swift", "types.swift", "fetch.swift"]
case "openapi_swift_server":
filenames = ["server.swift", "types.swift"]
default:
filenames = ["client.swift", "server.swift", "types.swift", "fetch.swift"]
}
try renderer.generate(filenames:filenames, response:&response)
// return the results
let serializedResponse = try response.serializedData()
Stdout.write(bytes: serializedResponse)
}
try main()
| apache-2.0 | b630ad9208142a062644574498624a77 | 32.333333 | 78 | 0.728824 | 4.038005 | false | false | false | false |
pixelmaid/DynamicBrushes | swift/Palette-Knife/ViewController.swift | 1 | 52882 | //
// ViewController.swift
// Palette-Knife
//
// Created by JENNIFER MARY JACOBS on 5/4/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import UIKit
import SwiftyJSON
let behaviorMapper = BehaviorMapper()
var stylus = Stylus(x: 0,y:0,angle:0,force:0)
let uiInput = UIInput();
//CONSTANTS:
let kBrightness = 1.0
let kSaturation = 0.45
let kPaletteHeight = 30
let kPaletteSize = 5
let kMinEraseInterval = 0.5
// Padding for margins
let kLeftMargin = 10.0
let kTopMargin = 10.0
let kRightMargin = 10.0
let pX = Float(1366)
let pY = Float(1024)
class ViewController: UIViewController, UIGestureRecognizerDelegate,Requester{
// MARK: Properties
var layerContainerView:LayerContainerView!
var behaviorManager: BehaviorManager?
var currentCanvas: Canvas?
let drawKey = NSUUID().uuidString
let toolbarKey = NSUUID().uuidString
let layerEventKey = NSUUID().uuidString
let colorPickerKey = NSUUID().uuidString
let fileEventKey = NSUUID().uuidString
let behaviorEventKey = NSUUID().uuidString
let brushEventKey = NSUUID().uuidString
let dataEventKey = NSUUID().uuidString
let strokeGeneratedKey = NSUUID().uuidString
let strokeRemovedKey = NSUUID().uuidString
let exportKey = NSUUID().uuidString
let backupKey = NSUUID().uuidString
let saveEventKey = NSUUID().uuidString
var toolbarController: ToolbarViewController?
var layerPanelController: LayerPanelViewController?
var behaviorPanelController: BehaviorPanelViewController?
var fileListController: SavedFilesPanelViewController?
let targetSize = CGSize(width:CGFloat(pX),height:CGFloat(pY))
var blockAlert:UIAlertController!
//for checking if person is drawing
var touchesDown:Bool = false;
var colorPickerView: SwiftHSVColorPicker?
override var prefersStatusBarHidden: Bool {
return true
}
var drawInterval:Timer!
//variables for setting backups
var backupTimer:Timer!
//var cancelBackupTimer:Timer!
var backupInterval = 60*3; //set to backup every 5 min
var cancelBackupInterval = 60*2; //set to cancel after 2 min
var backupNeeded:Bool = false;
var currentBehaviorName = ""
var currentBehaviorFile = ""
var startup = true;
@IBOutlet weak var layerPanelContainerView: UIView!
@IBOutlet weak var colorPickerContainerView: UIView!
@IBOutlet weak var fileListContainerView: UIView!
@IBOutlet weak var behaviorPanelContainerView: UIView!
required init?(coder: NSCoder) {
layerContainerView = LayerContainerView(width:pX,height:pY);
super.init(coder: coder);
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "toolbarSegue"){
toolbarController = segue.destination as? ToolbarViewController;
_ = toolbarController?.toolEvent.addHandler(target: self, handler: ViewController.toolEventHandler, key: toolbarKey)
}
else if(segue.identifier == "layerPanelSegue"){
layerPanelController = segue.destination as? LayerPanelViewController;
_ = layerPanelController?.layerEvent.addHandler(target: self, handler: ViewController.layerEventHandler, key: layerEventKey)
}
else if(segue.identifier == "colorPickerSegue"){
colorPickerView = SwiftHSVColorPicker(frame: CGRect(x:10, y:20, width:300, height:400))
segue.destination.view.addSubview(colorPickerView!)
colorPickerView?.setViewColor(UIColor.red)
_ = colorPickerView?.colorEvent.addHandler(target: self, handler: ViewController.colorPickerEventHandler, key: colorPickerKey)
}
else if(segue.identifier == "fileListSegue"){
fileListController = segue.destination as? SavedFilesPanelViewController;
_ = fileListController?.fileEvent.addHandler(target: self, handler: ViewController.fileEventHandler, key: fileEventKey)
}
else if(segue.identifier == "behaviorPanelSegue"){
behaviorPanelController = segue.destination as? BehaviorPanelViewController;
_ = behaviorPanelController?.behaviorEvent.addHandler(target: self, handler: ViewController.behaviorEventHandler, key: behaviorEventKey)
}
}
func colorPickerEventHandler(data:(UIColor), key: String){
toolbarController?.setColor(color:data);
uiInput.setColor(color:data);
}
func toolEventHandler(data: (String), key: String){
print("tool event handler",data)
switch(data){
case "VIEW_LOADED":
toolbarController?.exportButton.addTarget(self, action: #selector(ViewController.exportImage), for: .touchUpInside)
toolbarController?.saveButton.addTarget(self, action: #selector(ViewController.saveProject), for: .touchUpInside)
break;
case "ERASE_MODE":
self.layerContainerView.removeAllStrokes()
layerContainerView.toggleDrawActive();
break;
case "PEN_MODE":
self.layerContainerView.removeAllStrokes()
layerContainerView.setPenActive();
break;
case "AIRBRUSH_MODE":
self.layerContainerView.removeAllStrokes()
layerContainerView.setAirbrushActive();
break;
case "TOGGLE_LAYER_PANEL":
if(layerPanelContainerView?.isHidden == true){
layerPanelContainerView?.isHidden = false
}
else{
layerPanelContainerView?.isHidden = true
}
colorPickerContainerView?.isHidden = true
behaviorPanelContainerView?.isHidden = true
break;
case "TOGGLE_BEHAVIOR_PANEL":
if(behaviorPanelContainerView?.isHidden == true){
behaviorPanelContainerView?.isHidden = false
}
else{
behaviorPanelContainerView?.isHidden = true
}
colorPickerContainerView?.isHidden = true
layerPanelContainerView?.isHidden = true
break;
case "TOGGLE_FILE_PANEL":
if(fileListContainerView?.isHidden == true){
fileListContainerView?.isHidden = false
}
else{
fileListContainerView?.isHidden = true
}
break;
case "TOGGLE_COLOR_PANEL":
if(colorPickerContainerView?.isHidden == true){
colorPickerContainerView?.isHidden = false
}
else{
colorPickerContainerView?.isHidden = true
}
layerPanelContainerView?.isHidden = true
behaviorPanelContainerView?.isHidden = true
break
case "DIAMETER_CHANGED":
uiInput.setDiameter(val: (toolbarController?.diameterSlider.value)!);
break;
case "ALPHA_CHANGED":
uiInput.setAlpha(val: (toolbarController?.alphaSlider.value)!);
break;
default:
break;
}
}
func layerEventHandler(data: (String,String,String?), key: String){
switch(data.0){
case "LAYER_SELECTED":
layerContainerView.selectActiveLayer(id:data.1);
break;
case "LAYER_ADDED":
self.userInitLayer();
break;
case "SHOW_LAYER":
layerContainerView.showLayer(id: data.1);
break;
case "HIDE_LAYER":
layerContainerView.hideLayer(id: data.1);
break;
case "DELETE_LAYER":
self.deleteAlert(layerName: data.2!, layerId: data.1)
break;
default:
break;
}
}
func behaviorEventHandler(data: (String,String,String?), key: String){
switch(data.0){
case "ACTIVATE_BEHAVIOR":
var authoringData:JSON = [:]
authoringData["type"] = JSON("set_behavior_active")
authoringData["behaviorId"] = JSON(data.1)
authoringData["active_status"] = JSON(true)
var data:JSON = [:]
data["data"] = authoringData
do {
try _ = behaviorManager?.handleAuthoringRequest(authoring_data: data)
self.synchronizeWithAuthoringClient();
}
catch{
#if DEBUG
print("error in authoring")
#endif
}
break;
case "DEACTIVATE_BEHAVIOR":
var authoringData:JSON = [:]
authoringData["type"] = JSON("set_behavior_active")
authoringData["behaviorId"] = JSON(data.1)
authoringData["active_status"] = JSON(false)
var data:JSON = [:]
data["data"] = authoringData
do {
try _ = behaviorManager?.handleAuthoringRequest(authoring_data: data)
self.synchronizeWithAuthoringClient();
}
catch{
#if DEBUG
print("error in authoring")
#endif
}
break;
case "REFRESH_BEHAVIOR":
var authoringData:JSON = [:]
authoringData["type"] = JSON("refresh_behavior")
authoringData["behaviorId"] = JSON(data.1)
var data:JSON = [:]
data["data"] = authoringData
do {
try _ = behaviorManager?.handleAuthoringRequest(authoring_data: data)
}
catch{
#if DEBUG
print("error in authoring")
#endif
}
break;
default:
break;
}
}
func fileEventHandler(data: (String,String,String?), key: String){
switch(data.0){
case "FILE_SELECTED":
let artistName = UserDefaults.standard.string(forKey: "userkey")
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Loading", message: "Loading Project", preferredStyle: .alert)
self.present(alert, animated: true);
}
}
self.loadProject(projectName: data.2!, artistName: artistName!);
break;
default:
break;
}
}
func strokeGeneratedHandler(data:(String),key:String){
self.layerContainerView.addStroke(id:data);
}
func strokeRemovedHandler(data:([String]),key:String){
self.layerContainerView.removeStroke(idList:data);
}
override func viewDidLoad() {
super.viewDidLoad()
self.initCanvas()
_ = RequestHandler.dataEvent.addHandler(target: self, handler: ViewController.processRequestHandler, key: dataEventKey)
let configureRequest = Request(target: "storage", action: "configure", data:JSON([]), requester: self)
RequestHandler.addRequest(requestData:configureRequest);
layerContainerView.center = CGPoint(x:self.view.frame.size.width/2,y:self.view.frame.size.height/2);
self.view.addSubview(layerContainerView);
self.view.sendSubview(toBack: layerContainerView);
let pinchRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(ViewController.handlePinch))
pinchRecognizer.delegate = self
layerContainerView.addGestureRecognizer(pinchRecognizer)
let rotateRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(ViewController.handleRotate))
rotateRecognizer.delegate = self
layerContainerView.addGestureRecognizer(rotateRecognizer)
let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(ViewController.handlePan))
panRecognizer.delegate = self
panRecognizer.minimumNumberOfTouches = 2;
layerContainerView.addGestureRecognizer(panRecognizer)
layerPanelContainerView.layer.cornerRadius = 8.0
layerPanelContainerView.clipsToBounds = true
self.newLayer();
layerPanelContainerView.isHidden = true;
behaviorPanelContainerView.layer.cornerRadius = 8.0
behaviorPanelContainerView.clipsToBounds = true
behaviorPanelContainerView.isHidden = true;
colorPickerContainerView.layer.cornerRadius = 8.0
colorPickerContainerView.clipsToBounds = true
colorPickerContainerView.isHidden = true;
uiInput.setDiameter(val: (toolbarController?.diameterSlider.value)!);
uiInput.setAlpha(val: (toolbarController?.alphaSlider.value)!);
uiInput.setColor(color: (colorPickerView?.color)!)
fileListContainerView.layer.cornerRadius = 8.0
fileListContainerView.clipsToBounds = true
fileListContainerView.isHidden = true;
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationDidEnterBackground, object: nil)
}
@objc func appMovedToForeground() {
print("App moved to ForeGround!")
}
@objc func appMovedToBackground() {
print("App moved to Background!")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
self.loginAlert(isIncorrect: false);
}
func addConnectionRequests(){
let connectRequest = Request(target: "socket", action: "connect", data:JSON([]), requester: self)
RequestHandler.addRequest(requestData:connectRequest);
}
func addProjectInitRequests(){
var templateJSON:JSON = [:]
templateJSON["filename"] = "templates/basic.json"
templateJSON["type"] = JSON("load")
let behaviorDownloadRequest = Request(target: "storage", action: "download", data:templateJSON, requester: self)
// RequestHandler.addRequest(requestData:behaviorDownloadRequest);
requestProjectList()
drawInterval = Timer.scheduledTimer(timeInterval:0.016 , target: self, selector: #selector(ViewController.drawIntervalCallback), userInfo: nil, repeats: true)
self.startBackupTimer(interval:self.backupInterval);
}
func requestProjectList(){
let artistName = UserDefaults.standard.string(forKey: "userkey")
var projectListJSON:JSON = [:]
projectListJSON["list_type"] = JSON("project_list")
projectListJSON["targetFolder"] = JSON("saved_files/"+artistName!+"/drawings/")
let projectListRequest = Request(target: "storage", action:"filelist", data:projectListJSON, requester: self);
RequestHandler.addRequest(requestData:projectListRequest);
}
func processProjectList(list:JSON){
let list_dict = list.dictionaryValue
var newFiles = [String:String]()
for(key,value) in list_dict{
if key.range(of: "data.json") != nil{
newFiles[key] = value.stringValue;
}
}
fileListController?.loadFiles(newFiles: newFiles)
}
func keyRecognized(){
#if DEBUG
print("key is recognized")
#endif
if(startup == true){
self.addProjectInitRequests()
startup = false;
}
}
func loginAlert(isIncorrect:Bool) {
let message:String
if(!isIncorrect){
message = "Enter your login key"
}
else{
message = "That key was not recognized, please try again"
}
let alertController = UIAlertController(title: "Login", message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
if let field = alertController.textFields?[0] {
// store your data
UserDefaults.standard.set(field.text, forKey: "userkey")
UserDefaults.standard.synchronize()
self.addConnectionRequests();
} else {
#if DEBUG
print("no login key provided");
#endif
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = ""
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func recconnectAlert(){
let alertController = UIAlertController(title:"Connection Issue", message: "You were disconnected from the server. Try to reconnect?", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
self.addConnectionRequests();
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func deleteAlert(layerName:String, layerId:String){
let alertController = UIAlertController(title:"Delete Layer", message: "Delete the layer \""+layerName+"\"?", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
let activeId = self.layerContainerView.deleteLayer(id: layerId)
self.layerPanelController?.removeLayer(layerId: layerId)
if(activeId != nil){
self.layerPanelController?.setActive(layerId:activeId!);
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func saveFileToTempDir(data:NSData,filename:String,ext:String)->String{
let fileManager = FileManager.default
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("\(filename).\(ext)")
fileManager.createFile(atPath: path as String, contents: data as Data, attributes: nil)
return path;
}
func uploadProject(type:String,filename:String){
// if(type != "backup"){
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Saving", message: "Saving Project", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
self.cancelBackupCallback()
}
alert.addAction(cancelAction)
self.present(alert, animated: true);
}
}
// }
UserDefaults.standard.set(type, forKey: "save_type")
UserDefaults.standard.set(filename, forKey: "save_filename")
UserDefaults.standard.synchronize()
_ = self.layerContainerView.saveEvent.addHandler(target: self, handler: ViewController.uploadProjectHandler, key: saveEventKey)
self.behaviorManager?.refreshAllBehaviors();
//TODO: this is a hack. need to create a delay in case it's saving a stroke to the texture
self.layerContainerView.save();
}
func uploadProjectHandler(data:(JSON,[String:String],[String:String],[String:[String]]),key:String){
self.layerContainerView.saveEvent.removeAllHandlers();
let type = UserDefaults.standard.string(forKey: "save_type")!
let filename = UserDefaults.standard.string(forKey: "save_filename")!
let prefix:String
if(type == "backup"){
prefix = "/drawing_backups/"
}
else{
prefix = "/drawings/"
}
let save_json = data.0;
let save_inks = data.1;
let save_plists = data.2
let save_strokes = data.3
let artistName = UserDefaults.standard.string(forKey:"userkey");
var uploadJSON:JSON = [:]
uploadJSON["filename"] = JSON("saved_files/"+artistName!+prefix+filename+"/"+"data.json")
uploadJSON["data"] = save_json
uploadJSON["type"] = JSON("project_save")
uploadJSON["targetFolder"] = JSON("saved_files/"+artistName!+prefix+filename+"/")
let uploadRequest = Request(target: "storage", action: "upload", data:uploadJSON, requester: self)
RequestHandler.addRequest(requestData:uploadRequest);
for (key,val) in save_inks{
if(val != "no_image"){
var uploadData:JSON = [:]
uploadData["content_type"] = JSON("image/png")
uploadData["save_type"] = JSON(type)
uploadData["filename"] = JSON("saved_files/"+artistName!+prefix+filename+"/"+"ink_"+key+".png")
uploadData["path"] = JSON(val)
uploadData["targetFolder"] = JSON("saved_files/"+artistName!+prefix)
let uploadRequest = Request(target: "storage", action: "upload_image", data:uploadData, requester: self)
RequestHandler.addRequest(requestData:uploadRequest);
}
}
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths[0] as! String
for (_, strokes) in save_strokes{
for s in strokes{
var uploadData:JSON = [:]
uploadData["content_type"] = JSON("text/strokedata")
uploadData["save_type"] = JSON(type)
uploadData["filename"] = JSON("saved_files/"+artistName!+prefix+filename+"/"+s+".strokedata")
let path = documentDirectory.appending("/"+s+".strokedata")
uploadData["path"] = JSON(path)
print("stroke data upload path",path);
uploadData["targetFolder"] = JSON("saved_files/"+artistName!+prefix)
let uploadRequest = Request(target: "storage", action: "upload_image", data:uploadData, requester: self)
RequestHandler.addRequest(requestData:uploadRequest);
}
}
var count = 0;
for (key,val) in save_plists{
count += 1
var uploadData:JSON = [:]
uploadData["content_type"] = JSON("text/plist")
uploadData["save_type"] = JSON(type)
uploadData["filename"] = JSON("saved_files/"+artistName!+prefix+filename+"/"+"state_"+key+".plist")
uploadData["path"] = JSON(val)
uploadData["targetFolder"] = JSON("saved_files/"+artistName!+prefix)
if(count == save_plists.count){
uploadData["isLast"] = JSON(true);
}
let uploadRequest = Request(target: "storage", action: "upload_image", data:uploadData, requester: self)
RequestHandler.addRequest(requestData:uploadRequest);
}
self.requestProjectList()
}
func startBackupTimer(interval:Int){
/* self.endBackupTimer();
self.toolbarController?.enableSaveLoad();
self.dismiss(animated: true, completion: nil)
//self.endCancelTimer();
backupTimer = Timer.scheduledTimer(timeInterval:TimeInterval(interval), target: self, selector: #selector(ViewController.backupCallback), userInfo: nil, repeats: true)
*/
}
/*func startCancelBackupTimer(){
cancelBackupTimer = Timer.scheduledTimer(timeInterval:TimeInterval(cancelBackupInterval), target: self, selector: #selector(ViewController.cancelBackupCallback), userInfo: nil, repeats: true)
}*/
func endBackupTimer(){
if(backupTimer != nil){
backupTimer.invalidate();
}
}
/*func endCancelTimer(){
if(cancelBackupTimer != nil){
cancelBackupTimer.invalidate();
}
}*/
func backupProject(filename:String){
self.uploadProject(type: "backup", filename: filename)
}
@objc func saveProject(){
endBackupTimer();
let alertController = UIAlertController(title: "Save", message: "Enter a name for your project", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Save", style: .default) { (_) in
if let field = alertController.textFields?[0] {
self.uploadProject(type:"save", filename: field.text!)
} else {
#if DEBUG
print("no name key provided");
#endif
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = ""
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func backupImage(){
_ = self.layerContainerView.exportEvent.addHandler(target: self, handler: ViewController.backupImageHandler, key: backupKey)
self.layerContainerView.exportPNG();
}
func backupImageHandler(data:(String,UIImage?),key:String){
layerContainerView.exportEvent.removeHandler(key: backupKey);
if(data.0 == "COMPLETE"){
let filename = UserDefaults.standard.string(forKey: "backup_filename")!
#if DEBUG
print("backing up image to",filename)
#endif
let prefix = "/image_backups/";
let artistName = UserDefaults.standard.string(forKey:"userkey");
let png = UIImagePNGRepresentation(data.1!)
let path = self.layerContainerView.exportPNGAsFile(image: png!)
var uploadData:JSON = [:]
uploadData["filename"] = JSON("saved_files/"+artistName!+prefix+filename+".png")
uploadData["path"] = JSON(path)
uploadData["isLast"] = JSON(true)
uploadData["save_type"] = "backup"
uploadData["content_type"] = "image/png"
uploadData["targetFolder"] = JSON("saved_files/"+artistName!+"/")
let uploadRequest = Request(target: "storage", action: "upload_image", data:uploadData, requester: self)
RequestHandler.addRequest(requestData:uploadRequest);
}
}
@objc func exportImage(){
self.endBackupTimer()
_ = self.layerContainerView.exportEvent.addHandler(target: self, handler: ViewController.handleExportRequest, key: exportKey)
self.behaviorManager?.refreshAllBehaviors();
//TODO: this is a hack. need to create a delay in case it's saving a stroke to the texture
DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Saving", message: "Saving Image", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in
self.cancelBackupCallback()
}
alert.addAction(cancelAction)
self.present(alert, animated: true);
}
}
self.layerContainerView.exportPNG();
}
func handleExportRequest(data:(String,UIImage?),key:String) {
let contentToShare = data.1;
#if DEBUG
print("handle export request",contentToShare as Any)
#endif
layerContainerView.exportEvent.removeHandler(key: exportKey);
if(contentToShare != nil){
let pngImageData: Data? = UIImagePNGRepresentation(contentToShare!)
let pngSmallImage = UIImage(data: pngImageData!)
UIImageWriteToSavedPhotosAlbum(pngSmallImage!, self, nil, nil)
let svg = (currentCanvas?.currentDrawing?.getSVG())! as NSString;
print("svg=",svg);
let svg_data = svg.data(using: String.Encoding.utf8.rawValue)!
let activityViewController = UIActivityViewController(activityItems: [svg_data], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
// present the view controller
self.present(activityViewController, animated: true, completion: nil)
self.dismiss(animated: true, completion: nil)
self.startBackupTimer(interval:self.backupInterval);
/*DispatchQueue.global(qos: .userInteractive).async {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Saved", message: "Your image has been saved to the photo album", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: { _ in }
)
}
}*/
/*let nsContent = NSData(data: contentToShare!)
let activityViewController = UIActivityViewController(activityItems: [nsContent], applicationActivities: nil)
// let activityViewController = UIActivityViewController(activityItems: [shareContent as NSString], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = toolbarController?.exportButton
present(activityViewController, animated: true, completion: {})*/
}
else{
#if DEBUG
print("cannot share image because nothing is there")
#endif
}
}
@objc func drawIntervalCallback(){
DispatchQueue.global(qos: .userInteractive).async {
#if DEBUG
//print("draw interval callback called",self.currentCanvas!.dirty)
#endif
if(self.currentCanvas!.dirty){
DispatchQueue.main.async {
self.layerContainerView.drawIntoCurrentLayer(currentCanvas:self.currentCanvas!);
}
self.backupNeeded = true;
}
}
}
@objc func cancelBackupCallback(){
RequestHandler.emptyQueue()
self.layerContainerView.saveEvent.removeAllHandlers();
self.layerContainerView.exportEvent.removeAllHandlers();
self.startBackupTimer(interval: self.backupInterval);
}
@objc func backupCallback(){
#if DEBUG
print("ready to export?",layerContainerView.isReadyToExport())
#endif
if(backupNeeded && layerContainerView.isReadyToExport() && !self.touchesDown){
self.endBackupTimer();
// self.startCancelBackupTimer();
let alertController = UIAlertController(title:"Backup", message: "Backup project now?", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Yes", style: .default) { (_) in
self.endBackupTimer()
#if DEBUG
print("begining backup")
#endif
self.toolbarController?.disableSaveLoad();
let filename = String(Int((NSDate().timeIntervalSince1970)*100000));
UserDefaults.standard.set(filename, forKey: "backup_filename")
UserDefaults.standard.synchronize()
self.behaviorManager?.refreshAllBehaviors();
self.backupProject(filename:filename)
self.backupNeeded = false;
}
let cancelAction = UIAlertAction(title: "Later", style: .cancel) { (_) in
self.startBackupTimer(interval:60*5)
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
else if(backupNeeded){
self.endBackupTimer();
self.startBackupTimer(interval:1)
}
}
func userInitLayer(){
DispatchQueue.main.async {
let alert = UIAlertController(title: "Layers", message: "Adding Layer", preferredStyle: .alert)
self.present(alert, animated: true);
}
let when = DispatchTime.now() + 1;
DispatchQueue.main.asyncAfter(deadline: when) {
self.dismiss(animated: true, completion: nil)
self.startBackupTimer(interval:self.backupInterval);
self.newLayer();
}
}
func newLayer(){
endBackupTimer()
self.behaviorManager?.refreshAllBehaviors();
//TODO: this is a hack. need to create a delay in case it's saving a stroke to the texture
let id = self.layerContainerView.newLayer(name: (self.layerPanelController?.getNextName())!,id:nil, size:self.targetSize);
self.layerPanelController?.addLayer(layerId: id);
}
func onErase(sender: UIButton!) {
layerContainerView.eraseCurrentLayer();
}
internal func processRequestHandler(data: (String, JSON?), key: String) {
self.processRequest(data:data)
}
//from Requester protocol. Handles result of request
internal func processRequest(data: (String, JSON?)) {
#if DEBUG
print("process request",data.0)
#endif
switch(data.0){
case "disconnected":
recconnectAlert();
break;
case "incorrect_key":
self.loginAlert(isIncorrect: true)
break;
case "correct_key":
self.keyRecognized()
break;
case "backup_complete":
self.startBackupTimer(interval: self.backupInterval)
break;
case "upload_image_complete":
let isLast = data.1?["isLast"].boolValue
let saveType = data.1?["save_type"].stringValue
let content_type = data.1?["content_type"].stringValue
if isLast != nil && isLast == true {
if(saveType == "backup" && content_type == "text/plist"){
#if DEBUG
print("backing up image")
#endif
self.backupImage()
}
else if(saveType == "backup" && content_type == "image/png"){
#if DEBUG
print("backing up behavior")
#endif
let filename = UserDefaults.standard.string(forKey: "backup_filename")!
self.backupBehavior(filename: filename)
}
else{
self.requestProjectList()
self.dismiss(animated: true, completion: nil)
self.startBackupTimer(interval:self.backupInterval);
}
}
break;
case "filelist_complete":
let listType = data.1?["list_type"].stringValue
if(listType == "project_list"){
processProjectList(list: (data.1?["filelist"])!);
}
else if(listType == "behavior_list"){
let filelist_complete_request = Request(target:"socket",action:"send_storage_data",data:data.1,requester:self)
RequestHandler.addRequest(requestData: filelist_complete_request)
}
break;
case "download_complete":
currentBehaviorName = (data.1?["short_filename"].stringValue)!
currentBehaviorFile = (data.1?["filename"].stringValue)!
behaviorManager?.loadBehavior(json: data.1!["data"])
self.behaviorPanelController?.loadBehaviors(json: data.1!["data"])
self.synchronizeWithAuthoringClient();
self.startBackupTimer(interval:self.backupInterval);
break;
case "download_project_complete":
let id = data.1!["id"].stringValue;
let path = data.1!["path"].stringValue;
let content_type = data.1!["content_type"].stringValue;
let isLast = data.1!["isLast"].boolValue
print("download project complete id:\(id),path:\(path),content_type:\(content_type)")
if(content_type == "plist"){
layerContainerView.loadImageIntoLayer(id:id);
}
if isLast == true{
fileListContainerView?.isHidden = true
self.dismiss(animated: true, completion: nil)
self.startBackupTimer(interval:self.backupInterval)
}
break;
case "project_data_download_complete":
let fileData = data.1!["data"];
let newLayers = layerContainerView.loadFromData(fileData: fileData,size:targetSize)
layerPanelController?.loadLayers(newLayers:newLayers);
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths[0] as! String
var jsonLayerArray = fileData["layers"].arrayValue;
for i in 0..<jsonLayerArray.count{
let layerData = jsonLayerArray[i];
let hasImageData = layerData["hasImageData"].boolValue
if(hasImageData){
let id = layerData["id"].stringValue;
let artistName = UserDefaults.standard.string(forKey: "userkey")!
let projectName = data.1!["projectName"].stringValue
var imageDownloadData:JSON = [:]
let imageUrl = documentDirectory.appending("/ink_"+id+".png")
imageDownloadData["id"] = JSON(id)
imageDownloadData["url"] = JSON(imageUrl)
imageDownloadData["content_type"] = JSON("ink")
let image_filename = "saved_files/"+artistName+"/drawings/"+projectName+"/ink_"+id+".png"
imageDownloadData["filename"] = JSON(image_filename);
let image_load_request = Request(target:"storage",action:"download_project_file",data:imageDownloadData,requester:self)
RequestHandler.addRequest(requestData: image_load_request)
let saved_strokes = layerData["saved_strokes"].arrayValue
print("saved strokes list json",saved_strokes);
for stroke in saved_strokes{
let stroke_id = stroke.stringValue
print("stroke id",stroke_id)
var strokeDownloadData:JSON = [:]
let strokeURL = documentDirectory.appending("/"+stroke_id+".strokedata")
strokeDownloadData["id"] = JSON(id)
strokeDownloadData["url"] = JSON(strokeURL)
strokeDownloadData["content_type"] = JSON("strokedata")
let stroke_filename = "saved_files/"+artistName+"/drawings/"+projectName+"/"+stroke_id+".strokedata"
strokeDownloadData["filename"] = JSON(stroke_filename);
let stroke_load_request = Request(target:"storage",action:"download_project_file",data:strokeDownloadData,requester:self)
RequestHandler.addRequest(requestData: stroke_load_request)
}
var plistDownloadData:JSON = [:]
let plistURL = documentDirectory.appending("/state_"+id+".plist")
plistDownloadData["id"] = JSON(id)
plistDownloadData["url"] = JSON(plistURL)
plistDownloadData["content_type"] = JSON("plist")
let plist_filename = "saved_files/"+artistName+"/drawings/"+projectName+"/state_"+id+".plist"
plistDownloadData["filename"] = JSON(plist_filename);
if(i == jsonLayerArray.count-1){
plistDownloadData["isLast"] = JSON(true)
}
let plist_load_request = Request(target:"storage",action:"download_project_file",data:plistDownloadData,requester:self)
RequestHandler.addRequest(requestData: plist_load_request)
}
}
break;
case "upload_complete":
let uploadtype = data.1!["type"].stringValue;
switch(uploadtype){
case "backup":
break;
case "save":
let saveCompleteRequest = Request(target:"socket",action:"send_storage_data",data:data.1,requester:self)
RequestHandler.addRequest(requestData: saveCompleteRequest)
break;
default:
break;
}
break;
case "synchronize_request", "authoring_client_connected":
self.synchronizeWithAuthoringClient();
break;
case "authoring_request":
do{
let authoring_data = data.1! as JSON
let attempt = try behaviorManager?.handleAuthoringRequest(authoring_data: authoring_data);
let data = authoring_data["data"]
if(data["type"].stringValue == "behavior_added"){
behaviorPanelController?.addBehavior(behaviorId: data["id"].stringValue, behaviorName: data["name"].stringValue, activeStatus: true)
}
else if(data["type"].stringValue == "delete_behavior_request"){
behaviorPanelController?.removeBehavior(behaviorId: data["behaviorId"].stringValue)
}
else if(data["type"].stringValue == "set_behavior_active"){
let active = data["active_status"].boolValue
if(active){
behaviorPanelController?.setActive(id: data["behaviorId"].stringValue)
}
else{
behaviorPanelController?.setInactive(id: data["behaviorId"].stringValue)
}
}
let socketRequest = Request(target: "socket", action: "authoring_response", data: attempt, requester: self)
RequestHandler.addRequest(requestData:socketRequest);
}
catch{
#if DEBUG
print("failed authoring request");
#endif
var jsonArg:JSON = [:]
jsonArg["type"] = "authoring_response"
jsonArg["result"] = "failed"
let socketRequest = Request(target: "socket", action: "authoring_request_response", data: jsonArg, requester: self)
RequestHandler.addRequest(requestData:socketRequest);
}
backupNeeded = true
break;
case "storage_request":
let storage_data = data.1!["data"];
let type = storage_data["type"].stringValue;
let filename = storage_data["filename"].stringValue;
let artistName = storage_data["artistName"].stringValue;
switch(type){
case "save_request":
self.saveBehavior(filename: filename, artistName: artistName);
break;
case "load_request":
self.loadBehavior(filename: filename, artistName: artistName);
break;
case "filelist_request":
var filelist_json:JSON = [:]
filelist_json["targetFolder"] = storage_data["targetFolder"];
filelist_json["list_type"] = storage_data["list_type"]
let request = Request(target: "storage", action: "filelist", data: filelist_json, requester: self)
RequestHandler.addRequest(requestData: request);
break;
default:
break;
}
break;
default:
break;
}
}
func synchronizeWithAuthoringClient(){
let behavior:JSON = behaviorManager!.getAllBehaviorJSON();
let request = Request(target: "socket", action: "synchronize", data: behavior, requester: self)
RequestHandler.addRequest(requestData: request)
}
func loadBehavior(filename:String, artistName:String){
let long_filename = filename;
//let long_filename = "saved_files/"+artistName+"/behaviors/"+filename
var loadJSON:JSON = [:]
loadJSON["filename"] = JSON(long_filename);
loadJSON["short_filename"] = JSON(filename);
loadJSON["type"] = JSON("load")
loadJSON["targetFolder"] = JSON("saved_files/"+artistName+"/behaviors/")
let request = Request(target: "storage", action: "download", data: loadJSON, requester: self)
RequestHandler.addRequest(requestData: request);
}
func loadProject(projectName:String, artistName:String){
endBackupTimer();
let project_filename = "saved_files/"+artistName+"/drawings/"+projectName+"/data.json"
var loadJSON:JSON = [:]
loadJSON["filename"] = JSON(project_filename);
loadJSON["type"] = JSON("project_data_load")
loadJSON["projectName"] = JSON(projectName)
loadJSON["targetFolder"] = JSON("saved_files/"+artistName+"/drawings/"+projectName+"/")
let request = Request(target: "storage", action: "download", data: loadJSON, requester: self)
RequestHandler.addRequest(requestData: request);
}
func saveBehavior(filename:String,artistName:String){
endBackupTimer()
var behavior_json:JSON = [:]
for (key,val) in BehaviorManager.behaviors{
behavior_json[key] = val.toJSON();
}
let filename = "saved_files/"+artistName+"/behaviors/"+filename
var saveJSON:JSON = [:]
saveJSON["filename"] = JSON(filename);
saveJSON["data"] = behavior_json
saveJSON["type"] = JSON("save")
saveJSON["targetFolder"] = JSON("saved_files/"+artistName+"/behaviors/")
let request = Request(target: "storage", action: "upload", data: saveJSON, requester: self)
RequestHandler.addRequest(requestData: request);
}
func backupBehavior(filename:String){
let artistName = UserDefaults.standard.string(forKey: "userkey")
var behavior_json:JSON = [:]
for (key,val) in BehaviorManager.behaviors{
behavior_json[key] = val.toJSON();
}
let filename = "saved_files/"+artistName!+"/behavior_backups/"+filename;
var backupJSON:JSON = [:]
backupJSON["filename"] = JSON(filename);
backupJSON["data"] = behavior_json
backupJSON["type"] = JSON("backup")
backupJSON["targetFolder"] = JSON("saved_files/"+artistName!+"/backup_behaviors/")
let request = Request(target: "storage", action: "upload", data: backupJSON, requester: self)
RequestHandler.addRequest(requestData: request);
}
//event handler for incoming data
func dataHandler(data:(String,JSON?), key:String){
switch(data.0){
case "data_request":
let requestJSON:JSON = behaviorManager!.getAllBehaviorJSON();
let socketRequest = Request(target: "socket", action: "data_request_response", data: requestJSON, requester: self)
RequestHandler.addRequest(requestData:socketRequest);
break
default:
break
}
}
func initCanvas(){
currentCanvas = Canvas();
behaviorManager = BehaviorManager(canvas: currentCanvas!);
currentCanvas!.initDrawing();
_ = currentCanvas!.currentDrawing?.strokeGeneratedEvent.addHandler(target: self, handler: ViewController.strokeGeneratedHandler, key: strokeGeneratedKey)
_ = currentCanvas!.currentDrawing?.strokeRemovedEvent.addHandler(target: self, handler: ViewController.strokeRemovedHandler, key: strokeRemovedKey)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
#if DEBUG
print("did receive memory warning")
#endif
// Dispose of any resources that can be recreated.
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if(layerContainerView.activeLayer != nil){
self.touchesDown = false;
layerContainerView.activeLayer?.layerTouchesEnded(touches, with: event)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if(layerContainerView.activeLayer != nil){
self.touchesDown = true;
layerContainerView.activeLayer?.layerTouchesBegan(touches, with: event)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if(layerContainerView.activeLayer != nil){
layerContainerView.activeLayer?.layerTouchesMoved(touches, with: event)
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
if(layerContainerView.activeLayer != nil){
self.touchesDown = false
//layerContainerView.activeLayer?.touchesCancelled(touches, with: event)
}
}
@objc func handlePinch(recognizer : UIPinchGestureRecognizer) {
if let view = recognizer.view {
self.layerContainerView.removeAllStrokes()
view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
recognizer.scale = 1
}
}
@objc func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
self.layerContainerView.removeAllStrokes()
view.transform = view.transform.rotated(by: recognizer.rotation)
recognizer.rotation = 0
}
}
@objc func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
self.layerContainerView.removeAllStrokes()
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.view)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mit | f633107552b6d2dfbc26d365b2bcc1f4 | 37.797506 | 200 | 0.581608 | 5.177306 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/DashboardRewardRowStackViewViewModel.swift | 1 | 2675 | import KsApi
import Prelude
import ReactiveExtensions
import ReactiveSwift
public protocol DashboardRewardRowStackViewViewModelInputs {
/// Call to configure view model with Country, RewardsStats, and total pledged.
func configureWith(
country: Project.Country,
reward: ProjectStatsEnvelope.RewardStats,
totalPledged: Int
)
}
public protocol DashboardRewardRowStackViewViewModelOutputs {
/// Emits string for backer text label.
var backersText: Signal<String, Never> { get }
/// Emits string for pledged text label.
var pledgedText: Signal<String, Never> { get }
/// Emits string for top rewards text label.
var topRewardText: Signal<String, Never> { get }
}
public protocol DashboardRewardRowStackViewViewModelType {
var inputs: DashboardRewardRowStackViewViewModelInputs { get }
var outputs: DashboardRewardRowStackViewViewModelOutputs { get }
}
public final class DashboardRewardRowStackViewViewModel: DashboardRewardRowStackViewViewModelType,
DashboardRewardRowStackViewViewModelInputs, DashboardRewardRowStackViewViewModelOutputs {
public init() {
let countryRewardPledged = self.countryRewardPledgedProperty.signal.skipNil()
self.backersText = countryRewardPledged.map { _, reward, _ in
Format.wholeNumber(reward.backersCount)
}
self.pledgedText = countryRewardPledged.map(pledgedWithPercentText)
self.topRewardText = countryRewardPledged
.map { country, reward, _ in
reward.rewardId == Reward.noReward.id
? Strings.dashboard_graphs_rewards_no_reward()
: Format.currency(reward.minimum ?? 0, country: country)
}
}
public var inputs: DashboardRewardRowStackViewViewModelInputs { return self }
public var outputs: DashboardRewardRowStackViewViewModelOutputs { return self }
public let backersText: Signal<String, Never>
public let pledgedText: Signal<String, Never>
public let topRewardText: Signal<String, Never>
fileprivate let countryRewardPledgedProperty =
MutableProperty<(Project.Country, ProjectStatsEnvelope.RewardStats, Int)?>(nil)
public func configureWith(
country: Project.Country,
reward: ProjectStatsEnvelope.RewardStats,
totalPledged: Int
) {
self.countryRewardPledgedProperty.value = (country, reward, totalPledged)
}
}
private func pledgedWithPercentText(
country: Project.Country,
reward: ProjectStatsEnvelope.RewardStats,
totalPledged: Int
) -> String {
let percent = Double(reward.pledged) / Double(totalPledged)
let percentText = (percent > 0.01 || percent == 0) ? Format.percentage(percent) : "<1%"
return Format.currency(reward.pledged, country: country) + " (\(percentText))"
}
| apache-2.0 | 200740a833c08faf23475b00ab283ba3 | 34.197368 | 98 | 0.762617 | 4.428808 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | 01--Great-Scott/Kata1.playground/Contents.swift | 1 | 3733 | //: # Coding Kata Week 1
//: ## Question 1
//: ### Multiples of 3 and 5
//: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000:
//: 1. *Inicialization of all constants n1, n2, and range and an Int var to store the sum*
let num1 = 3
let num2 = 5
let rangeBelow = 1000
var sumJointList = 0
//: 2. *Filtering of multiples for n1 and n2 in the range*
let listNum1 = Array(1..<rangeBelow).filter{$0 % num1 == 0}
let listNum2 = Array(1..<rangeBelow).filter{$0 % num2 == 0}
//: 3. *Just show values of each array list*
listNum1
listNum2
//: 4. *join the lists in an unique variable list*
var joinList_1_2 = listNum1 + listNum2
//: 5. *Just show value for new joinList*
joinList_1_2
//: 6. *while the size of joinList is > 0*
while joinList_1_2.count > 0
{
//: 7. *sum each popped element in sumJointList*
sumJointList += joinList_1_2.removeLast()
}
//: 8. *Just show value for new sumJointList*
sumJointList
//: ## Question 2
//: ### Largest Palindrome Product
//: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers:
//: 1. *Define the vars and temp vars to store the values all of them empty*
//var nDigits = 3
var palindrome = 0
var palTemp = 0
var largestPal = 0
var Number1 = 0
var Number2 = 0
var end = false
//: 2. *This is the first loop that calculate the last-1 number from 999 to 100 'numbers of 3 digits'*
for var n1 = 999; n1 > 99; n1--
{
//: 3. *Second loop to the second number from 999 to 100 to multipli by the last-1 number: *
for var n2 = 999; n2 > 99; n2--
{
//: 4. *Multiply both numbers n1 x n2*
palindrome = n1*n2
//: 5. *Store too it in a temporal var and Inicialization the temporals vars*
palTemp = palindrome
var nDigitsToSplit = 1 // 1 x max number of digits to split the temporal palindrome ex: 1234/1000
var sizeInt = 0 // number of digits of the int number
//: 6. *Calculate the number of digits of the posible number*
while nDigitsToSplit <= palindrome
{
nDigitsToSplit*=10
sizeInt++
}
//: 7. *check if is the number of digits is odd to calculate the limit of last number of digits*
var limit = 1
if sizeInt % 2 == 0
{
limit = 0
}
//: 8. *look if this number is palindrome or not*
while sizeInt > limit
{
nDigitsToSplit/=10
sizeInt--
var front:Int = palTemp/nDigitsToSplit
var rear:Int = palTemp%10
if front != rear
{
break
}
else
{
palTemp = palTemp - (front*nDigitsToSplit)
palTemp = palTemp/10
}
//nDigitsToSplit/=10
}
//: 9 *Compare if the number is in limit of digits*
if palTemp == limit
{
//: 10 *Compare if the last palindrome is smaller than the new palindrome*
if palindrome > largestPal
{
//: 11 *If yes then replace the last palindrome by the new palindrome*
largestPal = palindrome
Number1 = n1
Number2 = n2
}
else
{
end = true
break
}
}
}
if end
{break}
}
//: 13 *It shows the largest palindrome*
largestPal
Number1
Number2
| cc0-1.0 | 02196cd55c6bde86a369a64d864e9cb0 | 30.627119 | 211 | 0.577706 | 3.895616 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Notifications/ObjectObserverTokens/Helpers/KeySet.swift | 1 | 4236 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireUtilities
public enum AffectedKeys: Equatable {
case some(KeySet)
case all
func combinedWith(_ other: AffectedKeys) -> AffectedKeys {
switch (self, other) {
case let (.some(k1), .some(k2)):
return .some(k1.union(k2))
default:
return .all
}
}
func containsKey(_ key: StringKeyPath) -> Bool {
switch self {
case let .some(keySet):
return keySet.contains(key)
case .all:
return true
}
}
}
public func == (lhs: AffectedKeys, rhs: AffectedKeys) -> Bool {
switch (lhs, rhs) {
case let (.some(lk), .some(rk)):
return lk == rk
case (.all, .all):
return true
default:
return false
}
}
public struct KeySet: Sequence {
public typealias Key = StringKeyPath
public typealias Iterator = Set<StringKeyPath>.Iterator
fileprivate let backing: Set<StringKeyPath>
public init() {
backing = Set()
}
public init(_ set: NSSet) {
var a: [StringKeyPath] = []
for s in set {
if let ss = s as? String {
a.append(StringKeyPath.keyPathForString(ss))
} else {
fatal("\(type(of: s)) is not a string")
}
}
backing = Set(a)
}
public init (_ set: Set<Key>) {
backing = set
}
public init (_ keys: Set<String>) {
self.init(Array(keys))
}
public init(_ a: [String]) {
var aa: [StringKeyPath] = []
for s in a {
aa.append(StringKeyPath.keyPathForString(s))
}
backing = Set<StringKeyPath>(aa)
}
public init(key: StringKeyPath) {
self.init(Set([key]))
}
public init(keyPaths: [StringKeyPath]) {
self.init(Set(keyPaths))
}
public init(key: String) {
self.init(Set([StringKeyPath.keyPathForString(key)]))
}
public init(arrayLiteral elements: String...) {
self.init(elements)
}
init<S: Sequence>(_ seq: S) where S.Iterator.Element == Key {
backing = Set<Key>(seq)
}
public func contains(_ i: StringKeyPath) -> Bool {
return backing.contains(i)
}
public func contains(_ i: String) -> Bool {
return backing.contains(StringKeyPath.keyPathForString(i))
}
public func makeIterator() -> Set<StringKeyPath>.Iterator {
return backing.makeIterator()
}
public var count: Int {
return backing.count
}
}
extension KeySet: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(backing.hashValue)
}
}
public func == (lhs: KeySet, rhs: KeySet) -> Bool {
return lhs.backing == rhs.backing
}
extension KeySet {
func union(_ set: KeySet) -> KeySet {
return KeySet(backing.union(set.backing))
}
func subtract(_ set: KeySet) -> KeySet {
return KeySet(backing.subtracting(set.backing))
}
public var isEmpty: Bool {
return backing.isEmpty
}
func filter(_ match: (StringKeyPath) -> Bool) -> KeySet {
return KeySet(backing.filter {match($0)})
}
}
extension KeySet: CustomDebugStringConvertible {
public var description: String {
let a = [StringKeyPath](backing)
let ss = a.map { $0.rawValue }.sorted {
(lhs, rhs) in lhs < rhs
}
return "KeySet {" + ss.joined(separator: " ") + "}"
}
public var debugDescription: String {
return description
}
}
| gpl-3.0 | ac39308c548db01e3bac4550be46aa2b | 25.980892 | 71 | 0.595373 | 3.970009 | false | false | false | false |
nishiyamaosamu/ColorLogger | ColorLoggerExample/ColorLogger.swift | 2 | 5700 | //
// ColorLogger.swift
// pibo
//
// Created by Osamu Nishiyama on 2015/04/08.
// Copyright (c) 2015年 EVER SENSE, INC. All rights reserved.
//
import Foundation
public class ColorLogger {
class var defaultInstance : ColorLogger {
struct Singleton {
static var instance = ColorLogger()
}
return Singleton.instance
}
public enum LogLevel : Int {
case Verbose = 1
case Debug
case Info
case Warning
case Error
case None
public func description() -> String {
switch self {
case .Verbose:
return "Verbose"
case .Debug:
return "Debug"
case .Info:
return "Info"
case .Warning:
return "Warning"
case .Error:
return "Error"
case .None:
return "None"
}
}
}
public var outputLogLevel: LogLevel = .Debug
public var dateFormatter = "yyyy-MM-dd HH:mm:ss.SSS"
public var showDate = true
public var showLogLevel = true
public var showFileInfo = true
public var showFunctionName = true
private func logln(logMessage: [AnyObject?], logLevel: LogLevel, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) {
if self.isEnabledForLogLevel(logLevel) {
var logMessageStr = ""
var LogLevelStr = ""
var FileInfoStr = ""
var FunctionNameStr = ""
var DateTimeStr = ""
var output = ""
logMessage.forEach{
if $0 == nil {
logMessageStr += "nil"
}else{
logMessageStr += $0!.description
}
logMessageStr += " "
}
if self.showLogLevel {
LogLevelStr = "[" + logLevel.description() + "] "
}
if self.showFileInfo {
FileInfoStr = "[" + (fileName as NSString).lastPathComponent + ":" + String(lineNumber) + "] "
}
if self.showFunctionName {
FunctionNameStr = functionName + " "
}
if self.showDate {
let now = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = self.dateFormatter
DateTimeStr = dateFormatter.stringFromDate(now)
}
switch logLevel {
case .Verbose:
output += ColorLogStr.gray(LogLevelStr + logMessageStr)
case .Debug:
output += ColorLogStr.blue(LogLevelStr + logMessageStr)
case .Info:
output += ColorLogStr.cyan(LogLevelStr + logMessageStr)
case .Warning:
output += ColorLogStr.yellow(LogLevelStr + logMessageStr)
case .Error:
output += ColorLogStr.red(LogLevelStr + logMessageStr)
default:
output += LogLevelStr + logMessageStr
}
output += ColorLogStr.gray(FileInfoStr + FunctionNameStr + DateTimeStr)
print(output)
}
}
public func verbose(logMessage: AnyObject?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__){
self.logln(logMessage, logLevel: .Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
public func info(logMessage: AnyObject?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__){
self.logln(logMessage, logLevel: .Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
public func debug(logMessage: AnyObject?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__){
self.logln(logMessage, logLevel: .Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
public func warning(logMessage: AnyObject?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__){
self.logln(logMessage, logLevel: .Warning, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
public func error(logMessage: AnyObject?..., functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__){
self.logln(logMessage, logLevel: .Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber)
}
public func isEnabledForLogLevel(logLevel: ColorLogger.LogLevel) -> Bool {
return logLevel.rawValue >= self.outputLogLevel.rawValue
}
struct ColorLogStr {
static let ESCAPE = "\u{001b}["
static let RESET = ESCAPE + ";" // Clear any foreground or background color
static func red(str: String) -> String {
return "\(ESCAPE)fg220,50,47;\(str)\(RESET)"
}
static func cyan(str: String) -> String {
return "\(ESCAPE)fg42,161,152;\(str)\(RESET)"
}
static func blue(str: String) -> String {
return "\(ESCAPE)fg38,139,210;\(str)\(RESET)"
}
static func yellow(str: String) -> String {
return "\(ESCAPE)fg181,137,0;\(str)\(RESET)"
}
static func gray(str: String) -> String {
return "\(ESCAPE)fg88,110,117;\(str)\(RESET)"
}
}
} | mit | 23c05317d451145e1c2858776b51375b | 34.61875 | 164 | 0.545104 | 5.020264 | false | false | false | false |
Mioke/PlanB | PlanB/PlanB/AppConfig.swift | 1 | 927 | //
// AppConfig.swift
// PlanB
//
// Created by Klein Mioke on 5/17/16.
// Copyright © 2016 Klein Mioke. All rights reserved.
//
import UIKit
class AppConfig: NSObject {
private static let logKey = "s190n131kx"
private static let instance = AppConfig()
var isTodayFirstLogin = true
static func initialize_config() {
let now = NSDate()
if let last = NSUserDefaults.standardUserDefaults().objectForKey(logKey) as? NSDate {
if last.isDayEqualToDate(now) {
instance.isTodayFirstLogin = false
} else {
NSUserDefaults.standardUserDefaults().setObject(now, forKey: logKey)
}
} else {
NSUserDefaults.standardUserDefaults().setObject(now, forKey: logKey)
}
}
static var isFirstLoginToday: Bool {
get { return instance.isTodayFirstLogin }
}
}
| gpl-3.0 | 5653f1f6685103f776132e058b879819 | 24.027027 | 93 | 0.601512 | 4.539216 | false | true | false | false |
gongmingqm10/SwiftTraining | DesignerApp/DesignerApp/Story.swift | 1 | 681 | //
// Story.swift
// DesignerApp
//
// Created by Ming Gong on 6/24/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import Foundation
class Story: NSObject {
var title: String?
var badge: String?
var author: String?
var timeDesc: String?
var commentCount: Int
var voteCount: Int
init(json: NSDictionary) {
self.title = json["title"] as? String
self.badge = json["badge"] as? String
self.author = json["author"] as? String
self.timeDesc = json["time_desc"] as? String
self.commentCount = json["comment_count"] as! Int
self.voteCount = json["vote_count"] as! Int
}
}
| mit | e36f1828381c0da6494acd4da22ec20f | 22.448276 | 57 | 0.608824 | 3.636364 | false | false | false | false |
jboullianne/EndlessTunes | EndlessSoundFeed/PlaylistDetailViewController.swift | 1 | 10676 | //
// PlaylistDetailViewController.swift
// EndlessSoundFeed
//
// Created by Jean-Marc Boullianne on 6/16/17.
// Copyright © 2017 Jean-Marc Boullianne. All rights reserved.
//
import UIKit
import AlamofireImage
import Alamofire
class PlaylistDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var playlist:Playlist!
@IBOutlet var playlistTitleLabel: UILabel!
@IBOutlet var playlistDetailLabel: UILabel!
@IBOutlet var ownerLabel: UILabel!
@IBOutlet var headerImageView: UIImageView!
@IBOutlet var playlistEmptyContainer: UIView!
@IBOutlet var playButtonContainer: UIView!
@IBOutlet var playlistImage: UIImageView!
@IBOutlet var headerContainer: UIView!
@IBOutlet var headerContainerTop: NSLayoutConstraint!
@IBOutlet var tableView: UITableView!
var npIndexPath:IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.tableFooterView = UIView()
self.tableView.delegate = self
self.tableView.dataSource = self
if(playlist.tracks.count == 0){
playlistEmptyContainer.isHidden = false
}
else{
playlistTitleLabel.text = playlist.name
playlistDetailLabel.text = "\(playlist.tracks.count) Tracks"
if(playlist.tracks.count > 0){
//playlistThumbnailView.image = playlist.tracks[0].thumbnailImage
headerImageView.image = playlist.tracks[0].thumbnailImage
}
ownerLabel.text = "Jboullianne"
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = headerImageView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
headerImageView.addSubview(blurEffectView)
if(playlist.tracks.count > 0 && playlist.tracks[0].thumbnailURL != "" && playlist.tracks[0].thumbnailImage == nil){
Alamofire.request(playlist.tracks[0].thumbnailURL).responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
DispatchQueue.main.async {
//self.playlistThumbnailView.image = image
self.headerImageView.image = image
}
self.playlist.tracks[0].thumbnailImage = image
}
}
}
let topAccent = CALayer()
topAccent.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 1)
topAccent.backgroundColor = UIColor.white.cgColor
self.tableView.layer.addSublayer(topAccent)
self.playlistImage.layer.cornerRadius = 5.0
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
print("PLAYLIST?? : ", self.playlist)
return self.playlist.tracks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TrackCellSmall", for: indexPath) as! TrackCellSmall
let index = indexPath.row
let track = playlist.tracks[index]
cell.titleLabel.text = track.title
cell.detailLabel.text = track.author + " · " + track.sourceString
cell.titleLabel.textColor = UIColor.white
cell.numberLabel.text = "\(index + 1)"
//Round Track Icon
//cell.trackIcon.layer.cornerRadius = cell.trackIcon.frame.height / 2
//Rounded Corner Track Icon
cell.trackIcon.layer.cornerRadius = 3
if let row = npIndexPath?.row {
if indexPath.row == row {
cell.titleLabel.textColor = UIColor(red: 80/255, green: 148/255, blue: 228/255, alpha: 1.0)
}
}
//Load Small External Thumbnail if it Exists
if(track.smallThumbnailURL != nil && track.smallThumbnailImage == nil){
Alamofire.request(track.smallThumbnailURL!).responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
DispatchQueue.main.async {
let updatedCell = tableView.cellForRow(at: indexPath) as! TrackCellSmall
updatedCell.trackIcon.contentMode = .scaleAspectFill
updatedCell.trackIcon.image = image
}
//TO-DO: Attach Image To Original Playlist
self.playlist.tracks[index].smallThumbnailImage = image
//self.manager.attachImageToTrack(image: image, url: response.request!.url!.absoluteString)
}
}
}
//Load External Thumbnail if it Exists
else if(track.thumbnailURL != "" && track.thumbnailImage == nil){
Alamofire.request(track.thumbnailURL).responseImage { response in
if let image = response.result.value {
print("image downloaded: \(image)")
DispatchQueue.main.async {
let updatedCell = tableView.cellForRow(at: indexPath) as! TrackCellSmall
updatedCell.trackIcon.contentMode = .scaleAspectFill
updatedCell.trackIcon.image = image
}
//TO-DO: Attach Image To Original Playlist
self.playlist.tracks[index].thumbnailImage = image
//self.manager.attachImageToTrack(image: image, url: response.request!.url!.absoluteString)
}
}
}
if(track.thumbnailImage != nil){
cell.trackIcon.contentMode = .scaleAspectFill
cell.trackIcon.image = track.thumbnailImage!
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let track = self.playlist.tracks[indexPath.row]
MediaManager.sharedInstance.playTrack(track: track)
self.tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! TrackCellSmall
cell.titleLabel.textColor = UIColor(red: 80/255, green: 148/255, blue: 228/255, alpha: 1.0)
if(npIndexPath != nil){
if let cell = tableView.cellForRow(at: npIndexPath!) as? TrackCellSmall {
cell.titleLabel.textColor = UIColor.white
}
}
self.npIndexPath = indexPath
}
@IBAction func playButtonPressed(_ sender: Any) {
print("TO-DO: Start Playlist")
MediaManager.sharedInstance.playPlaylist(playlist: self.playlist)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = self.tableView.contentOffset.y
//Move HeaderContainer up as TableView Scrolls
UIView.animate(withDuration: 0) {
// 180 = the total amount of vertical movement
if(offset > 60){
self.headerContainerTop.constant = -60
}else if (offset > 0){
self.headerContainerTop.constant = -1 * offset
}else{
self.headerContainerTop.constant = 0
}
//Fade Out Header As TableView Scrolls
let alpha = 1.0 - (offset/60)
self.headerContainer.alpha = alpha
self.headerContainer.layoutIfNeeded()
self.tableView.layoutIfNeeded()
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | e4c8c22b9ce1bea7807f7706914ea652 | 36.452632 | 136 | 0.588908 | 5.462641 | false | false | false | false |
matthewpurcell/firefox-ios | ThirdParty/SQLite.swift/Source/Helpers.swift | 2 | 4773 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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.
//
public typealias Star = (Expression<Binding>?, Expression<Binding>?) -> Expression<Void>
public func *(_: Expression<Binding>?, _: Expression<Binding>?) -> Expression<Void> {
return Expression(literal: "*")
}
public protocol _OptionalType {
typealias WrappedType
}
extension Optional : _OptionalType {
public typealias WrappedType = Wrapped
}
func check(resultCode: Int32, statement: Statement? = nil) throws -> Int32 {
if let error = Result(errorCode: resultCode, statement: statement) {
throw error
}
return resultCode
}
// let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self)
let SQLITE_TRANSIENT = unsafeBitCast(-1, sqlite3_destructor_type.self)
extension String {
@warn_unused_result func quote(mark: Character = "\"") -> String {
let escaped = characters.reduce("") { string, character in
string + (character == mark ? "\(mark)\(mark)" : "\(character)")
}
return "\(mark)\(escaped)\(mark)"
}
@warn_unused_result func join(expressions: [Expressible]) -> Expressible {
var (template, bindings) = ([String](), [Binding?]())
for expressible in expressions {
let expression = expressible.expression
template.append(expression.template)
bindings.appendContentsOf(expression.bindings)
}
return Expression<Void>(template.joinWithSeparator(self), bindings)
}
@warn_unused_result func infix<T>(lhs: Expressible, _ rhs: Expressible, wrap: Bool = true) -> Expression<T> {
let expression = Expression<T>(" \(self) ".join([lhs, rhs]).expression)
guard wrap else {
return expression
}
return "".wrap(expression)
}
@warn_unused_result func prefix(expressions: Expressible) -> Expressible {
return "\(self) ".wrap(expressions) as Expression<Void>
}
@warn_unused_result func prefix(expressions: [Expressible]) -> Expressible {
return "\(self) ".wrap(expressions) as Expression<Void>
}
@warn_unused_result func wrap<T>(expression: Expressible) -> Expression<T> {
return Expression("\(self)(\(expression.expression.template))", expression.expression.bindings)
}
@warn_unused_result func wrap<T>(expressions: [Expressible]) -> Expression<T> {
return wrap(", ".join(expressions))
}
}
@warn_unused_result func infix<T>(lhs: Expressible, _ rhs: Expressible, wrap: Bool = true, function: String = __FUNCTION__) -> Expression<T> {
return function.infix(lhs, rhs, wrap: wrap)
}
@warn_unused_result func wrap<T>(expression: Expressible, function: String = __FUNCTION__) -> Expression<T> {
return function.wrap(expression)
}
@warn_unused_result func wrap<T>(expressions: [Expressible], function: String = __FUNCTION__) -> Expression<T> {
return function.wrap(", ".join(expressions))
}
@warn_unused_result func transcode(literal: Binding?) -> String {
if let literal = literal {
if let literal = literal as? NSData {
let buf = UnsafeBufferPointer(start: UnsafePointer<UInt8>(literal.bytes), count: literal.length)
let hex = buf.map { String(format: "%02x", $0) }.joinWithSeparator("")
return "x'\(hex)'"
}
if let literal = literal as? String { return literal.quote("'") }
return "\(literal)"
}
return "NULL"
}
@warn_unused_result func value<A: Value>(v: Binding) -> A {
return A.fromDatatypeValue(v as! A.Datatype) as! A
}
@warn_unused_result func value<A: Value>(v: Binding?) -> A {
return value(v!)
}
| mpl-2.0 | fbcb81252be9552a827ee6b9e14f2e1d | 35.707692 | 142 | 0.673512 | 4.230496 | false | false | false | false |
USAssignmentWarehouse/EnglishNow | EnglishNow/Controller/Profile/ProfileVC.swift | 1 | 28826 | //
// ProfileVCViewController.swift
// EnglishNow
//
// Created by Nha T.Tran on 5/21/17.
// Copyright © 2017 IceTeaViet. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
class ProfileVC: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource{
// MARK: -declare and hanlde click event
@IBAction func btnBack(_ sender: Any) {
var storyboard = UIStoryboard(name: "MainScreen", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "MainScreenVC") as UIViewController
self.present(controller, animated: true, completion: nil)
}
@IBOutlet var btnSendMessage: UIBarButtonItem!
@IBAction func actionSendMessage(_ sender: Any) {
performSegue(withIdentifier: SegueIdentifier.SegueSendMessage, sender: nil)
}
@IBOutlet var btnBack: UIBarButtonItem!
@IBOutlet var avatar: UIImageView!
@IBOutlet var numberView: UIView!
@IBOutlet var titleStats: UIView!
@IBOutlet var txtYourRating: UILabel!
@IBOutlet var yourRatingView: UIView!
@IBOutlet var imgLogout: UIImageView!
@IBOutlet var username: UILabel!
@IBOutlet var txtDrinksNumber: UILabel!
@IBOutlet weak var txtBeersNumber: UILabel!
@IBOutlet var txtConversationsNumber: UILabel!
@IBOutlet var tableStatus: UITableView!
@IBOutlet var txtListeningRating: UILabel!
@IBOutlet var txtSpeakingRating: UILabel!
@IBOutlet var txtPronunciationRating: UILabel!
var skills: [Skill] = [Skill]()
var skillRating:[Float] = [Float]()
var skillNumberRating:[Int] = [Int]()
var currentID: String = ""
@IBAction func actionStar(_ sender: UIButton) {
let tag = sender.tag
if let user = Auth.auth().currentUser {
if currentID.compare(user.uid) != ComparisonResult.orderedSame && currentID.compare("") != ComparisonResult.orderedSame{
for button in btnStars{
if (button.tag <= 5 && tag <= 5){
if button.tag <= tag {
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
} else {
button.setTitleColor(UIColor.lightGray, for: .normal)
}
}else if (button.tag <= 10 && button.tag > 5 && tag <= 10 && tag > 5 ){
if button.tag <= tag {
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
} else {
button.setTitleColor(UIColor.lightGray, for: .normal)
}
}else if (button.tag <= 15 && button.tag > 10 && tag <= 15 && tag > 10 ){
if button.tag <= tag {
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
} else {
button.setTitleColor(UIColor.lightGray, for: .normal)
}
}
}
var totalRating = (Float((tag - 1) % 5 + 1)) + skillRating[(tag - 1) / 5] * Float(skillNumberRating[(tag - 1) / 5])
var rate_value = (totalRating) / Float((skillNumberRating[(tag - 1) / 5] + 1))
print("rate_value: \(rate_value)")
Database.database().reference().child("user_profile").child((currentID)).child("skill").child(skills[(tag - 1) / 5].name).child("rate_value").setValue(rate_value)
Database.database().reference().child("user_profile").child((currentID)).child("skill").child(skills[(tag - 1) / 5].name).child("rate_list").child(user.uid).setValue((tag - 1) % 5 + 1)
}
}
}
@IBOutlet var btnStars: [UIButton]!
let deviceID = UIDevice.current.identifierForVendor?.uuidString
var statusList:[Status] = [Status]()
var contact: Contact?
override func viewDidLoad() {
super.viewDidLoad()
skills.append(Listening())
skills.append(Speaking())
skills.append(Pronunciation())
skillNumberRating.append(0)
skillNumberRating.append(0)
skillNumberRating.append(0)
initShow()
if currentID == ""{
//to make sure user is loaded before show
if let user = Auth.auth().currentUser{
loadProfile(userid: ((user.uid) as? String)!)
}
btnSendMessage.isEnabled = false
} else {
imgLogout.isHidden = true
if let user = Auth.auth().currentUser{
loadProfile(userid: ((user.uid) as? String)!)
}
}
let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
longPressGesture.minimumPressDuration = 1.0 // 1 second press
longPressGesture.delegate = self as? UIGestureRecognizerDelegate
tableStatus.addGestureRecognizer(longPressGesture)
}
func handleLongPress(gesture: UILongPressGestureRecognizer){
if gesture.state == UIGestureRecognizerState.began {
print("tapped!")
let touchPoint = gesture.location(in: tableStatus)
if let indexPath = tableStatus.indexPathForRow(at: touchPoint) {
print(indexPath.row)
if let user = Auth.auth().currentUser {
if (indexPath.row > -1 && indexPath.row < self.statusList.count && user.uid.compare(self.currentID) == ComparisonResult.orderedSame){
let id = self.statusList[indexPath.row].statusId
let alertController = UIAlertController(title: "Question", message: "Are you sure delete this status?", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
Database.database().reference().child("user_profile/\(user.uid)").child("status").observe(.value, with: { (snapshot) -> Void in
//go to each status
for item in snapshot.children {
let status = (item as! DataSnapshot).value as! [String:AnyObject]
if (item as! DataSnapshot).key == id {
(item as AnyObject).ref.child((item as AnyObject).key!).parent?.removeValue()
print("success!")
}
}
})
Database.database().reference().child("status").observe(.value, with: { (snapshot) -> Void in
//go to each status
for item in snapshot.children {
let status = (item as! DataSnapshot).value as! [String:AnyObject]
if (item as! DataSnapshot).key == id {
(item as AnyObject).ref.child((item as AnyObject).key!).parent?.removeValue()
print("success!")
}
}
})
self.statusList.remove(at: indexPath.row)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) in
}
alertController.addAction(OKAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}}
}
}
}
// MARK: -load data
func loadStatus(userid: String, username: String, avatar: UIImage){
if currentID == ""{
currentID = userid
}
Database.database().reference().child("user_profile/\(currentID)").child("status").observe(.value, with: { (snapshot) -> Void in
self.statusList.removeAll()
//go to each status
for item in snapshot.children {
let status = (item as! DataSnapshot).value as! [String:AnyObject]
if status.count >= FirebaseUtils.numberChildUserStatus - 1{
let content = status["content"] as! String
let time = status["time"] as! TimeInterval
let likeNumber = status["like_number"] as! Int
var photo:UIImage?
if let url = status["photo"] {
if let imgUrl = URL(string: url as! String){
let data = try? Data(contentsOf: imgUrl)
if let imageData = data {
let profilePic = UIImage(data: data!)
photo = profilePic
}
}
}
var isUserLiked: Bool = false
if status.index(forKey: "like") != nil{
let likes = ((item as! DataSnapshot).childSnapshot(forPath: "like") as! DataSnapshot).value as! [String:AnyObject]
if let user = Auth.auth().currentUser{
if (likes.index(forKey: user.uid) != nil) {
let isLiked = likes[user.uid]as! Bool
if isLiked == true {
isUserLiked = true
}
}
}
}
if photo == nil{
//if photo is nil -> call constructure has photo failed -->
//call constructure without photo
self.statusList.append(Status(statusId: (item as! DataSnapshot).key , user: self.currentID ,username: username, avatar: avatar, content: content, time: time, likeNumber: likeNumber , isUserLiked: isUserLiked))
} else {
//call constructure has photo
self.statusList.append(Status(statusId: (item as! DataSnapshot).key , user: self.currentID , username: username, avatar: avatar , content: content, time: time, photo: photo!, likeNumber: likeNumber , isUserLiked: isUserLiked))
}
self.tableStatus.reloadData()
}
}
})
}
func loadProfile(userid: String){
if currentID == ""{
currentID = userid
}
let queryRef = Database.database().reference().child("user_profile/\(currentID)").observe(.value, with: { (snapshot) -> Void in
if let dictionary = snapshot.value as? [String:Any] {
//TODO: ReCheck the stats
var drinks = dictionary["drinks"] as? Int ?? 0
if drinks == 0 {
drinks = User.current.review.gift.getDrinks()
}
var conversations = dictionary["conversations"] as? Int ?? 0
if conversations == 0 {
conversations = User.current.conversations
}
let beers : Int = User.current.review.gift.beer
self.txtDrinksNumber.text = "\(drinks)"
self.txtConversationsNumber.text = "\(conversations)"
self.txtBeersNumber.text = "\(beers)"
let username = dictionary["username"] as? String ?? ""
self.username.text = username
if let url = dictionary["profile_pic"] {
if let imgUrl = URL(string: url as! String){
let data = try? Data(contentsOf: imgUrl)
if let imageData = data {
let profilePic = UIImage(data: data!)
self.avatar.image = profilePic
}
}
}
self.contact = Contact(name: username, id: self.currentID, avatar: self.avatar.image!)
if dictionary.count == FirebaseUtils.numberChildOfUser {
self.statusList.removeAll()
self.loadStatus(userid: userid, username: username, avatar: self.avatar.image!)
}
}
})
//load data of level
Database.database().reference().child("user_profile/\(currentID)").child("skill").observe(.value, with: { (snapshot) -> Void in
let child = snapshot.value as! [String:AnyObject]
let listening = (snapshot.childSnapshot(forPath: "listening skill") as! DataSnapshot).value as! [String:Any]
let speaking = (snapshot.childSnapshot(forPath: "speaking skill") as! DataSnapshot).value as! [String:AnyObject]
let pronunciation = (snapshot.childSnapshot(forPath: "pronunciation skill") as! DataSnapshot).value as! [String:AnyObject]
var listeningRating:Float = listening["rate_value"] as! Float
var speakingRating: Float = speaking["rate_value"] as! Float
var pronunciationRating: Float = pronunciation["rate_value"] as! Float
self.skillRating.append(listeningRating)
self.skillRating.append(speakingRating)
self.skillRating.append(pronunciationRating)
var finalRating: Float = (listeningRating + speakingRating + pronunciationRating) / 3
self.txtYourRating.text = String(format: "%.1f", finalRating)
//set rating of each skill label here
self.txtListeningRating.text = String(format: "%.1f/5", listeningRating)
self.txtSpeakingRating.text = String(format: "%.1f/5", speakingRating)
self.txtPronunciationRating.text = String(format: "%.1f/5", pronunciationRating)
if ((listening.index(forKey: "rate_list")) != nil){
let listeningNumberRating = ((snapshot.childSnapshot(forPath: "listening skill") as! DataSnapshot).childSnapshot(forPath: "rate_list") as! DataSnapshot)
self.skillNumberRating[0] = Int(listeningNumberRating.childrenCount)
if (userid == self.currentID){
for button in self.btnStars{
if (button.tag <= 5 && (button.tag - 1) % 5 < Int(listeningRating)){
//selected
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
}
}
}else {
let listeningRatingOfUser = (listeningNumberRating.value as! [String:Any])[userid] as! Int
for button in self.btnStars{
if (button.tag <= 5 && (button.tag - 1) % 5 < listeningRatingOfUser){
//selected
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
}
}
}
}
if ((speaking.index(forKey: "rate_list")) != nil){
let speakNumberRating = ((snapshot.childSnapshot(forPath: "speaking skill") as! DataSnapshot).childSnapshot(forPath: "rate_list") as! DataSnapshot)
self.skillNumberRating[1] = Int(speakNumberRating.childrenCount)
if (userid == self.currentID){
for button in self.btnStars{
if (button.tag <= 10 && button.tag > 5 && (button.tag - 1) % 5 < Int(speakingRating)){
//selected
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
}
}
}else {
let speakingRatingOfUser = (speakNumberRating.value as! [String:Any])[userid] as! Int
for button in self.btnStars{
if (button.tag <= 10 && button.tag > 5 && (button.tag - 1) % 5 < speakingRatingOfUser){
//selected
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
}
}
}
}
if ((pronunciation.index(forKey: "rate_list")) != nil){
let pronunciationNumberRating = ((snapshot.childSnapshot(forPath: "pronunciation skill") as! DataSnapshot).childSnapshot(forPath: "rate_list") as! DataSnapshot)
self.skillNumberRating[2] = Int(pronunciationNumberRating.childrenCount)
if (userid == self.currentID){
for button in self.btnStars{
if (button.tag <= 15 && button.tag > 10 && (button.tag - 1) % 5 < Int(pronunciationRating)){
//selected
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
}
}
}else {
let pronunciationRatingOfUser = (pronunciationNumberRating.value as! [String:Any])[userid] as! Int
for button in self.btnStars{
if (button.tag <= 15 && button.tag > 10 && (button.tag - 1) % 5 < pronunciationRatingOfUser){
//selected
button.setTitleColor(#colorLiteral(red: 0.9994240403, green: 0.9855536819, blue: 0, alpha: 1), for: .normal)
}
}
}
}
})
}
// MARK: -init to show
func initShow(){
avatar.layer.masksToBounds = true
avatar.layer.cornerRadius = 68
numberView.layer.borderWidth = 1
numberView.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
numberView.layer.shadowColor = UIColor.black.cgColor
numberView.layer.shadowOpacity = 0.5
numberView.layer.shadowOffset = CGSize(width:0, height:1.75)
numberView.layer.shadowRadius = 1.7
numberView.layer.shadowPath = UIBezierPath(rect: numberView.bounds).cgPath
numberView.layer.shouldRasterize = true
txtYourRating.layer.cornerRadius = 15
txtYourRating.layer.borderWidth = 4
txtYourRating.layer.borderColor = UIColor(red:0, green:128/255, blue:128/255,alpha:1.0).cgColor
yourRatingView.layer.borderWidth = 1
yourRatingView.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
yourRatingView.layer.shadowColor = UIColor.black.cgColor
yourRatingView.layer.shadowOpacity = 0.5
yourRatingView.layer.shadowOffset = CGSize(width:0, height:1.75)
yourRatingView.layer.shadowRadius = 1.7
yourRatingView.layer.shadowPath = UIBezierPath(rect: numberView.bounds).cgPath
yourRatingView.layer.shouldRasterize = true
tableStatus.delegate = self
tableStatus.dataSource = self
setOnLogoutTapped()
setOnAvatarTapped()
}
// MARK: -tap event
func setOnAvatarTapped(){
avatar.isUserInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target:self, action: #selector(tappedAvatarImage))
avatar.addGestureRecognizer(tapRecognizer)
}
func tappedAvatarImage(gestureRecognizer: UIGestureRecognizer){
if let user = Auth.auth().currentUser {
if (currentID == user.uid || currentID == "" ){
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = true
present(picker,animated: true,completion:nil)
}
}
}
func setOnLogoutTapped() {
imgLogout.isUserInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target:self, action: #selector(tappedLogoutImage))
imgLogout.addGestureRecognizer(tapRecognizer)
}
func tappedLogoutImage(gestureRecognizer:UIGestureRecognizer) {
do {
try Auth.auth().signOut()
let user = Auth.auth().currentUser
var storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "LoginVC") as UIViewController
self.present(controller, animated: true, completion: nil)
} catch {
print("there was an rror when logout!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: -imagePickerController datasource
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print(info)
var selectedImageFromPicker: UIImage?
if let editedimage = info["UIImagePickerControllerEditedImage"]{
selectedImageFromPicker = editedimage as! UIImage
print("edited!")
} else if let originalImage = info["UIImagePickerControllerOriginalImage"]{
selectedImageFromPicker = originalImage as! UIImage
print("original!")
}
if (selectedImageFromPicker != nil) {
self.avatar.image = selectedImageFromPicker
}
let userRef = Database.database().reference().child("users").child(Auth.auth().currentUser!.uid)
var databaseRef = Database.database().reference()
var storageRef = Storage.storage().reference()
var currentUser = Auth.auth().currentUser
if let imageData:NSData = UIImagePNGRepresentation(selectedImageFromPicker!)! as NSData?{
let profilePicStorageRef = storageRef.child("user_profiles/\(currentUser?.uid)/profile_pic")
let uploadTask = profilePicStorageRef.putData(imageData as Data, metadata:nil){metadata, error in
if (error == nil){
let downloadUrl = metadata?.downloadURL()
databaseRef.child("user_profile").child((currentUser?.uid)!).child("profile_pic").setValue(downloadUrl?.absoluteString)
print("upload image success!")
}else{
print(error?.localizedDescription)
}
}
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
print("cancel!")
dismiss(animated: true, completion: nil)
}
//MARK: -status table datasource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statusList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath ) as! CellOfTimeLineVC
cell.layer.borderWidth = 0.5
cell.layer.borderColor = UIColor(red: 213/255,green: 216/255,blue: 220/255,alpha: 1.0).cgColor
if statusList.count > 0 {
let status = statusList[statusList.count - 1 - indexPath.row]
cell.status = status
cell.txtContent.text = status.content
let number:Int = status.likeNumber!
cell.txtNumberOfLike.text = "\(number)"
cell.avatar.image = status.avatar
cell.txtName.text = status.username
var milliseconds = status.time
let date = NSDate(timeIntervalSince1970: TimeInterval(milliseconds!))
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
cell.txtTime.text = formatter.string(from: date as Date)
if status.photo != nil {
cell.photo.isHidden = false
cell.photoBigHeightAnchor?.isActive = true
cell.photoSmallHeightAnchor?.isActive = false
cell.photo.image = status.photo
}else {
cell.photo.isHidden = true
cell.photoSmallHeightAnchor?.isActive = true
cell.photoBigHeightAnchor?.isActive = false
}
if status.isUserLiked == true {
cell.btnLike.setBackgroundImage(UIImage(named: "liked.png"), for: UIControlState.normal)
} else {
cell.btnLike.setBackgroundImage(UIImage(named: "like.png"), for: UIControlState.normal)
}
}
return cell
}
var selectedIndex = 0;
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndex = statusList.count - 1 - indexPath.row
performSegue(withIdentifier: SegueIdentifier.SegueUserDetailStatus, sender: self)
}
//auto cell size to fit content
override func viewWillAppear(_ animated: Bool) {
self.tableStatus.estimatedRowHeight = 200
self.tableStatus.rowHeight = UITableViewAutomaticDimension
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SegueIdentifier.SegueSendMessage {
let des = segue.destination as! DetailChatViewController
des.currentContact = contact
}
else if segue.identifier == SegueIdentifier.SegueUserDetailStatus {
let des = segue.destination as! DetailStatusVC
des.status = statusList[selectedIndex]
}
}
}
| apache-2.0 | 7bb0e70f20d55cf0c35001028ac4d677 | 39.886525 | 250 | 0.513027 | 5.471716 | false | false | false | false |
mactive/rw-courses-note | AdvancedSwift3/BitOperator.playground/Contents.swift | 1 | 437 | //: Playground - noun: a place where people can play
//: 按位运算
//: 0b 2进制 binary
//: 0o 8进制 octonary
//: 0x 16进制 hexadecimal
//: NOT(~(单目运算符)), AND(运算符为 &), OR(运算符为\|), XOR(运算符为 ^)以及左移和右移(运算符分别为 << 和 >>)。
import UIKit
let a:UInt8 = 0b01111111
let b:UInt8 = 0b00000010
let c = a & b
let d = a | b
let e = ~a
let f = a ^ b
let g = a << 1
let h = b >> 1 | mit | 3c58cf0f0ad527041e9a9a1ef8e6aec2 | 17.631579 | 79 | 0.592068 | 2.353333 | false | false | false | false |
fireunit/login | Pods/Material/Sources/iOS/RobotoFont.swift | 2 | 3594 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public struct RobotoFont : MaterialFontType {
/// Size of font.
public static var pointSize: CGFloat {
return MaterialFont.pointSize
}
/// Thin font.
public static var thin: UIFont {
return thinWithSize(MaterialFont.pointSize)
}
/// Thin with size font.
public static func thinWithSize(size: CGFloat) -> UIFont {
MaterialFont.loadFontIfNeeded("Roboto-Thin")
if let f = UIFont(name: "Roboto-Thin", size: size) {
return f
}
return MaterialFont.systemFontWithSize(size)
}
/// Light font.
public static var light: UIFont {
return lightWithSize(MaterialFont.pointSize)
}
/// Light with size font.
public static func lightWithSize(size: CGFloat) -> UIFont {
MaterialFont.loadFontIfNeeded("Roboto-Light")
if let f = UIFont(name: "Roboto-Light", size: size) {
return f
}
return MaterialFont.systemFontWithSize(size)
}
/// Regular font.
public static var regular: UIFont {
return regularWithSize(MaterialFont.pointSize)
}
/// Regular with size font.
public static func regularWithSize(size: CGFloat) -> UIFont {
MaterialFont.loadFontIfNeeded("Roboto-Regular")
if let f = UIFont(name: "Roboto-Regular", size: size) {
return f
}
return MaterialFont.systemFontWithSize(size)
}
/// Medium font.
public static var medium: UIFont {
return mediumWithSize(MaterialFont.pointSize)
}
/// Medium with size font.
public static func mediumWithSize(size: CGFloat) -> UIFont {
MaterialFont.loadFontIfNeeded("Roboto-Medium")
if let f = UIFont(name: "Roboto-Medium", size: size) {
return f
}
return MaterialFont.boldSystemFontWithSize(size)
}
/// Bold font.
public static var bold: UIFont {
return boldWithSize(MaterialFont.pointSize)
}
/// Bold with size font.
public static func boldWithSize(size: CGFloat) -> UIFont {
MaterialFont.loadFontIfNeeded("Roboto-Bold")
if let f = UIFont(name: "Roboto-Bold", size: size) {
return f
}
return MaterialFont.boldSystemFontWithSize(size)
}
} | mit | 79b6fb25fed7cb7ff2a57a86614a5109 | 32.287037 | 86 | 0.740679 | 3.988901 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Model/Profile/Profile.swift | 1 | 12714 | //
// Profile.swift
// DereGuide
//
// Created by zzk on 2017/8/2.
// Copyright © 2017年 zzk. All rights reserved.
//
import Foundation
import CoreData
import CloudKit
class Profile: NSManagedObject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Profile> {
return NSFetchRequest<Profile>(entityName: "Profile")
}
@NSManaged public var gameID: String
@NSManaged public var nickName: String
@NSManaged public var cuteCardID: Int32
@NSManaged public var coolCardID: Int32
@NSManaged public var passionCardID: Int32
@NSManaged public var cuteVocalLevel: Int16
@NSManaged public var allTypeCardID: Int32
@NSManaged public var guestAllTypeCardID: Int32
@NSManaged public var guestPassionCardID: Int32
@NSManaged public var guestCoolCardID: Int32
@NSManaged public var guestCuteCardID: Int32
@NSManaged public var passionVisualLevel: Int16
@NSManaged public var passionDanceLevel: Int16
@NSManaged public var passionVocalLevel: Int16
@NSManaged public var coolDanceLevel: Int16
@NSManaged public var coolVocalLevel: Int16
@NSManaged public var cuteVisualLevel: Int16
@NSManaged public var cuteDanceLevel: Int16
@NSManaged public var allTypeVisualLevel: Int16
@NSManaged public var allTypeDanceLevel: Int16
@NSManaged public var allTypeVocalLevel: Int16
@NSManaged public var message: String?
@NSManaged public var creatorID: String?
@NSManaged public var remoteIdentifier: String?
@NSManaged public var coolVisualLevel: Int16
@NSManaged public var allTypeLifeLevel: Int16
@NSManaged public var cuteLifeLevel: Int16
@NSManaged public var coolLifeLevel: Int16
@NSManaged public var passionLifeLevel: Int16
@NSManaged public var guestCuteMinLevel: Int16
@NSManaged public var guestCoolMinLevel: Int16
@NSManaged public var guestPassionMinLevel: Int16
@NSManaged public var guestAllTypeMinLevel: Int16
@NSManaged public var isOpen: Bool
@NSManaged public var remoteCreatedAt: Date?
@NSManaged public var leaderCardID: Int32
override func awakeFromInsert() {
super.awakeFromInsert()
setPrimitiveValue("", forKey: "gameID")
setPrimitiveValue("", forKey: "nickName")
}
}
extension Profile {
var cutePotential: CGSSPotential {
get {
return CGSSPotential(vocalLevel: Int(cuteVocalLevel), danceLevel: Int(cuteDanceLevel), visualLevel: Int(cuteVisualLevel), lifeLevel: Int(cuteLifeLevel))
}
set {
cuteVocalLevel = Int16(newValue.vocalLevel)
cuteDanceLevel = Int16(newValue.danceLevel)
cuteVisualLevel = Int16(newValue.visualLevel)
cuteLifeLevel = Int16(newValue.lifeLevel)
}
}
var coolPotential: CGSSPotential {
get {
return CGSSPotential(vocalLevel: Int(coolVocalLevel), danceLevel: Int(coolDanceLevel), visualLevel: Int(coolVisualLevel), lifeLevel: Int(coolLifeLevel))
}
set {
coolVocalLevel = Int16(newValue.vocalLevel)
coolDanceLevel = Int16(newValue.danceLevel)
coolVisualLevel = Int16(newValue.visualLevel)
coolLifeLevel = Int16(newValue.lifeLevel)
}
}
var passionPotential: CGSSPotential {
get {
return CGSSPotential(vocalLevel: Int(passionVocalLevel), danceLevel: Int(passionDanceLevel), visualLevel: Int(passionVisualLevel), lifeLevel: Int(passionLifeLevel))
}
set {
passionVocalLevel = Int16(newValue.vocalLevel)
passionDanceLevel = Int16(newValue.danceLevel)
passionVisualLevel = Int16(newValue.visualLevel)
passionLifeLevel = Int16(newValue.lifeLevel)
}
}
var allTypePotential: CGSSPotential {
get {
return CGSSPotential(vocalLevel: Int(allTypeVocalLevel), danceLevel: Int(allTypeDanceLevel), visualLevel: Int(allTypeVisualLevel), lifeLevel: Int(allTypeLifeLevel))
}
set {
allTypeVocalLevel = Int16(newValue.vocalLevel)
allTypeDanceLevel = Int16(newValue.danceLevel)
allTypeVisualLevel = Int16(newValue.visualLevel)
allTypeLifeLevel = Int16(newValue.lifeLevel)
}
}
var myCenters: [(Int, CGSSPotential)] {
set {
cuteCardID = Int32(newValue[0].0)
cutePotential = newValue[0].1
coolCardID = Int32(newValue[1].0)
coolPotential = newValue[1].1
passionCardID = Int32(newValue[2].0)
passionPotential = newValue[2].1
allTypeCardID = Int32(newValue[3].0)
allTypePotential = newValue[3].1
}
get {
return [(Int(cuteCardID), cutePotential),
(Int(coolCardID), coolPotential),
(Int(passionCardID), passionPotential),
(Int(allTypeCardID), allTypePotential)]
}
}
var centersWanted: [(Int, Int)] {
set {
guestCuteCardID = Int32(newValue[0].0)
guestCuteMinLevel = Int16(newValue[0].1)
guestCoolCardID = Int32(newValue[1].0)
guestCoolMinLevel = Int16(newValue[1].1)
guestPassionCardID = Int32(newValue[2].0)
guestPassionMinLevel = Int16(newValue[2].1)
guestAllTypeCardID = Int32(newValue[3].0)
guestAllTypeMinLevel = Int16(newValue[3].1)
}
get {
return [(Int(guestCuteCardID), Int(guestCuteMinLevel)),
(Int(guestCoolCardID), Int(guestCoolMinLevel)),
(Int(guestPassionCardID), Int(guestPassionMinLevel)),
(Int(guestAllTypeCardID), Int(guestAllTypeMinLevel))]
}
}
func reset() {
self.gameID = ""
self.nickName = ""
self.cuteCardID = 0
self.coolCardID = 0
self.passionCardID = 0
self.cuteVocalLevel = 0
self.allTypeCardID = 0
self.guestAllTypeCardID = 0
self.guestPassionCardID = 0
self.guestCoolCardID = 0
self.guestCuteCardID = 0
self.passionVisualLevel = 0
self.passionDanceLevel = 0
self.passionVocalLevel = 0
self.coolDanceLevel = 0
self.coolVocalLevel = 0
self.cuteVisualLevel = 0
self.cuteDanceLevel = 0
self.allTypeVisualLevel = 0
self.allTypeDanceLevel = 0
self.allTypeVocalLevel = 0
self.message = ""
self.coolVisualLevel = 0
self.passionLifeLevel = 0
self.cuteLifeLevel = 0
self.coolLifeLevel = 0
self.allTypeLifeLevel = 0
self.guestCuteMinLevel = 0
self.guestCoolMinLevel = 0
self.guestPassionMinLevel = 0
self.guestAllTypeMinLevel = 0
self.leaderCardID = 0
}
}
extension Profile: Managed {
public static var entityName: String {
return "Profile"
}
}
// not really need to be remote deletable
extension Profile: RemoteDeletable {
var markedForRemoteDeletion: Bool {
get {
return false
}
set {
// no-op
}
}
}
extension Profile: RemoteUploadable {
public func toCKRecord() -> CKRecord {
let record = CKRecord(recordType: RemoteProfile.recordType)
record["gameID"] = gameID as CKRecordValue
record["nickName"] = nickName as CKRecordValue
record["cuteCardID"] = cuteCardID as CKRecordValue
record["coolCardID"] = coolCardID as CKRecordValue
record["passionCardID"] = passionCardID as CKRecordValue
record["cuteVocalLevel"] = cuteVocalLevel as CKRecordValue
record["allTypeCardID"] = allTypeCardID as CKRecordValue
record["guestAllTypeCardID"] = guestAllTypeCardID as CKRecordValue
record["guestPassionCardID"] = guestPassionCardID as CKRecordValue
record["guestCoolCardID"] = guestCoolCardID as CKRecordValue
record["guestCuteCardID"] = guestCuteCardID as CKRecordValue
record["passionVisualLevel"] = passionVisualLevel as CKRecordValue
record["passionDanceLevel"] = passionDanceLevel as CKRecordValue
record["passionVocalLevel"] = passionVocalLevel as CKRecordValue
record["coolDanceLevel"] = coolDanceLevel as CKRecordValue
record["coolVocalLevel"] = coolVocalLevel as CKRecordValue
record["cuteVisualLevel"] = cuteVisualLevel as CKRecordValue
record["cuteDanceLevel"] = cuteDanceLevel as CKRecordValue
record["allTypeVisualLevel"] = allTypeVisualLevel as CKRecordValue
record["allTypeDanceLevel"] = allTypeDanceLevel as CKRecordValue
record["allTypeVocalLevel"] = allTypeVocalLevel as CKRecordValue
record["message"] = (message ?? "") as CKRecordValue
record["coolVisualLevel"] = coolVisualLevel as CKRecordValue
record["guestCuteMinLevel"] = guestCuteMinLevel as CKRecordValue
record["guestCoolMinLevel"] = guestCoolMinLevel as CKRecordValue
record["guestPassionMinLevel"] = guestPassionMinLevel as CKRecordValue
record["guestAllTypeMinLevel"] = guestAllTypeMinLevel as CKRecordValue
record["isOpen"] = (isOpen ? 1 : 0) as CKRecordValue
record["cuteTotalLevel"] = cutePotential.totalLevel as CKRecordValue
record["coolTotalLevel"] = coolPotential.totalLevel as CKRecordValue
record["passionTotalLevel"] = passionPotential.totalLevel as CKRecordValue
record["allTypeTotalLevel"] = allTypePotential.totalLevel as CKRecordValue
record["leaderCardID"] = leaderCardID as CKRecordValue
record["allTypeLifeLevel"] = allTypeLifeLevel as CKRecordValue
record["cuteLifeLevel"] = cuteLifeLevel as CKRecordValue
record["coolLifeLevel"] = coolLifeLevel as CKRecordValue
record["passionLifeLevel"] = passionLifeLevel as CKRecordValue
return record
}
}
extension Profile {
static func insert(remoteRecord: RemoteProfile, into context: NSManagedObjectContext) -> Profile {
let profile: Profile = context.insertObject()
profile.gameID = remoteRecord.gameID
profile.nickName = remoteRecord.nickName
profile.cuteCardID = Int32(remoteRecord.cuteCardID)
profile.coolCardID = Int32(remoteRecord.coolCardID)
profile.passionCardID = Int32(remoteRecord.passionCardID)
profile.cuteVocalLevel = Int16(remoteRecord.cuteVocalLevel)
profile.allTypeCardID = Int32(remoteRecord.allTypeCardID)
profile.guestAllTypeCardID = Int32(remoteRecord.guestAllTypeCardID)
profile.guestPassionCardID = Int32(remoteRecord.guestPassionCardID)
profile.guestCoolCardID = Int32(remoteRecord.guestCoolCardID)
profile.guestCuteCardID = Int32(remoteRecord.guestCuteCardID)
profile.passionVisualLevel = Int16(remoteRecord.passionVisualLevel)
profile.passionDanceLevel = Int16(remoteRecord.passionDanceLevel)
profile.passionVocalLevel = Int16(remoteRecord.passionVocalLevel)
profile.coolDanceLevel = Int16(remoteRecord.coolDanceLevel)
profile.coolVocalLevel = Int16(remoteRecord.coolVocalLevel)
profile.cuteVisualLevel = Int16(remoteRecord.cuteVisualLevel)
profile.cuteDanceLevel = Int16(remoteRecord.cuteDanceLevel)
profile.allTypeVisualLevel = Int16(remoteRecord.allTypeVisualLevel)
profile.allTypeDanceLevel = Int16(remoteRecord.allTypeDanceLevel)
profile.allTypeVocalLevel = Int16(remoteRecord.allTypeVocalLevel)
profile.message = remoteRecord.message
profile.remoteIdentifier = remoteRecord.id
profile.creatorID = remoteRecord.creatorID
profile.coolVisualLevel = Int16(remoteRecord.coolVisualLevel)
profile.guestCuteMinLevel = Int16(remoteRecord.guestCuteMinLevel)
profile.guestCoolMinLevel = Int16(remoteRecord.guestCoolMinLevel)
profile.guestPassionMinLevel = Int16(remoteRecord.guestPassionMinLevel)
profile.guestAllTypeMinLevel = Int16(remoteRecord.guestAllTypeMinLevel)
profile.isOpen = remoteRecord.isOpen == 1
profile.remoteCreatedAt = remoteRecord.remoteModifiedAt
profile.leaderCardID = Int32(remoteRecord.leaderCardID)
profile.passionLifeLevel = Int16(remoteRecord.passionLifeLevel)
profile.cuteLifeLevel = Int16(remoteRecord.cuteLifeLevel)
profile.coolLifeLevel = Int16(remoteRecord.coolLifeLevel)
profile.allTypeLifeLevel = Int16(remoteRecord.allTypeLifeLevel)
return profile
}
}
| mit | 91972976cd4728026d3e651e0dd50239 | 39.740385 | 176 | 0.679254 | 4.173014 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/Notifications/SwiftUI/NotificationsViewControllerSwiftUI.swift | 1 | 1269 | //
// NotificationsViewControllerSwiftUI.swift
// PennMobile
//
// Created by Raunaq Singh on 9/25/22.
// Copyright © 2022 PennLabs. All rights reserved.
//
import SwiftUI
class NotificationsViewControllerSwiftUI: GenericViewController {
override func viewDidLoad() {
super.viewDidLoad()
let hostingView = UIHostingController(rootView: NotificationsView())
view.backgroundColor = .uiBackground
self.screenName = "Notifications SwiftUI"
addChild(hostingView)
view.addSubview(hostingView.view)
hostingView.didMove(toParent: self)
hostingView.view.translatesAutoresizingMaskIntoConstraints = false
hostingView.view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
hostingView.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
hostingView.view.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor).isActive = true
hostingView.view.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.title = "Notifications"
}
}
| mit | da179f3bcf0b1b14381f05220886a559 | 34.222222 | 121 | 0.736593 | 4.992126 | false | false | false | false |
sravankumar143/HONDropDownTableView | Example/HONDropDownTableView/ViewController.swift | 1 | 2031 | //
// ViewController.swift
// HONDropDownTableView
//
// Created by sravankumar143 on 07/12/2017.
// Copyright (c) 2017 sravankumar143. All rights reserved.
//
import UIKit
import HONDropDownTableView
class ViewController: UIViewController {
@IBOutlet weak var customView: HONButtonView!
@IBOutlet weak var button4: UIButton!
@IBOutlet weak var honTableView: HONTableView!
var dropDownVc2: HONDropDownTableViewController?
var dropDownVc4: HONDropDownTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
customUI()
honTableView.menuArray = ["Recently Computed","ETD","Tail","Filing Status","Departure","Destination","Hidden Flight Plans"]
honTableView.selectedItem = "Recently Computed"
customView.menuType = 1
customView.dataSourceArray = ["Recently Computed","ETD","Tail","Filing Status","Departure","Destination","Hidden Flight Plans"]
//customView.selectArrowImage = UIImage(named: "arrowup")
//customView.selectedItem = "Recently Computed"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK:- Private Methods
fileprivate func customUI() {
customizeTableView()
}
fileprivate func customizeTableView() {
customView.dropDownTable.separatorColor = UIColor.lightGray
customView.dropDownTable.backgroundColor = UIColor.black
customView.dropDownTable.cellSelectionStyle = UITableViewCellSelectionStyle.none
customView.dropDownTable.separatorStyle = .singleLine
customView.dropDownTable.cellLblTextColor = UIColor.white
}
}
extension ViewController: HONButtonViewDelegate {
func dropDownView(_ dropDown: HONDropDownTableViewController, didSelectedItem item: String, atIndex index: Int) {
}
}
| mit | 23f5f40a69ea6983a20f03d0c9c830ba | 32.295082 | 135 | 0.702117 | 5.141772 | false | false | false | false |
ochan1/OC-PublicCode | MakeSchoolNotes-Swift-V2-Starter-swift3-coredata/MakeSchoolNotes/Helpers/CoreDataHelper.swift | 2 | 1215 | //
// CoreDataHelper.swift
// MakeSchoolNotes
//
// Created by Oscar Chan on 6/27/17.
// Copyright © 2017 MakeSchool. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class CoreDataHelper {
static let appDelegate = UIApplication.shared.delegate as! AppDelegate
static let persistentContainer = appDelegate.persistentContainer
static let managedContext = persistentContainer.viewContext
static func newNote() -> Note {
let note = NSEntityDescription.insertNewObject(forEntityName: "Note", into: managedContext) as! Note
return note
}
static func saveNote() {
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error)")
}
}
static func delete(note: Note) {
managedContext.delete(note)
saveNote()
}
static func retrieveNotes() -> [Note] {
let fetchRequest = NSFetchRequest<Note>(entityName: "Note")
do {
let results = try managedContext.fetch(fetchRequest)
return results
} catch let error as NSError {
print("Could not fetch \(error)")
}
return []
}
}
| mit | 48183591f97b41a56092fafbe74f59d3 | 27.232558 | 108 | 0.632619 | 4.836653 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/SwifterSwift/Source/Extensions/URLExtensions.swift | 5 | 940 | //
// URLExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 03/02/2017.
// Copyright © 2017 omaralbeik. All rights reserved.
//
import Foundation
public extension URL {
/// SwifterSwift: URL with appending query parameters.
///
/// - Parameter parameters: parameters dictionary.
/// - Returns: URL with appending given query parameters.
public func appendingQueryParameters(_ parameters: [String: String]) -> URL {
var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)!
var items = urlComponents.queryItems ?? []
items += parameters.map({ URLQueryItem(name: $0, value: $1) })
urlComponents.queryItems = items
return urlComponents.url!
}
/// SwifterSwift: Append query parameters to URL.
///
/// - Parameter parameters: parameters dictionary.
public mutating func appendQueryParameters(_ parameters: [String: String]) {
self = appendingQueryParameters(parameters)
}
}
| mit | 737cd00c385f8ddee308283b57fe97d6 | 27.454545 | 78 | 0.722045 | 4.118421 | false | false | false | false |
kuzmir/kazimir-ios | kazimir-ios/Data/EntityExtensions/PhotoExtensions.swift | 1 | 1525 | //
// PhotoExtensions.swift
// kazimir-ios
//
// Created by Krzysztof Cieplucha on 14/05/15.
// Copyright (c) 2015 Kazimir. All rights reserved.
//
import Foundation
enum PhotoRelation: String {
case Images = "images"
}
enum PhotoProperty: String {
case Id = "id"
case Details = "details"
case UpdateDate = "updated_at"
}
extension Photo {
static func getImagesJSON(#json: JSON) -> RelationInfo {
let images = json[PhotoRelation.Images.rawValue] as? JSON
if images == nil { return (nil, Storage.storageError) }
return ([images!], nil)
}
}
extension Photo: JSONConvertible {
static func getIdFromJSON(json: JSON) -> NSNumber? {
return json[PhotoProperty.Id.rawValue] as? NSNumber
}
func fromJSON(json: JSON) -> ConversionResult {
let updateDateString = json[PhotoProperty.UpdateDate.rawValue] as? String
if updateDateString == nil { return (nil, Storage.storageError) }
let updateDate = Storage.dateFormatter.dateFromString(updateDateString!)
if updateDate == nil { return (nil, Storage.storageError) }
if self.updateDate.compare(updateDate!) == .OrderedAscending {
self.updateDate = updateDate!
let details = json[PhotoProperty.Details.rawValue] as? JSON
if details == nil { return (nil, Storage.storageError) }
self.details = details!
return (true, nil)
}
return (false, nil)
}
}
| apache-2.0 | 5bf848f260e93464696763ec72aace80 | 27.240741 | 81 | 0.627541 | 4.121622 | false | true | false | false |
MA806P/SwiftDemo | SwiftTestDemo/SwiftTestDemo/Extensions.swift | 1 | 3742 | //
// Extensions.swift
// SwiftTestDemo
//
// Created by MA806P on 2018/8/30.
// Copyright © 2018年 myz. All rights reserved.
//
import Foundation
/*
Extensions:为已存在的类、结构体、枚举或者协议类型增添了一个新的功能
与 Objective-C 中 Categories 有所不同的是,Swift 中的 Extensions 并没有一个具体的命名
Swift 中 Extensions 可以做到:
添加计算实例属性和计算类型属性
定义实例方法和类方法
提供新的初始化方法
定义下标脚本
定义和使用新的嵌套类型
使现有类型符合协议
extension SomeType { }
Extension 可以实现扩展现有类型去遵循一个或多个协议
extension SomeType: SomeProtocol, AnotherProtocol { }
*/
//计算属性
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
//let oneInch = 25.4.mm
//print("One inch is \(oneInch) meters")
//// Prints "One inch is 0.0254 meters"
//let threeFeet = 3.ft
//print("Three feet is \(threeFeet) meters")
//// Prints "Three feet is 0.914399970739201 meters"
//添加一个新的初始化构造器
struct Size1 {
var width = 0.0, height = 0.0
}
struct Point1 {
var x = 0.0, y = 0.0
}
struct Rect1 {
var origin = Point1()
var size = Size1()
}
//let defaultRect = Rect()
//let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0))
extension Rect1 {
init(center: Point1, size: Size1) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point1(x: originX, y: originY), size: size)
}
}
//新的初始化器可以基于 Center 和 Size 的值去计算一个恰当的初始点,
//然后通过这个初始化器去调用 init(origin:size:) 这个自动初始化成员方法,
//这将会把新的 Origin 和 Size 保存在相对的属性中
//向已经存在的类型添加实例方法或类方法
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
//3.repetitions {
// print("Hello!")
//}
//添加实例方法来实现修改变量
extension Int {
mutating func square() {
self = self * self
}
}
//var someInt = 3
//someInt.square()
//// someInt = 9
//对已经存在的类型添加下标
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
//746381295[0]
//// 返回 5
//746381295[1]
//// 返回 9
//向任何已经存在的类、结构体或枚举添加新的嵌套类型
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}
//针对 Int 类型的扩展 Kind,在这个扩展中,我们可以针对任意一个 Int 类型作出进一步的细分,
//比如:负数(negative),零 (zero), 与正数 (positive)。
func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .negative:
print("- ", terminator: "")
case .zero:
print("0 ", terminator: "")
case .positive:
print("+ ", terminator: "")
}
}
print("")
}
//printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
//// Prints "+ + - 0 - 0 + "
| apache-2.0 | dc97c173dfa904e0958bb513d2f7ee31 | 17.742331 | 95 | 0.588543 | 3.107833 | false | false | false | false |
mownier/sambag | Sambag/Source/SambagTheme.swift | 1 | 1939 | //
// SambagTheme.swift
// Sambag
//
// Created by Mounir Ybanez on 02/06/2017.
// Copyright © 2017 Ner. All rights reserved.
//
import UIKit
public struct SambagThemeAttribute {
public var contentViewBackgroundColor: UIColor!
public var stripColor: UIColor!
public var titleTextColor: UIColor!
public var titleFont: UIFont!
public var wheelFont: UIFont!
public var wheelTextColor: UIColor!
public var buttonFont: UIFont!
public var buttonTextColor: UIColor!
public var is24:Bool!
public init() {
contentViewBackgroundColor = .white
stripColor = UIColor(red: 61/255, green: 187/255, blue: 234/255, alpha: 1)
titleTextColor = stripColor
titleFont = UIFont(name: "AvenirNext-Medium", size: 20)
wheelFont = UIFont(name: "AvenirNext-Medium", size: 15)
wheelTextColor = .black
buttonFont = UIFont(name: "AvenirNext-Regular", size: 15)
buttonTextColor = .black
is24 = is24Format()
}
func is24Format() -> Bool {
let locale = NSLocale.current
let formatter : String = DateFormatter.dateFormat(fromTemplate: "j", options:0, locale:locale)!
if (formatter.contains("a")) {
return false
} else {
return true
}
}
}
public enum SambagTheme {
case light
case dark
case custom(SambagThemeAttribute)
public var attribute: SambagThemeAttribute {
switch self {
case .light:
return SambagThemeAttribute()
case .dark:
var attrib = SambagThemeAttribute()
attrib.contentViewBackgroundColor = UIColor(red: 40/255, green: 40/255, blue: 40/255, alpha: 1)
attrib.buttonTextColor = .white
attrib.wheelTextColor = .white
return attrib
case .custom(let attrib):
return attrib
}
}
}
| mit | c740aa6f77921264d9a50d7736063f3b | 27.5 | 107 | 0.613003 | 4.414579 | false | false | false | false |
sugimotoak/ExpressBusTimetable | ExpressBusTimetable/Controllers/SearchViewController.swift | 1 | 9290 | //
// SearchViewController.swift
// ExpressBusTimetable
//
// Created by akira on 5/14/17.
// Copyright © 2017 Spreadcontent G.K. All rights reserved.
//
import UIKit
import ActionSheetPicker_3_0
class SearchViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = EBTColor.sharedInstance.primaryColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath {
case IndexPath(row: 0, section: 0):
let title = (tableView.cellForRow(at: indexPath)?.viewWithTag(2) as? UILabel)?.text
let label = tableView.cellForRow(at: indexPath)?.viewWithTag(1) as? UILabel
let list = TimetableList.nameList
log.debug("\(list)")
let selection = TimetableList.list.index(of: UserDefaults.searchTimetableList) ?? 0
log.debug("\(selection),\(UserDefaults.searchTimetableList)")
let picker = ActionSheetStringPicker(title: title,
rows: list,
initialSelection: selection,
doneBlock: {
_, selectedIndex, selectedValue in
if selectedIndex != selection {
let value: String = selectedValue as! String
label?.text = value
UserDefaults.searchTimetableList = TimetableList.list[selectedIndex]
DispatchQueue.main.async { () -> Void in
tableView.reloadData()
}
}
tableView.deselectRow(at: indexPath, animated: true)
return },
cancel: { _ in
tableView.deselectRow(at: indexPath, animated: true)
return },
origin: view)
picker?.show()
break
case IndexPath(row: 1, section: 0):
let title = (tableView.cellForRow(at: indexPath)?.viewWithTag(2) as? UILabel)?.text
let label = tableView.cellForRow(at: indexPath)?.viewWithTag(1) as? UILabel
let timetableWeekDayUp = TimetableStatus.WeekdayUp.getSearchTimetable()
let list = timetableWeekDayUp.busStopList
log.debug("\(list)")
let selection = list.index(of: UserDefaults.searchOnBusStop) ?? 0
log.debug("\(selection),\(UserDefaults.searchOnBusStop)")
let picker = ActionSheetStringPicker(title: title,
rows: list,
initialSelection: selection,
doneBlock: {
_, _, selectedValue in
let value: String = selectedValue as! String
if !value.isEmpty {
label?.text = value
UserDefaults.searchOnBusStop = value
if let upDown = timetableWeekDayUp.checkUpDown(value, UserDefaults.searchOffBusStop) {
UserDefaults.searchTimetableStatus = UserDefaults.searchTimetableStatus.changeUpDown(upDown: upDown)
}
}
tableView.deselectRow(at: indexPath, animated: true)
return },
cancel: { _ in
tableView.deselectRow(at: indexPath, animated: true)
return },
origin: view)
picker?.show()
break
case IndexPath(row: 2, section: 0):
let title = (tableView.cellForRow(at: indexPath)?.viewWithTag(2) as? UILabel)?.text
let label = tableView.cellForRow(at: indexPath)?.viewWithTag(1) as? UILabel
let timetableWeekDayUp = TimetableStatus.WeekdayUp.getSearchTimetable()
let list = timetableWeekDayUp.busStopList
log.debug("\(list)")
let selection = list.index(of: UserDefaults.searchOffBusStop) ?? 0
log.debug("\(selection),\(UserDefaults.searchOffBusStop)")
let picker = ActionSheetStringPicker(title: title,
rows: list,
initialSelection: selection,
doneBlock: {
_, _, selectedValue in
let value: String = selectedValue as! String
if !value.isEmpty {
label?.text = value
UserDefaults.searchOffBusStop = value
if let upDown = timetableWeekDayUp.checkUpDown(UserDefaults.searchOnBusStop, value) {
UserDefaults.searchTimetableStatus = UserDefaults.searchTimetableStatus.changeUpDown(upDown: upDown)
}
}
tableView.deselectRow(at: indexPath, animated: true)
return },
cancel: { _ in
tableView.deselectRow(at: indexPath, animated: true)
return },
origin: view)
picker?.show()
break
default:
break
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
switch indexPath {
case IndexPath(row: 0, section: 0):
let timetableName = UserDefaults.searchTimetableList.getName()
let timetableLabel = cell.viewWithTag(1) as? UILabel
timetableLabel?.text = timetableName
break
case IndexPath(item: 1, section: 0):
let onBusStop = UserDefaults.searchOnBusStop
let onBusStopLabel = cell.viewWithTag(1) as? UILabel
onBusStopLabel?.text = onBusStop
break
case IndexPath(item: 2, section: 0):
let offBusStop = UserDefaults.searchOffBusStop
let offBusStopLabel = cell.viewWithTag(1) as? UILabel
offBusStopLabel?.text = offBusStop
break
default:
break
}
cell.backgroundColor = EBTColor.sharedInstance.secondaryColor
(cell.viewWithTag(1) as? UILabel)?.textColor = EBTColor.sharedInstance.secondaryTextColor
(cell.viewWithTag(2) as? UILabel)?.textColor = EBTColor.sharedInstance.secondaryTextColor
return cell
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let v = view as! UITableViewHeaderFooterView
v.tintColor = EBTColor.sharedInstance.primaryColor
v.textLabel?.textColor = EBTColor.sharedInstance.primaryTextColor
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "Search" {
let vc = segue.destination as! CommuteViewController
vc.isSearch = true
}
}
}
| mit | 56c2d3fc898e4b010bd4878f9b725a70 | 53.641176 | 161 | 0.463774 | 6.880741 | false | false | false | false |
rhx/gir2swift | Sources/libgir2swift/models/Gir.swift | 1 | 15516 | //
// gir.swift
// gir2swift
//
// Created by Rene Hexel on 25/03/2016.
// Copyright © 2016, 2017, 2018, 2019, 2020, 2022 Rene Hexel. All rights reserved.
//
import SwiftLibXML
/// Designated containers for types that can have associated methods
private let methodContainers: Set<String> = [ "record", "class", "interface", "enumeration", "bitfield" ]
/// Check whether a given XML element represents a free function
/// (as opposed to a method inside a type)
/// - Parameter function: XML element to be checked
func isFreeFunction(_ function: XMLElement) -> Bool {
let isContained = methodContainers.contains(function.parent.name)
return !isContained
}
/// Representation of a GIR file
public final class GIR {
/// The parsed XML document represented by the receiver
public let xml: XMLDocument
/// Preample boilerplate to output before any generated code
public var preamble = ""
/// Namespace prefix defined by the receiver
public var prefix = "" {
didSet {
GIR.prefix = prefix
GIR.dottedPrefix = prefix + "."
}
}
/// Current namespace prefix
public static var prefix = ""
/// Current namespace prefix with a trailing "."
public static var dottedPrefix = ""
/// Collection of identifier prefixes
public var identifierPrefixes = Array<String>()
/// Collection of symbol prefixes
public var symbolPrefixes = Array<String>()
/// Type-erased sequence of namespaces
public var namespaces: AnySequence<XMLNameSpace> = emptySequence()
/// Aliases defined by this GIR file
public var aliases: [Alias] = []
/// Constants defined by this GIR file
public var constants: [Constant] = []
/// Enums defined by this GIR file
public var enumerations: [Enumeration] = []
/// Bitfields defined by this GIR file
public var bitfields: [Bitfield] = []
/// Interfaces defined by this GIR file
public var interfaces: [Interface] = []
/// Records defined by this GIR file
public var records: [Record] = []
/// Unions defined by this GIR file
public var unions: [Union] = []
/// Classes defined by this GIR file
public var classes: [Class] = []
/// Free functions defined by this GIR file
public var functions: [Function] = []
/// Callbacs defined by this GIR file
public var callbacks: [Callback] = []
/// names of black-listed identifiers
public static var blacklist: Set<String> = []
/// names of constants to be taken verbatim
public static var verbatimConstants: Set<String> = []
/// names of override initialisers
public static var overrides: Set<String> = []
/// context of known types
public static var knownDataTypes: [ String : Datatype ] = [:]
/// context of known records
public static var knownRecords: [ String : Record ] = [:]
/// context of known records
public static var knownBitfields: [ String : Bitfield ] = [:]
/// context of known functions
public static var KnownFunctions: [ String : Function ] = [:]
/// suffixes for `@escaping` callback heuristics
public static var callbackSuffixes = [String]()
/// types to turn into force-unwrapped optionals
public static var forceUnwrapped: Set<String> = ["gpointer", "gconstpointer"]
/// Dotted namespace replacements
public static var namespaceReplacements: [ Substring : Substring ] = [
"GObject." : "GLibObject.", "Gio." : "GIO.", "GdkPixbuf." : "GdkPixBuf.", "cairo." : "Cairo."
]
/// designated constructor
public init(xmlDocument: XMLDocument, quiet: Bool = false) {
xml = xmlDocument
if let rp = xml.first(where: { $0.name == "repository" }) {
namespaces = rp.namespaces
}
//
// set up name space prefix
//
if let ns = xml.xpath("//gir:namespace", namespaces: namespaces, defaultPrefix: "gir")?.makeIterator().next() {
if let name = ns.attribute(named: "name") {
prefix = name
GIR.prefix = name
GIR.dottedPrefix = name + "."
}
identifierPrefixes = ns.sortedSubAttributesFor(attr: "identifier-prefixes")
symbolPrefixes = ns.sortedSubAttributesFor(attr: "symbol-prefixes")
}
withUnsafeMutablePointer(to: &GIR.knownDataTypes) { (knownTypes: UnsafeMutablePointer<[ String : Datatype ]>) -> Void in
withUnsafeMutablePointer(to: &GIR.knownRecords) { (knownRecords: UnsafeMutablePointer<[ String : Record]>) -> Void in
withUnsafeMutablePointer(to: &GIR.knownBitfields) { (knownBitfields: UnsafeMutablePointer<[ String : Bitfield]>) -> Void in
let prefixed: (String) -> String = { $0.prefixed(with: self.prefix) }
func setKnown<T>(_ d: UnsafeMutablePointer<[ String : T]>) -> (String, T) -> Bool {
return { (name: String, type: T) -> Bool in
guard d.pointee[name] == nil || d.pointee[prefixed(name)] == nil else { return false }
let prefixedName = prefixed(name)
d.pointee[name] = type
d.pointee[prefixedName] = type
if GIR.namespaceReplacements[prefixedName.dottedPrefix] != nil {
let alternativelyPrefixed = prefixedName.withNormalisedPrefix
d.pointee[alternativelyPrefixed] = type
}
return true
}
}
let setKnownType = setKnown(knownTypes)
let setKnownRecord = setKnown(knownRecords)
let setKnownBitfield = setKnown(knownBitfields)
//
// get all type alias records
//
if let entries = xml.xpath("/*/*/gir:alias", namespaces: namespaces, defaultPrefix: "gir") {
aliases = entries.enumerated().map { Alias(node: $0.1, at: $0.0) }.filter {
let name = $0.name
guard setKnownType(name, $0) else {
if !quiet { print("Warning: duplicate type '\(name)' for alias ignored!", to: &Streams.stdErr) }
return false
}
return true
}
}
// closure for recording known types
func notKnownType<T>(_ e: T) -> Bool where T: Datatype {
return setKnownType(e.name, e)
}
let notKnownRecord: (Record) -> Bool = {
guard notKnownType($0) else { return false }
return setKnownRecord($0.name, $0)
}
let notKnownBitfield: (Bitfield) -> Bool = {
guard notKnownType($0) else { return false }
return setKnownBitfield($0.name, $0)
}
let notKnownFunction: (Function) -> Bool = {
let name = $0.name
guard GIR.KnownFunctions[name] == nil else { return false }
GIR.KnownFunctions[name] = $0
return true
}
//
// get all constants, enumerations, records, classes, and functions
//
constants = enumerate(xml, path: "/*/*/gir:constant", inNS: namespaces, quiet: quiet, construct: { Constant(node: $0, at: $1) }, check: notKnownType)
enumerations = enumerate(xml, path: "/*/*/gir:enumeration", inNS: namespaces, quiet: quiet, construct: { Enumeration(node: $0, at: $1) }, check: notKnownType)
bitfields = enumerate(xml, path: "/*/*/gir:bitfield", inNS: namespaces, quiet: quiet, construct: { Bitfield(node: $0, at: $1) }, check: notKnownBitfield)
interfaces = enumerate(xml, path: "/*/*/gir:interface", inNS: namespaces, quiet: quiet, construct: { Interface(node: $0, at: $1) }, check: notKnownRecord)
records = enumerate(xml, path: "/*/*/gir:record", inNS: namespaces, quiet: quiet, construct: { Record(node: $0, at: $1) }, check: notKnownRecord)
classes = enumerate(xml, path: "/*/*/gir:class", inNS: namespaces, quiet: quiet, construct: { Class(node: $0, at: $1) }, check: notKnownRecord)
unions = enumerate(xml, path: "/*/*/gir:union", inNS: namespaces, quiet: quiet, construct: { Union(node: $0, at: $1) }, check: notKnownRecord)
callbacks = enumerate(xml, path: "/*/*/gir:callback", inNS: namespaces, quiet: quiet, construct: { Callback(node: $0, at: $1) }, check: notKnownType)
functions = enumerate(xml, path: "//gir:function", inNS: namespaces, quiet: quiet, construct: {
isFreeFunction($0) ? Function(node: $0, at: $1) : nil
}, check: notKnownFunction)
}
}
}
buildClassHierarchy()
buildConformanceGraph()
}
/// convenience constructor to read a gir file
public convenience init?(fromFile name: String) {
guard let xml = XMLDocument(fromFile: name) else { return nil }
self.init(xmlDocument: xml)
}
/// convenience constructor to read from memory
public convenience init?(buffer content: UnsafeBufferPointer<CChar>, quiet q: Bool = false) {
guard let xml = XMLDocument(buffer: content) else { return nil }
self.init(xmlDocument: xml, quiet: q)
}
/// Traverse all the classes and record their relationship in the type hierarchy
@inlinable
public func buildClassHierarchy() {
for cl in classes {
recordImplementedInterfaces(for: cl)
guard cl.typeRef.type.parent == nil else { continue }
if let parent = cl.parentType {
cl.typeRef.type.parent = parent.typeRef
}
}
}
/// Traverse all the records and record all the interfaces implemented
@inlinable
public func buildConformanceGraph() {
records.forEach { recordImplementedInterfaces(for: $0) }
}
/// Traverse all the records and record all the interfaces implemented
@discardableResult @inlinable
public func recordImplementedInterfaces(for record: Record) -> Set<TypeReference> {
let t = record.typeRef.type
if let interfaces = GIR.implements[t] { return interfaces }
let implements = record.implements.compactMap { GIR.knownDataTypes[$0] }
var implementations = Set(implements.map(\.typeRef))
let implementedRecords = implements.compactMap { $0 as? Record }
implementations.formUnion(implementedRecords.flatMap { recordImplementedInterfaces(for: $0) })
if let parent = record.parentType {
implementations.formUnion(recordImplementedInterfaces(for: parent))
}
GIR.implements[t] = implementations
if let ref = GIR.recordRefs[t] { GIR.implements[ref.type] = implementations }
if let pro = GIR.protocols[t] { GIR.implements[pro.type] = implementations }
return implementations
}
}
extension GIR {
///
/// return the documentation for the given child nodes
///
public class func docs(children: LazySequence<AnySequence<XMLElement>>) -> String {
return documentation(name: "doc", children: children)
}
///
/// return the documentation for the given child nodes
///
public class func deprecatedDocumentation(children: LazySequence<AnySequence<XMLElement>>) -> String? {
let doc = documentation(name: "doc-deprecated", children: children)
guard !doc.isEmpty else { return nil }
return doc
}
///
/// return the documentation for the given child nodes
///
public class func documentation(name: String, children: LazySequence<AnySequence<XMLElement>>) -> String {
let docs = children.filter { $0.name == name }
let comments = docs.map { $0.content}
return comments.joined(separator: "\n")
}
///
/// return the method/function arguments for the given child nodes
///
public class func args(children: LazySequence<AnySequence<XMLElement>>) -> [Argument] {
let parameters = children.filter { $0.name.hasSuffix("parameter") }
let args = parameters.enumerated().map { Argument(node: $1, at: $0) }
return args
}
///
/// return the type information of an argument or return type node
///
class func typeOf(node: XMLElement) -> TypeReference {
let t = node.type
if !t.isVoid { return t }
for child in node.children {
let t = child.type
if !t.isVoid { return t }
}
return .void
}
///
/// dump Swift code
///
public func dumpSwift() -> String {
var context = ConversionContext([:])
context = ConversionContext(["repository": {
let s = indent(level: $0.level, "// \($0.node.name) @ \($0.level)+\(context.level)")
context = context.push(node: $0, ["namespace": {
let s = indent(level: $0.level, "// \($0.node.name) @ \($0.level)+\(context.level)")
context = context.push(node: $0, ["alias": {
context = context.push(node: $0, ["type": {
if let type = $0.node.attribute(named: "name"),
let alias = context.parentNode.node.attribute(named: "name"),
!alias.isEmpty && !type.isEmpty {
context.outputs = ["public typealias \(alias) = \(type)"]
} else {
context.outputs = ["// error alias \(String(describing: $0.node.attribute(named: "name"))) = \(String(describing: context.parentNode.node.attribute(named: "name")))"]
}
return ""
}])
return s
}, "function": {
let s: String
if let name = $0.node.attribute(named: "name"), !name.isEmpty {
s = "func \(name)("
} else { s = "// empty function " }
context = context.push(node: $0, ["type": {
if let type = $0.node.attribute(named: "name"),
let alias = context.parentNode.node.attribute(named: "name"),
!alias.isEmpty && !type.isEmpty {
context.outputs = ["public typealias \(alias) = \(type)"]
} else {
context.outputs = ["// error alias \(String(describing: $0.node.attribute(named: "name"))) = \(String(describing: context.parentNode.node.attribute(named: "name")))"]
}
return ""
}])
return s
}])
return s
}])
return s
}])
return (xml.tree.map { (tn: XMLTree.Node) -> String in
if let f = context.conversion[tn.node.name] { return f(tn) }
while context.level > tn.level {
if let parent = context.parent { context = parent }
else { assert(context.level == 0) }
}
return indent(level: tn.level, "// unhandled: \(tn.node.name) @ \(tn.level)+\(context.level)")
}).reduce("") { (output: String, element: String) -> String in
output + "\(element)\n"
}
}
}
| bsd-2-clause | 18f6370ea5bace445712e535c246e7af | 45.452096 | 194 | 0.573896 | 4.494496 | false | false | false | false |
brentdax/swift | test/Profiler/coverage_ternary.swift | 7 | 1163 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_ternary %s | %FileCheck %s
// CHECK-LABEL: sil hidden @$s16coverage_ternary3barCACycfc
// CHECK-NOT: return
// CHECK: builtin "int_instrprof_increment"
// CHECK-LABEL: sil hidden @$s16coverage_ternary3barCfD
// CHECK-NOT: return
// CHECK: builtin "int_instrprof_increment"
var flag: Int = 0
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_ternary.foo
func foo(_ x : Int32) -> Int32 {
return x == 3
? 9000 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : 1
: 1234 // CHECK: [[@LINE]]:16 -> [[@LINE]]:20 : (0 - 1)
}
foo(1)
foo(2)
foo(3)
// rdar://problem/23256795 - Avoid crash if an if_expr has no parent
// CHECK: sil_coverage_map {{.*}}// __ntd_bar_line:[[@LINE+1]]
class bar {
var m1 = flag == 0
? "false" // CHECK: [[@LINE]]:16 -> [[@LINE]]:23 : 0
: "true"; // CHECK: [[@LINE]]:16 -> [[@LINE]]:22 : (1 - 0)
}
// Note: We didn't instantiate bar, but we still expect to see instrumentation
// for its *structors, and coverage mapping information for it.
| apache-2.0 | e3a098e77bc33e6200ed8faf1161dff6 | 34.242424 | 176 | 0.614789 | 3.221607 | false | false | false | false |
honghaoz/2048-Solver-AI | 2048 AI/Components/Settings/SettingViewController.swift | 1 | 14280 | // Copyright © 2019 ChouTi. All rights reserved.
import ChouTi
import ChouTiUI
import Firebase
import UIKit
class SettingViewController: UIViewController {
var mainContainerView: UIView!
var animationDurationTitleLabel: UILabel!
var animationDurationNumberLabel: UILabel!
var animationDurationNumberUnderscoreView: UIView!
var animationDurationUnitLabel: UILabel!
var animationDurationSlider: BlackSlider!
var dimensionTitleLabel: UILabel!
var dimensionNumberLabel: UILabel!
var dimensionSlider: BlackSlider!
var dimension: Int!
var aiAlgorithmTitleLabel: UILabel!
var aiAlgorithmTableView: UITableView!
var kAIAlgorithmCellIdentifier: String = "AICell"
let kTableViewRowHeight: CGFloat = 34.0
var saveButton: BlackBorderButton!
var cancelButton: BlackBorderButton!
var views = [String: UIView]()
var metrics = [String: CGFloat]()
var saveClosure: (() -> Void)?
var cancelClosure: (() -> Void)?
var dismissClosure: (() -> Void)?
let animator = DropPresentingAnimator()
weak var mainViewController: MainViewController!
convenience init(mainViewController: MainViewController) {
self.init()
self.mainViewController = mainViewController
// 230 is height without table view rows, 10 bottom spacing
var height: CGFloat = 230 + 10
height += CGFloat(mainViewController.aiChoices.count) * kTableViewRowHeight
animator.animationDuration = 0.5
animator.allowDragToDismiss = false
animator.shouldDismissOnTappingOutsideView = true
animator.overlayViewStyle = .normal(UIColor(white: 0.0, alpha: 0.7))
animator.presentingViewSize = CGSize(width: ceil(screenWidth * (is320ScreenWidth ? 0.82 : 0.7) + 24), height: height)
modalPresentationStyle = .custom
transitioningDelegate = animator
}
override func viewDidLoad() {
super.viewDidLoad()
dimension = mainViewController.dimension
setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Select AI
let selectedIndexPath = IndexPath(row: mainViewController.aiSelectedChoiceIndex, section: 0)
aiAlgorithmTableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .none)
}
private func setupViews() {
view.backgroundColor = SharedColors.BackgroundColor
view.layer.borderColor = UIColor.black.cgColor
view.layer.borderWidth = 5.0
// MainContainerView
mainContainerView = UIView()
mainContainerView.translatesAutoresizingMaskIntoConstraints = false
views["mainContainerView"] = mainContainerView
view.addSubview(mainContainerView)
// Animation Duration Title Label
animationDurationTitleLabel = UILabel()
animationDurationTitleLabel.translatesAutoresizingMaskIntoConstraints = false
views["animationDurationTitleLabel"] = animationDurationTitleLabel
mainContainerView.addSubview(animationDurationTitleLabel)
animationDurationTitleLabel.text = "Animation Duration:"
animationDurationTitleLabel.textColor = UIColor.black
animationDurationTitleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
animationDurationTitleLabel.textAlignment = .left
animationDurationTitleLabel.numberOfLines = 1
// Animation Duration Number Label
animationDurationNumberLabel = UILabel()
animationDurationNumberLabel.translatesAutoresizingMaskIntoConstraints = false
views["animationDurationNumberLabel"] = animationDurationNumberLabel
mainContainerView.addSubview(animationDurationNumberLabel)
animationDurationNumberLabel.text = String(format: "%0.2f", sharedAnimationDuration)
animationDurationNumberLabel.textColor = UIColor.black
animationDurationNumberLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
animationDurationNumberLabel.textAlignment = .center
animationDurationNumberLabel.numberOfLines = 1
// Animation Duration Under score view
animationDurationNumberUnderscoreView = UIView()
animationDurationNumberUnderscoreView.translatesAutoresizingMaskIntoConstraints = false
views["animationDurationNumberUnderscoreView"] = animationDurationNumberUnderscoreView
mainContainerView.addSubview(animationDurationNumberUnderscoreView)
animationDurationNumberUnderscoreView.backgroundColor = UIColor.black
let cHeight = NSLayoutConstraint(item: animationDurationNumberUnderscoreView!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0.0, constant: 3.0)
animationDurationNumberUnderscoreView.addConstraint(cHeight)
let cWidth = NSLayoutConstraint(item: animationDurationNumberUnderscoreView!, attribute: .width, relatedBy: .equal, toItem: animationDurationNumberLabel, attribute: .width, multiplier: 1.0, constant: 0.0)
let cTopSpacing = NSLayoutConstraint(item: animationDurationNumberUnderscoreView!, attribute: .top, relatedBy: .equal, toItem: animationDurationNumberLabel, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let cLeading = NSLayoutConstraint(item: animationDurationNumberUnderscoreView!, attribute: .leading, relatedBy: .equal, toItem: animationDurationNumberLabel, attribute: .leading, multiplier: 1.0, constant: 0.0)
mainContainerView.addConstraints([cWidth, cTopSpacing, cLeading])
// Animation Duration Unit Label
animationDurationUnitLabel = UILabel()
animationDurationUnitLabel.translatesAutoresizingMaskIntoConstraints = false
views["animationDurationUnitLabel"] = animationDurationUnitLabel
mainContainerView.addSubview(animationDurationUnitLabel)
animationDurationUnitLabel.text = "s"
animationDurationUnitLabel.textColor = UIColor.black
animationDurationUnitLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
animationDurationUnitLabel.textAlignment = .center
animationDurationUnitLabel.numberOfLines = 1
animationDurationUnitLabel.setContentHuggingPriority(UILayoutPriority.required, for: NSLayoutConstraint.Axis.horizontal)
animationDurationUnitLabel.setContentHuggingPriority(UILayoutPriority.required, for: NSLayoutConstraint.Axis.vertical)
animationDurationUnitLabel.setContentCompressionResistancePriority(UILayoutPriority.required, for: NSLayoutConstraint.Axis.horizontal)
animationDurationUnitLabel.setContentCompressionResistancePriority(UILayoutPriority.required, for: NSLayoutConstraint.Axis.vertical)
// Animation Duration Slider
animationDurationSlider = BlackSlider()
animationDurationSlider.translatesAutoresizingMaskIntoConstraints = false
views["animationDurationSlider"] = animationDurationSlider
mainContainerView.addSubview(animationDurationSlider)
animationDurationSlider.minimumValue = 0.0
animationDurationSlider.maximumValue = 1.0
animationDurationSlider.value = Float(sharedAnimationDuration)
animationDurationSlider.addTarget(self, action: #selector(animationDurationSliderValueChanged(_:)), for: .valueChanged)
// Dimension Title Label
dimensionTitleLabel = UILabel()
dimensionTitleLabel.translatesAutoresizingMaskIntoConstraints = false
views["dimensionTitleLabel"] = dimensionTitleLabel
mainContainerView.addSubview(dimensionTitleLabel)
dimensionTitleLabel.text = "Board Size:"
dimensionTitleLabel.textColor = UIColor.black
dimensionTitleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
dimensionTitleLabel.textAlignment = .left
dimensionTitleLabel.numberOfLines = 1
// Dimension Number Label
dimensionNumberLabel = UILabel()
dimensionNumberLabel.translatesAutoresizingMaskIntoConstraints = false
views["dimensionNumberLabel"] = dimensionNumberLabel
mainContainerView.addSubview(dimensionNumberLabel)
dimensionNumberLabel.text = String(format: "%d×%d", dimension, dimension)
dimensionNumberLabel.textColor = UIColor.black
dimensionNumberLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
dimensionNumberLabel.textAlignment = .center
dimensionNumberLabel.numberOfLines = 1
// Dimension Slider
dimensionSlider = BlackSlider()
dimensionSlider.translatesAutoresizingMaskIntoConstraints = false
views["dimensionSlider"] = dimensionSlider
mainContainerView.addSubview(dimensionSlider)
dimensionSlider.minimumValue = 2
dimensionSlider.maximumValue = 12
dimensionSlider.value = Float(dimension)
dimensionSlider.addTarget(self, action: #selector(dimensionSliderValueChanged(_:)), for: .valueChanged)
// aiAlgorithmTitleLabel
aiAlgorithmTitleLabel = UILabel()
aiAlgorithmTitleLabel.translatesAutoresizingMaskIntoConstraints = false
views["aiAlgorithmTitleLabel"] = aiAlgorithmTitleLabel
mainContainerView.addSubview(aiAlgorithmTitleLabel)
aiAlgorithmTitleLabel.text = "AI Algorithm:"
aiAlgorithmTitleLabel.textColor = UIColor.black
aiAlgorithmTitleLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 20)
aiAlgorithmTitleLabel.textAlignment = .left
aiAlgorithmTitleLabel.numberOfLines = 1
// aiAlgorithmTableView
aiAlgorithmTableView = UITableView()
aiAlgorithmTableView.translatesAutoresizingMaskIntoConstraints = false
views["aiAlgorithmTableView"] = aiAlgorithmTableView
mainContainerView.addSubview(aiAlgorithmTableView)
setupTableView()
// Save button
saveButton = BlackBorderButton()
saveButton.translatesAutoresizingMaskIntoConstraints = false
saveButton.title = "Save"
saveButton.addTarget(self, action: #selector(saveButtonTapped(_:)), for: .touchUpInside)
views["saveButton"] = saveButton
view.addSubview(saveButton)
// Cancel button
cancelButton = BlackBorderButton()
cancelButton.translatesAutoresizingMaskIntoConstraints = false
cancelButton.title = "Cancel"
cancelButton.addTarget(self, action: #selector(cancelButtonTapped(_:)), for: .touchUpInside)
views["cancelButton"] = cancelButton
view.addSubview(cancelButton)
// Auto Layout
// H:
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[mainContainerView]|", options: [], metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[animationDurationTitleLabel]-3-[animationDurationNumberLabel]-2-[animationDurationUnitLabel]-(>=12)-|", options: .alignAllLastBaseline, metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-32-[animationDurationSlider]-32-|", options: [], metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[dimensionTitleLabel]-3-[dimensionNumberLabel]-(>=12)-|", options: .alignAllLastBaseline, metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-32-[dimensionSlider]-32-|", options: [], metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-12-[aiAlgorithmTitleLabel]", options: [], metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-24-[aiAlgorithmTableView]-24-|", options: [], metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[saveButton]-(-5)-[cancelButton(==saveButton)]|", options: [], metrics: metrics, views: views))
// V:
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mainContainerView][saveButton(50)]|", options: [], metrics: metrics, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[mainContainerView][cancelButton]|", options: [], metrics: metrics, views: views))
mainContainerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-10-[animationDurationTitleLabel]-10-[animationDurationSlider]-10-[dimensionTitleLabel]-10-[dimensionSlider]-10-[aiAlgorithmTitleLabel]-10-[aiAlgorithmTableView]|", options: [], metrics: metrics, views: views))
}
@objc func animationDurationSliderValueChanged(_ sender: UISlider) {
animationDurationNumberLabel.text = String(format: "%0.2f", sender.value)
}
@objc func dimensionSliderValueChanged(_ sender: UISlider) {
dimension = Int(floor(sender.value))
dimensionNumberLabel.text = String(format: "%d×%d", dimension, dimension)
}
@objc func saveButtonTapped(_: UIButton) {
Analytics.logEvent("save_settings", parameters: nil)
log.debug()
sharedAnimationDuration = TimeInterval(animationDurationSlider.value)
mainViewController.aiSelectedChoiceIndex = aiAlgorithmTableView.indexPathForSelectedRow!.row
mainViewController.dimension = dimension
saveClosure?()
dismissClosure?()
dismiss(animated: true, completion: nil)
}
@objc func cancelButtonTapped(_: UIButton) {
Analytics.logEvent("cancel_settings", parameters: nil)
log.debug()
cancelClosure?()
dismissClosure?()
dismiss(animated: true, completion: nil)
}
}
extension SettingViewController: UITableViewDataSource, UITableViewDelegate {
func setupTableView() {
aiAlgorithmTableView.backgroundColor = UIColor.clear
aiAlgorithmTableView.separatorStyle = .none
aiAlgorithmTableView.allowsMultipleSelection = false
aiAlgorithmTableView.register(AIAlgorithmCell.self, forCellReuseIdentifier: kAIAlgorithmCellIdentifier)
aiAlgorithmTableView.dataSource = self
aiAlgorithmTableView.delegate = self
}
func numberOfSections(in _: UITableView) -> Int {
return 1
}
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return mainViewController.aiChoices.count
}
func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat {
return kTableViewRowHeight
}
func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
return kTableViewRowHeight
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kAIAlgorithmCellIdentifier) as! AIAlgorithmCell
// Configuration
let aiTuple = mainViewController.aiChoices[indexPath.row]!
cell.titleLabel.text = aiTuple.description
return cell
}
}
| gpl-2.0 | 3b487098ba8721632dcddd253f51f947 | 45.656863 | 300 | 0.781327 | 5.516615 | false | false | false | false |
acidstudios/WorldCupSwift | WorldCup/Classes/TodayMatches/ACDTodayGamesTableViewController.swift | 1 | 2665 | //
// ACDTodayGamesTableViewController.swift
// WorldCup
//
// Created by Acid Studios on 20/06/14.
// Copyright (c) 2014 Acid Studios. All rights reserved.
//
import UIKit
class ACDTodayGamesTableViewController: UITableViewController {
var today: MatchModel[] = Array()
init(style: UITableViewStyle) {
super.init(style: style)
// Custom initialization
}
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
var request = NSURLRequest(URL: NSURL(string: "http://worldcup.sfg.io/matches/today"))
var session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as AnyObject[]
if(json.count > 0) {
var matches: MatchModel[] = json.map {
var model: MatchModel = MatchModel(dict: $0 as NSDictionary)
return model
}
self.today = matches
self.tableView.reloadData()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}).resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
return 1
}
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return self.today.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("TodayMatchCell", forIndexPath: indexPath) as UITableViewCell
var match = self.today[indexPath.row]
cell.textLabel.text = "\(match.home_team.country) V.S \(match.away_team.country)"
cell.detailTextLabel.text = "Stadium: \(match.location)"
if(match.status == "completed") {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
}
return cell;
}
}
| mit | ed2cad19e911ca39aa74b1feec8821b5 | 33.166667 | 143 | 0.633396 | 5.266798 | false | false | false | false |
ldjhust/BeautifulPhotos-Swift2.0 | BeautifulPhotos(Swift2.0)/ListPhotos/Views/MyCollectionHeaderView.swift | 1 | 800 | //
// MyCollectionHeaderView.swift
// BeautifulPhotos(Swift2.0)
//
// Created by ldjhust on 15/9/19.
// Copyright © 2015年 example. All rights reserved.
//
import UIKit
class MyCollectionHeaderView: UICollectionReusableView {
var backgroundImageView: UIImageView!
// MARK: - Initializer
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 5
self.layer.masksToBounds = true
self.backgroundImageView = UIImageView()
self.backgroundImageView.frame.size = self.frame.size
self.backgroundImageView.center = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
self.addSubview(self.backgroundImageView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | aebca1c19767155c3b0fab9e020ac9f9 | 21.771429 | 102 | 0.698871 | 4.025253 | false | false | false | false |
eebean2/DevTools | DevTools/Classes/DevUser.swift | 1 | 4527 | //
// DevUser.swift
// Pods
//
// Created by Erik Bean on 7/24/17.
//
//
import Foundation
/// A Base User Profile
public class DevUser: NSObject, Comparable {
/// The current User
static public let current = DevUser()
private override init() {}
/// The current user's username
public var username: String = ""
/// The users saved data
public var userData: [String: Any]!
/// Set the users username
///
/// - Parameters:
/// - username: The username of the user
public func set(username: String) {
self.username = username
}
/// Returns a generic user profile with the set username
///
/// - Parameters:
/// - username: The username of the generic user
public static func generic(username: String) -> DevUser {
let user = DevUser()
user.username = username
return user
}
/// Get a generic user profile with the username "Unknown"
public static var unknown: DevUser {
let user = DevUser()
user.username = "Unknown"
return user
}
/// Add data to the users saved data
///
/// - Parameters:
/// - key: The key the data will be saved under
/// - data: The data to be saved
/// - warning: Throws an error if the key is already present
public func addData(key: String, data: Any) throws {
if userData.keys.contains(key) {
throw NSError(domain: "DevUserError", code: 100, userInfo: [NSLocalizedDescriptionKey: "Cannot add user data, key already present."])
} else {
userData[key] = data
}
}
/// Update an object on the users data list
///
/// - Parameters:
/// - key: The key the data will be updated for
/// - data: The data to be updated
/// - warning: Throws an error if the key is not present
public func updateData(key: String, data: Any) throws {
if userData.keys.contains(key) {
userData[key] = data
} else {
throw NSError(domain: "DevUserError", code: 101, userInfo: [NSLocalizedDescriptionKey: "Cannot update user data, key not present."])
}
}
/// Remove an object on the users data list
///
/// - Parameters:
/// - key: The key the data will be removed
/// - warning: Throws an error if the key is not present
public func removeData(key: String) throws {
if userData.keys.contains(key) {
userData.removeValue(forKey: key)
} else {
throw NSError(domain: "DevUserError", code: 102, userInfo: [NSLocalizedDescriptionKey: "Cannot remove user data, key not present."])
}
}
/// Returns a Boolean value indicating whether the username of the first
/// profile is less than that of the second profile.
///
/// This function is the only requirement of the `Comparable` protocol. The
/// remainder of the relational operator functions are implemented by the
/// standard library for any type that conforms to `Comparable`.
///
/// - Parameters:
/// - lhs: A DTUser profile to compare.
/// - rhs: Another DTUser profile to compare.
public static func <(lhs: DevUser, rhs: DevUser) -> Bool {
return lhs.username < rhs.username
}
/// Checks if two profiles are the same
///
/// - Parameters:
/// - lhs: A DTUser profile to compare.
/// - rhs: Another DTUser profile to compare.
public static func ==(lhs: DevUser, rhs: DevUser) -> Bool {
return lhs.username == rhs.username
}
}
/// Email Address preset for DevUser Userdata
public let userEmailAddress: String = "Email"
/// Authentication Token preset for DevUser Userdata
public let userToken: String = "Authentication Token"
/// First Name preset for DevUser Userdata
public let userFirstName: String = "First Name"
/// Last Name preset for DevUser Userdata
public let userLastName: String = "Last Name"
/// Full Name preset for DevUser Userdata
public let userFullName: String = "Full Name"
/// Phone Number preset for DevUser Userdata
public let userPhoneNumber: String = "Phone Number"
/// Profile Picture preset for DevUser Userdata
public let userProfilePicture: String = "Profile Picture"
/// Date of Birth preset for DevUser Userdata
public let userDateOfBirth: String = "Date of Birth"
/// Age preset for DevUser Userdata
public let userAge: String = "Age"
/// Gender preset for DevUser Userdata
public let userGender: String = "Gender"
| mit | 2e267d6d01facb420eb854ebbcb4fe5c | 33.557252 | 145 | 0.636846 | 4.382381 | false | false | false | false |
ddddxxx/LyricsX | LyricsX/View/KaraokeLyricsView.swift | 2 | 7439 | //
// KaraokeLyricsView.swift
// LyricsX - https://github.com/ddddxxx/LyricsX
//
// 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 https://mozilla.org/MPL/2.0/.
//
import Cocoa
import SnapKit
class KaraokeLyricsView: NSView {
private let backgroundView: NSView
private let stackView: NSStackView
@objc dynamic var isVertical = false {
didSet {
stackView.orientation = isVertical ? .horizontal : .vertical
(isVertical ? displayLine2 : displayLine1).map { stackView.insertArrangedSubview($0, at: 0) }
updateFontSize()
}
}
@objc dynamic var drawFurigana = false
@objc dynamic var font = NSFont.labelFont(ofSize: 24) { didSet { updateFontSize() } }
@objc dynamic var textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
@objc dynamic var shadowColor = #colorLiteral(red: 0, green: 1, blue: 0.8333333333, alpha: 1)
@objc dynamic var progressColor = #colorLiteral(red: 0, green: 1, blue: 0.8333333333, alpha: 1)
@objc dynamic var backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.6018835616) {
didSet {
backgroundView.layer?.backgroundColor = backgroundColor.cgColor
}
}
@objc dynamic var shouldHideWithMouse = true {
didSet {
updateTrackingAreas()
}
}
var displayLine1: KaraokeLabel?
var displayLine2: KaraokeLabel?
override init(frame frameRect: NSRect) {
stackView = NSStackView(frame: frameRect)
stackView.orientation = .vertical
stackView.autoresizingMask = [.width, .height]
backgroundView = NSView() //NSVisualEffectView(frame: frameRect)
// backgroundView.material = .dark
// backgroundView.state = .active
backgroundView.autoresizingMask = [.width, .height]
backgroundView.wantsLayer = true
super.init(frame: frameRect)
wantsLayer = true
addSubview(backgroundView)
backgroundView.addSubview(stackView)
backgroundView.layer?.cornerRadius = 12
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateFontSize() {
var insetX = font.pointSize
var insetY = insetX / 3
if isVertical {
(insetX, insetY) = (insetY, insetX)
}
stackView.snp.remakeConstraints {
$0.edges.equalToSuperview().inset(NSEdgeInsets(top: insetY, left: insetX, bottom: insetY, right: insetX))
}
stackView.spacing = font.pointSize / 3
backgroundView.layer?.cornerRadius = font.pointSize / 2
// cornerRadius = font.pointSize / 2
}
private func lyricsLabel(_ content: String) -> KaraokeLabel {
if let view = stackView.subviews.lazy.compactMap({ $0 as? KaraokeLabel }).first(where: { !stackView.arrangedSubviews.contains($0) }) {
view.alphaValue = 0
view.stringValue = content
view.removeProgressAnimation()
view.removeFromSuperview()
return view
}
return KaraokeLabel(labelWithString: content).then {
$0.bind(\.font, to: self, withKeyPath: \.font)
$0.bind(\.textColor, to: self, withKeyPath: \.textColor)
$0.bind(\.progressColor, to: self, withKeyPath: \.progressColor)
$0.bind(\._shadowColor, to: self, withKeyPath: \.shadowColor)
$0.bind(\.isVertical, to: self, withKeyPath: \.isVertical)
$0.bind(\.drawFurigana, to: self, withKeyPath: \.drawFurigana)
$0.alphaValue = 0
}
}
func displayLrc(_ firstLine: String, secondLine: String = "") {
var toBeHide = stackView.arrangedSubviews.compactMap { $0 as? KaraokeLabel }
var toBeShow: [NSTextField] = []
var shouldHideAll = false
let index = isVertical ? 0 : 1
if firstLine.trimmingCharacters(in: .whitespaces).isEmpty {
displayLine1 = nil
shouldHideAll = true
} else if toBeHide.count == 2, toBeHide[index].stringValue == firstLine {
displayLine1 = toBeHide[index]
toBeHide.remove(at: index)
} else {
let label = lyricsLabel(firstLine)
displayLine1 = label
toBeShow.append(label)
}
if !secondLine.trimmingCharacters(in: .whitespaces).isEmpty {
let label = lyricsLabel(secondLine)
displayLine2 = label
toBeShow.append(label)
} else {
displayLine2 = nil
}
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.25
context.allowsImplicitAnimation = true
context.timingFunction = .swiftOut
toBeHide.forEach {
stackView.removeArrangedSubview($0)
$0.isHidden = true
$0.alphaValue = 0
$0.removeProgressAnimation()
}
toBeShow.forEach {
if isVertical {
stackView.insertArrangedSubview($0, at: 0)
} else {
stackView.addArrangedSubview($0)
}
$0.isHidden = false
$0.alphaValue = 1
}
isHidden = shouldHideAll
layoutSubtreeIfNeeded()
}, completionHandler: {
self.mouseTest()
})
}
// MARK: - Event
private var trackingArea: NSTrackingArea?
override func updateTrackingAreas() {
super.updateTrackingAreas()
trackingArea.map(removeTrackingArea)
if shouldHideWithMouse {
let trackingOptions: NSTrackingArea.Options = [.mouseEnteredAndExited, .activeAlways, .assumeInside, .enabledDuringMouseDrag]
trackingArea = NSTrackingArea(rect: bounds, options: trackingOptions, owner: self)
trackingArea.map(addTrackingArea)
}
mouseTest()
}
private func mouseTest() {
if shouldHideWithMouse,
let point = NSEvent.mouseLocation(in: self),
bounds.contains(point) {
animator().alphaValue = 0
} else {
animator().alphaValue = 1
}
}
override func mouseEntered(with event: NSEvent) {
animator().alphaValue = 0
}
override func mouseExited(with event: NSEvent) {
animator().alphaValue = 1
}
}
extension NSEvent {
class func mouseLocation(in view: NSView) -> NSPoint? {
guard let window = view.window else { return nil }
let windowLocation = window.convertFromScreen(NSRect(origin: NSEvent.mouseLocation, size: .zero)).origin
return view.convert(windowLocation, from: nil)
}
}
extension NSTextField {
// swiftlint:disable:next identifier_name
@objc dynamic var _shadowColor: NSColor? {
get {
return shadow?.shadowColor
}
set {
shadow = newValue.map { color in
NSShadow().then {
$0.shadowBlurRadius = 3
$0.shadowColor = color
$0.shadowOffset = .zero
}
}
}
}
}
| mpl-2.0 | 7f8bd7581f78a4d867fec2eb495d2830 | 33.924883 | 142 | 0.588789 | 4.787001 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/course-schedule-ii.swift | 2 | 1155 | /**
* https://leetcode.com/problems/course-schedule-ii/
*
*
*/
// Date: Mon Jun 8 16:03:47 PDT 2020
class Solution {
/// Topological sort.
func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
var graph: [[Int]] = Array(repeating: [], count: numCourses)
var degree = Array(repeating: 0, count: numCourses)
for item in prerequisites {
graph[item[1]].append(item[0])
degree[item[0]] += 1
}
var visitedQ: [Int] = []
for index in 0 ..< numCourses {
if degree[index] == 0 {
visitedQ.append(index)
}
}
var children: [[Int]] = Array(repeating: [], count: numCourses)
var path: [Int] = []
while visitedQ.isEmpty == false {
let preCourse = visitedQ.removeFirst()
path.append(preCourse)
for course in graph[preCourse] {
degree[course] -= 1
if degree[course] == 0 {
visitedQ.append(course)
}
}
}
return path.count == numCourses ? path : []
}
}
| mit | 42ff80f39555b1adf389589c29e7b43d | 30.216216 | 74 | 0.492641 | 4.038462 | false | false | false | false |
hgwhittle/HGWActivityButton | Demo/ViewController.swift | 1 | 2751 |
//
// ViewController.swift
// Demo
//
// Created by Hunter Whittle on 6/25/14.
// Copyright (c) 2014 Hunter Whittle. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var activityButton: HGWActivityButton
var activityButton2: HGWActivityButton
var activityButton3: HGWActivityButton
required init?(coder aDecoder: NSCoder) {
self.activityButton = HGWActivityButton(frame: CGRectZero)
self.activityButton2 = HGWActivityButton(frame: CGRectZero)
self.activityButton3 = HGWActivityButton(frame: CGRectZero)
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let middleMain: CGFloat = self.view.bounds.size.width / 2
var middleButton: CGFloat = 100.0 / 2
activityButton = HGWActivityButton(frame: CGRect(x: middleMain - middleButton, y: 60, width: 100, height: 100))
activityButton.backgroundColor = UIColor.blueColor()
activityButton.titleLabel.text = "Process"
activityButton.activityTitle = "Processing"
activityButton.rotatorColor = UIColor.blackColor()
activityButton.rotatorSize = 12.0
activityButton.rotatorSpeed = 8.0
view.addSubview(activityButton)
middleButton = 76.0 / 2
activityButton2 = HGWActivityButton(frame: CGRect(x: middleMain - middleButton, y: 227, width: 76, height: 76))
activityButton2.backgroundColor = UIColor.orangeColor()
activityButton2.titleLabel.text = "Load"
activityButton2.activityTitle = "Loading"
activityButton2.rotatorColor = UIColor.darkGrayColor()
activityButton2.rotatorSize = 12.0
activityButton2.rotatorSpeed = 8.0
activityButton2.rotatorPadding = 15.0
view.addSubview(activityButton2)
middleButton = 150.0 / 2
activityButton3 = HGWActivityButton(frame: CGRect(x: middleMain - middleButton, y: 375, width: 150, height: 150))
activityButton3.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
activityButton3.titleLabel.text = "Download";
activityButton3.activityTitle = "Downloading"
activityButton3.rotatorColor = UIColor.blueColor()
activityButton3.rotatorSize = 16.0
activityButton3.rotatorSpeed = 8.0
activityButton3.rotatorPadding = -7.0
view.addSubview(activityButton3)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
activityButton.stopActivity()
activityButton2.stopActivity()
activityButton3.stopActivity()
}
}
| mit | bd9bdce7590e7e7250c1263e872ef467 | 37.746479 | 121 | 0.677935 | 4.212864 | false | false | false | false |
gcba/hermes | sdks/swift/Pods/SwifterSwift/Sources/Extensions/Foundation/ArrayExtensions.swift | 1 | 19189 | //
// ArrayExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
// MARK: - Methods (Integer)
public extension Array where Element: Integer {
/// SwifterSwift: Sum of all elements in array.
///
/// [1, 2, 3, 4, 5].sum -> 15
///
/// - Returns: sum of the array's elements.
public func sum() -> Element {
var total: Element = 0
forEach { total += $0 }
return total
}
}
// MARK: - Methods (FloatingPoint)
public extension Array where Element: FloatingPoint {
/// SwifterSwift: Average of all elements in array.
///
/// [1.2, 2.3, 4.5, 3.4, 4.5].average = 3.18
///
/// - Returns: average of the array's elements.
public func average() -> Element {
guard isEmpty == false else { return 0 }
var total: Element = 0
forEach { total += $0 }
return total / Element(count)
}
/// SwifterSwift: Sum of all elements in array.
///
/// [1.2, 2.3, 4.5, 3.4, 4.5].sum -> 15.9
///
/// - Returns: sum of the array's elements.
public func sum() -> Element {
var total: Element = 0
forEach { total += $0 }
return total
}
}
// MARK: - Methods
public extension Array {
/// SwifterSwift: Element at the given index if it exists.
///
/// [1, 2, 3, 4, 5].item(at: 2) -> 3
/// [1.2, 2.3, 4.5, 3.4, 4.5].item(at: 3) -> 3.4
/// ["h", "e", "l", "l", "o"].item(at: 10) -> nil
///
/// - Parameter index: index of element.
/// - Returns: optional element (if exists).
public func item(at index: Int) -> Element? {
guard startIndex..<endIndex ~= index else { return nil }
return self[index]
}
/// SwifterSwift: Remove last element from array and return it.
///
/// [1, 2, 3, 4, 5].pop() // returns 5 and remove it from the array.
/// [].pop() // returns nil since the array is empty.
///
/// - Returns: last element in array (if applicable).
@discardableResult public mutating func pop() -> Element? {
return popLast()
}
/// SwifterSwift: Insert an element at the beginning of array.
///
/// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5]
/// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
public mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// SwifterSwift: Insert an element to the end of array.
///
/// [1, 2, 3, 4].push(5) -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l"].push("o") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
public mutating func push(_ newElement: Element) {
append(newElement)
}
/// SwifterSwift: Safely Swap values at index positions.
///
/// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func safeSwap(from index: Int, to otherIndex: Int) {
guard index != otherIndex,
startIndex..<endIndex ~= index,
startIndex..<endIndex ~= otherIndex else { return }
Swift.swap(&self[index], &self[otherIndex])
}
/// SwifterSwift: Swap values at index positions.
///
/// [1, 2, 3, 4, 5].swap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].swap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func swap(from index: Int, to otherIndex: Int) {
Swift.swap(&self[index], &self[otherIndex])
}
/// SwifterSwift: Get first index where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 6].firstIndex { $0 % 2 == 0 } -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: first index where the specified condition evaluates to true. (optional)
public func firstIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: Get last index where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 8].lastIndex { $0 % 2 == 0 } -> 6
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: last index where the specified condition evaluates to true. (optional)
public func lastIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated().reversed() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: Get all indices where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 8].indices(where: { $0 == 1 }) -> [0, 2, 5]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: all indices where the specified condition evaluates to true. (optional)
public func indices(where condition: (Element) throws -> Bool) rethrows -> [Int]? {
var indicies: [Int] = []
for (index, value) in lazy.enumerated() {
if try condition(value) { indicies.append(index) }
}
return indicies.isEmpty ? nil : indicies
}
/// SwifterSwift: Check if all elements in array match a conditon.
///
/// [2, 2, 4].all(matching: {$0 % 2 == 0}) -> true
/// [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -> false
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when all elements in the array match the specified condition.
public func all(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// SwifterSwift: Check if no elements in array match a conditon.
///
/// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
public func none(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// SwifterSwift: Get last element that satisfies a conditon.
///
/// [2, 2, 4, 7].last(where: {$0 % 2 == 0}) -> 4
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: the last element in the array matching the specified condition. (optional)
public func last(where condition: (Element) throws -> Bool) rethrows -> Element? {
for element in reversed() {
if try condition(element) { return element }
}
return nil
}
/// SwifterSwift: Filter elements based on a rejection condition.
///
/// [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -> [7]
///
/// - Parameter condition: to evaluate the exclusion of an element from the array.
/// - Returns: the array with rejected values filtered from it.
public func reject(where condition: (Element) throws -> Bool) rethrows -> [Element] {
return try filter { return try !condition($0) }
}
/// SwifterSwift: Get element count based on condition.
///
/// [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: number of times the condition evaluated to true.
public func count(where condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try condition(element) { count += 1 }
}
return count
}
/// SwifterSwift: Iterate over a collection in reverse order. (right to left)
///
/// [0, 2, 4, 7].forEachReversed({ print($0)}) -> //Order of print: 7,4,2,0
///
/// - Parameter body: a closure that takes an element of the array as a parameter.
public func forEachReversed(_ body: (Element) throws -> Void) rethrows {
try reversed().forEach { try body($0) }
}
/// SwifterSwift: Calls given closure with each element where condition is true.
///
/// [0, 2, 4, 7].forEach( where: {$0 % 2 == 0}, body: { print($0)}) -> //print: 0, 2, 4
///
/// - Parameters:
/// - condition: condition to evaluate each element against.
/// - body: a closure that takes an element of the array as a parameter.
public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
for element in self where try condition(element) {
try body(element)
}
}
/// SwifterSwift: Reduces an array while returning each interim combination.
///
/// [1, 2, 3].accumulate(initial: 0, next: +) -> [1, 3, 6]
///
/// - Parameters:
/// - initial: initial value.
/// - next: closure that combines the accumulating value and next element of the array.
/// - Returns: an array of the final accumulated value and each interim combination.
public func accumulate<U>(initial: U, next: (U, Element) throws -> U) rethrows -> [U] {
var runningTotal = initial
return try map { element in
runningTotal = try next(runningTotal, element)
return runningTotal
}
}
/// SwifterSwift: Filtered and map in a single operation.
///
/// [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -> ["2", "4"]
///
/// - Parameters:
/// - isIncluded: condition of inclusion to evaluate each element against.
/// - transform: transform element function to evaluate every element.
/// - Returns: Return an filtered and mapped array.
public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
return try flatMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
}
/// SwifterSwift: Keep elements of Array while condition is true.
///
/// [0, 2, 4, 7].keep( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
public mutating func keep(while condition: (Element) throws -> Bool) rethrows {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
self = Array(self[startIndex..<index])
break
}
}
}
/// SwifterSwift: Take element of Array while condition is true.
///
/// [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: All elements up until condition evaluates to false.
public func take(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[startIndex..<index])
}
}
return self
}
/// SwifterSwift: Skip elements of Array while condition is true.
///
/// [0, 2, 4, 7, 6, 8].skip( where: {$0 % 2 == 0}) -> [6, 8]
///
/// - Parameter condition: condition to eveluate each element against.
/// - Returns: All elements after the condition evaluates to false.
public func skip(while condition: (Element) throws-> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[index..<endIndex])
}
}
return [Element]()
}
/// SwifterSwift: Calls given closure with an array of size of the parameter slice where condition is true.
///
/// [0, 2, 4, 7].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7]
/// [0, 2, 4, 7, 6].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7], [6]
///
/// - Parameters:
/// - slice: size of array in each interation.
/// - body: a closure that takes an array of slice size as a parameter.
public func forEach(slice: Int, body: ([Element]) throws -> Void) rethrows {
guard slice > 0, !isEmpty else { return }
var value : Int = 0
while value < count {
try body(Array(self[Swift.max(value,startIndex)..<Swift.min(value + slice, endIndex)]))
value += slice
}
}
/// SwifterSwift: Returns an array of slices of length "size" from the array. If array can't be split evenly, the final slice will be the remaining elements.
///
/// [0, 2, 4, 7].group(by: 2) -> [[0, 2], [4, 7]]
/// [0, 2, 4, 7, 6].group(by: 2) -> [[0, 2], [4, 7], [6]]
///
/// - Parameters:
/// - size: The size of the slices to be returned.
public func group(by size: Int) -> [[Element]]? {
//Inspired by: https://lodash.com/docs/4.17.4#chunk
guard size > 0, !isEmpty else { return nil }
var value : Int = 0
var slices : [[Element]] = []
while value < count {
slices.append(Array(self[Swift.max(value,startIndex)..<Swift.min(value + size, endIndex)]))
value += size
}
return slices
}
/// SwifterSwift: Group the elements of the array in a dictionary.
///
/// [0, 2, 5, 4, 7].groupByKey { $0%2 ? "evens" : "odds" } -> [ "evens" : [0, 2, 4], "odds" : [5, 7] ]
///
/// - Parameter getKey: Clousure to define the key for each element.
/// - Returns: A dictionary with values grouped with keys.
public func groupByKey<K: Hashable>(keyForValue: (_ element: Element) throws -> K) rethrows -> [K: [Element]] {
var group : [K: [Element]] = [:]
for value in self {
let key = try keyForValue(value)
group[key] = (group[key] ?? []) + [value]
}
return group
}
/// SwifterSwift: Returns a new rotated array by the given places.
///
/// [1, 2, 3, 4].rotated(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotated(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
/// - Returns: The new rotated array
public func rotated(by places: Int) -> [Element] {
//Inspired by: https://ruby-doc.org/core-2.2.0/Array.html#method-i-rotate
guard places != 0 && places < count else {
return self
}
var array : [Element] = self
if places > 0 {
let range = (array.count - places)..<array.endIndex
let slice = array[range]
array.removeSubrange(range)
array.insert(contentsOf: slice, at: 0)
} else {
let range = array.startIndex..<(places * -1)
let slice = array[range]
array.removeSubrange(range)
array.append(contentsOf: slice)
}
return array
}
/// SwifterSwift: Rotate the array by the given places.
///
/// [1, 2, 3, 4].rotate(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotate(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array should be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
public mutating func rotate(by places: Int) {
self = rotated(by: places)
}
}
// MARK: - Methods (Equatable)
public extension Array where Element: Equatable {
/// SwifterSwift: Shuffle array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffle() // shuffles array
///
public mutating func shuffle() {
//http://stackoverflow.com/questions/37843647/shuffle-array-swift-3
guard count > 1 else { return }
for index in startIndex..<endIndex - 1 {
let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
if index != randomIndex { Swift.swap(&self[index], &self[randomIndex]) }
}
}
/// SwifterSwift: Shuffled version of array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffled // return a shuffled version from given array e.g. [2, 4, 1, 3, 5].
///
/// - Returns: the array with its elements shuffled.
public func shuffled() -> [Element] {
var array = self
array.shuffle()
return array
}
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { // elements array is empty
return true
}
var found = true
for element in elements {
if !contains(element) {
found = false
}
}
return found
}
/// SwifterSwift: All indexes of specified item.
///
/// [1, 2, 2, 3, 4, 2, 5].indexes(of 2) -> [1, 2, 5]
/// [1.2, 2.3, 4.5, 3.4, 4.5].indexes(of 2.3) -> [1]
/// ["h", "e", "l", "l", "o"].indexes(of "l") -> [2, 3]
///
/// - Parameter item: item to check.
/// - Returns: an array with all indexes of the given item.
public func indexes(of item: Element) -> [Int] {
var indexes: [Int] = []
for index in startIndex..<endIndex {
if self[index] == item {
indexes.append(index)
}
}
return indexes
}
/// SwifterSwift: Remove all instances of an item from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
public mutating func removeAll(_ item: Element) {
self = filter { $0 != item }
}
/// SwifterSwift: Remove all instances contained in items parameter from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4]
/// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"]
///
/// - Parameter items: items to remove.
public mutating func removeAll(_ items: [Element]) {
guard !items.isEmpty else { return }
self = filter { !items.contains($0) }
}
/// SwifterSwift: Remove all duplicate elements from Array.
///
/// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"]
///
public mutating func removeDuplicates() {
// Thanks to https://github.com/sairamkotha for improving the method
self = reduce([]){ $0.contains($1) ? $0 : $0 + [$1] }
}
/// SwifterSwift: Return array with all duplicate elements removed.
///
/// [1, 2, 2, 3, 4, 5, 5].duplicatesRemoved() -> [ 2, 5]
/// ["h", "e", "l", "l", "o"]. duplicatesRemoved() -> ["l"]
///
/// - Returns: an array of unique elements.
public func duplicatesRemoved() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the property
return reduce([]){ ($0 as [Element]).contains($1) ? $0 : $0 + [$1] }
}
/// SwifterSwift: First index of a given item in an array.
///
/// [1, 2, 2, 3, 4, 2, 5].firstIndex(of 2) -> 1
/// [1.2, 2.3, 4.5, 3.4, 4.5].firstIndex(of 6.5) -> nil
/// ["h", "e", "l", "l", "o"].firstIndex(of "l") -> 2
///
/// - Parameter item: item to check.
/// - Returns: first index of item in array (if exists).
public func firstIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated() {
if value == item { return index }
}
return nil
}
/// SwifterSwift: Last index of element in array.
///
/// [1, 2, 2, 3, 4, 2, 5].lastIndex(of 2) -> 5
/// [1.2, 2.3, 4.5, 3.4, 4.5].lastIndex(of 6.5) -> nil
/// ["h", "e", "l", "l", "o"].lastIndex(of "l") -> 3
///
/// - Parameter item: item to check.
/// - Returns: last index of item in array (if exists).
public func lastIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated().reversed() {
if value == item { return index }
}
return nil
}
}
| mit | fbae126937cbfaf4e13927432111cc3c | 33.122995 | 173 | 0.603928 | 3.032314 | false | false | false | false |
gilserrap/Bigotes | Pods/GRMustache.swift/Mustache/Parsing/ExpressionParser.swift | 2 | 18249 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
final class ExpressionParser {
func parse(string: String, inout empty outEmpty: Bool) throws -> Expression {
enum State {
// error
case Error(String)
// Any expression can start
case WaitingForAnyExpression
// Expression has started with a dot
case LeadingDot
// Expression has started with an identifier
case Identifier(identifierStart: String.Index)
// Parsing a scoping identifier
case ScopingIdentifier(identifierStart: String.Index, baseExpression: Expression)
// Waiting for a scoping identifier
case WaitingForScopingIdentifier(baseExpression: Expression)
// Parsed an expression
case DoneExpression(expression: Expression)
// Parsed white space after an expression
case DoneExpressionPlusWhiteSpace(expression: Expression)
}
var state: State = .WaitingForAnyExpression
var filterExpressionStack: [Expression] = []
var i = string.startIndex
let end = string.endIndex
stringLoop: while i < end {
let c = string[i]
switch state {
case .Error:
break stringLoop
case .WaitingForAnyExpression:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
state = .LeadingDot
case "(", ")", ",", "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
default:
state = .Identifier(identifierStart: i)
}
case .LeadingDot:
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .DoneExpressionPlusWhiteSpace(expression: Expression.ImplicitIterator)
case ".":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
case "(":
filterExpressionStack.append(Expression.ImplicitIterator)
state = .WaitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.Filter(filterExpression: filterExpression, argumentExpression: Expression.ImplicitIterator, partialApplication: false)
state = .DoneExpression(expression: expression)
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.Filter(filterExpression: filterExpression, argumentExpression: Expression.ImplicitIterator, partialApplication: true))
state = .WaitingForAnyExpression
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
default:
state = .ScopingIdentifier(identifierStart: i, baseExpression: Expression.ImplicitIterator)
}
case .Identifier(identifierStart: let identifierStart):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = string.substringWithRange(identifierStart..<i)
state = .DoneExpressionPlusWhiteSpace(expression: Expression.Identifier(identifier: identifier))
case ".":
let identifier = string.substringWithRange(identifierStart..<i)
state = .WaitingForScopingIdentifier(baseExpression: Expression.Identifier(identifier: identifier))
case "(":
let identifier = string.substringWithRange(identifierStart..<i)
filterExpressionStack.append(Expression.Identifier(identifier: identifier))
state = .WaitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substringWithRange(identifierStart..<i)
let expression = Expression.Filter(filterExpression: filterExpression, argumentExpression: Expression.Identifier(identifier: identifier), partialApplication: false)
state = .DoneExpression(expression: expression)
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substringWithRange(identifierStart..<i)
filterExpressionStack.append(Expression.Filter(filterExpression: filterExpression, argumentExpression: Expression.Identifier(identifier: identifier), partialApplication: true))
state = .WaitingForAnyExpression
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
default:
break
}
case .ScopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
let identifier = string.substringWithRange(identifierStart..<i)
let scopedExpression = Expression.Scoped(baseExpression: baseExpression, identifier: identifier)
state = .DoneExpressionPlusWhiteSpace(expression: scopedExpression)
case ".":
let identifier = string.substringWithRange(identifierStart..<i)
let scopedExpression = Expression.Scoped(baseExpression: baseExpression, identifier: identifier)
state = .WaitingForScopingIdentifier(baseExpression: scopedExpression)
case "(":
let identifier = string.substringWithRange(identifierStart..<i)
let scopedExpression = Expression.Scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(scopedExpression)
state = .WaitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substringWithRange(identifierStart..<i)
let scopedExpression = Expression.Scoped(baseExpression: baseExpression, identifier: identifier)
let expression = Expression.Filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: false)
state = .DoneExpression(expression: expression)
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let identifier = string.substringWithRange(identifierStart..<i)
let scopedExpression = Expression.Scoped(baseExpression: baseExpression, identifier: identifier)
filterExpressionStack.append(Expression.Filter(filterExpression: filterExpression, argumentExpression: scopedExpression, partialApplication: true))
state = .WaitingForAnyExpression
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
default:
break
}
case .WaitingForScopingIdentifier(let baseExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .Error("Unexpected white space character at index \(string.startIndex.distanceTo(i))")
case ".":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
case "(":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
case ")":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
case ",":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
case "{", "}", "&", "$", "#", "^", "/", "<", ">":
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
default:
state = .ScopingIdentifier(identifierStart: i, baseExpression: baseExpression)
}
case .DoneExpression(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
state = .DoneExpressionPlusWhiteSpace(expression: doneExpression)
case ".":
state = .WaitingForScopingIdentifier(baseExpression: doneExpression)
case "(":
filterExpressionStack.append(doneExpression)
state = .WaitingForAnyExpression
case ")":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.Filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .DoneExpression(expression: expression)
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case ",":
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.Filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .WaitingForAnyExpression
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
default:
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case .DoneExpressionPlusWhiteSpace(let doneExpression):
switch c {
case " ", "\r", "\n", "\r\n", "\t":
break
case ".":
// Prevent "a .b"
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
case "(":
// Accept "a (b)"
filterExpressionStack.append(doneExpression)
state = .WaitingForAnyExpression
case ")":
// Accept "a(b )"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
let expression = Expression.Filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: false)
state = .DoneExpression(expression: expression)
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
case ",":
// Accept "a(b ,c)"
if let filterExpression = filterExpressionStack.last {
filterExpressionStack.removeLast()
filterExpressionStack.append(Expression.Filter(filterExpression: filterExpression, argumentExpression: doneExpression, partialApplication: true))
state = .WaitingForAnyExpression
} else {
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
default:
state = .Error("Unexpected character `\(c)` at index \(string.startIndex.distanceTo(i))")
}
}
i = i.successor()
}
// Parsing done
enum FinalState {
case Error(String)
case Empty
case Valid(expression: Expression)
}
let finalState: FinalState
switch state {
case .WaitingForAnyExpression:
if filterExpressionStack.isEmpty {
finalState = .Empty
} else {
finalState = .Error("Missing `)` character at index \(string.startIndex.distanceTo(string.endIndex))")
}
case .LeadingDot:
if filterExpressionStack.isEmpty {
finalState = .Valid(expression: Expression.ImplicitIterator)
} else {
finalState = .Error("Missing `)` character at index \(string.startIndex.distanceTo(string.endIndex))")
}
case .Identifier(identifierStart: let identifierStart):
if filterExpressionStack.isEmpty {
let identifier = string.substringFromIndex(identifierStart)
finalState = .Valid(expression: Expression.Identifier(identifier: identifier))
} else {
finalState = .Error("Missing `)` character at index \(string.startIndex.distanceTo(string.endIndex))")
}
case .ScopingIdentifier(identifierStart: let identifierStart, baseExpression: let baseExpression):
if filterExpressionStack.isEmpty {
let identifier = string.substringFromIndex(identifierStart)
let scopedExpression = Expression.Scoped(baseExpression: baseExpression, identifier: identifier)
finalState = .Valid(expression: scopedExpression)
} else {
finalState = .Error("Missing `)` character at index \(string.startIndex.distanceTo(string.endIndex))")
}
case .WaitingForScopingIdentifier:
finalState = .Error("Missing identifier at index \(string.startIndex.distanceTo(string.endIndex))")
case .DoneExpression(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .Valid(expression: doneExpression)
} else {
finalState = .Error("Missing `)` character at index \(string.startIndex.distanceTo(string.endIndex))")
}
case .DoneExpressionPlusWhiteSpace(let doneExpression):
if filterExpressionStack.isEmpty {
finalState = .Valid(expression: doneExpression)
} else {
finalState = .Error("Missing `)` character at index \(string.startIndex.distanceTo(string.endIndex))")
}
case .Error(let message):
finalState = .Error(message)
}
// End
switch finalState {
case .Empty:
outEmpty = true
throw MustacheError(kind: .ParseError, message: "Missing expression")
case .Error(let description):
outEmpty = false
throw MustacheError(kind: .ParseError, message: "Invalid expression `\(string)`: \(description)")
case .Valid(expression: let expression):
return expression
}
}
}
| mit | eabd7927570c80530dc3197f86ed0e4e | 51.587896 | 200 | 0.550362 | 6.480114 | false | false | false | false |
benlangmuir/swift | test/Generics/simplify_concrete_substitutions.swift | 6 | 907 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s
// The rule
//
// [P:Y].[concrete: G<τ_0_0, τ_0_1> with <[P:Z1], [P:Z2]>] => [P:Y]
//
// overlaps with [P].[P:Y] => [P], which applies the adjustment prepending
// [P] to [P:Z1] and [P:Z2], respectively.
//
// This produces the rule
//
// [P:Y].[concrete: G<τ_0_0, τ_0_1> with <[P].[P:Z1], [P].[P:Z2]>] => [P:Y]
//
// When adding the rule, we have to simplify the concrete substitutions to
// reduce [P].[P:Z1] to [P:Z1] and [P].[P:Z2] to [P:Z2], respectively.
// CHECK-LABEL: simplify_concrete_substitutions.(file).P@
// CHECK-LABEL: Requirement signature: <Self where Self == Self.[P]X.[P]X, Self.[P]X : P, Self.[P]Y == G<Self.[P]Z1, Self.[P]Z2>>
protocol P {
associatedtype X : P where X.X == Self
associatedtype Y where Y == G<Z1, Z2>
associatedtype Z1
associatedtype Z2
}
struct G<T, U> {}
| apache-2.0 | 205b2533c24c62db79a4e0eba9845762 | 32.444444 | 129 | 0.610188 | 2.565341 | false | false | false | false |
somegeekintn/SimDirs | SimDirs/Presentation/SourceState.swift | 1 | 7992 | //
// SourceState.swift
// SimDirs
//
// Created by Casey Fleser on 6/21/22.
//
import Foundation
import Combine
class SourceState: ObservableObject {
typealias ProductFamily = SourceItemVal<SimProductFamily, DeviceType_DS>
typealias Platform = SourceItemVal<SimPlatform, Runtime_RT>
typealias DeviceType_DS = SourceItemVal<SimDeviceType, Runtime_DS>
typealias DeviceType_RT = SourceItemVal<SimDeviceType, Device>
typealias Runtime_DS = SourceItemVal<SimRuntime, Device>
typealias Runtime_RT = SourceItemVal<SimRuntime, DeviceType_RT>
typealias Device = SourceItemVal<SimDevice, App>
typealias App = SourceItemVal<SimApp, SourceItemNone>
enum Base: Identifiable {
case placeholder(id: UUID = UUID())
case device(id: UUID = UUID(), SourceItemVal<SourceItemDataNone, ProductFamily>)
case runtime(id: UUID = UUID(), SourceItemVal<SourceItemDataNone, Platform>)
var id : UUID {
switch self {
case let .placeholder(id): return id
case let .device(id, _): return id
case let .runtime(id, _): return id
}
}
}
enum Style: Int, CaseIterable, Identifiable {
case placeholder
case byDevice
case byRuntime
var id : Int { rawValue }
var title : String {
switch self {
case .placeholder: return "Placeholder"
case .byDevice: return "By Device"
case .byRuntime: return "By Runtime"
}
}
var visible : Bool {
switch self {
case .placeholder: return false
default: return true
}
}
}
@Published var style = Style.placeholder { didSet { rebuildBase() } }
@Published var filter = SourceFilter.restore() { didSet { applyFilter() } }
@Published var selection : UUID?
var model : SimModel
var base = Base.placeholder()
var deviceUpdates : Cancellable?
var filterApps : Bool {
get { filter.options.contains(.withApps) }
set { filter.options.booleanSet(newValue, options: .withApps) }
}
var filterRuntimes : Bool {
get { filter.options.contains(.runtimeInstalled) }
set { filter.options.booleanSet(newValue, options: .runtimeInstalled) }
}
init(model: SimModel) {
self.style = .byDevice
self.model = model
self.rebuildBase()
deviceUpdates = model.deviceUpdates.sink(receiveValue: applyDeviceUpdates)
}
func applyDeviceUpdates(_ updates: SimDevicesUpdates) {
switch base {
case .placeholder:
break
case let .device(_, item):
for prodFamily in item.children {
for devType in prodFamily.children {
for runtime in devType.children {
guard updates.runtime.identifier == runtime.data.identifier else { continue }
let devTypeDevices = updates.additions.filter { $0.isDeviceOfType(devType.data) }
runtime.children = runtime.children.filter { device in !updates.removals.contains { $0.udid == device.data.udid } }
runtime.children.append(contentsOf: devTypeDevices.map { device in
let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red)
return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc)
})
}
}
}
case let .runtime(_, item):
for platform in item.children {
for runtime in platform.children {
guard updates.runtime.identifier == runtime.data.identifier else { continue }
for devType in runtime.children {
let devTypeDevices = updates.additions.filter { $0.isDeviceOfType(devType.data) }
devType.children = devType.children.filter { device in !updates.removals.contains { $0.udid == device.data.udid } }
devType.children.append(contentsOf: devTypeDevices.map { device in
let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red)
return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc)
})
}
}
}
}
applyFilter()
}
func applyFilter() {
switch base {
case .placeholder: break
case let .device(_, item): item.applyFilter(filter)
case let .runtime(_, item): item.applyFilter(filter)
}
}
func rebuildBase() {
var baseID : UUID
// Preserve identifier if style is not changing
switch (style, base) {
case (.placeholder, let .placeholder(id)): baseID = id;
case (.byDevice, let .device(id, _)): baseID = id;
case (.byRuntime, let .runtime(id, _)): baseID = id;
default: baseID = UUID()
}
switch style {
case .placeholder: base = .placeholder(id: baseID)
case .byDevice: base = .device(id: baseID, SourceItemVal(data: .none, children: deviceStyleItems()))
case .byRuntime: base = .runtime(id: baseID, SourceItemVal(data: .none, children: runtimeStyleItems()))
}
applyFilter()
}
func baseFor(style: Style) -> Base {
switch style {
case .placeholder: return .placeholder()
case .byDevice: return .device(SourceItemVal(data: .none, children: deviceStyleItems()))
case .byRuntime: return .runtime(SourceItemVal(data: .none, children: runtimeStyleItems()))
}
}
func deviceStyleItems() -> [ProductFamily] {
SimProductFamily.presentation.map { family in
ProductFamily(data: family, children: model.deviceTypes.supporting(productFamily: family).map { devType in
DeviceType_DS(data: devType, children: model.runtimes.supporting(deviceType: devType).map { runtime in
Runtime_DS(data: runtime, children: runtime.devices.of(deviceType: devType).map { device in
let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red)
return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc)
})
})
})
}
}
func runtimeStyleItems() -> [Platform] {
SimPlatform.presentation.map { platform in
Platform(data: platform, children: model.runtimes.supporting(platform: platform).map { runtime in
Runtime_RT(data: runtime, children: model.deviceTypes.supporting(runtime: runtime).map { devType in
DeviceType_RT(data: devType, children: runtime.devices.of(deviceType: devType).map { device in
let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red)
return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc)
})
})
})
}
}
}
| mit | 0d440a4436c6c19db6e8b77f86ce0f7f | 40.842932 | 152 | 0.546922 | 4.762813 | false | false | false | false |
szk-atmosphere/URLEmbeddedView | URLEmbeddedView/Extension/MD5.swift | 1 | 10688 | //
// MD5.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 06/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
/*
* In this file, CommonCrypto is used to create md5 hash.
* CommonCrypto is created by Marcin Krzyżanowski.
* https://github.com/krzyzanowskim/CryptoSwift
* The original copyright is here.
*/
/*
* Copyright (C) 2014 Marcin Krzyżanowski [email protected]
* This software is provided 'as-is', without any express or implied warranty.
*
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* - The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment in the product documentation is required.
* - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
* - This notice may not be removed or altered from any source or binary distribution.
*/
import Foundation
extension String {
public func md5() -> String {
let md5 = MD5().calculate(for: self.utf8.lazy.map({ $0 as UInt8 }))
return md5.lazy.reduce("") {
var s = String($1, radix: 16)
if s.count == 1 {
s = "0" + s
}
return $0 + s
}
}
}
private final class MD5 {
private struct BytesSequence: Sequence {
let chunkSize: Int
let data: Array<UInt8>
func makeIterator() -> AnyIterator<ArraySlice<UInt8>> {
var offset = data.startIndex
return AnyIterator {
let end = Swift.min(self.chunkSize, self.data.count &- offset)
let result = self.data[offset ..< offset &+ end]
offset = offset.advanced(by: result.count)
if !result.isEmpty {
return result
}
return nil
}
}
}
static let blockSize: Int = 64
static let digestLength: Int = 16 // 128 / 8
fileprivate static let hashInitialValue: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
fileprivate var accumulated: [UInt8] = []
fileprivate var processedBytesTotalCount: Int = 0
fileprivate var accumulatedHash: [UInt32] = MD5.hashInitialValue
/** specifies the per-round shift amounts */
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
/** binary integer part of the sines of integers (Radians) */
private let k: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
init() {}
func calculate(for bytes: [UInt8]) -> [UInt8] {
do {
return try self.update(withBytes: bytes, isLast: true)
} catch {
fatalError()
}
}
// mutating currentHash in place is way faster than returning new result
private func process(block chunk: ArraySlice<UInt8>, currentHash: inout [UInt32]) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
var M: [UInt32] = {
var result: [UInt32] = []
result.reserveCapacity(16)
for idx in stride(from: chunk.startIndex, to: chunk.endIndex, by: MemoryLayout<UInt32>.size) {
var val: UInt32 = 0
val |= chunk.count > 3 ? UInt32(chunk[idx.advanced(by: 3)]) << 24 : 0
val |= chunk.count > 2 ? UInt32(chunk[idx.advanced(by: 2)]) << 16 : 0
val |= chunk.count > 1 ? UInt32(chunk[idx.advanced(by: 1)]) << 8 : 0
val |= chunk.count > 0 ? UInt32(chunk[idx]) : 0
result.append(val)
}
return result
}()
assert(M.count == 16, "Invalid array")
// Initialize hash value for this chunk:
var A: UInt32 = currentHash[0]
var B: UInt32 = currentHash[1]
var C: UInt32 = currentHash[2]
var D: UInt32 = currentHash[3]
var dTemp: UInt32 = 0
func rotateLeft(_ value: UInt32, by: UInt32) -> UInt32 {
return ((value << by) & 0xFFFFFFFF) | (value >> (32 - by))
}
// Main loop
for j in 0 ..< k.count {
var g = 0
var F: UInt32 = 0
switch (j) {
case 0 ... 15:
F = (B & C) | ((~B) & D)
g = j
break
case 16 ... 31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32 ... 47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48 ... 63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
B = B &+ rotateLeft(A &+ F &+ k[j] &+ M[g], by: s[j])
A = dTemp
}
currentHash[0] = currentHash[0] &+ A
currentHash[1] = currentHash[1] &+ B
currentHash[2] = currentHash[2] &+ C
currentHash[3] = currentHash[3] &+ D
}
func update<T: Collection>(withBytes bytes: T, isLast: Bool = false) throws -> [UInt8] where T.Iterator.Element == UInt8 {
self.accumulated += bytes
if isLast {
let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8
let lengthBytes:[UInt8] = {
let totalBytes: Int = 64 / 8 // A 64-bit representation of b
let value = lengthInBits
let valuePointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
valuePointer.pointee = value
let bytesPointer = UnsafeMutablePointer<UInt8>(OpaquePointer(valuePointer))
var bytes = Array<UInt8>(repeating: 0, count: totalBytes)
for j in 0 ..< min(MemoryLayout<T>.size, totalBytes) {
bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee
}
#if swift(>=4.1)
valuePointer.deinitialize(count: 1)
valuePointer.deallocate()
#else
valuePointer.deinitialize()
valuePointer.deallocate(capacity: 1)
#endif
return bytes
}()
/**
ISO/IEC 9797-1 Padding method 2.
Add a single bit with value 1 to the end of the data.
If necessary add bits with value 0 to the end of the data until the padded data is a multiple of blockSize.
- parameters:
- blockSize: Padding size in bytes.
- allowance: Excluded trailing number of bytes.
*/
@inline(__always)
func bitPadding(to data: inout [UInt8], blockSize: Int, allowance: Int = 0) {
let msgLength = data.count
// Step 1. Append Padding Bits
// append one bit (UInt8 with one bit) to message
data.append(0x80)
// Step 2. append "0" bit until message length in bits ≡ 448 (mod 512)
let max = blockSize - allowance // 448, 986
if msgLength % blockSize < max { // 448
data += [UInt8](repeating: 0, count: max - 1 - (msgLength % blockSize))
} else {
data += [UInt8](repeating: 0, count: blockSize + max - 1 - (msgLength % blockSize))
}
}
// Step 1. Append padding
bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8)
// Step 2. Append Length a 64-bit representation of lengthInBits
self.accumulated += lengthBytes.reversed()
}
var processedBytes = 0
for chunk in BytesSequence(chunkSize: MD5.blockSize, data: self.accumulated) {
if (isLast || (self.accumulated.count - processedBytes) >= MD5.blockSize) {
self.process(block: chunk, currentHash: &self.accumulatedHash)
processedBytes += chunk.count
}
}
self.accumulated.removeFirst(processedBytes)
self.processedBytesTotalCount += processedBytes
// output current hash
var result: [UInt8] = []
result.reserveCapacity(MD5.digestLength)
for hElement in self.accumulatedHash {
let hLE = hElement.littleEndian
result += [UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)]
}
// reset hash value for instance
if isLast {
self.accumulatedHash = MD5.hashInitialValue
}
return result
}
}
| mit | b378fc124245c1577a90be474a0ccf61 | 40.076923 | 126 | 0.522659 | 4.057751 | false | false | false | false |
jngd/advanced-ios10-training | T7E02/T7E02/AppDelegate.swift | 1 | 3730 | //
// AppDelegate.swift
// T7E02
//
// Created by jngd on 05/03/2017.
// Copyright © 2017 jngd. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,
UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .sound]) { (granted,
error) in
if granted {
let ok = UNNotificationAction(identifier: "OKIdentifier",
title: "OK", options: [])
let cancel = UNNotificationAction(identifier: "CancelIdentifier",
title: "Cancel", options: [])
let category = UNNotificationCategory(identifier: "message",
actions: [ok, cancel], intentIdentifiers: ["OKIdentifier",
"CancelIdentifier"], options: [])
center.setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.categoryIdentifier = "message"
content.title = "T7E02"
content.body = "How are you?"
content.sound = UNNotificationSound.default()
let attach = try! UNNotificationAttachment(identifier: "IMG_8793c_free", url: Bundle.main.url(forResource: "IMG_8793c_free", withExtension: "jpg")!, options: [:])
content.attachments = [attach]
// create a 1-second delay for our alert
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
// the identifier lets you cancel the alert later if needed
let request = UNNotificationRequest(identifier: "MyAlert", content: content, trigger: trigger)
// schedule the alert to run
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
print(error)
}
}
}
}
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:.
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive
response: UNNotificationResponse, withCompletionHandler completionHandler:
@escaping () -> Void) {
if (response.actionIdentifier == "OkIdentifier") {
print("OK pressed")
} else if (response.actionIdentifier == "CancelIdentifier") {
print("Cancel pressed")
}
}
}
| apache-2.0 | ae0ae59cb8fdc6ce34b3441192135a63 | 40.433333 | 279 | 0.716814 | 4.855469 | false | false | false | false |
Ethenyl/JAMFKit | JamfKit/Sources/Models/BaseObject.swift | 1 | 2695 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
/// Represents the common denominator between all the JSS objects which must contains at least an `identifier` and a `name` properties.
@objc
public class BaseObject: NSObject, Requestable, Identifiable {
// MARK: - Constants
enum CodingKeys: String {
case identifier = "id"
case name = "name"
}
// MARK: - Properties
@objc
public let identifier: UInt
@objc
public var name: String
public override var description: String {
return "[\(String(describing: type(of: self)))][\(identifier) - \(self.name)]"
}
// MARK: - Initialization
@objc
public required init?(json: [String: Any], node: String = "") {
guard
let identifier = json[BaseObject.CodingKeys.identifier.rawValue] as? UInt,
let name = json[BaseObject.CodingKeys.name.rawValue] as? String
else {
return nil
}
self.identifier = identifier
self.name = name
}
@objc
public init?(identifier: UInt, name: String) {
guard !name.isEmpty else {
return nil
}
self.identifier = identifier
self.name = name
super.init()
}
// MARK: - Functions
@objc
public func toJSON() -> [String: Any] {
var json = [String: Any]()
json[BaseObject.CodingKeys.identifier.rawValue] = identifier
json[BaseObject.CodingKeys.name.rawValue] = name
return json
}
/**
* Parse the supplied JSON dictionary and extract a list of elements matching the supplied type.
*
* - Parameter json: The JSON payload to extract the list of elements from.
* - Parameter nodeKey: The name of the main node to extract the element from.
* - Parameter singleNodeKey: The string key used to identify a single element within the main node.
*
*/
static func parseElements<Element: Requestable>(from json: [String: Any], nodeKey: String, singleNodeKey: String) -> [Element] {
var elements = [Element]()
guard let elementsNode = json[nodeKey] as? [[String: [String: Any]]] else {
return elements
}
let newElements = elementsNode.map { $0[singleNodeKey] }.compactMap { rawElementNode -> Element? in
guard let rawElement = rawElementNode else {
return nil
}
return Element(json: rawElement, node: "")
}
elements.append(contentsOf: newElements)
return elements
}
}
| mit | 3eed6cbdd387acd570b6e74badc31f1e | 27.357895 | 135 | 0.613586 | 4.59727 | false | false | false | false |
GitTennis/SuccessFramework | Templates/_BusinessAppSwift_/_BusinessAppSwift_/AppDelegate.swift | 2 | 26508 | //
// AppDelegate.swift
// _BusinessAppSwift_
//
// Created by Gytenis Mikulenas on 06/09/16.
// Copyright © 2016 Gytenis Mikulėnas
// https://github.com/GitTennis/SuccessFramework
//
// 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. All rights reserved.
//
import UIKit
import iVersion
import UserNotifications
let kAppConfigRetryDelayDuration = 1.5
let kTabHomeItemTitle = "TabItemHome"
let kTabMenuItemTitle = "TabItemMenu"
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, WalkthroughViewControllerDelegate, UserContainerViewControllerDelegate {
// Common
var window: UIWindow?
// Configuration
var backendEnvironment: BackendEnvironmentType!
var appConfig: AppConfigEntity!
// Dependencies
lazy var viewControllerFactory: ViewControllerFactoryProtocol = {
return ViewControllerFactory.init(managerFactory: self.managerFactory)
}()
var managerFactory: ManagerFactoryProtocol = ManagerFactory.shared()
var userManager: UserManagerProtocol = ManagerFactory.shared().userManager
var keychainManager: KeychainManagerProtocol = ManagerFactory.shared().keychainManager
var settingsManager: SettingsManagerProtocol = ManagerFactory.shared().settingsManager
var crashManager: CrashManagerProtocol = ManagerFactory.shared().crashManager
var analyticsManager: AnalyticsManagerProtocol = ManagerFactory.shared().analyticsManager
var messageBarManager: MessageBarManagerProtocol = ManagerFactory.shared().messageBarManager
var reachabilityManager: ReachabilityManagerProtocol = ManagerFactory.shared().reachabilityManager
var networkOperationFactory: NetworkOperationFactoryProtocol = ManagerFactory.shared().networkOperationFactory
var localizationManager: LocalizationManagerProtocol = ManagerFactory.shared().localizationManager
var logManager: LogManagerProtocol = ManagerFactory.shared().logManager
var pushNotificationManager: PushNotificationManagerProtocol = ManagerFactory.shared().pushNotificationManager
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = self.viewControllerFactory.launchViewController(context: nil);
// Setting app new app version detection and alerting functionality
self.setupIVersion()
// Setup push notifications
self.registerForPushNotifications(application: application)
// Get app configuration
self.getAppConfig(isAppLaunch:true)
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
analyticsManager.endSession()
}
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.
self.getAppConfig(isAppLaunch:false)
}
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.
// Reset badges if any exists upong opening the app
if (application.applicationIconBadgeNumber > 0) {
application.applicationIconBadgeNumber = 0
}
// Start GA session
analyticsManager.startSession()
// Track user status for crash reports
if (userManager.isUserLoggedIn()) {
crashManager.updateUserWith(isLoggedIn: true)
} else {
crashManager.updateUserWith(isLoggedIn: false)
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if (isIpad) {
return [UIInterfaceOrientationMask.landscapeRight, UIInterfaceOrientationMask.landscapeLeft]
} else if (isIphone) {
return [UIInterfaceOrientationMask.portrait, UIInterfaceOrientationMask.portraitUpsideDown]
} else {
return UIInterfaceOrientationMask.portrait
}
}
// MARK: WalkthroughViewControllerDelegate
func didFinishShowingWalkthrough() {
// Proceed to the app after user completes walkthrough
self.continueLaunchTheApp()
}
// MARK: UserContainerViewControllerDelegate
func didAuthentificateUser() {
// Proceed to the app after user completes walkthrough
self.proceedToTheApp()
}
// MARK: Push and local Notifications
// Source1: http://stackoverflow.com/a/39618207/597292
// Source2: https://makeapppie.com/2016/08/08/how-to-make-local-notifications-in-ios-10/
func registerForPushNotifications(application: UIApplication) {
DispatchQueue.main.async {
let options: UNAuthorizationOptions = [.badge, .sound, .alert]
UNUserNotificationCenter.current().delegate = self
// This in general asks a user if he wants to be bored with any type of notifications (both push and local notifications
UNUserNotificationCenter.current().requestAuthorization(options: options, completionHandler: { [weak self] (granted, error) in
// Store user's preference
self?.settingsManager.isGrantedNotificationAccess = granted
DDLogDebug(log: "AppDelegate: registerForPushNotifications, user granted: " + stringify(object: granted))
if (granted) {
// This registers for push notifications
application.registerForRemoteNotifications()
} else {
// ...
}
})
}
}
// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
var message: String = "AppDelegate: center:willPresent:notification"
if let responseValue = notification.request.content.userInfo["myDictKey"] as? String {
message = message + " passedValue: " + responseValue
}
DDLogDebug(log: message)
}
// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
var message: String = "AppDelegate: center:didReceive:response"
if let responseValue = response.notification.request.content.userInfo["myDictKey"] as? String {
message = message + " passedValue: " + responseValue
}
DDLogDebug(log: message)
}
// Interactive notifications
// http://www.thinkandbuild.it/interactive-notifications-with-notification-actions/
func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
DDLogDebug(log: "AppDelegate: handleActionWithIdentifierForRemoteNotification :" + identifier! + userInfo.description)
//handle the actions
if (identifier?.isEqual("declineAction"))!{
// ...
} else if (identifier?.isEqual("answerAction"))! {
// ...
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
DDLogDebug(log: "AppDelegate: didRegisterForRemoteNotificationsWithDeviceToken :" + deviceToken.description)
self.pushNotificationManager.registerPushNotification(token: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
DDLogDebug(log: "AppDelegate: didFailToRegisterForRemoteNotificationsWithError: " + error.localizedDescription);
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
DDLogDebug(log: "AppDelegate: didReceiveRemoteNotification: " + userInfo.description);
let topVC: UIViewController = UIApplication.topViewController()!
pushNotificationManager.handleReceivedPushNotification(userInfo: userInfo, application: application, topViewController: topVC)
// Check if force app reload notification was received
let shouldAppReload: Bool? = userInfo["appShouldReload"] as? Bool
if shouldAppReload != nil {
if (application.applicationState == UIApplicationState.active) {
self.performForceReload()
}
}
}
// MARK: iVersionDelegate
func iVersionDidDetect(newVersion: String, details: String) {
messageBarManager.showMessage(title: localizedString(key:"New app version is available"), description: localizedString(key:"New app version is available"), type: MessageBarMessageType.info, duration: 5) { () in
iVersion.sharedInstance().lastChecked = Date()
iVersion.sharedInstance().lastReminded = Date()
iVersion.sharedInstance().openAppPageInAppStore()
}
}
func iVersionShouldDisplay(newVersion: String, details: String) -> Bool {
return true
}
func setupIVersion() {
// More info on configuration: http://www.binpress.com/app/iversion-automatic-update-tracking-for-your-apps/615
//Checking period is set to 1 day
iVersion.sharedInstance().checkPeriod = 1;
//[iVersion sharedInstance].displayAppUsingStorekitIfAvailable = NO;
}
// MARK : Force to update and reload
// Method performs request to the backend and passes current app version. Backend returns bool indicating app should be updated or not. If yes then user is shown alert, navigated to app store for update and app is closed. Sometimes we need such functionality because of:
//
// 1. Previously released app contains critical errors and we need to update ASAP.
// 2. We released new app version which uses new backend API which is not backwards compatible with the old app
// 3. We have released a new app version which introduces major changes and there's no profit in allowing a users to continue to use old app.
//
// A good example of such force to update is Clash of clans game app.
//
func getAppConfig(callback: @escaping Callback) {
// Read hardcoded default config: which backend to use in this build
if let backendEnvironment = Bundle.plistValue(key: kAppConfigBackendEnvironmentPlistKey) as? Int {
// Store
self.backendEnvironment = BackendEnvironmentType(rawValue: backendEnvironment)
// Request
let request: NetworkRequestEntity = NetworkRequestEntity.init(backendEnvironment: BackendEnvironmentType(rawValue: backendEnvironment)!)
let configOperation = networkOperationFactory.configNetworkOperation(context: request as Any)
// Perform
configOperation.perform(callback: callback)
}
}
// Solution used from http://stackoverflow.com/questions/355168/proper-way-to-exit-iphone-
func closeTheApp() {
//let app: UIApplication = UIApplication.shared
//app.perform(#selector(UIApplication.suspend))
UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)
//wait 2 seconds while app is going background
Thread.sleep(forTimeInterval: 2.0)
//exit app when app is in background
exit(EXIT_SUCCESS);
}
func performForceUpdate(appConfig: AppConfigEntity) {
DDLogDebug(log: "App needs update...")
self.messageBarManager.showAlertOkWithTitle(title: "", description: localizedString(key:"AppNeedsUpdate"), okTitle: "Update") { [weak self] () in
let iTunesLink: String = appConfig.appStoreUrlString
UIApplication.shared.open(NSURL(string:iTunesLink) as! URL, options: [:], completionHandler: nil)
self?.closeTheApp()
}
}
// It's a backdoor for critical cases. If app config request will return param indicating appConfigVersion has changed AND app is already running THEN app will close and therefore will reload itself (all the backend URLs)
func performForceReload() {
DDLogDebug(log: "App needs reload...")
self.messageBarManager.showAlertOkWithTitle(title: "", description: "AppNeedsReload", okTitle: "Reload") { [weak self] () in
self?.closeTheApp()
}
}
// MARK: App config
func setAppConfig(appConfig: AppConfigEntity) {
// Store app config
self.appConfig = appConfig;
// Set config to point to backend environment which is defined in main plist
appConfig.setCurrentRequests(backendEnvironment: self.backendEnvironment)
// Update global log level
self.logManager.set(logLevel: appConfig.logLevel)
// Update with new appConfig
self.networkOperationFactory = NetworkOperationFactory.init(appConfig: appConfig, settingsManager: self.settingsManager)
self.networkOperationFactory.userManager = self.userManager
self.userManager.networkOperationFactory = self.networkOperationFactory
self.managerFactory.networkOperationFactory = self.networkOperationFactory
}
func getAppConfig(isAppLaunch: Bool) {
// Check if app needs force update
self.getAppConfig { [weak self] (success, result, context, error) in
let newAppConfig: AppConfigEntity? = result as? AppConfigEntity
// If for any reason app config fails then retry (unlimited)
if (!success || newAppConfig == nil) {
self?.perform(#selector(AppDelegate.getAppConfig(isAppLaunch:)), with: isAppLaunch, afterDelay: kAppConfigRetryDelayDuration)
} else {
if (newAppConfig?.isAppNeedUpdate)! {
self?.performForceUpdate(appConfig: newAppConfig!)
} else {
// If app is already launched and we just received app config upon returning from background
if (!isAppLaunch) {
// Check if backend tells APIs has changed and app needs to reload
if ((self?.appConfig?.appConfigVersion)! < (newAppConfig?.appConfigVersion)! || !(newAppConfig?.isConfigForIosPlatform)!) {
self?.performForceReload()
} else {
// TODO: Disabling config update when app returns from bg. It causes to create new UserManager object while UserContainer and LoginVC will hold reference to previous UserManager object which will perform login and store token. However, new VC will use new UserManager from Registry, which is empty and doesn't have a token
// Update config
//[weakSelf setAppConfig:newAppConfig];
}
// Else continue launching app...
} else {
// Store config
self?.setAppConfig(appConfig: newAppConfig!)
self?.checkAndOverrideGeneralSettingsLanguageIfNotSupported()
// Continue
// Check if app runs the very first time
if let settingsManager = self?.settingsManager {
if (settingsManager.isFirstTimeAppLaunch) {
self?.showWalkthrough()
} else {
self?.continueLaunchTheApp()
}
}
}
}
}
}
}
// MARK:
// MARK: Internal
// MARK:
internal func tabBar() -> BaseTabBarController {
let tab0Vc: HomeViewController = viewControllerFactory.homeViewController(context: nil)
let tab1Vc: MenuViewController = viewControllerFactory.menuViewController(context: nil)
let tab0NavCtrl: BaseNavigationController = BaseNavigationController.init(rootViewController: tab0Vc)
let tab1NavCtrl: BaseNavigationController = BaseNavigationController.init(rootViewController: tab1Vc)
let tabBarController: BaseTabBarController = BaseTabBarController()
tabBarController.viewControllers = [tab0NavCtrl, tab1NavCtrl]
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : kColorGray], for: UIControlState.normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : kColorBlue], for: UIControlState.selected)
//------ Configure first tab -------//
let tabBarItem0 = tabBarController.tabBar.items?[0]
var deselectedImage: UIImage = (UIImage(named:"iconTabHomeInactive")?.withRenderingMode(.alwaysOriginal))!
var selectedImage: UIImage = (UIImage(named:"iconTabHomeActive")?.withRenderingMode(.alwaysOriginal))!
tabBarItem0?.title = localizedString(key: kTabHomeItemTitle)
tabBarItem0?.image = deselectedImage
tabBarItem0?.selectedImage = selectedImage
//------ Configure second tab -------//
let tabBarItem1 = tabBarController.tabBar.items?[1]
deselectedImage = (UIImage(named:"iconTabMenuInactive")?.withRenderingMode(.alwaysOriginal))!
selectedImage = (UIImage(named:"iconTabMenuActive")?.withRenderingMode(.alwaysOriginal))!
tabBarItem1?.title = localizedString(key: kTabMenuItemTitle)
tabBarItem1?.image = deselectedImage
tabBarItem1?.selectedImage = selectedImage
return tabBarController
}
internal func continueLaunchTheApp() {
//if (self.userManager.isUserLoggedIn()) {
// Or jump straight to the app
self.proceedToTheApp()
/*} else {
// Show tutorial
self.showLogin(error: nil)
}*/
}
internal func showWalkthrough() {
// Protection: don't show twice
if (!(self.window?.rootViewController is WalkthroughViewController)) {
let walkthroughVC: WalkthroughViewController = viewControllerFactory.walkthroughViewController(context: nil)
walkthroughVC.delegate = self
self.window?.rootViewController = walkthroughVC
}
}
internal func showLogin(error: ErrorEntity?) {
// Protection: don't show twice
if (!(self.window?.rootViewController is UserContainerViewController)) {
let userContainerVc: UserContainerViewController = viewControllerFactory.userContainerViewController(context: nil)
userContainerVc.delegate_ = self
self.window?.rootViewController = userContainerVc
if let error = error {
self.messageBarManager .showMessage(title: "", description: error.message, type: MessageBarMessageType.error)
}
}
}
internal func proceedToTheApp() {
// set as the root window
let rootVc: BaseTabBarController = self.tabBar()
self.animateTransitioning(newView: rootVc.view, newRootViewController: rootVc, callback: nil)
}
// TODO: temporary
internal func animateTransitioning(newView: UIView, newRootViewController: UIViewController, callback: Callback?) {
self.window?.rootViewController = newRootViewController
// Override
/*UIViewAnimationOptions options = UIViewAnimationOptionTransitionCurlUp;//UIViewAnimationOptionTransitionFlipFromTop;//UIViewAnimationOptionTransitionCrossDissolve;
newView.frame = [UIScreen mainScreen].bounds;
UIView *oldView = nil;
if ([self.window.rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController *oldNavCon = (UINavigationController *)self.window.rootViewController;
oldView = oldNavCon.topViewController.view;
} else if ([self.window.rootViewController isKindOfClass:[UIViewController class]]) {
oldView = self.window.rootViewController.view;
} else if ([self.window.rootViewController isKindOfClass:[MenuNavigator class]]) {
MenuNavigator *menuNavCon = (MenuNavigator *)self.window.rootViewController;
UIViewController *centerVC = (UIViewController *)menuNavCon.centerViewController;
oldView = centerVC.view;
}
// Perform animation
__weak typeof(self) weakSelf = self;
[UIView transitionFromView:oldView
toView:newView
duration:0.65f
options:options
completion:^(BOOL finished) {
weakSelf.window.rootViewController = newRootViewControler;
if (callback) {
callback(YES, nil, nil);
}
}];*/
}
internal func checkAndOverrideGeneralSettingsLanguageIfNotSupported() {
if let language = settingsManager.language {
if (language != ConstLangKeys.langEnglish && language != ConstLangKeys.langGerman){
settingsManager.setLanguageGerman()
}
} else {
settingsManager.setLanguageGerman()
}
}
}
| mit | 9334f5a326271d6ea1a1a165490c601f | 43.176667 | 451 | 0.642119 | 5.992765 | false | true | false | false |
PiasMasumKhan/Swift | iCloud/iCloud/DocumentPhoto.swift | 33 | 1927 | //
// DocumentPhoto.swift
// iCloud
//
// Created by Carlos Butron on 07/12/14.
// Copyright (c) 2014 Carlos Butron.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
// version.
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along with this program. If not, see
// http:/www.gnu.org/licenses/.
//
import UIKit
class DocumentPhoto: UIDocument {
var image : UIImage!
override func loadFromContents(contents: AnyObject, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
var data = NSData(bytes: contents.bytes, length: contents.length)
self.image = UIImage(data: data)
return true
}
override func contentsForType(typeName: String, error outError: NSErrorPointer) -> AnyObject? {
return UIImageJPEGRepresentation(self.image, 1.0)
}
// override func loadFromContents(contents: AnyObject, ofType typeName:
// String, error outError: NSErrorPointer) -> Bool {
// if (contents.length > 0){
// var data = NSData(bytes: contents.bytes, length:
// contents.length)
// self.image = UIImage(data: data)
// }
// return true
// }
// override func contentsForType(typeName: String, error outError:
// NSErrorPointer) -> AnyObject? {
// if (self.image == nil){
// image = UIImage()
// }
// return UIImageJPEGRepresentation(self.image, 1.0)
// }
}
| gpl-3.0 | 087ece7f26e0c107732061db7cfdfed5 | 33.410714 | 122 | 0.654904 | 4.272727 | false | false | false | false |
muukii/Bulk | Sources/BulkLogger/Logger/LogBasicFormatter.swift | 1 | 2308 | //
// BasicFormatter.swift
//
// Copyright (c) 2017 muukii
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct LogBasicFormatter {
public struct LevelString {
public var verbose = "[VERBOSE]"
public var debug = "[DEBUG]"
public var info = "[INFO]"
public var warn = "[WARN]"
public var error = "[ERROR]"
}
public let dateFormatter: DateFormatter
public var levelString = LevelString()
public init() {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
self.dateFormatter = formatter
}
public func format(element: LogData) -> String {
let level: String = {
switch element.level {
case .verbose: return levelString.verbose
case .debug: return levelString.debug
case .info: return levelString.info
case .warn: return levelString.warn
case .error: return levelString.error
}
}()
let timestamp = dateFormatter.string(from: element.date)
let file = URL(string: element.file.description)?.deletingPathExtension()
let string = "[\(timestamp)] \(level) \(file?.lastPathComponent ?? "???").\(element.function):\(element.line) \(element.body)"
return string
}
}
| mit | 2b8dd430a099ac90f499c24033723b38 | 32.941176 | 130 | 0.69844 | 4.579365 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/NotificationAuthorizer.swift | 1 | 10256 | //
// NotificationAuthorizer.swift
// breadwallet
//
// Created by Ehsan Rezaie on 2018-07-16.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
import Foundation
import UserNotifications
import UIKit
// Handles user authorization for push notifications.
struct NotificationAuthorizer: Trackable {
// When the user is initially prompted to opt into push notifications, they can defer the decision,
// or proceed to the system notifications prompt and either allow or deny
enum OptInPromptResponse {
case deferred
case allowed
case denied
}
typealias AuthorizationHandler = (_ granted: Bool) -> Void
typealias ShouldShowOptInCallback = (_ shouldShowOptIn: Bool) -> Void
typealias OptInResponseCallback = (_ optInResponse: OptInPromptResponse) -> Void
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
let nagUserLaunchCountInterval = 10 // nag the user every 10 launches if notifications were deferred
let maxNagUserCountForNotificationsOptIn = 2 // initial plus nag twice => 3 total
var optInDeferralCount: Int {
return UserDefaults.notificationOptInDeferralCount
}
private func bumpOptInDeferralCount() {
UserDefaults.notificationOptInDeferralCount += 1
}
var launchesSinceLastDeferral: Int {
return UserDefaults.appLaunchCount - UserDefaults.appLaunchesAtLastNotificationDeferral
}
var haveEnoughLaunchesSinceLastDeferral: Bool {
let launchesSinceLastDeferral = UserDefaults.appLaunchCount - UserDefaults.appLaunchesAtLastNotificationDeferral
return launchesSinceLastDeferral >= nagUserLaunchCountInterval
}
var isOkToNagUserForOptIn: Bool {
return UserDefaults.notificationOptInDeferralCount <= maxNagUserCountForNotificationsOptIn
}
func requestAuthorization(fromViewController viewController: UIViewController, completion: @escaping AuthorizationHandler) {
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
switch settings.authorizationStatus {
case .authorized, .provisional, .ephemeral:
if !(settings.alertSetting == .enabled ||
settings.soundSetting == .enabled ||
settings.notificationCenterSetting == .enabled ||
settings.lockScreenSetting == .enabled ||
settings.badgeSetting == .enabled) {
self.showAlertForDisabledNotifications(fromViewController: viewController, completion: completion)
} else {
UIApplication.shared.registerForRemoteNotifications()
completion(true)
}
case .notDetermined:
self.showAlertForInitialAuthorization(fromViewController: viewController, completion: completion)
case .denied:
self.showAlertForDisabledNotifications(fromViewController: viewController, completion: completion)
@unknown default:
assertionFailure("unknown notification auth status")
completion(false)
}
}
}
}
func areNotificationsAuthorized(completion: @escaping AuthorizationHandler) {
UNUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .authorized, .provisional, .ephemeral:
completion(true)
case .notDetermined, .denied:
completion(false)
@unknown default:
assertionFailure("unknown notification auth status")
completion(false)
}
}
}
func checkShouldShowOptIn(completion: @escaping ShouldShowOptInCallback) {
// Don't show the opt-in prompt on top of the login screen.
guard !Store.state.isLoginRequired else {
completion(false)
return
}
// Don't show the opt-in prompt if we haven't had sufficent app launches since there
// is already a lot going on when the user first creates or restores a wallet.
guard UserDefaults.appLaunchCount > ApplicationController.initialLaunchCount else {
completion(false)
return
}
// First check if the user has already granted or denied push notifications.
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { settings in
switch settings.authorizationStatus {
case .authorized, .denied, .provisional:
completion(false)
return
default:
break
}
if self.optInDeferralCount == 0 {
completion(true)
return
}
if self.isOkToNagUserForOptIn && self.haveEnoughLaunchesSinceLastDeferral {
completion(true)
return
}
completion(false)
})
}
func userDidDeferNotificationsOptIn() {
// Keeping track of this count will be used to ensure we don't nag the user forever about notifications.
bumpOptInDeferralCount()
// Record the launch count at which the user deferred the opt-in so we can determine when
// it's ok to show it again.
UserDefaults.appLaunchesAtLastNotificationDeferral = UserDefaults.appLaunchCount
}
// Shows an alert dialog asking the user to opt into push notifications or defer making a decision.
func showNotificationsOptInAlert(from viewController: UIViewController, callback: @escaping (Bool) -> Void) {
// First check if it's ok to prompt the user.
checkShouldShowOptIn(completion: { (shouldShow) in
guard shouldShow else {
callback(false)
return
}
self.showOptInAlert(fromViewController: viewController, completion: { (response) in
switch response {
case .deferred:
self.userDidDeferNotificationsOptIn()
case .denied: break
case .allowed: break
}
callback(true) // 'true' => showed the opt-in alert
})
})
}
private func showOptInAlert(fromViewController viewController: UIViewController, completion: @escaping OptInResponseCallback) {
let alert = UIAlertController(title: S.PushNotifications.title,
message: S.PushNotifications.body,
preferredStyle: .alert)
let enableAction = UIAlertAction(title: S.Button.ok, style: .default) { _ in
self.logEvent(.optInPrompt, .okButton)
UNUserNotificationCenter.current().requestAuthorization(options: self.options) { (granted, _) in
DispatchQueue.main.async {
if granted {
UIApplication.shared.registerForRemoteNotifications()
self.logEvent(.systemPrompt, .allowButton)
completion(.allowed)
} else {
self.logEvent(.systemPrompt, .denyButton)
completion(.denied)
}
}
}
}
let deferAction = UIAlertAction(title: S.Button.maybeLater, style: .cancel) { _ in
// Logging this here rather than in `userDidDeferNotificationsOptIn()` so that it's not logged
// during unit testing; however, at this point 'optInDeferralCount' won't be updated yet, so
// add 1 when logging the event.
self.logEvent(.optInPrompt, .deferButton, [ "count": String(self.optInDeferralCount + 1) ])
completion(.deferred)
}
alert.addAction(enableAction)
alert.addAction(deferAction)
DispatchQueue.main.async {
viewController.present(alert, animated: true, completion: nil)
}
}
private func showAlertForInitialAuthorization(fromViewController viewController: UIViewController,
completion: @escaping AuthorizationHandler) {
showOptInAlert(fromViewController: viewController, completion: { (response) in
switch response {
case .deferred, .denied:
completion(false)
case .allowed:
completion(true)
}
})
}
private func showAlertForDisabledNotifications(fromViewController viewController: UIViewController, completion: @escaping AuthorizationHandler) {
let alert = UIAlertController(title: S.PushNotifications.disabled,
message: S.PushNotifications.enableInstructions,
preferredStyle: .alert)
let settingsAction = UIAlertAction(title: S.Button.settings, style: .default) { _ in
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
completion(false)
}
let cancelAction = UIAlertAction(title: S.Button.cancel, style: .cancel) { _ in
completion(false)
}
alert.addAction(settingsAction)
alert.addAction(cancelAction)
viewController.present(alert, animated: true, completion: nil)
}
func logEvent(_ screen: Screen, _ event: Event, _ attributes: [String: String]? = nil) {
let eventName = makeEventName([EventContext.pushNotifications.name, screen.name, event.name])
if let attr = attributes {
saveEvent(eventName, attributes: attr)
} else {
saveEvent(eventName)
}
}
}
| mit | dc876cebf2b5d16ac498006b8ffe5010 | 40.184739 | 149 | 0.600683 | 5.767717 | false | false | false | false |
gu704823/huobanyun | huobanyun/listTableViewController.swift | 1 | 1707 | //
// listTableViewController.swift
// huobanyun
//
// Created by AirBook on 2017/6/17.
// Copyright © 2017年 AirBook. All rights reserved.
//
import UIKit
class listTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupui()
tableView.separatorStyle = .none
navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
}
fileprivate lazy var creatbutton:UIButton = {[weak self] in
let btn = UIButton()
btn.frame = CGRect(x: screenwidh*0.85, y: screenheight*0.8, width: 0.1*screenwidh, height: 0.1*screenwidh)
btn.setImage(#imageLiteral(resourceName: "add"), for: .normal)
btn.addTarget(self, action: #selector(onclick), for: .touchUpInside)
return btn
}()
//按钮点击
@objc fileprivate func onclick(){
let vc = UIStoryboard(name: "completion", bundle: nil).instantiateInitialViewController() as! UITableViewController
show(vc, sender: nil)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 20
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listcell", for: indexPath)
return cell
}
}
extension listTableViewController{
fileprivate func setupui(){
view.addSubview(creatbutton)
}
}
| mit | 6b1770e0a80ba3bee78e4bf5b0f01f1f | 35 | 124 | 0.674941 | 4.488064 | false | false | false | false |
svanimpe/around-the-table | Sources/AroundTheTable/Forms/ActivityForm.swift | 1 | 2981 | import Foundation
/**
Form for submitting a new activity.
*/
struct ActivityForm: Codable {
let game: Int
let name: String
let playerCount: Int
let minPlayerCount: Int
let prereservedSeats: Int
let day: Int
let month: Int
let year: Int
let hour: Int
let minute: Int
/// The activity's date.
/// Returns `nil` if the form's fields do not represent a valid date.
var date: Date? {
var components = DateComponents()
components.calendar = Settings.calendar
components.day = day
components.month = month
components.year = year
components.hour = hour
components.minute = minute
components.timeZone = Settings.timeZone
guard components.isValidDate,
let date = components.date else {
return nil
}
return date
}
let deadlineType: String
/// The activity's deadline.
/// Returns `nil` if either the deadline type or date is invalid.
var deadline: Date? {
guard let date = date else {
return nil
}
switch deadlineType {
case "one hour":
return Settings.calendar.date(byAdding: .hour, value: -1, to: date)!
case "one day":
return Settings.calendar.date(byAdding: .day, value: -1, to: date)!
case "two days":
return Settings.calendar.date(byAdding: .day, value: -2, to: date)!
case "one week":
return Settings.calendar.date(byAdding: .weekOfYear, value: -1, to: date)!
default:
return nil
}
}
let address: String
let city: String
let country: String
let latitude: Double
let longitude: Double
/// The activity's location.
var location: Location {
return Location(coordinates: Coordinates(latitude: latitude, longitude: longitude),
address: address,
city: city,
country: country)
}
let info: String
/// Whether the form's fields are valid. Checks:
/// - if the form does not contain an empty string for a required field,
/// - if the player count is at least 1,
/// - if the minimum player count is between 1 and the player count,
/// - if the number of prereserved seats is at least 0 and less than the player count,
/// - if the date is valid and in the future,
/// - if the deadline is valid and in the future.
var isValid: Bool {
let checks = [
![name, address, city, country].contains { $0.isEmpty },
playerCount >= 1,
minPlayerCount >= 1 && minPlayerCount <= playerCount,
prereservedSeats >= 0 && prereservedSeats < playerCount,
date?.compare(Date()) == .orderedDescending,
deadline?.compare(Date()) == .orderedDescending
]
return !checks.contains(false)
}
}
| bsd-2-clause | 17b945112bdcb715e067a22990d64e04 | 30.712766 | 91 | 0.581684 | 4.665102 | false | false | false | false |
shrishrirang/azure-mobile-apps-quickstarts | client/iOS-Swift/ZUMOAPPNAME/ZUMOAPPNAME/ToDoTableViewController.swift | 1 | 10847 | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import CoreData
class ToDoTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, ToDoItemDelegate {
var table : MSSyncTable?
var store : MSCoreDataStore?
lazy var fetchedResultController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "TodoItem")
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
// show only non-completed items
fetchRequest.predicate = NSPredicate(format: "complete != true")
// sort by item text
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
// Note: if storing a lot of data, you should specify a cache for the last parameter
// for more information, see Apple's documentation: http://go.microsoft.com/fwlink/?LinkId=524591&clcid=0x409
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
resultsController.delegate = self;
return resultsController
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let client = MSClient(applicationURLString: "ZUMOAPPURL")
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
self.store = MSCoreDataStore(managedObjectContext: managedObjectContext)
client.syncContext = MSSyncContext(delegate: nil, dataSource: self.store, callback: nil)
self.table = client.syncTableWithName("TodoItem")
self.refreshControl?.addTarget(self, action: #selector(ToDoTableViewController.onRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
var error : NSError? = nil
do {
try self.fetchedResultController.performFetch()
} catch let error1 as NSError {
error = error1
print("Unresolved error \(error), \(error?.userInfo)")
abort()
}
// Refresh data on load
self.refreshControl?.beginRefreshing()
self.onRefresh(self.refreshControl)
}
func onRefresh(sender: UIRefreshControl!) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.pullWithQuery(self.table?.query(), queryId: "AllRecords") {
(error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
// A real application would handle various errors like network conditions,
// server conflicts, etc via the MSSyncContextDelegate
print("Error: \(error!.description)")
// We will just discard our changes and keep the servers copy for simplicity
if let opErrors = error!.userInfo[MSErrorPushResultKey] as? Array<MSTableOperationError> {
for opError in opErrors {
print("Attempted operation to item \(opError.itemId)")
if (opError.operation == .Insert || opError.operation == .Delete) {
print("Insert/Delete, failed discarding changes")
opError.cancelOperationAndDiscardItemWithCompletion(nil)
} else {
print("Update failed, reverting to server's copy")
opError.cancelOperationAndUpdateItem(opError.serverItem!, completion: nil)
}
}
}
}
self.refreshControl?.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Table Controls
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle
{
return UITableViewCellEditingStyle.Delete
}
override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String?
{
return "Complete"
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
let record = self.fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
var item = self.store!.tableItemFromManagedObject(record)
item["complete"] = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.update(item) { (error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
print("Error: \(error!.description)")
return
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if let sections = self.fetchedResultController.sections {
return sections[section].numberOfObjects
}
return 0;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath)
cell = configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) -> UITableViewCell {
let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
// Set the label on the cell and make sure the label color is black (in case this cell
// has been reused and was previously greyed out
if let text = item.valueForKey("text") as? String {
cell.textLabel!.text = text
} else {
cell.textLabel!.text = "?"
}
cell.textLabel!.textColor = UIColor.blackColor()
return cell
}
// MARK: Navigation
@IBAction func addItem(sender : AnyObject) {
self.performSegueWithIdentifier("addItem", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "addItem" {
let todoController = segue.destinationViewController as! ToDoItemViewController
todoController.delegate = self
}
}
// MARK: - ToDoItemDelegate
func didSaveItem(text: String)
{
if text.isEmpty {
return
}
// We set created at to now, so it will sort as we expect it to post the push/pull
let itemToInsert = ["text": text, "complete": false, "__createdAt": NSDate()]
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.insert(itemToInsert) {
(item, error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
print("Error: " + error!.description)
}
}
}
// MARK: - NSFetchedResultsDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.beginUpdates()
});
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let indexSectionSet = NSIndexSet(index: sectionIndex)
if type == .Insert {
self.tableView.insertSections(indexSectionSet, withRowAnimation: .Fade)
} else if type == .Delete {
self.tableView.deleteSections(indexSectionSet, withRowAnimation: .Fade)
}
})
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Move:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Update:
// note: Apple samples show a call to configureCell here; this is incorrect--it can result in retrieving the
// wrong index when rows are reordered. For more information, see:
// http://go.microsoft.com/fwlink/?LinkID=524590&clcid=0x409
self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
}
})
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.endUpdates()
});
}
}
| apache-2.0 | 92902edaab09e04cba13ae3af15f0269 | 40.880309 | 211 | 0.627916 | 5.907952 | false | false | false | false |
wang-chuanhui/CHSDK | Source/Utils/RegularExpression.swift | 1 | 1770 | //
// RegularExpression.swift
// CHSDK
//
// Created by 王传辉 on 2017/8/18.
// Copyright © 2017年 王传辉. All rights reserved.
//
import Foundation
public struct RegularExpression {
let regular: NSRegularExpression?
public init(_ pattern: String) {
do {
self.regular = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
} catch {
self.regular = nil
}
}
public func match(_ input: String) -> Bool {
guard let regular = regular else {
return false
}
let matches = regular.matches(in: input, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSRange(location: 0, length: input.lengthOfBytes(using: String.Encoding.utf8)))
return matches.count > 0
}
}
public extension RegularExpression {
static let username: RegularExpression = RegularExpression("^[a-z0-9_-]{3,16}$")
static let password: RegularExpression = RegularExpression("^[a-z0-9_-]{6,18}$")
static let hexValue: RegularExpression = RegularExpression("^#?([a-f0-9]{6}|[a-f0-9]{3})$")
static let slug: RegularExpression = RegularExpression("^[a-z0-9-]+$")
static let email: RegularExpression = RegularExpression("^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$")
static let url: RegularExpression = RegularExpression("^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$")
static let ipAddress: RegularExpression = RegularExpression("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
static let htmlTag: RegularExpression = RegularExpression("^<([a-z]+)([^<]+)*(?:>(.*)<\\/\\1>|\\s+\\/>)$")
}
| mit | 41866e941836823589cceba212d7e41e | 38.886364 | 196 | 0.598291 | 3.75 | false | false | false | false |
lovecrafts/Veneer | Veneer/Classes/UIBezierPath+Outline.swift | 1 | 3963 | //
// UIBezierPath+Outline.swift
// Pods
//
// Created by Sam Watts on 10/02/2017.
//
//
import UIKit
extension CGRect {
var topLeft: CGPoint {
return CGPoint(x: self.minX, y: self.minY)
}
var topRight: CGPoint {
return CGPoint(x: self.maxX, y: self.minY)
}
var bottomRight: CGPoint {
return CGPoint(x: self.maxX, y: self.maxY)
}
var bottomLeft: CGPoint {
return CGPoint(x: self.minX, y: self.maxY)
}
}
extension Collection where Iterator.Element == CGRect {
var topPoints: [CGPoint] {
return self.reduce([]) { $0 + [$1.topLeft, $1.topRight] }
}
var bottomPoints: [CGPoint] {
return self.reduce([]) { $0 + [$1.bottomLeft, $1.bottomRight] }
}
}
extension UIBezierPath {
//code adapted from http://stackoverflow.com/a/35711310/1138900
//works through top points from left to right, then bottom points right to left, adding intersection points if crossing the axis of previous point
convenience init(outliningViewFrames frames: [CGRect]) {
self.init()
//nothing to do for empty frames
guard frames.isEmpty == false else { return }
//check for simple case of a single frame
guard frames.count != 1 else { self.append(UIBezierPath(rect: frames[0])); return }
// top left and right corners of each view
// sorted from left to right, top to bottom
var topPoints:[CGPoint] = frames.topPoints
topPoints = topPoints.sorted(by: { $0.x == $1.x ? $0.y < $1.y : $0.x < $1.x })
// trace top line from left to right
// moving up or down when appropriate
var previousPoint = topPoints.removeFirst()
self.move(to: previousPoint)
for point in topPoints {
//guard against non outline points (e.g. corner points withing other rects)
guard point.y == previousPoint.y
|| (point.y < previousPoint.y && frames.contains(where: {$0.minX == point.x && $0.minY < previousPoint.y }))
|| (point.y > previousPoint.y && !frames.contains(where: { $0.maxX > point.x && $0.minY < point.y }))
else { continue }
if point.y < previousPoint.y {
self.addLine(to: CGPoint(x:point.x, y:previousPoint.y))
} else if point.y > previousPoint.y {
self.addLine(to: CGPoint(x:previousPoint.x, y:point.y))
}
self.addLine(to: point)
previousPoint = point
}
// botom left and right corners of each view
// sorted from right to left, bottom to top
var bottomPoints: [CGPoint] = frames.bottomPoints
bottomPoints = bottomPoints.sorted(by: { $0.x == $1.x ? $0.y > $1.y : $0.x > $1.x })
// trace bottom line from right to left
// starting where top line left off (rightmost top corner)
// moving up or down when appropriate
for point in bottomPoints {
//guard against non outline points (e.g. corner points withing other rects)
guard point.y == previousPoint.y
|| (point.y > previousPoint.y && frames.contains(where: {$0.maxX == point.x && $0.maxY > previousPoint.y }))
|| (point.y < previousPoint.y && !frames.contains(where: { $0.minX < point.x && $0.maxY > point.y }))
else { continue }
if point.y > previousPoint.y {
self.addLine(to: CGPoint(x:point.x, y:previousPoint.y))
} else if point.y < previousPoint.y {
self.addLine(to: CGPoint(x:previousPoint.x, y:point.y))
}
self.addLine(to: point)
previousPoint = point
}
// close back to leftmost point of top line
self.close()
}
}
| mit | e4a3816434b8988999632a2787545135 | 34.383929 | 150 | 0.558163 | 4.094008 | false | false | false | false |
nalexn/ViewInspector | Tests/ViewInspectorTests/SwiftUI/MenuTests.swift | 1 | 4020 | import XCTest
import SwiftUI
@testable import ViewInspector
#if os(iOS) || os(macOS)
@available(iOS 13.0, macOS 10.15, *)
@available(tvOS, unavailable)
final class MenuTests: XCTestCase {
func testExtractionFromSingleViewContainer() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let view = AnyView(Menu("abc", content: { EmptyView() }))
XCTAssertNoThrow(try view.inspect().anyView().menu())
}
func testExtractionFromMultipleViewContainer() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let view = HStack {
Text("")
Menu("abc", content: { EmptyView() })
Text("")
}
XCTAssertNoThrow(try view.inspect().hStack().menu(1))
}
func testSearch() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let view = AnyView(Menu(content: {
HStack { Text("abc") }
}, label: {
VStack { Text("xyz") }
}))
XCTAssertEqual(try view.inspect().find(ViewType.Menu.self).pathToRoot,
"anyView().menu()")
XCTAssertEqual(try view.inspect().find(text: "abc").pathToRoot,
"anyView().menu().hStack(0).text(0)")
XCTAssertEqual(try view.inspect().find(text: "xyz").pathToRoot,
"anyView().menu().labelView().vStack().text(0)")
}
func testLabelInspection() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let view = Menu(content: {
HStack { Text("abc") }
}, label: {
VStack { Text("xyz") }
})
let sut = try view.inspect().menu().labelView().vStack().text(0).string()
XCTAssertEqual(sut, "xyz")
}
func testContentInspection() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let view = Menu(content: {
HStack { Text("abc") }
}, label: {
VStack { Text("xyz") }
})
let sut = try view.inspect().menu().hStack(0).text(0).string()
XCTAssertEqual(sut, "abc")
}
func testLabelStyleInspection() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let sut = EmptyView().menuStyle(DefaultMenuStyle())
XCTAssertTrue(try sut.inspect().menuStyle() is DefaultMenuStyle)
}
func testPrimaryAction() throws {
guard #available(iOS 15, macOS 12.0, *) else { throw XCTSkip() }
let exp = XCTestExpectation(description: #function)
let sut = Menu(content: { EmptyView() }, label: { EmptyView() },
primaryAction: {
exp.fulfill()
})
try sut.inspect().menu().callPrimaryAction()
wait(for: [exp], timeout: 0.1)
}
func testAbsentPrimaryActionCall() throws {
guard #available(iOS 15, macOS 12.0, *) else { throw XCTSkip() }
let sut = Menu(content: { EmptyView() }, label: { EmptyView() })
XCTAssertThrows(try sut.inspect().menu().callPrimaryAction(),
"Menu does not have 'primaryAction' attribute")
}
func testCustomMenuStyleInspection() throws {
guard #available(iOS 14, tvOS 14, macOS 11.0, *) else { throw XCTSkip() }
let sut = TestMenuStyle()
let menu = try sut.inspect().vStack().menu(0)
XCTAssertEqual(try menu.blur().radius, 3)
XCTAssertEqual(try sut.inspect().find(ViewType.StyleConfiguration.Content.self).pathToRoot,
"vStack().menu(0).styleConfigurationContent(0)")
}
}
@available(iOS 14.0, macOS 11.0, *)
@available(tvOS, unavailable)
private struct TestMenuStyle: MenuStyle {
func makeBody(configuration: Configuration) -> some View {
VStack {
Menu(configuration)
.blur(radius: 3)
}
}
}
#endif
| mit | 1aa6a33ef2fe7754e30f146d7acf7f07 | 36.570093 | 99 | 0.571144 | 4.290288 | false | true | false | false |
fuzza/vapor-demo | Sources/App/Models/AuthToken.swift | 1 | 1252 | import Vapor
import FluentProvider
final class AuthToken: Model {
let storage = Storage()
let userId: Identifier
let token: String
init(user: User) throws {
self.userId = try user.assertExists()
self.token = UUID().uuidString
}
var user: Parent<AuthToken, User> {
return parent(id: userId)
}
init(row: Row) throws {
userId = try row.get(Keys.userId)
token = try row.get(Keys.token)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(Keys.userId, userId)
try row.set(Keys.token, token)
return row
}
}
extension AuthToken {
struct Keys {
static let id = "id"
static let token = "token"
static let userId = User.foreignIdKey
}
}
extension AuthToken: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { tokens in
tokens.id()
tokens.string(Keys.token)
tokens.foreignId(for: User.self)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
extension AuthToken: JSONRepresentable {
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(Keys.token, token)
return json
}
}
extension AuthToken: ResponseRepresentable {}
| mit | b5b26693aa68ff9d941ce92a6bb335e7 | 19.193548 | 52 | 0.65016 | 3.817073 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.