hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
ddf365381b61d73c37794093fcfa303604c55f92 | 1,871 | //
// ChatBotStartView.swift
// ChannelIO
//
// Created by Jam on 2020/02/17.
// Copyright © 2020 ZOYI. All rights reserved.
//
import Foundation
class ChatBotStartView: BaseView {
struct Metrics {
static let viewHeight = 45.f
static let labelLeading = 8.f
}
let containerView = UIView().then {
$0.backgroundColor = .white
$0.layer.borderWidth = 2.f
$0.layer.borderColor = UIColor.whiteBorder.cgColor
$0.layer.cornerRadius = 4.f
$0.dropShadow(
with: CHColors.black10,
opacity: 0.5,
offset: CGSize(width: 0, height: 2),
radius: 2
)
}
let centerView = UIView()
let imageView = UIImageView().then {
$0.image = CHAssets.getImage(named: "bot")
}
let messageLabel = UILabel().then {
$0.font = UIFont.boldSystemFont(ofSize: 15)
$0.textColor = .cobalt400
$0.text = CHAssets.localized("ch.chat.marketing_to_support_bot")
}
override func initialize() {
super.initialize()
self.addSubview(self.containerView)
self.containerView.addSubview(self.centerView)
self.centerView.addSubview(self.messageLabel)
self.centerView.addSubview(self.imageView)
}
override func setLayouts() {
super.setLayouts()
self.containerView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
self.centerView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
self.imageView.snp.makeConstraints { (make) in
make.leading.equalToSuperview()
make.centerY.equalToSuperview()
}
self.messageLabel.snp.makeConstraints { (make) in
make.leading.equalTo(self.imageView.snp.trailing).offset(Metrics.labelLeading)
make.centerY.equalToSuperview()
make.trailing.equalToSuperview()
}
}
func viewHeight() -> CGFloat {
return Metrics.viewHeight
}
}
| 24.298701 | 84 | 0.664885 |
fc0f140c86b3146e8ffd7ab5a307b256a958c922 | 1,120 | //
// ImagePropertiesAnnotation.swift
//
// Copyright (c) 2016 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//
/// Describes the result of image properties detection.
public struct ImagePropertiesAnnotation: APIRepresentationConvertible {
/// Array of dominant colors with their scores and pixel fractions.
let dominantColors: [ColorInformation]
// MARK: Initializers
/// Initializes the receiver with raw values.
///
/// - Parameter dominantColors: Array of dominant colors with their scores
/// and pixel fractions.
public init(dominantColors: [ColorInformation]) {
self.dominantColors = dominantColors
}
/// - SeeAlso: APIRepresentationConvertible.init(APIRepresentationValue:)
public init(APIRepresentationValue value: APIRepresentationValue) throws {
try self.init(dominantColors: value.get("dominantColors").get("colors"))
}
}
// MARK: -
extension ImagePropertiesAnnotation: Equatable {}
/// - SeeAlso: Equatable.==
public func == (lhs: ImagePropertiesAnnotation, rhs: ImagePropertiesAnnotation) -> Bool {
return lhs.dominantColors == rhs.dominantColors
}
| 28.717949 | 89 | 0.757143 |
7a2c4103d01d445e2fcb2a54ecb5d3b9e0fdd753 | 365 | import UIKit
/**
* Constants
*/
extension MatchCell {
static let backgroundColor: UIColor = .blue
static let cellHeight: CGFloat = 124
static let cellReuseIdendifier: String = "\(MatchCell.self)"
enum Margin {
static let horizontal: CGFloat = 12
static let vertical: CGFloat = 12
static let verticalSpaceBetween: CGFloat = 4
}
}
| 22.8125 | 63 | 0.684932 |
03ed63c947c3a6d5a40130e8ed42d209af1d439f | 1,932 | //
// WalkthroughPageViewController.swift
// AnywhereFitness
//
// Created by Lambda_School_Loaner_204 on 1/6/20.
// Copyright © 2020 Lambda_School_Loaner_219. All rights reserved.
//
import UIKit
protocol WalkthroughPageViewControllerDelegate: class {
func walkthroughSkipButtonWasPressed()
}
class WalkthroughPageViewController: UIViewController {
@IBOutlet var containerView: UIView!
@IBOutlet var imageContainerView: UIView!
@IBOutlet var imageView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var subtitleLabel: UILabel!
@IBOutlet var skipButton: UIButton!
let model: WalkthroughModel
weak var walkthroughPageDelegate: WalkthroughPageViewControllerDelegate?
init(model: WalkthroughModel,
nibName nibNameOrNil: String?,
bundle nibBundleOrNil: Bundle?) {
self.model = model
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = UIImage.localImage(model.icon, template: true)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.tintColor = .white
imageContainerView.backgroundColor = .clear
titleLabel.text = model.title
titleLabel.font = UIFont.boldSystemFont(ofSize: 20.0)
titleLabel.textColor = .white
subtitleLabel.attributedText = NSAttributedString(string: model.subtitle)
subtitleLabel.font = UIFont.systemFont(ofSize: 14.0)
subtitleLabel.textColor = .white
containerView.backgroundColor = UIColor(hexString: "#3068CC")
}
@IBAction func skipTapped(sender: UIButton) {
self.walkthroughPageDelegate?.walkthroughSkipButtonWasPressed()
}
}
| 32.2 | 81 | 0.700828 |
d9c5537472ad1f6c6576b7f7ad109927b39b380d | 996 | import Fluent
import Foundation
import SQLKit
struct Stats: Decodable, Equatable {
static let schema = "stats"
var packageCount: Int
var versionCount: Int
enum CodingKeys: String, CodingKey {
case packageCount = "package_count"
case versionCount = "version_count"
}
}
extension Stats {
static func refresh(on database: Database) -> EventLoopFuture<Void> {
guard let db = database as? SQLDatabase else {
fatalError("Database must be an SQLDatabase ('as? SQLDatabase' must succeed)")
}
return db.raw("REFRESH MATERIALIZED VIEW \(raw: Self.schema)").run()
}
static func fetch(on database: Database) -> EventLoopFuture<Stats?> {
guard let db = database as? SQLDatabase else {
fatalError("Database must be an SQLDatabase ('as? SQLDatabase' must succeed)")
}
return db.raw("SELECT * FROM \(raw: Self.schema)")
.first(decoding: Stats.self)
}
}
| 28.457143 | 90 | 0.633534 |
89024cb66432eff0bed7e6ea8b057b7d6937d93d | 3,759 | import UIKit
class NodeSearchResultViewController: DataViewController {
// MARK: - UI
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.keyboardDismissMode = .onDrag
tableView.estimatedRowHeight = 120
tableView.rowHeight = UITableView.automaticDimension
tableView.backgroundColor = .clear
tableView.hideEmptyCells()
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
self.view.addSubview(tableView)
return tableView
}()
// MARK: - Propertys
public var originData: [NodeModel]?
public var didSelectedNodeHandle:((NodeModel) -> Void)?
private var query: String?
private var searchResults: [NodeModel] = [] {
didSet {
tableView.reloadData()
endLoading()
}
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
automaticallyAdjustsScrollViewInsets = false
status = .noSearchResult
ThemeStyle.style.asObservable()
.subscribeNext { [weak self] theme in
self?.tableView.separatorColor = theme.borderColor
}.disposed(by: rx.disposeBag)
}
// MARK: - Setup
override func setupSubviews() {
status = .empty
startLoading()
}
override func setupConstraints() {
tableView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
// MARK: State Handle
override func hasContent() -> Bool {
return searchResults.count.boolValue
}
override func loadData() {
}
override func errorView(_ errorView: ErrorView, didTapActionButton sender: UIButton) {
}
}
// MARK: - UITableViewDelegate & UITableViewDataSource
extension NodeSearchResultViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "NodesCell")
if cell == nil {
cell = BaseTableViewCell(style: .default, reuseIdentifier: "NodesCell")
cell?.separatorInset = .zero
}
cell?.textLabel?.text = searchResults[indexPath.row].title
if let `query` = query {
cell?.textLabel?.makeSubstringColor(query, color: UIColor.hex(0xD33F3F))
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let node = searchResults[indexPath.row]
if let callback = didSelectedNodeHandle {
dismiss(animated: true, completion: {
callback(node)
})
return
}
tableView.deselectRow(at: indexPath, animated: true)
let nodeDetailVC = NodeDetailViewController(node: node)
presentingViewController?.navigationController?.pushViewController(nodeDetailVC, animated: true)
}
}
// MARK: - UISearchResultsUpdating
extension NodeSearchResultViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let query = searchController.searchBar.text?.trimmed,
query.isNotEmpty,
let `originData` = originData else {
return
}
self.query = query
searchResults = originData.filter { $0.title.lowercased().contains(query.lowercased()) }
}
}
| 29.598425 | 104 | 0.64299 |
61998ee0901556d7a5e4273da1116f27eee7b804 | 6,064 | //
// PGPKeyArmorImportTableViewController.swift
// pass
//
// Created by Mingshen Sun on 17/2/2017.
// Copyright © 2017 Bob Sun. All rights reserved.
//
import UIKit
import passKit
class PGPKeyArmorImportTableViewController: AutoCellHeightUITableViewController, UITextViewDelegate, QRScannerControllerDelegate {
@IBOutlet weak var armorPublicKeyTextView: UITextView!
@IBOutlet weak var armorPrivateKeyTextView: UITextView!
@IBOutlet weak var scanPublicKeyCell: UITableViewCell!
@IBOutlet weak var scanPrivateKeyCell: UITableViewCell!
class ScannedPGPKey {
enum KeyType {
case publicKey, privateKey
}
var keyType = KeyType.publicKey
var segments = [String]()
var message = ""
func reset(keytype: KeyType) {
self.keyType = keytype
self.segments.removeAll()
message = "LookingForStartingFrame.".localize()
}
func addSegment(segment: String) -> (accept: Bool, message: String) {
let keyTypeStr = self.keyType == .publicKey ? "Public" : "Private"
let theOtherKeyTypeStr = self.keyType == .publicKey ? "Private" : "Public"
// Skip duplicated segments.
guard segment != self.segments.last else {
return (accept: false, message: self.message)
}
// Check whether we have found the first block.
guard !self.segments.isEmpty || segment.contains("-----BEGIN PGP \(keyTypeStr.uppercased()) KEY BLOCK-----") else {
// Check whether we are scanning the wrong key type.
if segment.contains("-----BEGIN PGP \(theOtherKeyTypeStr.uppercased()) KEY BLOCK-----") {
self.message = "Scan\(keyTypeStr)Key.".localize()
}
return (accept: false, message: self.message)
}
// Update the list of scanned segment and return.
self.segments.append(segment)
if segment.contains("-----END PGP \(keyTypeStr.uppercased()) KEY BLOCK-----") {
self.message = "Done".localize()
return (accept: true, message: self.message)
} else {
self.message = "ScannedQrCodes(%d)".localize(self.segments.count)
return (accept: false, message: self.message)
}
}
}
var scanned = ScannedPGPKey()
override func viewDidLoad() {
super.viewDidLoad()
scanPublicKeyCell?.textLabel?.text = "ScanPublicKeyQrCodes".localize()
scanPublicKeyCell?.selectionStyle = .default
scanPublicKeyCell?.accessoryType = .disclosureIndicator
scanPrivateKeyCell?.textLabel?.text = "ScanPrivateKeyQrCodes".localize()
scanPrivateKeyCell?.selectionStyle = .default
scanPrivateKeyCell?.accessoryType = .disclosureIndicator
}
@IBAction func save(_ sender: Any) {
savePassphraseDialog()
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == UIPasteboard.general.string {
// user pastes something, do the copy here again and clear the pasteboard in 45s
SecurePasteboard.shared.copy(textToCopy: text)
}
return true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
if selectedCell == scanPublicKeyCell {
scanned.reset(keytype: ScannedPGPKey.KeyType.publicKey)
self.performSegue(withIdentifier: "showPGPScannerSegue", sender: self)
} else if selectedCell == scanPrivateKeyCell {
scanned.reset(keytype: ScannedPGPKey.KeyType.privateKey)
self.performSegue(withIdentifier: "showPGPScannerSegue", sender: self)
}
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - QRScannerControllerDelegate Methods
func checkScannedOutput(line: String) -> (accept: Bool, message: String) {
return scanned.addSegment(segment: line)
}
// MARK: - QRScannerControllerDelegate Methods
func handleScannedOutput(line: String) {
let key = scanned.segments.joined(separator: "")
switch scanned.keyType {
case .publicKey:
armorPublicKeyTextView.text = key
case .privateKey:
armorPrivateKeyTextView.text = key
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPGPScannerSegue" {
if let navController = segue.destination as? UINavigationController {
if let viewController = navController.topViewController as? QRScannerController {
viewController.delegate = self
}
} else if let viewController = segue.destination as? QRScannerController {
viewController.delegate = self
}
}
}
}
extension PGPKeyArmorImportTableViewController: PGPKeyImporter {
static let keySource = KeySource.armor
static let label = "AsciiArmorEncryptedKey".localize()
func isReadyToUse() -> Bool {
guard !armorPublicKeyTextView.text.isEmpty else {
Utils.alert(title: "CannotSave".localize(), message: "SetPublicKey.".localize(), controller: self, completion: nil)
return false
}
guard !armorPrivateKeyTextView.text.isEmpty else {
Utils.alert(title: "CannotSave".localize(), message: "SetPrivateKey.".localize(), controller: self, completion: nil)
return false
}
return true
}
func importKeys() throws {
try KeyFileManager.PublicPgp.importKey(from: armorPublicKeyTextView.text ?? "")
try KeyFileManager.PrivatePgp.importKey(from: armorPrivateKeyTextView.text ?? "")
}
func saveImportedKeys() {
performSegue(withIdentifier: "savePGPKeySegue", sender: self)
}
}
| 39.122581 | 130 | 0.635884 |
9ca82bf30e43d3b2ab70f1a8baa8ddca8af23c95 | 4,688 | //
// DemoViewController.swift
// iOSDemo
//
// Created by Stan Hu on 2018/8/1.
// Copyright © 2018 Stan Hu. All rights reserved.
//
import UIKit
class DemoViewController: BaseViewController {
let btnLargeTouch = UIButton()
let btnLargeTouch2 = TouchIncreaseButton()
let btn3 = UIButton()
let vCover = UIView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
btnLargeTouch.layer.cornerRadius = 50
btnLargeTouch.touchInsets = UIEdgeInsets(top: -30, left: -30, bottom: 30, right: 30) //这样没有用,因为根本没触发到
btnLargeTouch.addTarget(self, action: #selector(testTouch), for: .touchUpInside)
btnLargeTouch.color(color: UIColor.gray).title(title: "大的边缘范围").bgColor(color: UIColor.yellow).addTo(view: view).snp.makeConstraints { (m) in
m.left.equalTo(100)
m.top.equalTo(200)
m.width.height.equalTo(100)
}
btnLargeTouch2.layer.cornerRadius = 50
btnLargeTouch2.addTarget(self, action: #selector(testTouch2), for: .touchUpInside)
// btnLargeTouch2.color(color: UIColor.gray).title(title: "大的边缘范围").bgColor(color: UIColor.yellow).addTo(view: view).snp.makeConstraints { (m) in
// m.left.equalTo(100)
// m.top.equalTo(400)
// m.width.height.equalTo(100)
// }
btnLargeTouch2.translatesAutoresizingMaskIntoConstraints = false
btnLargeTouch2.color(color: UIColor.gray).title(title: "大的边缘范围").bgColor(color: UIColor.yellow).addTo(view: view).completed()
let cenX = NSLayoutConstraint(item: btnLargeTouch2, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
let cenY = NSLayoutConstraint(item: btnLargeTouch2, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: btnLargeTouch2, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
let height = NSLayoutConstraint(item: btnLargeTouch2, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 100)
NSLayoutConstraint.activate([cenX,cenY,width,height])
btn3.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
btn3.backgroundColor = UIColor.green
btn3.addTarget(self, action: #selector(throuTouch), for: .touchUpInside)
view.addSubview(btn3)
// vCover.backgroundColor = UIColor.purple.withAlphaComponent(0.3)
// vCover.frame = CGRect(x: 80, y: 80, width: 130, height: 80)
// view.addSubview(vCover)
}
@objc func throuTouch() {
print("throuTouch")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
btnLargeTouch.touchInsets = UIEdgeInsets(top: -50, left: -50, bottom: -50, right: -50) //要这样写才有用,那我还是感觉实用不是很大
}
@objc func testTouch() {
Log(message: "这里也可以点到我")
UIApplication.shared.open(URL(string: "tel:17665262225")!, options: [UIApplication.OpenExternalURLOptionsKey.universalLinksOnly:false], completionHandler: nil)
}
@objc func testTouch2() {
Log(message: "这里也可以点到我的另一个")
}
}
class TouchIncreaseButton: UIButton {
private let btnWidth : CGFloat = 44
private let btnHeight : CGFloat = 44
private func hitTestBounds(minimumHitTestWidth minWidth : CGFloat,minimumHitTestHeight minHeight : CGFloat) -> CGRect {
var hitTestBounds = self.bounds
if minWidth > bounds.size.width {
hitTestBounds.size.width = minWidth
hitTestBounds.origin.x -= (hitTestBounds.size.width - bounds.size.width)/2
}
if minHeight > bounds.size.height {
hitTestBounds.size.height = minHeight
hitTestBounds.origin.y -= (hitTestBounds.size.height - bounds.size.height)/2
}
return hitTestBounds
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let rect = hitTestBounds(minimumHitTestWidth: btnWidth, minimumHitTestHeight: btnHeight)
return rect.contains(point)
}
}
| 43.009174 | 254 | 0.675341 |
ffa580daacb1b50c1bbffd8b6b21b318ef99b4f8 | 15,212 | import UIKit
@IBDesignable
class IceCreamView: UIView {
// MARK: Variables
@IBInspectable var iceCreamTopColor: UIColor = Flavor.vanilla().topColor {
didSet {
setNeedsDisplay()
}
}
@IBInspectable var iceCreamBottomColor: UIColor = Flavor.vanilla().bottomColor {
didSet {
setNeedsDisplay()
}
}
private let coneOuterColor = UIColor.RGB(red: 184, green: 104, blue: 50)
private let coneInnerColor = UIColor.RGB(red: 209, green: 160, blue: 102)
private let coneLaticeColor = UIColor.RGB(red: 235, green: 183, blue: 131)
// MARK: View Lifecycle
override func draw(_ frame: CGRect) {
// General Declarations
let context = UIGraphicsGetCurrentContext()!
// Gradient Declarations
let iceCreamGradient = CGGradient(
colorsSpace: CGColorSpaceCreateDeviceRGB(),
colors: [iceCreamTopColor.cgColor, iceCreamBottomColor.cgColor] as CFArray,
locations: [0, 1])
// Shadow Declarations
let coneInnerShadow = coneOuterColor
let coneInnerShadowOffset = CGSize(width: 0.1, height: -0.1)
let coneInnerShadowBlurRadius: CGFloat = 35
let scoopShadow = UIColor.black.withAlphaComponent(0.25)
let scoopShadowOffset = CGSize(width: 0.1, height: 3.1)
let scoopShadowBlurRadius: CGFloat = 2
let coneOuterShadow = UIColor.black.withAlphaComponent(0.35)
let coneOuterShadowOffset = CGSize(width: 0.1, height: 3.1)
let coneOuterShadowBlurRadius: CGFloat = 3
// Cone Drawing
let conePath = UIBezierPath()
conePath.move(to: CGPoint(x: frame.minX + 0.98284 * frame.width, y: frame.minY + 0.29579 * frame.height))
conePath.addCurve(to: CGPoint(x: frame.minX + 0.49020 * frame.width, y: frame.minY + 0.35519 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.98284 * frame.width, y: frame.minY + 0.29579 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.72844 * frame.width, y: frame.minY + 0.35519 * frame.height))
conePath.addCurve(to: CGPoint(x: frame.minX + 0.01225 * frame.width, y: frame.minY + 0.29579 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.25196 * frame.width, y: frame.minY + 0.35519 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.01225 * frame.width, y: frame.minY + 0.29579 * frame.height))
conePath.addLine(to: CGPoint(x: frame.minX + 0.49265 * frame.width, y: frame.minY + 0.98886 * frame.height))
conePath.addLine(to: CGPoint(x: frame.minX + 0.98284 * frame.width, y: frame.minY + 0.29579 * frame.height))
conePath.close()
conePath.lineJoinStyle = CGLineJoin.round
context.saveGState()
context.setShadow(offset: coneOuterShadowOffset, blur: coneOuterShadowBlurRadius, color: coneOuterShadow.cgColor)
coneInnerColor.setFill()
conePath.fill()
// Cone Inner Shadow
context.saveGState()
context.clip(to: conePath.bounds)
context.setShadow(offset: CGSize(width: 0, height: 0), blur: 0)
context.setAlpha(coneInnerShadow.cgColor.alpha)
context.beginTransparencyLayer(auxiliaryInfo: nil)
let coneOpaqueShadow = coneInnerShadow.withAlphaComponent(1)
context.setShadow(offset: coneInnerShadowOffset, blur: coneInnerShadowBlurRadius, color: coneOpaqueShadow.cgColor)
context.setBlendMode(CGBlendMode.sourceOut)
context.beginTransparencyLayer(auxiliaryInfo: nil)
coneOpaqueShadow.setFill()
conePath.fill()
context.endTransparencyLayer()
context.endTransparencyLayer()
context.restoreGState()
context.restoreGState()
coneOuterColor.setStroke()
conePath.lineWidth = 0.5
conePath.stroke()
// Lattice 1 Drawing
let lattice1Path = UIBezierPath()
lattice1Path.move(to: CGPoint(x: frame.minX + 0.41667 * frame.width, y: frame.minY + 0.86881 * frame.height))
lattice1Path.addLine(to: CGPoint(x: frame.minX + 0.62255 * frame.width, y: frame.minY + 0.79950 * frame.height))
coneLaticeColor.setStroke()
lattice1Path.lineWidth = 1
lattice1Path.stroke()
// Lattice 2 Drawing
let lattice2Path = UIBezierPath()
lattice2Path.move(to: CGPoint(x: frame.minX + 0.34804 * frame.width, y: frame.minY + 0.76980 * frame.height))
lattice2Path.addLine(to: CGPoint(x: frame.minX + 0.73039 * frame.width, y: frame.minY + 0.64604 * frame.height))
coneLaticeColor.setStroke()
lattice2Path.lineWidth = 1
lattice2Path.stroke()
// Lattice 3 Drawing
let lattice3Path = UIBezierPath()
lattice3Path.move(to: CGPoint(x: frame.minX + 0.27941 * frame.width, y: frame.minY + 0.67079 * frame.height))
lattice3Path.addLine(to: CGPoint(x: frame.minX + 0.82843 * frame.width, y: frame.minY + 0.50743 * frame.height))
coneLaticeColor.setStroke()
lattice3Path.lineWidth = 1
lattice3Path.stroke()
// Lattice 4 Drawing
let lattice4Path = UIBezierPath()
lattice4Path.move(to: CGPoint(x: frame.minX + 0.21078 * frame.width, y: frame.minY + 0.57178 * frame.height))
lattice4Path.addLine(to: CGPoint(x: frame.minX + 0.92647 * frame.width, y: frame.minY + 0.36881 * frame.height))
coneLaticeColor.setStroke()
lattice4Path.lineWidth = 1
lattice4Path.stroke()
// Lattice 5 Drawing
let lattice5Path = UIBezierPath()
lattice5Path.move(to: CGPoint(x: frame.minX + 0.14216 * frame.width, y: frame.minY + 0.47277 * frame.height))
lattice5Path.addLine(to: CGPoint(x: frame.minX + 0.53431 * frame.width, y: frame.minY + 0.35891 * frame.height))
coneLaticeColor.setStroke()
lattice5Path.lineWidth = 1
lattice5Path.stroke()
// Lattice 6 Drawing
let lattice6Path = UIBezierPath()
lattice6Path.move(to: CGPoint(x: frame.minX + 0.07353 * frame.width, y: frame.minY + 0.37376 * frame.height))
lattice6Path.addLine(to: CGPoint(x: frame.minX + 0.20098 * frame.width, y: frame.minY + 0.33416 * frame.height))
coneLaticeColor.setStroke()
lattice6Path.lineWidth = 1
lattice6Path.stroke()
// Lattice 7 Drawing
let lattice7Path = UIBezierPath()
coneLaticeColor.setStroke()
lattice7Path.lineWidth = 1
lattice7Path.stroke()
// Lattice 8 Drawing
let lattice8Path = UIBezierPath()
UIColor.black.setStroke()
lattice8Path.lineWidth = 1
lattice8Path.stroke()
// Lattice 9 Drawing
let lattice9Path = UIBezierPath()
lattice9Path.move(to: CGPoint(x: frame.minX + 0.64706 * frame.width, y: frame.minY + 0.76733 * frame.height))
lattice9Path.addLine(to: CGPoint(x: frame.minX + 0.25490 * frame.width, y: frame.minY + 0.64356 * frame.height))
coneLaticeColor.setStroke()
lattice9Path.lineWidth = 1
lattice9Path.stroke()
// Lattice 10 Drawing
let lattice10Path = UIBezierPath()
lattice10Path.move(to: CGPoint(x: frame.minX + 0.71569 * frame.width, y: frame.minY + 0.66832 * frame.height))
lattice10Path.addLine(to: CGPoint(x: frame.minX + 0.16176 * frame.width, y: frame.minY + 0.50248 * frame.height))
coneLaticeColor.setStroke()
lattice10Path.lineWidth = 1
lattice10Path.stroke()
// Lattice 11 Drawing
let lattice11Path = UIBezierPath()
lattice11Path.move(to: CGPoint(x: frame.minX + 0.78922 * frame.width, y: frame.minY + 0.56683 * frame.height))
lattice11Path.addLine(to: CGPoint(x: frame.minX + 0.06373 * frame.width, y: frame.minY + 0.35891 * frame.height))
coneLaticeColor.setStroke()
lattice11Path.lineWidth = 1
lattice11Path.stroke()
// Lattice 12 Drawing
let lattice12Path = UIBezierPath()
lattice12Path.move(to: CGPoint(x: frame.minX + 0.85294 * frame.width, y: frame.minY + 0.46535 * frame.height))
lattice12Path.addLine(to: CGPoint(x: frame.minX + 0.46078 * frame.width, y: frame.minY + 0.35644 * frame.height))
coneLaticeColor.setStroke()
lattice12Path.lineWidth = 1
lattice12Path.stroke()
// Lattice 13 Drawing
let lattice13Path = UIBezierPath()
lattice13Path.move(to: CGPoint(x: frame.minX + 0.92157 * frame.width, y: frame.minY + 0.37129 * frame.height))
lattice13Path.addLine(to: CGPoint(x: frame.minX + 0.79412 * frame.width, y: frame.minY + 0.33168 * frame.height))
coneLaticeColor.setStroke()
lattice13Path.lineWidth = 1
lattice13Path.stroke()
// Lattice 14 Drawing
let lattice14Path = UIBezierPath()
lattice14Path.move(to: CGPoint(x: frame.minX + 0.58333 * frame.width, y: frame.minY + 0.85891 * frame.height))
lattice14Path.addCurve(to: CGPoint(x: frame.minX + 0.35784 * frame.width, y: frame.minY + 0.78465 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.36765 * frame.width, y: frame.minY + 0.78465 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.35784 * frame.width, y: frame.minY + 0.78465 * frame.height))
coneLaticeColor.setStroke()
lattice14Path.lineWidth = 1
lattice14Path.stroke()
// Scoop Drawing
let scoopPath = UIBezierPath()
scoopPath.move(to: CGPoint(x: frame.minX + 0.39216 * frame.width, y: frame.minY + 0.35149 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.50000 * frame.width, y: frame.minY + 0.40099 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.43137 * frame.width, y: frame.minY + 0.35149 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.43137 * frame.width, y: frame.minY + 0.40099 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.58824 * frame.width, y: frame.minY + 0.35149 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.56863 * frame.width, y: frame.minY + 0.40099 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.54902 * frame.width, y: frame.minY + 0.35149 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.68627 * frame.width, y: frame.minY + 0.40099 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.62745 * frame.width,y: frame.minY + 0.35149 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.62745 * frame.width, y: frame.minY + 0.40099 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.78431 * frame.width, y: frame.minY + 0.33663 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.74510 * frame.width, y: frame.minY + 0.40099 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.74510 * frame.width, y: frame.minY + 0.33663 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.88235 * frame.width, y: frame.minY + 0.37129 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.82353 * frame.width, y: frame.minY + 0.33663 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.82353 * frame.width, y: frame.minY + 0.37129 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.99020 * frame.width, y: frame.minY + 0.30198 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.94118 * frame.width, y: frame.minY + 0.37129 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.99020 * frame.width, y: frame.minY + 0.31683 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.99020 * frame.width, y: frame.minY + 0.25248 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.99020 * frame.width, y: frame.minY + 0.28713 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.99020 * frame.width, y: frame.minY + 0.26967 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.50000 * frame.width, y: frame.minY + 0.00495 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.99020 * frame.width, y: frame.minY + 0.11577 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.77073 * frame.width, y: frame.minY + 0.00495 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.00980 * frame.width, y: frame.minY + 0.25248 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.22927 * frame.width, y: frame.minY + 0.00495 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.00980 * frame.width, y: frame.minY + 0.11577 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.00980 * frame.width, y: frame.minY + 0.30198 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.00980 * frame.width, y: frame.minY + 0.27047 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.00980 * frame.width, y: frame.minY + 0.28713 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.10784 * frame.width, y: frame.minY + 0.37624 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.00980 * frame.width, y: frame.minY + 0.31683 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.04902 * frame.width, y: frame.minY + 0.37624 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.19608 * frame.width, y: frame.minY + 0.33663 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.16667 * frame.width, y: frame.minY + 0.37624 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.15686 * frame.width, y: frame.minY + 0.33663 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.29412 * frame.width, y: frame.minY + 0.40099 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.23529 * frame.width, y: frame.minY + 0.33663 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.22549 * frame.width, y: frame.minY + 0.40099 * frame.height))
scoopPath.addCurve(to: CGPoint(x: frame.minX + 0.39216 * frame.width, y: frame.minY + 0.35149 * frame.height),
controlPoint1: CGPoint(x: frame.minX + 0.36275 * frame.width, y: frame.minY + 0.40099 * frame.height),
controlPoint2: CGPoint(x: frame.minX + 0.35294 * frame.width, y: frame.minY + 0.35149 * frame.height))
scoopPath.close()
context.saveGState()
context.setShadow(offset: scoopShadowOffset, blur: scoopShadowBlurRadius, color: scoopShadow.cgColor)
context.beginTransparencyLayer(auxiliaryInfo: nil)
scoopPath.addClip()
let scoopBounds = scoopPath.cgPath.boundingBoxOfPath
context.drawLinearGradient(iceCreamGradient!,
start: CGPoint(x: scoopBounds.midX, y: scoopBounds.minY),
end: CGPoint(x: scoopBounds.midX, y: scoopBounds.maxY),
options: CGGradientDrawingOptions())
context.endTransparencyLayer()
context.restoreGState()
}
}
extension IceCreamView: FlavorAdapter {
func updateWithFlavor(_ flavor: Flavor) {
self.iceCreamTopColor = flavor.topColor
self.iceCreamBottomColor = flavor.bottomColor
setNeedsDisplay()
}
}
| 53.56338 | 129 | 0.655667 |
33cf670e733c27679a9f7d1d9f7af099552a2428 | 258 | //
// MBMask.swift
// Pods
//
// Created by ZhengYidong on 14/12/2016.
//
//
import Foundation
/// Mask protocol for `MBLoadable`, View that conforms to this protocol will be treated as mask
public protocol MBMaskable {
var maskId: String { get }
}
| 17.2 | 95 | 0.686047 |
2094ff32c063023d1efcdd43f1ce8dce97d4b4d7 | 1,524 | //
// MovieBLImplementation.swift
// TestMerqueo
//
// Created by Juan Esteban Monsalve Echeverry on 6/01/21.
//
import Foundation
import RxSwift
class MovieBLImplementation : MovieBL {
var movieRepository : MovieRepository
init(movieRepository : MovieRepository) {
self.movieRepository = movieRepository
}
func getPopularMovies(_ page: Int) throws -> Observable<PopularMoviesResponse> {
return try movieRepository.getPopularMovies(page).asObservable().flatMap({
response -> Observable<PopularMoviesResponse> in
return Observable.just(response)
})
}
func getMovieDetail(_ movieId: Int) throws -> Observable<MovieDetailResponse> {
return try movieRepository.getMovieDetail(movieId).asObservable().flatMap({
response -> Observable<MovieDetailResponse> in
return Observable.just(response)
})
}
func getMovieCredits(_ movieId: Int) throws -> Observable<MovieCreditsResponse> {
return try movieRepository.getMovieCredits(movieId).asObservable().flatMap({
response -> Observable<MovieCreditsResponse> in
return Observable.just(response)
})
}
func getMovieByWord(_ word: String) throws -> Observable<PopularMoviesResponse> {
return try movieRepository.getMovieByWord(word).asObservable().flatMap({
response -> Observable<PopularMoviesResponse> in
return Observable.just(response)
})
}
}
| 31.75 | 85 | 0.676509 |
164a7e2cc821790c1711b5de9de2bb6f9330ae5d | 1,742 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct CallbackConfigData : CallbackConfigProtocol {
public var serviceUri: String
public var customHeaders: [String:String]?
enum CodingKeys: String, CodingKey {case serviceUri = "serviceUri"
case customHeaders = "customHeaders"
}
public init(serviceUri: String) {
self.serviceUri = serviceUri
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.serviceUri = try container.decode(String.self, forKey: .serviceUri)
if container.contains(.customHeaders) {
self.customHeaders = try container.decode([String:String]?.self, forKey: .customHeaders)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.serviceUri, forKey: .serviceUri)
if self.customHeaders != nil {try container.encode(self.customHeaders, forKey: .customHeaders)}
}
}
extension DataFactory {
public static func createCallbackConfigProtocol(serviceUri: String) -> CallbackConfigProtocol {
return CallbackConfigData(serviceUri: serviceUri)
}
}
| 38.711111 | 119 | 0.716992 |
b9708efaadebf7413a3cc45c6f7a411d63f60c4b | 702 | //
// Bowtie+CoreDataProperties.swift
// Bow Ties
//
// Created by Karsten Gresch on 08.06.17.
// Copyright © 2017 Razeware. All rights reserved.
//
import Foundation
import CoreData
extension Bowtie {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Bowtie> {
return NSFetchRequest<Bowtie>(entityName: "Bowtie")
}
@NSManaged public var isFavorite: Bool
@NSManaged public var lastWorn: NSDate?
@NSManaged public var name: String?
@NSManaged public var photoData: NSData?
@NSManaged public var searchKey: String?
@NSManaged public var timesWorn: Int32
@NSManaged public var tintColor: NSObject?
@NSManaged public var rating: Double
}
| 24.206897 | 73 | 0.712251 |
561ad8b3e6f59cca350cdd38e324584fe47f9d94 | 673 | //
// BandMenuOption.swift
// Metal Archives
//
// Created by Thanh-Nhon Nguyen on 01/06/2019.
// Copyright © 2019 Thanh-Nhon Nguyen. All rights reserved.
//
import Foundation
enum BandMenuOption: Int, CustomStringConvertible, CaseIterable {
case discography = 0, members, reviews, similarArtists, about, relatedLinks
var description: String {
switch self {
case .discography: return "Discography"
case .members: return "Members"
case .reviews: return "Reviews"
case .similarArtists: return "Similar Artists"
case .about: return "About"
case .relatedLinks: return "Related Links"
}
}
}
| 26.92 | 79 | 0.662704 |
c1d52ceac460e7928a52d31072ef3127b12f68a2 | 4,514 | //
// ViewController.swift
// Blockstack
//
// Created by Yukan Liao on 03/27/2018.
//
import UIKit
import Blockstack
import SafariServices
class ViewController: UIViewController {
@IBOutlet var signInButton: UIButton?
@IBOutlet var nameLabel: UILabel?
@IBOutlet weak var putFileButton: UIButton!
override func viewDidLoad() {
self.updateUI()
}
@IBAction func signIn() {
// Address of deployed example web app
Blockstack.shared.signIn(redirectURI: "https://heuristic-brown-7a88f8.netlify.com/redirect.html",
appDomain: URL(string: "https://heuristic-brown-7a88f8.netlify.com")!) { authResult in
switch authResult {
case .success(let userData):
print("sign in success")
self.handleSignInSuccess(userData: userData)
case .cancelled:
print("sign in cancelled")
case .failed(let error):
print("sign in failed, error: ", error ?? "n/a")
}
}
}
func handleSignInSuccess(userData: UserData) {
print(userData.profile?.name as Any)
self.updateUI()
// Check if signed in
// checkIfSignedIn()
}
@IBAction func signOut(_ sender: Any) {
// Sign user out
Blockstack.shared.signOut(redirectURI: "myBlockstackApp") { error in
if let error = error {
print("sign out failed, error: \(error)")
} else {
self.updateUI()
print("sign out success")
}
}
}
@IBAction func putFileTapped(_ sender: Any) {
guard let userData = Blockstack.shared.loadUserData(),
let privateKey = userData.privateKey,
let publicKey = Keys.getPublicKeyFromPrivate(privateKey) else {
return
}
// Store data on Gaia
let content: Dictionary<String, String> = ["property1": "value", "property2": "hello"]
guard let data = try? JSONSerialization.data(withJSONObject: content, options: []),
let jsonString = String(data: data, encoding: .utf8) else {
return
}
// Encrypt content
guard let cipherText = Encryption.encryptECIES(recipientPublicKey: publicKey, content: jsonString) else {
return
}
// Decrypt content
guard let plainTextJson = Encryption.decryptECIES(privateKey: privateKey, cipherObjectJSONString: cipherText)?.plainText,
let dataFromJson = plainTextJson.data(using: .utf8),
let jsonObject = try? JSONSerialization.jsonObject(with: dataFromJson, options: []),
let decryptedContent = jsonObject as? [String: String] else {
return
}
// Put file example
Blockstack.shared.putFile(path: "test.json", content: decryptedContent) { (publicURL, error) in
if error != nil {
print("put file error")
} else {
print("put file success \(publicURL!)")
// Read data from Gaia
Blockstack.shared.getFile(path: "test.json", completion: { (response, error) in
if error != nil {
print("get file error")
} else {
print("get file success")
print(response as Any)
}
})
}
}
}
private func updateUI() {
DispatchQueue.main.async {
if Blockstack.shared.isSignedIn() {
// Read user profile data
let retrievedUserData = Blockstack.shared.loadUserData()
print(retrievedUserData?.profile?.name as Any)
let name = retrievedUserData?.profile?.name ?? "Nameless Person"
self.nameLabel?.text = "Hello, \(name)"
self.nameLabel?.isHidden = false
self.signInButton?.isHidden = true
self.putFileButton.isHidden = false
} else {
self.nameLabel?.isHidden = true
self.signInButton?.isHidden = false
self.putFileButton.isHidden = true
}
}
}
func checkIfSignedIn() {
Blockstack.shared.isSignedIn() ? print("currently signed in") : print("not signed in")
}
}
| 34.723077 | 129 | 0.544307 |
48fc86d548416b5c8c7b0f236e42ac161182e85d | 5,956 | //
// SettingsBackup
// Slide for Reddit
//
// Created by Carlos Crane on 6/11/18.
// Copyright © 2018 Haptic Apps. All rights reserved.
//
import BiometricAuthentication
import LicensesViewController
import RealmSwift
import RLBAlertsPickers
import SDWebImage
import UIKit
class SettingsBackup: UITableViewController {
static var changed = false
var restore: UITableViewCell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
var backup: UITableViewCell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight() && SettingValues.reduceColor {
return .default
} else {
return .lightContent
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupBaseBarColors()
navigationController?.setToolbarHidden(true, animated: false)
doCells()
}
override func loadView() {
super.loadView()
}
func doCells(_ reset: Bool = true) {
self.view.backgroundColor = ColorUtil.backgroundColor
// set the title
self.title = "Backup"
self.tableView.separatorStyle = .none
self.backup.textLabel?.text = "Backup"
self.backup.detailTextLabel?.text = "Backup your Slide data to iCloud"
self.backup.backgroundColor = ColorUtil.foregroundColor
self.backup.detailTextLabel?.textColor = ColorUtil.fontColor
self.backup.textLabel?.textColor = ColorUtil.fontColor
self.backup.imageView?.image = UIImage.init(named: "download")?.toolbarIcon().getCopy(withColor: ColorUtil.fontColor)
self.backup.imageView?.tintColor = ColorUtil.fontColor
self.restore.textLabel?.text = "Restore"
self.restore.backgroundColor = ColorUtil.foregroundColor
self.restore.detailTextLabel?.textColor = ColorUtil.fontColor
self.restore.textLabel?.textColor = ColorUtil.fontColor
self.restore.detailTextLabel?.text = "Restore your backup data from iCloud"
self.restore.imageView?.image = UIImage.init(named: "restore")?.toolbarIcon().getCopy(withColor: ColorUtil.fontColor)
self.restore.imageView?.tintColor = ColorUtil.fontColor
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension SettingsBackup {
func doBackup() {
let alert = UIAlertController.init(title: "Really back up your data?", message: "This will overwrite any previous backups", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in
self.backupSync()
}))
alert.addAction(UIAlertAction.init(title: "No", style: .cancel, handler: { (_) in
}))
present(alert, animated: true)
}
func doRestore() {
let alert = UIAlertController.init(title: "Really restore your data?", message: "This will overwrite all current Slide settings and you will have to restart Slide for the changes to take place", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Yes", style: .destructive, handler: { (_) in
self.restoreSync()
}))
alert.addAction(UIAlertAction.init(title: "No", style: .cancel, handler: { (_) in
}))
present(alert, animated: true)
}
func backupSync() {
let icloud = NSUbiquitousKeyValueStore.default
for item in icloud.dictionaryRepresentation {
icloud.removeObject(forKey: item.key)
}
for item in UserDefaults.standard.dictionaryRepresentation() {
icloud.set(item.value, forKey: item.key)
}
icloud.synchronize()
let alert = UIAlertController.init(title: "Your data has been synced!", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .cancel, handler: { (_) in
self.dismiss(animated: true, completion: nil)
}))
present(alert, animated: true)
}
func restoreSync() {
let icloud = NSUbiquitousKeyValueStore.default
for item in icloud.dictionaryRepresentation {
UserDefaults.standard.set(item.value, forKey: item.key)
}
UserDefaults.standard.synchronize()
let alert = UIAlertController.init(title: "Your data has been restored!", message: "Slide will now close to apply changes", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close Slide", style: .cancel, handler: { (_) in
exit(0)
}))
present(alert, animated: true)
}
}
// MARK: - UITableView
extension SettingsBackup {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return self.backup
case 1: return self.restore
default: fatalError("Unknown row in section 0")
}
default: fatalError("Unknown section")
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0 {
doBackup()
} else {
doRestore()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 2
default: fatalError("Unknown number of sections")
}
}
}
| 36.09697 | 226 | 0.656145 |
09affb2924853ba6e3d89a40f35767249f2c9e30 | 448 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
// AutoUserSpecificationProtocol is
public protocol AutoUserSpecificationProtocol : Codable {
var scope: AutoUserScopeEnum? { get set }
var elevationLevel: ElevationLevelEnum? { get set }
}
| 40.727273 | 96 | 0.754464 |
48517cae7b8fe55c00f905d38f6a1c2bec52f7bb | 385 | //
// WKRDefaults.swift
// WKRKit
//
// Created by Andrew Finke on 7/18/20.
// Copyright © 2020 Andrew Finke. All rights reserved.
//
import Foundation
struct WKRDefaults {
private static let fastlaneKey = "FASTLANE_SNAPSHOT"
static var isFastlaneSnapshotInstance: Bool {
get {
return UserDefaults.standard.bool(forKey: fastlaneKey)
}
}
}
| 20.263158 | 66 | 0.664935 |
397c9d8bcb6b4d8f86b518f64444480afc2384a5 | 257 | //
// ErrorCodes.swift
// AppliverySDK
//
// Created by Alejandro Jiménez Agudo on 27/10/16.
// Copyright © 2016 Applivery S.L. All rights reserved.
//
import Foundation
struct ErrorCodes {
static let Unknown = -1
static let JsonParse = 10001
}
| 15.117647 | 56 | 0.692607 |
db0c10dd5879a97d2630fb37eb1707fc69145b25 | 1,012 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "BlueShift-iOS-SDK",
products: [
.library(
name: "BlueShift_iOS_SDK",
targets: ["BlueShift_iOS_SDK"]),
.library(
name: "BlueShift_iOS_Extension_SDK",
targets: ["BlueShift_iOS_Extension_SDK"]),
],
dependencies: [],
targets: [
.binaryTarget(name: "BlueShift_iOS_SDK", url: "https://github.com/blueshift-labs/Blueshift-iOS-SDK/releases/download/2.1.14/BlueShift_iOS_SDK.xcframework.zip", checksum: "658186fcc319bba577a36282ee02998e5f9ecdcffdf8be495ccc13ece44daa55"),
.binaryTarget(name: "BlueShift_iOS_Extension_SDK", url: "https://github.com/blueshift-labs/Blueshift-iOS-SDK/releases/download/2.1.14/BlueShift_iOS_Extension_SDK.xcframework.zip", checksum: "ec382d09fac5649bd61cf995ef331cb9c03553d593b472e5b000208bd482a008"),
]
)
| 46 | 266 | 0.721344 |
6256e5fd6855090b35c65d37ca32635ad52309e2 | 5,140 | //
// GroupsViewController.swift
// Shares
//
// Created by Dan Xiaoyu Yu on 12/2/15.
// Copyright © 2015 Corner Innovations LLC. All rights reserved.
//
import Foundation
import UIKit
import Parse
import MBProgressHUD
// **********************************
// MARK: - SearchGroupsViewController
// **********************************
class SearchGroupsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
// *****************************************
// MARK: - Variables, Outlets, and Constants
// *****************************************
@IBOutlet weak var tableView: UITableView!
var searchActive: Bool = false
var data: [PFObject]!
var filtered: [PFObject]!
// **************************
// MARK: - View Configuration
// **************************
override func viewDidLoad() {
super.viewDidLoad()
search()
}
// ***************************
// MARK: - Parse Configuration
// ***************************
/*
* Function: joinGroup(sender)
* ---------------------------
* Alternative to picker view that looks nicer. Instead of having a picker view in a table view
* cell, allow a custom picker view to move onto the screen, allowing the user to select industry.
*/
func joinGroup(sender: UIButton) {
let group = self.data[sender.tag]
group.addUniqueObject(CURRENT_USER, forKey: "members")
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
group.saveInBackgroundWithBlock() { (success, error) -> Void in
if error == nil {
MBProgressHUD.hideHUDForView(self.view, animated: true)
let alertController = UIAlertController(
title: "Success",
message: "You have successfully been added to the group. Please check your groups.",
preferredStyle: .Alert
)
alertController.addAction(UIAlertAction(
title: "Continue",
style: .Default,
handler: nil
))
self.presentViewController(alertController, animated: true, completion: nil)
self.performSegueWithIdentifier("groupAddedSuccess", sender: self)
} else {
MBProgressHUD.hideHUDForView(self.view, animated: true)
if let errorString = error!.userInfo["error"] as? NSString {
let alertController = UIAlertController(
title: "Error",
message: errorString as String,
preferredStyle: .Alert
)
alertController.addAction(UIAlertAction(
title: "Continue",
style: .Default,
handler: nil
))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
}
// ********************************
// MARK: - Search Bar Configuration
// ********************************
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
search(searchText)
}
func search(searchText: String? = nil){
let query = PFQuery(className: "Groups")
if (searchText != nil) {
query.whereKey("groupname", containsString: searchText!.lowercaseString)
}
query.findObjectsInBackgroundWithBlock { (results, error) -> Void in
self.data = results! as [PFObject]
self.tableView.reloadData()
}
}
// ********************************
// MARK: - Table View Configuration
// ********************************
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data != nil ? self.data.count : 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if self.data != nil && self.data.count != 0 {
let group = self.data[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("SearchGroupCell", forIndexPath: indexPath) as! SearchGroupCell
cell.groupnameLabel!.text = group["groupname"] as? String
cell.groupTaglineLabel!.text = group["tagline"] as? String
cell.numMembersLabel!.text = "(" + String(group["members"].count) + " members)"
cell.joinButton.tag = indexPath.row
cell.joinButton.addTarget(self, action: "joinGroup:", forControlEvents: .TouchUpInside)
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("SearchNoneCell", forIndexPath: indexPath)
return cell
}
}
}
| 28.876404 | 124 | 0.597665 |
26672e81aee519b8a8f6164f6afcff578504fa92 | 905 | // swift-tools-version:4.2
import PackageDescription
let package = Package(
name: "Deli",
products: [
.executable(name: "deli", targets: ["deli"])
],
dependencies: [
.package(url: "https://github.com/jpsim/SourceKitten.git", from: "0.21.1"),
.package(url: "https://github.com/jpsim/Yams.git", from: "1.0.0"),
.package(url: "https://github.com/crossroadlabs/Regex.git", from: "1.1.0"),
.package(url: "https://github.com/tuist/xcodeproj.git", from: "6.0.0"),
.package(url: "https://github.com/Carthage/Commandant.git", from: "0.15.0")
],
targets: [
.target(
name: "deli",
dependencies: [
"SourceKittenFramework",
"Yams",
"Regex",
"xcodeproj",
"Commandant"
],
path: "Sources/Deli"
)
]
)
| 30.166667 | 83 | 0.510497 |
715fd755d31d713d197e789ddf7b6f86a98c85f6 | 360 | //
// UIImage+Extension.swift
// NeoMusic
//
// Created by Jordan Christensen on 7/31/20.
// Copyright © 2020 Mazjap Co. All rights reserved.
//
import UIKit
extension UIImage {
static var placeholder = UIImage(named: "Placeholder")!
static var play = UIImage(systemName: "play.fill")!
static var pause = UIImage(systemName: "pause.fill")!
}
| 22.5 | 59 | 0.688889 |
d62466fd76f64f87d4e91a896ba4d980bca697ec | 749 | //
// ClickTrackingTests.swift
// SendGridTests
//
// Created by Scott Kawai on 9/16/17.
//
import XCTest
@testable import SendGrid
class ClickTrackingTests: XCTestCase, EncodingTester {
typealias EncodableObject = ClickTracking
func testExample() {
let onSettingMin = ClickTracking(section: .htmlBody)
XCTAssertEncodedObject(onSettingMin, equals: ["enable": true, "enable_text": false])
let onSettingMax = ClickTracking(section: .plainTextAndHTMLBodies)
XCTAssertEncodedObject(onSettingMax, equals: ["enable": true, "enable_text": true])
let offSetting = ClickTracking(section: .off)
XCTAssertEncodedObject(offSetting, equals: ["enable": false])
}
}
| 27.740741 | 92 | 0.682243 |
7968e4639baaefb823de50bd65ab05d04dedd544 | 5,559 | //
// ThemedWindowTests.swift
// GaudiTests
//
// Created by Giuseppe Lanza on 13/12/2019.
// Copyright © 2019 Giuseppe Lanza. All rights reserved.
//
@testable import Gaudi
import XCTest
import UIKit
class ThemedWindowTests: XCTestCase {
let semanticColors = SemanticColor.allCases
let lightTheme = MockTheme()
let darkTheme = MockDarkTheme()
var window: ThemedWindow!
var rootViewController: MockViewController!
var windowsContainer: MockWindowsContainer!
override func setUp() {
super.setUp()
windowsContainer = MockWindowsContainer()
rootViewController = MockViewController()
window = ThemedWindow(lightTheme: lightTheme, darkTheme: darkTheme)
window.rootViewController = rootViewController
windowsContainer.windows.append(window)
ThemeContainer.windowsContainer = windowsContainer
}
override func tearDown() {
super.tearDown()
window = nil
rootViewController = nil
windowsContainer = nil
ThemeContainer.windowsContainer = UIApplication.shared
ThemeContainer.currentTheme = nil
if #available(iOS 13.0, *) {
let traitCollection = UITraitCollection(userInterfaceStyle: .unspecified)
UITraitCollection.current = traitCollection
}
}
@available(iOS 13.0, *)
func test__current_theme__is_light__for_light_mode() {
let traitCollection = UITraitCollection(userInterfaceStyle: .light)
UITraitCollection.current = traitCollection
XCTAssertEqual(
semanticColors.map { lightTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
}
@available(iOS 13.0, *)
func test__current_theme__is_light__for_unspecified_mode() {
let traitCollection = UITraitCollection(userInterfaceStyle: .unspecified)
UITraitCollection.current = traitCollection
XCTAssertEqual(
semanticColors.map { lightTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
}
@available(iOS 13.0, *)
func test__current_theme__is_dark__for_dark_mode() {
let traitCollection = UITraitCollection(userInterfaceStyle: .dark)
UITraitCollection.current = traitCollection
XCTAssertEqual(
semanticColors.map { darkTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
}
func test__current_theme__can_be_switched__for_light_mode() {
let otherTheme = OtherMockTheme()
window.lightTheme = otherTheme
XCTAssertEqual(
semanticColors.map { otherTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
XCTAssert(ThemeContainer.currentTheme === otherTheme)
}
@available(iOS 13.0, *)
func test__current_theme__cant_be_switched__for_light_mode() {
let traitCollection = UITraitCollection(userInterfaceStyle: .dark)
UITraitCollection.current = traitCollection
let otherTheme = OtherMockTheme()
window.lightTheme = otherTheme
XCTAssertEqual(
semanticColors.map { darkTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
}
@available(iOS 13.0, *)
func test__current_theme__can_be_switched__for_dark_mode() {
let traitCollection = UITraitCollection(userInterfaceStyle: .dark)
UITraitCollection.current = traitCollection
let otherTheme = OtherMockTheme()
window.darkTheme = otherTheme
XCTAssertEqual(
semanticColors.map { otherTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
XCTAssert(ThemeContainer.currentTheme === otherTheme)
}
@available(iOS 13.0, *)
func test__current_theme__cant_be_switched__for_dark_mode() {
let traitCollection = UITraitCollection(userInterfaceStyle: .light)
UITraitCollection.current = traitCollection
let otherTheme = OtherMockTheme()
window.darkTheme = otherTheme
XCTAssertEqual(
semanticColors.map { lightTheme.color(forSemanticColor: $0) },
semanticColors.map { window.currentTheme.color(forSemanticColor: $0) }
)
}
@available(iOS 13.0, *)
func test__light_theme__is_applied__on_trait_change() {
let previous = UITraitCollection.current
let traitCollection = UITraitCollection(userInterfaceStyle: .light)
UITraitCollection.current = traitCollection
window.traitCollectionDidChange(previous)
XCTAssert(ThemeContainer.currentTheme === lightTheme)
}
@available(iOS 13.0, *)
func test__dark_theme__is_applied__on_trait_change() {
let previous = UITraitCollection.current
let traitCollection = UITraitCollection(userInterfaceStyle: .dark)
UITraitCollection.current = traitCollection
window.traitCollectionDidChange(previous)
XCTAssert(ThemeContainer.currentTheme === darkTheme)
}
}
| 35.407643 | 85 | 0.659831 |
56bdad2ee96975c893bb010cb52939728fab248a | 229 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a{class a{class T{let i{struct c<f:f.c{}}enum A{enum b
| 38.166667 | 87 | 0.751092 |
8aae9b44202cfcb051b3ff7f212253c630c8419d | 239 | //
// YouHungryApp.swift
// YouHungry
//
// Created by Kristijan Kralj on 13.01.2021..
//
import SwiftUI
@main
struct YouHungryApp: App {
var body: some Scene {
WindowGroup {
OnboardingView()
}
}
}
| 13.277778 | 46 | 0.577406 |
01ee5fa285af9a94170891d2bcdd60b2b8b96f65 | 3,906 | //
// StatisticsViewController.swift
// emojiFinder
//
// Created by Vlad on 17.11.2017.
// Copyright © 2017 Vlad. All rights reserved.
//
import UIKit
class StatisticsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.dataSource = self
tableView.delegate = self
StatisticsCell.register(table: tableView)
}
}
@IBOutlet weak var segmentedControl: UISegmentedControl! {
didSet {
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: Fonts.segmentedControlFont, NSAttributedStringKey.foregroundColor: Colors.menuText], for: .normal)
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: Fonts.segmentedControlFont, NSAttributedStringKey.foregroundColor: UIColor.white], for: .focused)
segmentedControl.tintColor = Colors.menuText
segmentedControl.setTitle(VZGameComplexity.easy.rawValue, forSegmentAt: 0)
segmentedControl.setTitle(VZGameComplexity.medium.rawValue, forSegmentAt: 1)
segmentedControl.setTitle(VZGameComplexity.hard.rawValue, forSegmentAt: 2)
}
}
@IBOutlet weak var nameLabel: UILabel! {
didSet {
nameLabel.type = .statisticsTitle
}
}
@IBOutlet weak var actionsLabel: UILabel! {
didSet {
actionsLabel.type = .statisticsTitle
}
}
@IBOutlet weak var timeLabel: UILabel! {
didSet {
timeLabel.type = .statisticsTitle
}
}
@IBOutlet weak var placeLabel: UILabel! {
didSet {
placeLabel.type = .statisticsTitle
}
}
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var noResultsLabel: UILabel! {
didSet {
noResultsLabel.type = .noDataInTable
noResultsLabel.text = "Oops!\nYou don't have results here!\nGo to play!"
}
}
var model: StatisticsModel!
override func viewDidLoad() {
super.viewDidLoad()
model.didFetchResults = { [weak self] in
self?.tableView.reloadData()
}
closeButton.addTarget(self, action: #selector(self.close), for: .touchUpInside)
segmentedControl.addTarget(self, action: #selector(self.segmentedControlDidChanged(_:)), for: .valueChanged)
Colors.addGradientBackgroundOn(view: self.view, with: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
}
@objc private func segmentedControlDidChanged(_ sender: UISegmentedControl) {
let segmentIndex = sender.selectedSegmentIndex
assert(segmentIndex <= 2)
let complexity = VZGameComplexity.init(intValue: segmentIndex)
model.setFilter(complexity: complexity)
}
@objc func close() {
self.navigationController?.popViewController(animated: true)
}
deinit {
print("deinit - StatisticsViewController")
}
}
extension StatisticsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = model.numberOfResults()
noResultsLabel.isHidden = (numberOfRowsInSection != 0)
return numberOfRowsInSection
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = model.resultFor(index: indexPath.row)
let cell = StatisticsCell.cell(table: tableView, indexPath: indexPath)
cell.configure(data: data, place: indexPath.row)
return cell
}
}
extension StatisticsViewController: StoryboardInstanceable {
static var storyboardName: StoryboardList = .statistics
}
| 32.823529 | 179 | 0.657706 |
fc04d694fd939637042501420d6a2952afedab26 | 1,421 | //
// AppDelegate.swift
// iExpense
//
// Created by Oscar da Silva on 06.05.20.
// Copyright © 2020 Oscar da Silva. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.394737 | 179 | 0.746657 |
1d76e1dedeb1aaf68b2faf25b69ae6e8845fced2 | 1,550 | //
// UITextField+Config.swift
// UIBuilder
//
// Created by Mr.wang on 2019/5/24.
// Copyright © 2019 Mr.wang. All rights reserved.
//
import UIKit
public extension UIConfig where ViewType: UITextField {
@discardableResult
func text(_ text: String?) -> Self {
view.text = text
return self
}
@discardableResult
func attributedText(_ attributedText: NSAttributedString?) -> Self {
view.attributedText = attributedText
return self
}
@discardableResult
func textColor(_ textColor: UIColor) -> Self {
view.textColor = textColor
return self
}
@discardableResult
func font(_ font: UIFont?) -> Self {
view.font = font
return self
}
@discardableResult
func fontSize(_ fontSize: CGFloat) -> Self {
view.font = UIFont.systemFont(ofSize: fontSize)
return self
}
@discardableResult
func textAlignment(_ textAlignment: NSTextAlignment) -> Self {
view.textAlignment = textAlignment
return self
}
@discardableResult
func borderStyle(_ borderStyle: UITextField.BorderStyle) -> Self {
view.borderStyle = borderStyle
return self
}
@discardableResult
func placeholder(_ placeholder: String?) -> Self {
view.placeholder = placeholder
return self
}
@discardableResult
func delegate(_ delegate: UITextFieldDelegate?) -> Self {
view.delegate = delegate
return self
}
}
| 22.794118 | 72 | 0.62 |
d71c4ccf04d2170b7b34fa34217ab7fd4e1e3fc8 | 469 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "YMOverride",
platforms: [
.iOS(.v10),
.tvOS(.v10),
],
products: [
.library(
name: "YMOverride",
targets: ["YMOverride"]),
],
dependencies: [],
targets: [
.target(
name: "YMOverride",
path: "Source",
exclude: [
"TestSupport"
]),
]
)
| 18.038462 | 37 | 0.445629 |
9090d2ef00ac816fea495ec191f8b6c302cd9c98 | 168 | import XCTest
#if !canImport(ObjectiveC)
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(mobile_buy_sdk_iosTests.allTests),
]
}
#endif
| 16.8 | 51 | 0.690476 |
d6468cd2eabf56bc8a95988abdd8314a8355a739 | 536 | import Foundation
final class ExecutionService {
static let shared = ExecutionService()
static var isHelperInstalled: Bool { FileManager().fileExists(atPath: HelperConstants.helperPath) }
func executeScript(at path: String, options: [String], completion: @escaping (Result<String, Error>) -> Void) throws {
let proxy = try ExecutionServiceProxy().getProxy()
proxy.executeScript(at: path, options: options) { (output, error) in
completion(Result(string: output, error: error))
}
}
}
| 38.285714 | 122 | 0.692164 |
db451d2c67077c7fa5799fee7811202d52c8be14 | 1,541 | //
// ProfileEditor.swift
// Landmarks
//
// Created by Adam Rafiandri on 7/8/21.
//
import SwiftUI
struct ProfileEditor: View {
@Binding var profile: Profile
var dateRange: ClosedRange<Date> {
let min = Calendar.current.date(byAdding: .year, value: -1, to: profile.goalDate)!
let max = Calendar.current.date(byAdding: .year, value: 1, to: profile.goalDate)!
return min...max
}
var body: some View {
List {
HStack {
Text("Username").bold()
Divider()
TextField("Username", text: $profile.username)
}
Toggle(isOn: $profile.prefersNotifications) {
Text("Enable Notifications").bold()
}
VStack(alignment: .leading, spacing: 20) {
Text("Seasonal Photo").bold()
Picker("Seasonal Photo", selection: $profile.seasonalPhoto) {
ForEach(Profile.Season.allCases) { season in
Text(season.rawValue).tag(season)
}
}
.pickerStyle(SegmentedPickerStyle())
}
DatePicker(selection: $profile.goalDate, in: dateRange, displayedComponents: .date) {
Text("Goal Date").bold()
}
}
}
}
struct ProfileEditor_Previews: PreviewProvider {
static var previews: some View {
ProfileEditor(profile: .constant(.default))
}
}
| 28.537037 | 97 | 0.52109 |
8fc8630d0a315093870d0e6321b637e5a584b4f3 | 6,598 | import XCTest
import SwiftSyntax
fileprivate func cannedStructDecl() -> StructDeclSyntax {
let structKW = SyntaxFactory.makeStructKeyword(trailingTrivia: .spaces(1))
let fooID = SyntaxFactory.makeIdentifier("Foo", trailingTrivia: .spaces(1))
let rBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: .newlines(1))
let members = MemberDeclBlockSyntax {
$0.useLeftBrace(SyntaxFactory.makeLeftBraceToken())
$0.useRightBrace(rBrace)
}
return StructDeclSyntax {
$0.useStructKeyword(structKW)
$0.useIdentifier(fooID)
$0.useMembers(members)
}
}
public class SyntaxFactoryTests: XCTestCase {
public func testGenerated() {
let structDecl = cannedStructDecl()
XCTAssertEqual("\(structDecl)",
"""
struct Foo {
}
""")
let forType = SyntaxFactory.makeIdentifier("`for`",
leadingTrivia: [],
trailingTrivia: [
.spaces(1)
])
let newBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: .newlines(2))
let renamed = structDecl.withIdentifier(forType)
.withMembers(structDecl.members
.withRightBrace(newBrace))
XCTAssertEqual("\(renamed)",
"""
struct `for` {
}
""")
XCTAssertNotEqual(structDecl.members, renamed.members)
XCTAssertEqual(structDecl, StructDeclSyntax(structDecl.root))
XCTAssertNil(structDecl.parent)
XCTAssertNotNil(structDecl.members.parent)
XCTAssertEqual(structDecl.members.parent.map(StructDeclSyntax.init), structDecl)
XCTAssertEqual("\(structDecl.members.rightBrace)",
"""
}
""")
}
public func testTokenSyntax() {
let tok = SyntaxFactory.makeStructKeyword()
XCTAssertEqual("\(tok)", "struct")
XCTAssertTrue(tok.isPresent)
let preSpacedTok = tok.withLeadingTrivia(.spaces(3))
XCTAssertEqual("\(preSpacedTok)", " struct")
var mutablePreSpacedTok = tok
mutablePreSpacedTok.leadingTrivia = .spaces(4)
XCTAssertEqual("\(mutablePreSpacedTok)", " struct")
let postSpacedTok = tok.withTrailingTrivia(.spaces(6))
XCTAssertEqual("\(postSpacedTok)", "struct ")
var mutablePostSpacedTok = tok
mutablePostSpacedTok.trailingTrivia = .spaces(3)
XCTAssertEqual("\(mutablePostSpacedTok)", "struct ")
let prePostSpacedTok = preSpacedTok.withTrailingTrivia(.spaces(4))
XCTAssertEqual("\(prePostSpacedTok)", " struct ")
mutablePreSpacedTok.trailingTrivia = .spaces(2)
XCTAssertEqual("\(mutablePreSpacedTok)", " struct ")
}
public func testFunctionCallSyntaxBuilder() {
let string = SyntaxFactory.makeStringLiteralExpr("Hello, world!")
let printID = SyntaxFactory.makeVariableExpr("print")
let arg = TupleExprElementSyntax {
$0.useExpression(ExprSyntax(string))
}
let call = FunctionCallExprSyntax {
$0.useCalledExpression(ExprSyntax(printID))
$0.useLeftParen(SyntaxFactory.makeLeftParenToken())
$0.addArgument(arg)
$0.useRightParen(SyntaxFactory.makeRightParenToken())
}
XCTAssertEqual("\(call)", "print(\"Hello, world!\")")
let terminatorArg = TupleExprElementSyntax {
$0.useLabel(SyntaxFactory.makeIdentifier("terminator"))
$0.useColon(SyntaxFactory.makeColonToken(trailingTrivia: .spaces(1)))
$0.useExpression(ExprSyntax(SyntaxFactory.makeStringLiteralExpr(" ")))
}
let callWithTerminator = call.withArgumentList(
SyntaxFactory.makeTupleExprElementList([
arg.withTrailingComma(
SyntaxFactory.makeCommaToken(trailingTrivia: .spaces(1))),
terminatorArg
])
)
XCTAssertEqual("\(callWithTerminator)",
"print(\"Hello, world!\", terminator: \" \")")
}
public func testWithOptionalChild() {
let string = SyntaxFactory.makeStringLiteralExpr("Hello, world!")
let printID = SyntaxFactory.makeVariableExpr("print")
let arg = TupleExprElementSyntax {
$0.useExpression(ExprSyntax(string))
}
let call1 = FunctionCallExprSyntax {
$0.useCalledExpression(ExprSyntax(printID))
$0.useLeftParen(SyntaxFactory.makeLeftParenToken())
$0.addArgument(arg)
$0.useRightParen(SyntaxFactory.makeRightParenToken())
}
XCTAssertNotNil(call1.leftParen)
XCTAssertNotNil(call1.rightParen)
let call2 = call1.withLeftParen(nil).withRightParen(nil)
XCTAssertNil(call2.leftParen)
XCTAssertNil(call2.rightParen)
let call3 = FunctionCallExprSyntax {
$0.useCalledExpression(ExprSyntax(printID))
$0.addArgument(arg)
}
XCTAssertNil(call3.leftParen)
XCTAssertNil(call3.rightParen)
}
public func testUnknownSyntax() {
let expr = SyntaxFactory.makeStringLiteralExpr("Hello, world!")
XCTAssertFalse(expr.isUnknown)
let unknown = SyntaxFactory.makeUnknownSyntax(
tokens: [SyntaxFactory.makeLeftBraceToken()])
XCTAssertTrue(unknown.isUnknown)
XCTAssertNoThrow(try SyntaxVerifier.verify(Syntax(expr)))
XCTAssertThrowsError(try SyntaxVerifier.verify(Syntax(unknown)))
}
public func testMakeStringLiteralExpr() {
let expr = SyntaxFactory.makeStringLiteralExpr(
"Hello, world!",
leadingTrivia: .init(pieces: [.lineComment("// hello"), .newlines(1)])
)
let expected = """
// hello
"Hello, world!"
"""
XCTAssertEqual(expr.description, expected)
}
public func testMakeBinaryOperator() {
let first = IntegerLiteralExprSyntax {
$0.useDigits(SyntaxFactory.makeIntegerLiteral("1", trailingTrivia: .spaces(1)))
}!
let second = IntegerLiteralExprSyntax {
$0.useDigits(SyntaxFactory.makeIntegerLiteral("1"))
}!
let operatorNames = ["==", "!=", "+", "-", "*", "/", "<", ">", "<=", ">="]
operatorNames.forEach { operatorName in
let operatorToken = SyntaxFactory.makeBinaryOperator(operatorName, trailingTrivia: .spaces(1))
let operatorExpr = BinaryOperatorExprSyntax {
$0.useOperatorToken(operatorToken)
}
let exprList = SyntaxFactory.makeExprList([ExprSyntax(first),
ExprSyntax(operatorExpr),
ExprSyntax(second)])
XCTAssertEqual("\(exprList)", "1 \(operatorName) 1")
}
}
}
| 34.910053 | 100 | 0.643528 |
7a343f75a9bbcd2f8f25ce0a91f50bf00bd0c05c | 3,726 | //
// AppearanceExampleCollectionView.swift
// FalconMessenger
//
// Created by Roman Mizin on 3/16/19.
// Copyright © 2019 Roman Mizin. All rights reserved.
//
import UIKit
class AppearanceExampleCollectionView: ChatCollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
fileprivate var messages = AppearanceExampleMessagesFactory.messages()
required public init() {
super.init()
delegate = self
dataSource = self
backgroundColor = .clear
isScrollEnabled = false
isUserInteractionEnabled = false
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
reloadData()
}
func updateTheme() {
messages = AppearanceExampleMessagesFactory.messages()
DispatchQueue.main.async { [weak self] in self?.reloadData() }
}
func fullContentSize() -> CGSize {
let indexPaths = [IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0)]
var fullSize = CGSize(width: 0, height: 0)
for indexPath in indexPaths {
let itemSize = selectSize(indexPath: indexPath)
fullSize.width += itemSize.width
fullSize.height += itemSize.height
}
return fullSize
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return messages.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return CGSize(width: frame.width, height: 25)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let isOutgoingMessage = indexPath.row == 1
let message = messages[indexPath.row]
message.isCrooked.value = true
switch isOutgoingMessage {
case true:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: outgoingTextMessageCellID,
for: indexPath) as? OutgoingTextMessageCell ?? OutgoingTextMessageCell()
cell.textView.font = MessageFontsAppearance.defaultMessageTextFont
cell.setupData(message: message)
return cell
case false:
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: incomingTextMessageCellID,
for: indexPath) as? IncomingTextMessageCell ?? IncomingTextMessageCell()
cell.textView.font = MessageFontsAppearance.defaultMessageTextFont
cell.setupData(message: message, isGroupChat: false)
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return selectSize(indexPath: indexPath)
}
fileprivate func selectSize(indexPath: IndexPath) -> CGSize {
let message = messages[indexPath.row]
let isTextMessage = true
let isOutgoingMessage = indexPath.row == 1
guard !isTextMessage else {
if UIDevice.current.orientation.isLandscape {
return CGSize(width: frame.width,
height: setupCellHeight(isGroupChat: false,
isOutgoingMessage: isOutgoingMessage,
frame: message.landscapeEstimatedFrameForText,
indexPath: indexPath))
} else {
return CGSize(width: frame.width,
height: setupCellHeight(isGroupChat: false,
isOutgoingMessage: isOutgoingMessage,
frame: message.estimatedFrameForText,
indexPath: indexPath))
}
}
}
}
| 34.5 | 167 | 0.735641 |
5b32a6abd97775bd5c23f7e0b2fdf83ef574d98d | 10,300 | //
// EditorTableViewController.swift
// stts
//
import Cocoa
class EditorTableViewController: NSObject, SwitchableTableViewController {
let contentView: NSStackView
let scrollView: CustomScrollView
let bottomBar: BottomBar
let tableView = NSTableView()
let allServices: [BaseService] = BaseService.all().sorted()
let allServicesWithoutSubServices: [BaseService] = BaseService.allWithoutSubServices().sorted()
var filteredServices: [BaseService]
var selectedServices: [BaseService] = Preferences.shared.selectedServices
var selectionChanged = false
let settingsView = SettingsView()
var hidden: Bool = true
var savedScrollPosition: CGPoint = .zero
var selectedCategory: ServiceCategory? {
didSet {
// Save the scroll position between screens
let scrollToPosition: CGPoint?
if selectedCategory != nil && oldValue == nil {
savedScrollPosition = CGPoint(x: 0, y: tableView.visibleRect.minY)
scrollToPosition = .zero
} else if selectedCategory == nil && oldValue != nil {
scrollToPosition = savedScrollPosition
} else {
scrollToPosition = nil
}
// Adjust UI
bottomBar.openedCategory(selectedCategory, backCallback: { [weak self] in
self?.selectedCategory = nil
})
guard let category = selectedCategory else {
// Show the unfiltered services
filteredServices = allServicesWithoutSubServices
tableView.reloadData()
if let scrollPosition = scrollToPosition {
tableView.scroll(scrollPosition)
}
return
}
// Find the sub services
var subServices = allServices.filter {
// Can't check superclass matches without mirror
Mirror(reflecting: $0).superclassMirror?.subjectType == category.subServiceSuperclass
// Exclude the category so that we can add it at the top
&& $0 != category as? BaseService
}.sorted()
// Add the category as the top item
(category as? BaseService).flatMap { subServices.insert($0, at: 0) }
filteredServices = subServices
tableView.reloadData()
if let scrollPosition = scrollToPosition {
tableView.scroll(scrollPosition)
}
}
}
var isSearching: Bool {
settingsView.searchField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) != ""
}
private var maxNameWidth: CGFloat? {
didSet {
if oldValue != maxNameWidth {
tableView.tile()
}
}
}
init(contentView: NSStackView, scrollView: CustomScrollView, bottomBar: BottomBar) {
self.contentView = contentView
self.scrollView = scrollView
self.filteredServices = allServicesWithoutSubServices
self.bottomBar = bottomBar
super.init()
setup()
}
func setup() {
tableView.frame = scrollView.bounds
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "editorColumnIdentifier"))
column.width = 200
tableView.addTableColumn(column)
tableView.autoresizesSubviews = true
tableView.wantsLayer = true
tableView.layer?.cornerRadius = 6
tableView.headerView = nil
tableView.gridStyleMask = NSTableView.GridLineStyle.init(rawValue: 0)
tableView.dataSource = self
tableView.delegate = self
tableView.selectionHighlightStyle = .none
tableView.backgroundColor = NSColor.clear
if #available(OSX 11.0, *) {
tableView.style = .fullWidth
}
settingsView.isHidden = true
settingsView.searchCallback = { [weak self] searchString in
guard
let strongSelf = self,
let allServices = strongSelf.allServices as? [Service],
let allServicesWithoutSubServices = strongSelf.allServicesWithoutSubServices as? [Service]
else { return }
if searchString.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
strongSelf.filteredServices = allServicesWithoutSubServices
} else {
// Can't filter array with NSPredicate without making Service inherit KVO from NSObject, therefore we create
// an array of service names that we can run the predicate on
let allServiceNames = allServices.compactMap { $0.name } as NSArray
let predicate = NSPredicate(format: "SELF LIKE[cd] %@", argumentArray: ["*\(searchString)*"])
guard let filteredServiceNames = allServiceNames.filtered(using: predicate) as? [String] else { return }
strongSelf.filteredServices = allServices.filter { filteredServiceNames.contains($0.name) }
}
if strongSelf.selectedCategory != nil {
strongSelf.selectedCategory = nil
}
strongSelf.tableView.reloadData()
}
settingsView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(settingsView)
NSLayoutConstraint.activate([
settingsView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
settingsView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
settingsView.topAnchor.constraint(equalTo: contentView.topAnchor),
settingsView.heightAnchor.constraint(equalToConstant: 130)
])
}
func willShow() {
self.selectionChanged = false
scrollView.topConstraint?.constant = settingsView.frame.size.height
scrollView.documentView = tableView
settingsView.isHidden = false
// We should be using NSWindow's makeFirstResponder: instead of the search field's selectText:, but in this case, makeFirstResponder
// is causing a bug where the search field "gets focused" twice (focus ring animation) the first time it's drawn.
settingsView.searchField.selectText(nil)
resizeViews()
}
func resizeViews() {
tableView.frame = scrollView.bounds
tableView.tableColumns.first?.width = tableView.frame.size.width
scrollView.frame.size.height = 400
(NSApp.delegate as? AppDelegate)?.popupController.resizePopup(
height: scrollView.frame.size.height + 30 // bottomBar.frame.size.height
)
}
func willOpenPopup() {
resizeViews()
}
func didOpenPopup() {
settingsView.searchField.window?.makeFirstResponder(settingsView.searchField)
}
func willHide() {
settingsView.isHidden = true
}
@objc func deselectCategory() {
selectedCategory = nil
}
}
extension EditorTableViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return filteredServices.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
guard tableView.selectedRow != -1 else { return }
// We're only interested in selections of categories
guard
selectedCategory == nil,
let category = filteredServices[tableView.selectedRow] as? ServiceCategory
else { return }
// Change the selected category
selectedCategory = category
}
}
extension EditorTableViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
guard
let maxNameWidth = maxNameWidth,
let service = filteredServices[row] as? Service
else { return EditorTableCell.defaultHeight }
return service.name.height(forWidth: maxNameWidth, font: NSFont.systemFont(ofSize: 11)) + (8 * 2)
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let identifier = tableColumn?.identifier ?? NSUserInterfaceItemIdentifier(rawValue: "identifier")
let cell = tableView.makeView(withIdentifier: identifier, owner: self) ?? EditorTableCell()
guard let view = cell as? EditorTableCell else { return nil }
guard let service = filteredServices[row] as? Service else { return nil }
if isSearching || selectedCategory != nil {
view.type = .service
} else {
view.type = (service is ServiceCategory) ? .category : .service
}
switch view.type {
case .service:
view.textField?.stringValue = service.name
view.selected = selectedServices.contains(service)
view.toggleCallback = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.selectionChanged = true
if view.selected {
self?.selectedServices.append(service)
} else {
if let index = self?.selectedServices.firstIndex(of: service) {
self?.selectedServices.remove(at: index)
}
}
Preferences.shared.selectedServices = strongSelf.selectedServices
}
case .category:
view.textField?.stringValue = (service as? ServiceCategory)?.categoryName ?? service.name
view.selected = false
view.toggleCallback = {}
}
maxNameWidth = EditorTableCell.maxNameWidth(for: tableView)
return view
}
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "rowView")
let cell = tableView.makeView(withIdentifier: cellIdentifier, owner: self) ?? ServiceTableRowView()
guard let view = cell as? ServiceTableRowView else { return nil }
view.showSeparator = row + 1 < filteredServices.count
return view
}
}
| 35.888502 | 140 | 0.631845 |
010ebf18f0ae4e29bfc1c3ec9994bee1cb35aa7a | 3,596 | //
// Sequence+SwiftPatches.swift
// SwiftPatches
//
// Created by Tyler Anger on 2019-06-06.
//
import Foundation
public extension Sequence {
#if !swift(>=4.0.4)
/// Returns an array containing the non-`nil` results of calling the given
/// transformation with each element of this sequence.
///
/// Use this method to receive an array of nonoptional values when your
/// transformation produces an optional value.
///
/// In this example, note the difference in the result of using `map` and
/// `compactMap` with a transformation that returns an optional `Int` value.
///
/// let possibleNumbers = ["1", "2", "three", "///4///", "5"]
///
/// let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
/// // [1, 2, nil, nil, 5]
///
/// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
/// // [1, 2, 5]
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns an optional value.
/// - Returns: An array of the non-`nil` results of calling `transform`
/// with each element of the sequence.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
var rtn: [ElementOfResult] = []
for element in self {
if let nE = try transform(element) {
rtn.append(nE)
}
}
return rtn
}
#endif
#if !swift(>=4.1.4)
/// Returns a Boolean value indicating whether every element of a sequence
/// satisfies a given predicate.
///
/// The following code uses this method to test whether all the names in an
/// array have at least five characters:
///
/// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
/// // allHaveAtLeastFive == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element satisfies a condition.
/// - Returns: `true` if the sequence contains only elements that satisfy
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool {
var rtn: Bool = true
for v in self where rtn {
rtn = try predicate(v)
}
return rtn
}
#endif
}
public extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether every element of the sequence equals each other
///
/// This is a helper method and is not part of Swift.
///
/// - Returns: `true` if all elements in the sequence equal; otherwise `false`
/// - Complexity: O(*n*), where *n* is the length of the sequence.
func allEquals() -> Bool {
guard let firstElement: Element = self.first(where: { _ in return true }) else { return true }
return self.allSatisfy({ return $0 == firstElement })
}
}
| 40.404494 | 123 | 0.56535 |
e4323a00fa6cab367e7b388c6ff904d5ed4d92f8 | 4,982 | //
// ImageManager.swift
// xMexico
//
// Created by Development on 3/13/17.
// Copyright © 2018 Rodrigo Chousal. All rights reserved.
//
import Foundation
import Firebase
import FirebaseUI
class ImageManager {
// MARK: - UP ☁️
static func postImageToFirebase(forFireUser fireUser: User, image: UIImage, completion: ((Error?) -> Void)?) {
let imageData = UIImagePNGRepresentation(image)
let imagePath = "userPictures/" + fireUser.uid + "/" + "userProfile.png"
let metadata = StorageMetadata()
metadata.contentType = "image/png"
Global.storageRef.child(imagePath)
.putData(imageData!, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
if let cmp = completion { cmp(error) }
return
} else {
if let cmp = completion { cmp(nil) }
}
}
}
static func postBackgroundImageToFirebase(forFireUser fireUser: User, image: UIImage, completion: ((Error?) -> Void)?) {
let imageData = UIImagePNGRepresentation(image)
let imagePath = "userPictures/" + fireUser.uid + "/" + "userBackground.png"
let metadata = StorageMetadata()
metadata.contentType = "image/png"
Global.storageRef.child(imagePath)
.putData(imageData!, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
if let cmp = completion { cmp(error) }
return
} else {
if let cmp = completion { cmp(nil) }
}
}
}
// MARK: - DOWN ☔️
static func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) { data, response, error in
completion(data, response, error)
}.resume()
}
static func fetchImageFromFirebase(forFireUser fireUser: User, profilePicture: Bool) {
// Check if profile picture or not, and make reference appropriately
var imgRef = StorageReference()
if profilePicture {
imgRef = Global.storageRef.child("userPictures/" + fireUser.uid + "/userProfile.png")
} else {
imgRef = Global.storageRef.child("userPictures/" + fireUser.uid + "/userBackground.png")
}
var image = UIImage()
// Fetch the download URL
imgRef.downloadURL { url, error in
if let error = error {
// Handle any errors
print("Error getting URL: " + error.localizedDescription)
} else {
// Get image from Firebase
if let imageUrl = url {
print("Download Started")
getDataFromUrl(url: imageUrl) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? imageUrl.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() {
image = UIImage(data: data)!
if let localUser = Global.localUser {
if profilePicture {
localUser.profilePicture = image
NotificationCenter.default.post(Notification(name: .profileImageFinished))
} else {
localUser.backgroundPicture = image
NotificationCenter.default.post(Notification(name: .backgroundImageFinished))
}
}
}
}
}
}
}
}
static func fetchCampaignImageFromFirebase(forCampaign campaign: Campaign, kind: Campaign.ImageType, galleryFileName: String?, completion: @escaping (UIImage) -> Void) {
var imgRef: StorageReference
switch kind {
case .MAIN: imgRef = Global.storageRef.child("campaignPictures/" + campaign.uniqueID + "/main.png")
case .THUMB: imgRef = Global.storageRef.child("campaignPictures/" + campaign.uniqueID + "/thumb.png")
case .GALLERY: imgRef = Global.storageRef.child("campaignPictures/" + campaign.uniqueID + "/gallery/\(galleryFileName!)") // TODO: Implement
}
var image = UIImage()
imgRef.downloadURL { (url, error) in
if let error = error {
print(error.localizedDescription)
} else {
if let imageUrl = url {
print("Download Started")
getDataFromUrl(url: imageUrl, completion: { (data, response, error) in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? imageUrl.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async {
image = UIImage(data: data)!
completion(image)
}
})
}
}
}
}
}
| 38.323077 | 170 | 0.572662 |
ed78e32616cd5cd519e558a824466bb785153da9 | 375 | //
// PluginType.swift
// Network
//
// Created by Nick on 4/12/20.
// Copyright © 2020 kciNniL. All rights reserved.
//
import Foundation
public
protocol PluginType {
typealias ResultType = (Data?, URLResponse?, Error?)
func willSend<Req: Request>(_ request: Req, urlRequest: URLRequest)
func didReceive<Req: Request>(_ request: Req, result: ResultType)
}
| 22.058824 | 71 | 0.698667 |
e08d8fa43c716002e3ec60459b830b8214d642ce | 1,434 | //
// AppDelegate.swift
// How-To-Scan-A-Barcode
//
// Created by Thomas Kellough on 8/8/20.
// Copyright © 2020 Thomas Kellough. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.736842 | 179 | 0.747559 |
6455e34413812a68d23d7302267b21d3237bac32 | 21,430 | //
// Extensions.swift
// BreadWallet
//
// Created by Samuel Sutch on 1/30/16.
// Copyright (c) 2016 breadwallet LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import BRCore
import libbz2
import UIKit
public extension String {
static func buildQueryString(_ options: [String: [String]]?, includeQ: Bool = false) -> String {
var s = ""
if let options = options , options.count > 0 {
s = includeQ ? "?" : ""
var i = 0
for (k, vals) in options {
for v in vals {
if i != 0 {
s += "&"
}
i += 1
s += "\(k.urlEscapedString)=\(v.urlEscapedString)"
}
}
}
return s
}
static var urlQuoteCharacterSet: CharacterSet {
if let cset = (NSMutableCharacterSet.urlQueryAllowed as NSCharacterSet).mutableCopy() as? NSMutableCharacterSet {
cset.removeCharacters(in: "?=&")
return cset as CharacterSet
}
return NSMutableCharacterSet.urlQueryAllowed as CharacterSet
}
func md5() -> String {
guard let data = self.data(using: .utf8) else {
assert(false, "couldnt encode string as utf8 data")
return ""
}
var result = Data(count: 128/8)
let resultCount = result.count
return result.withUnsafeMutableBytes { (resultBytes: UnsafeMutablePointer<CUnsignedChar>) -> String in
data.withUnsafeBytes { (dataBytes) -> Void in
BRMD5(resultBytes, dataBytes, data.count)
}
var hash = String()
for i in 0..<resultCount {
hash = hash.appendingFormat("%02x", resultBytes[i])
}
return hash
}
}
func base58DecodedData() -> Data {
let len = BRBase58Decode(nil, 0, self)
var data = Data(count: len)
_ = data.withUnsafeMutableBytes({ BRBase58Decode($0, len, self) })
return data
}
var urlEscapedString: String {
return addingPercentEncoding(withAllowedCharacters: String.urlQuoteCharacterSet) ?? ""
}
func parseQueryString() -> [String: [String]] {
var ret = [String: [String]]()
var strippedString = self
if String(self[..<self.index(self.startIndex, offsetBy: 1)]) == "?" {
strippedString = String(self[self.index(self.startIndex, offsetBy: 1)...])
}
strippedString = strippedString.replacingOccurrences(of: "+", with: " ")
strippedString = strippedString.removingPercentEncoding!
for s in strippedString.components(separatedBy: "&") {
let kp = s.components(separatedBy: "=")
if kp.count == 2 {
if var k = ret[kp[0]] {
k.append(kp[1])
} else {
ret[kp[0]] = [kp[1]]
}
}
}
return ret
}
}
extension UserDefaults {
var deviceID: String {
if let s = string(forKey: "BR_DEVICE_ID") {
return s
}
let s = CFUUIDCreateString(nil, CFUUIDCreate(nil)) as String
setValue(s, forKey: "BR_DEVICE_ID")
print("new device id \(s)")
return s
}
}
let VAR_INT16_HEADER: UInt64 = 0xfd
let VAR_INT32_HEADER: UInt64 = 0xfe
let VAR_INT64_HEADER: UInt64 = 0xff
extension NSMutableData {
func appendVarInt(i: UInt64) {
if (i < VAR_INT16_HEADER) {
var payload = UInt8(i)
append(&payload, length: MemoryLayout<UInt8>.size)
}
else if (Int32(i) <= UINT16_MAX) {
var header = UInt8(VAR_INT16_HEADER)
var payload = CFSwapInt16HostToLittle(UInt16(i))
append(&header, length: MemoryLayout<UInt8>.size)
append(&payload, length: MemoryLayout<UInt16>.size)
}
else if (UInt32(i) <= UINT32_MAX) {
var header = UInt8(VAR_INT32_HEADER)
var payload = CFSwapInt32HostToLittle(UInt32(i))
append(&header, length: MemoryLayout<UInt8>.size)
append(&payload, length: MemoryLayout<UInt32>.size)
}
else {
var header = UInt8(VAR_INT64_HEADER)
var payload = CFSwapInt64HostToLittle(i)
append(&header, length: MemoryLayout<UInt8>.size)
append(&payload, length: MemoryLayout<UInt64>.size)
}
}
}
var BZCompressionBufferSize: UInt32 = 1024
var BZDefaultBlockSize: Int32 = 7
var BZDefaultWorkFactor: Int32 = 100
private struct AssociatedKeys {
static var hexString = "hexString"
}
public extension Data {
var hexString: String {
if let string = getCachedHexString() {
return string
} else {
let string = reduce("") {$0 + String(format: "%02x", $1)}
setHexString(string: string)
return string
}
}
private func setHexString(string: String) {
objc_setAssociatedObject(self, &AssociatedKeys.hexString, string, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func getCachedHexString() -> String? {
return objc_getAssociatedObject(self, &AssociatedKeys.hexString) as? String
}
var bzCompressedData: Data? {
guard !self.isEmpty else {
return self
}
var compressed = Data()
var stream = bz_stream()
var mself = self
var success = true
mself.withUnsafeMutableBytes { (selfBuff: UnsafeMutablePointer<Int8>) -> Void in
let outBuff = UnsafeMutablePointer<Int8>.allocate(capacity: Int(BZCompressionBufferSize))
defer { outBuff.deallocate() }
stream.next_in = selfBuff
stream.avail_in = UInt32(self.count)
stream.next_out = outBuff
stream.avail_out = BZCompressionBufferSize
var bzret = BZ2_bzCompressInit(&stream, BZDefaultBlockSize, 0, BZDefaultWorkFactor)
guard bzret == BZ_OK else {
print("failed compression init")
success = false
return
}
repeat {
bzret = BZ2_bzCompress(&stream, stream.avail_in > 0 ? BZ_RUN : BZ_FINISH)
guard bzret >= BZ_OK else {
print("failed compress")
success = false
return
}
let bpp = UnsafeBufferPointer(start: outBuff, count: (Int(BZCompressionBufferSize) - Int(stream.avail_out)))
compressed.append(bpp)
stream.next_out = outBuff
stream.avail_out = BZCompressionBufferSize
} while bzret != BZ_STREAM_END
}
BZ2_bzCompressEnd(&stream)
guard success else { return nil }
return compressed
}
init?(bzCompressedData data: Data) {
guard !data.isEmpty else {
return nil
}
var stream = bz_stream()
var decompressed = Data()
var myDat = data
var success = true
myDat.withUnsafeMutableBytes { (datBuff: UnsafeMutablePointer<Int8>) -> Void in
let outBuff = UnsafeMutablePointer<Int8>.allocate(capacity: Int(BZCompressionBufferSize))
defer { outBuff.deallocate() }
stream.next_in = datBuff
stream.avail_in = UInt32(data.count)
stream.next_out = outBuff
stream.avail_out = BZCompressionBufferSize
var bzret = BZ2_bzDecompressInit(&stream, 0, 0)
guard bzret == BZ_OK else {
print("failed decompress init")
success = false
return
}
repeat {
bzret = BZ2_bzDecompress(&stream)
guard bzret >= BZ_OK else {
print("failed decompress")
success = false
return
}
let bpp = UnsafeBufferPointer(start: outBuff, count: (Int(BZCompressionBufferSize) - Int(stream.avail_out)))
decompressed.append(bpp)
stream.next_out = outBuff
stream.avail_out = BZCompressionBufferSize
} while bzret != BZ_STREAM_END
}
BZ2_bzDecompressEnd(&stream)
guard success else { return nil }
self.init(decompressed)
}
var base58: String {
return self.withUnsafeBytes { (selfBytes: UnsafePointer<UInt8>) -> String in
let len = BRBase58Encode(nil, 0, selfBytes, self.count)
var data = Data(count: len)
return data.withUnsafeMutableBytes { (b: UnsafeMutablePointer<Int8>) in
BRBase58Encode(b, len, selfBytes, self.count)
return String(cString: b)
}
}
}
var sha1: Data {
var data = Data(count: 20)
data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in
self.withUnsafeBytes({ (selfBytes: UnsafePointer<UInt8>) in
BRSHA1(bytes, selfBytes, self.count)
})
}
return data
}
var sha256: Data {
var data = Data(count: 32)
data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) in
self.withUnsafeBytes({ (selfBytes: UnsafePointer<UInt8>) in
BRSHA256(bytes, selfBytes, self.count)
})
}
return data
}
var sha256_2: Data {
return self.sha256.sha256
}
var uInt256: UInt256 {
return self.withUnsafeBytes { (ptr: UnsafePointer<UInt256>) -> UInt256 in
return ptr.pointee
}
}
func uInt8(atOffset offset: UInt) -> UInt8 {
let offt = Int(offset)
let size = MemoryLayout<UInt8>.size
if self.count < offt + size { return 0 }
return self.subdata(in: offt..<(offt+size)).withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> UInt8 in
return ptr.pointee
}
}
func uInt32(atOffset offset: UInt) -> UInt32 {
let offt = Int(offset)
let size = MemoryLayout<UInt32>.size
if self.count < offt + size { return 0 }
return self.subdata(in: offt..<(offt+size)).withUnsafeBytes { (ptr: UnsafePointer<UInt32>) -> UInt32 in
return CFSwapInt32LittleToHost(ptr.pointee)
}
}
func uInt64(atOffset offset: UInt) -> UInt64 {
let offt = Int(offset)
let size = MemoryLayout<UInt64>.size
if self.count < offt + size { return 0 }
return self.subdata(in: offt..<(offt+size)).withUnsafeBytes { (ptr: UnsafePointer<UInt64>) -> UInt64 in
return CFSwapInt64LittleToHost(ptr.pointee)
}
}
func compactSign(key: BRKey) -> Data {
return self.withUnsafeBytes({ (selfBytes: UnsafePointer<UInt8>) -> Data in
var data = Data(count: 65)
var k = key
_ = data.withUnsafeMutableBytes({ BRKeyCompactSign(&k, $0, 65, self.uInt256) })
return data
})
}
fileprivate func genNonce() -> [UInt8] {
var tv = timeval()
gettimeofday(&tv, nil)
var t = UInt64(tv.tv_usec) * 1_000_000 + UInt64(tv.tv_usec)
let p = [UInt8](repeating: 0, count: 4)
return Data(bytes: &t, count: MemoryLayout<UInt64>.size).withUnsafeBytes { (dat: UnsafePointer<UInt8>) -> [UInt8] in
let buf = UnsafeBufferPointer(start: dat, count: MemoryLayout<UInt64>.size)
return p + Array(buf)
}
}
func chacha20Poly1305AEADEncrypt(key: BRKey) -> Data {
let data = [UInt8](self)
let inData = UnsafePointer<UInt8>(data)
let nonce = genNonce()
var null = CChar(0)
var sk = key.secret
return withUnsafePointer(to: &sk) {
let outSize = BRChacha20Poly1305AEADEncrypt(nil, 0, $0, nonce, inData, data.count, &null, 0)
var outData = [UInt8](repeating: 0, count: outSize)
BRChacha20Poly1305AEADEncrypt(&outData, outSize, $0, nonce, inData, data.count, &null, 0)
return Data(nonce + outData)
}
}
func chacha20Poly1305AEADDecrypt(key: BRKey) throws -> Data {
let data = [UInt8](self)
guard data.count > 12 else { throw BRReplicatedKVStoreError.malformedData }
let nonce = Array(data[data.startIndex...data.startIndex.advanced(by: 12)])
let inData = Array(data[data.startIndex.advanced(by: 12)...(data.endIndex-1)])
var null = CChar(0)
var sk = key.secret
return withUnsafePointer(to: &sk) {
let outSize = BRChacha20Poly1305AEADDecrypt(nil, 0, $0, nonce, inData, inData.count, &null, 0)
var outData = [UInt8](repeating: 0, count: outSize)
BRChacha20Poly1305AEADDecrypt(&outData, outSize, $0, nonce, inData, inData.count, &null, 0)
return Data(outData)
}
}
var masterPubKey: BRMasterPubKey? {
guard self.count >= (4 + 32 + 33) else { return nil }
var mpk = BRMasterPubKey()
mpk.fingerPrint = self.subdata(in: 0..<4).withUnsafeBytes { $0.pointee }
mpk.chainCode = self.subdata(in: 4..<(4 + 32)).withUnsafeBytes { $0.pointee }
mpk.pubKey = self.subdata(in: (4 + 32)..<(4 + 32 + 33)).withUnsafeBytes { $0.pointee }
return mpk
}
init(masterPubKey mpk: BRMasterPubKey) {
var data = [mpk.fingerPrint].withUnsafeBufferPointer { Data(buffer: $0) }
[mpk.chainCode].withUnsafeBufferPointer { data.append($0) }
[mpk.pubKey].withUnsafeBufferPointer { data.append($0) }
self.init(data)
}
var urlEncodedObject: [String: [String]]? {
guard let str = String(data: self, encoding: .utf8) else {
return nil
}
return str.parseQueryString()
}
}
public extension Date {
static func withMsTimestamp(_ ms: UInt64) -> Date {
return Date(timeIntervalSince1970: Double(ms) / 1000.0)
}
func msTimestamp() -> UInt64 {
return UInt64((self.timeIntervalSince1970 < 0 ? 0 : self.timeIntervalSince1970) * 1000.0)
}
// this is lifted from: https://github.com/Fykec/NSDate-RFC1123/blob/master/NSDate%2BRFC1123.swift
// Copyright © 2021 Foster Yin. All rights reserved.
fileprivate static func cachedThreadLocalObjectWithKey<T: AnyObject>(_ key: String, create: () -> T) -> T {
let threadDictionary = Thread.current.threadDictionary
if let cachedObject = threadDictionary[key] as! T? {
return cachedObject
}
else {
let newObject = create()
threadDictionary[key] = newObject
return newObject
}
}
fileprivate static func RFC1123DateFormatter() -> DateFormatter {
return cachedThreadLocalObjectWithKey("RFC1123DateFormatter") {
let locale = Locale(identifier: "en_US")
let timeZone = TimeZone(identifier: "GMT")
let dateFormatter = DateFormatter()
dateFormatter.locale = locale //need locale for some iOS 9 verision, will not select correct default locale
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
return dateFormatter
}
}
fileprivate static func RFC850DateFormatter() -> DateFormatter {
return cachedThreadLocalObjectWithKey("RFC850DateFormatter") {
let locale = Locale(identifier: "en_US")
let timeZone = TimeZone(identifier: "GMT")
let dateFormatter = DateFormatter()
dateFormatter.locale = locale //need locale for some iOS 9 verision, will not select correct default locale
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = "EEEE, dd-MMM-yy HH:mm:ss z"
return dateFormatter
}
}
fileprivate static func asctimeDateFormatter() -> DateFormatter {
return cachedThreadLocalObjectWithKey("asctimeDateFormatter") {
let locale = Locale(identifier: "en_US")
let timeZone = TimeZone(identifier: "GMT")
let dateFormatter = DateFormatter()
dateFormatter.locale = locale //need locale for some iOS 9 verision, will not select correct default locale
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = "EEE MMM d HH:mm:ss yyyy"
return dateFormatter
}
}
static func fromRFC1123(_ dateString: String) -> Date? {
var date: Date?
// RFC1123
date = Date.RFC1123DateFormatter().date(from: dateString)
if date != nil {
return date
}
// RFC850
date = Date.RFC850DateFormatter().date(from: dateString)
if date != nil {
return date
}
// asctime-date
date = Date.asctimeDateFormatter().date(from: dateString)
if date != nil {
return date
}
return nil
}
func RFC1123String() -> String? {
return Date.RFC1123DateFormatter().string(from: self)
}
}
public extension BRKey {
var publicKey: Data {
var k = self
let len = BRKeyPubKey(&k, nil, 0)
var data = Data(count: len)
BRKeyPubKey(&k, data.withUnsafeMutableBytes({ (d: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8> in d }), len)
return data
}
}
extension UIImage {
/// Represents a scaling mode
enum ScalingMode {
case aspectFill
case aspectFit
/// Calculates the aspect ratio between two sizes
///
/// - parameters:
/// - size: the first size used to calculate the ratio
/// - otherSize: the second size used to calculate the ratio
///
/// - return: the aspect ratio between the two sizes
func aspectRatio(between size: CGSize, and otherSize: CGSize) -> CGFloat {
let aspectWidth = size.width/otherSize.width
let aspectHeight = size.height/otherSize.height
switch self {
case .aspectFill:
return max(aspectWidth, aspectHeight)
case .aspectFit:
return min(aspectWidth, aspectHeight)
}
}
}
/// Scales an image to fit within a bounds with a size governed by the passed size. Also keeps the aspect ratio.
///
/// - parameters:
/// - newSize: the size of the bounds the image must fit within.
/// - scalingMode: the desired scaling mode
///
/// - returns: a new scaled image.
func scaled(to newSize: CGSize, scalingMode: UIImage.ScalingMode = .aspectFill) -> UIImage {
let aspectRatio = scalingMode.aspectRatio(between: newSize, and: size)
/* Build the rectangle representing the area to be drawn */
var scaledImageRect = CGRect.zero
scaledImageRect.size.width = size.width * aspectRatio
scaledImageRect.size.height = size.height * aspectRatio
scaledImageRect.origin.x = (newSize.width - size.width * aspectRatio) / 2.0
scaledImageRect.origin.y = (newSize.height - size.height * aspectRatio) / 2.0
/* Draw and retrieve the scaled image */
UIGraphicsBeginImageContext(newSize)
draw(in: scaledImageRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage!
}
}
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
var flattened: [Key: String] {
var ret = [Key: String]()
for (k, v) in self {
if let v = v as? [String] {
if v.count > 0 {
ret[k] = v[0]
}
}
}
return ret
}
var jsonString: String {
guard let json = try? JSONSerialization.data(withJSONObject: self, options: []) else {
return "null"
}
guard let jstring = String(data: json, encoding: .utf8) else {
return "null"
}
return jstring
}
}
| 36.632479 | 131 | 0.585581 |
8a9d92db7a7e4ee22908c632889d584c229694b9 | 6,224 | //
// PhotoThumbCell.swift
// PhotoBrowserProject
//
// Created by ty on 15/11/25.
// Copyright © 2015年 ty. All rights reserved.
//
import UIKit
import Photos
class PhotoThumbCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var selectedStatusContainerView: UIView!
@IBOutlet weak var selectedImageView: UIImageView!
@IBOutlet weak var unselectedImageView: UIImageView!
@IBOutlet weak var selectedButton: UIControl!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var maskButton: UIButton!
@IBOutlet weak var iCloudLabel: UILabel!
private var asset: PHAsset!
weak var photoColletionViewController: PhotoColletionViewController?
override func awakeFromNib() {
super.awakeFromNib()
self.iCloudLabel.text = self.GetLocalizableText(key: "TYImagePickerInCloudImage")
}
@IBAction func onClickMask(_ sender: UIButton) {
if PhotosManager.sharedInstance.maxSelectedCount == 9 {
let alert = UIAlertView(title: "", message: self.GetLocalizableText(key: "TYImagePickerMaximumText"), delegate: nil, cancelButtonTitle: self.GetLocalizableText(key: "TYImagePickerSureText"))
alert.show()
}
}
@IBAction func onClickRadio() {
guard let vc = photoColletionViewController else { return }
PhotosManager.sharedInstance.checkImageIsInLocal(with: asset) { isExistInLocal in
// print(isExistInLocal == false ? "在云端" : "在本地")
self.setResourceSelectedStatus(isInLocal: isExistInLocal)
vc.updateUI()
}
}
func setAsset(_ asset: PHAsset) {
self.asset = asset
updateSelectedStatus()
updateIsSelectable()
let currentTag = tag + 1
tag = currentTag
imageView.image = nil
PhotosManager.sharedInstance.fetchImage(with: asset, sizeType: .thumbnail) { (image, isInICloud) in
guard image != nil else {
return
}
if currentTag == self.tag {
self.imageView.image = image
}
}
}
func setResourceSelectedStatus(isInLocal: Bool) {
guard asset.mediaType == .image else {
let isSelected = PhotosManager.sharedInstance.selectVideo(with: asset)
setPhotoStatusWithAnimation(isSelected)
return
}
let isSuccess = PhotosManager.sharedInstance.selectPhoto(with: asset)
if !isSuccess {
if PhotosManager.sharedInstance.maxSelectedCount == 9 {
let alert = UIAlertView(title: "", message: self.GetLocalizableText(key: "TYImagePickerMaximumText"), delegate: nil, cancelButtonTitle: self.GetLocalizableText(key: "TYImagePickerSureText"))
alert.show()
}
return
}
let isSelected = PhotosManager.sharedInstance.getPhotoSelectedStatus(with: asset)
if isInLocal {
self.iCloudLabel.isHidden = true
}else{
self.iCloudLabel.isHidden = !isSelected
}
setPhotoStatusWithAnimation(isSelected)
}
func setPhotoStatusWithAnimation(_ isSelected: Bool) {
self.setResourceSelected(!isSelected)
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.5, options: UIViewAnimationOptions(), animations: { () -> Void in
self.setResourceSelected(isSelected)
}) { _ in
}
}
func updateSelectedStatus() {
if asset.mediaType == .video {
durationLabel.text = formatSecond(second: Int(round(asset.duration)))
if let selectedVideo = PhotosManager.sharedInstance.selectedVideo, selectedVideo == asset {
setResourceSelected(true)
} else {
setResourceSelected(false)
}
} else {
let isSelected = PhotosManager.sharedInstance.getPhotoSelectedStatus(with: asset)
setResourceSelected(isSelected)
durationLabel.text = ""
}
}
func updateGrayMaskStatus() {
if asset.mediaType == .image {
let isSelected = PhotosManager.sharedInstance.getPhotoSelectedStatus(with: asset)
if PhotosManager.sharedInstance.selectedImages.count == PhotosManager.sharedInstance.maxSelectedCount {
self.maskButton.isHidden = isSelected
}else{
self.maskButton.isHidden = true
}
}
}
func updateIsSelectable() {
if PhotosManager.sharedInstance.maxSelectedCount == 1 {
selectedButton.isHidden = true
unselectedImageView.isHidden = true
selectedImageView.isHidden = true
return
}
if asset.mediaType == .video {
let isHide = !PhotosManager.sharedInstance.selectedImages.isEmpty
selectedStatusContainerView.isHidden = isHide
selectedButton.isHidden = isHide
} else if asset.mediaType == .image {
let isHide = !(PhotosManager.sharedInstance.selectedVideo == nil)
selectedStatusContainerView.isHidden = isHide
selectedButton.isHidden = isHide
}
}
func setResourceSelected(_ isSelected: Bool) {
if PhotosManager.sharedInstance.maxSelectedCount == 1 {
selectedButton.isHidden = true
unselectedImageView.isHidden = true
selectedImageView.isHidden = true
return
}
selectedImageView.isHidden = false
unselectedImageView.isHidden = false
selectedImageView.transform = isSelected == false ? CGAffineTransform(scaleX: 0.5, y: 0.5) : CGAffineTransform.identity
self.selectedImageView.alpha = isSelected ? 1 : 0
if isSelected {
PhotosManager.sharedInstance.checkImageIsInLocal(with: asset, completion: { (isInLocal) in
self.iCloudLabel.isHidden = isInLocal
})
}else{
self.iCloudLabel.isHidden = true
}
}
func formatSecond(second: Int) -> String {
let hour = second / (60 * 60)
let minute = second % (60 * 60) / 60
let second = second % 60
let hourStr = String(format: "%02d", hour)
let minuteStr = String(format: "%02d", minute)
let secondStr = String(format: "%02d", second)
if hour == 0 {
return minuteStr + ":" + secondStr
} else {
return hourStr + ":" + minuteStr + ":" + secondStr
}
}
}
| 27.662222 | 202 | 0.663239 |
561ab4bc9e154980d3fdeb50d0d0074a377621c3 | 817 | //
// CircleProgressBar.swift
// iOS Example
//
// Created by Dao Duy Duong on 31/12/2020.
// Copyright © 2020 Duong Dao. All rights reserved.
//
import SwiftUI
struct CircleProgressBar: View {
@Binding var progress: Float
let lineWidth: CGFloat = 4
var body: some View {
ZStack {
Circle()
.stroke(lineWidth: lineWidth)
.opacity(0.3)
.foregroundColor(Color.red)
Circle()
.trim(from: 0.0, to: CGFloat(min(self.progress, 1.0)))
.stroke(style: StrokeStyle(lineWidth: lineWidth, lineCap: .round, lineJoin: .round))
.foregroundColor(Color.red)
.rotationEffect(Angle(degrees: 270.0))
.animation(.linear)
}
}
}
| 25.53125 | 100 | 0.53978 |
4af652323ea78a4db51fbf950050bc3ee2cc04af | 4,938 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import XCTest
final class DarkModeKitUITests: XCTestCase {
// swiftlint:disable overridden_super_call
override func setUp() {
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test.
// Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
}
func testUIView() {
_test(UIView.self)
}
func testUIActivityIndicatorView() {
_test(UIActivityIndicatorView.self)
}
func testUIButton() {
_test(UIButton.self)
}
func testUIPageControl() {
_test(UIPageControl.self)
}
func testUILabel() {
_test(UILabel.self)
}
func testUIImageView() {
_test(UIImageView.self)
}
func _test(_ `class`: UIView.Type) {
_test(by: NSStringFromClass(`class`))
}
func _test(by itemName: String) {
let app = XCUIApplication()
let navigationBarIdentifier = "0" // Current window index is used as navigation bar title
let refreshButtonIdentifier = "Refresh"
let compareNavigatonBarTitle = "FluentDarkModeKitExample.View"
let refreshButton = app.navigationBars[navigationBarIdentifier].buttons[refreshButtonIdentifier]
refreshButton.tap() // light mode
refreshButton.tap() // dark mode
let uiviewStaticText = app.tables.staticTexts[itemName]
uiviewStaticText.tap()
sleep(1)
let screenshot1 = app.screenshot()
let backButtonTitle = navigationBarIdentifier
app.navigationBars[navigationBarIdentifier].buttons[backButtonTitle].tap()
refreshButton.tap() // unspecified
refreshButton.tap() // light mode
uiviewStaticText.tap()
let tabBarsQuery = app.tabBars
tabBarsQuery.children(matching: .button).element(boundBy: 1).tap()
app.navigationBars[compareNavigatonBarTitle].buttons[refreshButtonIdentifier].tap()
tabBarsQuery.children(matching: .button).element(boundBy: 0).tap() // dark mode
let screenshot2 = app.screenshot()
XCTAssertTrue(compare(screenshot1.image, screenshot2.image, precision: 1))
}
}
private func compare(_ old: UIImage, _ new: UIImage, precision: Float) -> Bool {
guard let oldCgImage = old.cgImage else { return false }
guard let newCgImage = new.cgImage else { return false }
guard oldCgImage.width != 0 else { return false }
guard newCgImage.width != 0 else { return false }
guard oldCgImage.width == newCgImage.width else { return false }
guard oldCgImage.height != 0 else { return false }
guard newCgImage.height != 0 else { return false }
guard oldCgImage.height == newCgImage.height else { return false }
// Values between images may differ due to padding to multiple of 64 bytes per row,
// because of that a freshly taken view snapshot may differ from one stored as PNG.
// At this point we're sure that size of both images is the same, so we can go with minimal `bytesPerRow` value
// and use it to create contexts.
let minBytesPerRow = min(oldCgImage.bytesPerRow, newCgImage.bytesPerRow)
let byteCount = minBytesPerRow * oldCgImage.height
var oldBytes = [UInt8](repeating: 0, count: byteCount)
guard let oldContext = context(for: oldCgImage, bytesPerRow: minBytesPerRow, data: &oldBytes) else { return false }
guard let oldData = oldContext.data else { return false }
if let newContext = context(for: newCgImage, bytesPerRow: minBytesPerRow), let newData = newContext.data {
if memcmp(oldData, newData, byteCount) == 0 {
return true
}
}
let newer = UIImage(data: new.pngData()!)!
guard let newerCgImage = newer.cgImage else { return false }
var newerBytes = [UInt8](repeating: 0, count: byteCount)
guard let newerContext = context(for: newerCgImage, bytesPerRow: minBytesPerRow, data: &newerBytes) else { return false }
guard let newerData = newerContext.data else { return false }
if memcmp(oldData, newerData, byteCount) == 0 {
return true
}
if precision >= 1 {
return false
}
var differentPixelCount = 0
let threshold = 1 - precision
for byte in 0..<byteCount {
if oldBytes[byte] != newerBytes[byte] { differentPixelCount += 1 }
if Float(differentPixelCount) / Float(byteCount) > threshold {
return false
}
}
return true
}
private func context(for cgImage: CGImage, bytesPerRow: Int, data: UnsafeMutableRawPointer? = nil) -> CGContext? {
guard
let space = cgImage.colorSpace,
let context = CGContext(
data: data,
width: cgImage.width,
height: cgImage.height,
bitsPerComponent: cgImage.bitsPerComponent,
bytesPerRow: bytesPerRow,
space: space,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
)
else { return nil }
context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height))
return context
}
| 34.291667 | 123 | 0.714257 |
e44b71af5c366e2ed1b8b93568a1745fe3cc1bcb | 819 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}
b((Range() -> Any) -> Any, y)
protocol P {
assert(n: U.a)(mx : A {
}
assert(A>()
class a(range.lowerBound, y: A> T: C {
e {
protocol a {
import Foundation
}
let i()
}
a(self.<b: () {
func a: b {
}
func g<j : Collection where H) {
}
import Foundation
class a {
typealias h: (() -> ()() -> (_ c()
}
protocol A {
struct Q<T) -> String {
case C: A {
assert()
let h = b[""")
}
}
}
}
struct c<T where B : U>) -> {
}
var _ c]
| 19.046512 | 79 | 0.641026 |
64c76b29b1af0561aa1bc508dc8a7096a798b00e | 2,282 | //
// SceneDelegate.swift
// Prework
//
// Created by U Shin on 2/4/22.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.056604 | 147 | 0.711656 |
489c677a14f80d51c291d54bb9c4a1e4dc919fb9 | 534 | //
// PPBadgeView.swift
// PPBadgeViewSwift
//
// Created by jkpang on 2018/4/17.
// Copyright © 2018年 AndyPang. All rights reserved.
//
import UIKit
public struct PP<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
public extension NSObjectProtocol {
var pp: PP<Self> {
return PP(self)
}
}
public enum PPBadgeViewFlexMode {
case head // 左伸缩 Head Flex : <==●
case tail // 右伸缩 Tail Flex : ●==>
case middle // 左右伸缩 Middle Flex : <=●=>
}
| 18.413793 | 52 | 0.593633 |
284016ada6af128917dbe0fbef7320f47e42ed2c | 1,926 | //
// NoticeViewTests.swift
// ChargeBack
//
// Created by Antoine Barrault on 24/03/2017.
// Copyright © 2017 Antoine Barrault. All rights reserved.
//
import XCTest
@testable import ChargeBack
class NoticeViewTests: XCTestCase {
let noticeView = NoticeView()
func testConfiguringNoticeView() {
//given
let firstAction = ActionInNotice(title: "Continue", action: "action_next")
let secondAction = ActionInNotice(title: "Cancel", action: "action_cancel")
let notice = Notice(title: "title",
description: "description",
primaryAction: firstAction,
secondaryAction: secondAction,
nextAction: .chargeback)
//when
noticeView.configure(with: notice)
//then
let title = noticeView.title.text
XCTAssert(title == "title")
let description = noticeView.textView.text
XCTAssert(description == "description")
let continueBtnText = noticeView.continueButton.titleLabel?.text
XCTAssert(continueBtnText == firstAction.title.uppercased())
let cancelButtonText = noticeView.cancelButton.titleLabel?.text
XCTAssert(cancelButtonText == secondAction.title.uppercased())
}
func testClickOnFirstActionButton() {
//given
var clicked = false
noticeView.clickOnFirstActionButton = {
clicked = true
}
//when
noticeView.didClickOnFirstAction(self.noticeView.continueButton)
//then
XCTAssert(clicked)
}
func testClickOnSecondActionButton() {
//given
var clicked = false
noticeView.clickOnSecondActionButton = {
clicked = true
}
//when
noticeView.didClickOnSecondAction(self.noticeView.cancelButton)
//then
XCTAssert(clicked)
}
}
| 29.630769 | 83 | 0.61838 |
fbb1996a2f85d394bcc4e17627cfb86a61b3e848 | 1,353 | //
// AppDelegate.swift
// Milestone 2
//
// Created by Hümeyra Şahin on 8.10.2021.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.567568 | 179 | 0.74575 |
893c2c6d0adc70e46759e31cd0bd8294962076ba | 912 | //
// NoSessionInterceptor.swift
// FRExample
//
// Copyright (c) 2020 ForgeRock. All rights reserved.
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
//
import FRCore
class NoSessionInterceptor: RequestInterceptor {
func intercept(request: Request, action: Action) -> Request {
if action.type == "START_AUTHENTICATE" || action.type == "AUTHENTICATE" {
var urlParams = request.urlParams
urlParams["noSession"] = "true"
let newRequest = Request(url: request.url, method: request.method, headers: request.headers, bodyParams: request.bodyParams, urlParams: urlParams, requestType: request.requestType, responseType: request.responseType, timeoutInterval: request.timeoutInterval)
return newRequest
}
else {
return request
}
}
}
| 33.777778 | 270 | 0.678728 |
e261dd8a301302297004f36c278dbd6521ef88af | 3,292 | import Foundation
let MAX_SYMBOLS = 256
protocol Tree {
func freq() -> UInt
func writeTo(writer: BitOutputStream)
func dumpCodes(codes: inout [String], prefix: String)
func readChar(reader: BitInputStream) -> UInt8
}
class Leaf : Tree {
var frecuency : UInt
var symbol : UInt8
init(frq:UInt, sym:UInt8) {
frecuency = frq
symbol = sym
}
func freq() -> UInt {
return frecuency
}
func writeTo(writer: BitOutputStream) {
writer.writeBit(bit: 1)
writer.writeByte(byte: UInt16(symbol))
}
func dumpCodes(codes: inout [String], prefix: String) {
codes[Int(symbol)] = prefix
}
func readChar(reader: BitInputStream) -> UInt8 {
return symbol
}
}
class Node : Tree {
var left: Tree
var right: Tree
init( left: Tree, right: Tree) {
self.left = left
self.right = right
}
func freq() -> UInt {
return left.freq() + right.freq()
}
func writeTo(writer: BitOutputStream) {
writer.writeBit(bit: 0)
left.writeTo(writer: writer)
right.writeTo(writer: writer)
}
func dumpCodes(codes: inout [String], prefix: String) {
left.dumpCodes(codes: &codes, prefix: prefix+"0")
right.dumpCodes(codes: &codes, prefix: prefix+"1")
}
func readChar(reader: BitInputStream) -> UInt8 {
if reader.readBool() {
return right.readChar(reader: reader)
} else {
return left.readChar(reader: reader)
}
}
}
class HuffTree {
var tree: Tree? = nil
var codes: [String] = [String]()
init(buildFrom: BitInputStream) {
let freqs = calcFrecuencies(source: buildFrom)
let heap = Heap(size: MAX_SYMBOLS)
for (s, f) in freqs.enumerated() {
if f > 0 {
heap.insert(elem: Leaf(frq: UInt(f), sym: UInt8(s)))
}
}
while heap.size() > 1 {
let l = heap.extract()
let r = heap.extract()
heap.insert(elem: Node(left: l!, right: r!))
}
tree = heap.extract()
codes = buildCodes(tree: tree!)
}
init(readFrom: BitInputStream) {
tree = readTree(reader: readFrom)
}
func compress(readFrom: BitInputStream, writeTo: BitOutputStream) {
tree!.writeTo(writer: writeTo)
writeSymbols(reader: readFrom, writer: writeTo)
writeTo.close()
}
func decompress(readFrom: BitInputStream, writeTo: BitOutputStream) {
let len = readFrom.readInt()
for _ in 0..<len {
writeTo.writeByte(byte: UInt16(tree!.readChar(reader: readFrom)))
}
writeTo.close()
}
func readTree(reader: BitInputStream) -> Tree {
let flag = reader.readBool()
if flag {
return Leaf(frq: 0, sym: reader.readChar())
} else {
let l = readTree(reader: reader)
let r = readTree(reader: reader)
return Node(left: l, right: r)
}
}
func calcFrecuencies(source: BitInputStream) -> [Int]{
var freqs = [Int](repeating: 0, count: MAX_SYMBOLS)
let bytes = source.getBytes()
for i in 0 ..< bytes.count {
let c = bytes[i]
freqs[Int(c)] += 1
}
return freqs
}
func buildCodes(tree: Tree) -> [String] {
var codes = [String](repeating: "", count: MAX_SYMBOLS)
tree.dumpCodes(codes: &codes, prefix: "")
return codes
}
func writeSymbols(reader: BitInputStream, writer: BitOutputStream) {
let bytes = reader.getBytes()
let lbytes = bytes.count
writer.writeInt(i: UInt32(lbytes))
for (_, s) in bytes.enumerated() {
let code = codes[Int(s)]
for c in code {
writer.writeBitc(bit: c)
}
}
}
} | 20.447205 | 70 | 0.660996 |
f9d80f226cc6cb878a1b391354674a84edcbaad5 | 4,944 | //
// ModalViewController.swift
// Stylit
//
// Created by Kavi Ramamurthy on 2/24/19.
// Copyright © 2019 Lucas Wotton. All rights reserved.
//
import UIKit
import SnapKit
import PMSuperButton
class ItemModalViewController: UIViewController {
private let pulldownButton = PMSuperButton()
let itemImageView = UIImageView()
private let separatorView = UIView()
private let scrollView = UIScrollView()
private let contentView = UIView()
private let nameLabel = UILabel()
private let brandLabel = UILabel()
private let priceLabel = UILabel()
private let detailsLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
setupSubviews()
setupLayout()
}
private func setupSubviews() {
pulldownButton.setImage(UIImage(named: "down-arrow"), for: .normal)
pulldownButton.tintColor = .purple
pulldownButton.animatedScaleWhenHighlighted = 1.2
pulldownButton.addTarget(self, action: #selector(ItemModalViewController.pulldownButtonTapped(_:)), for: .touchUpInside)
itemImageView.contentMode = .scaleAspectFit
separatorView.backgroundColor = UIColor.purple
brandLabel.font = UIFont.systemFont(ofSize: 18, weight: .light)
brandLabel.textAlignment = .left
brandLabel.textColor = UIColor.lightGray
detailsLabel.font = UIFont.systemFont(ofSize: 18, weight: .medium)
detailsLabel.textAlignment = .left
detailsLabel.numberOfLines = 0
priceLabel.font = UIFont.systemFont(ofSize: 24, weight: .semibold)
priceLabel.textAlignment = .left
nameLabel.font = UIFont.systemFont(ofSize: 40, weight: .semibold)
nameLabel.textAlignment = .left
contentView.addSubview(itemImageView)
contentView.addSubview(nameLabel)
contentView.addSubview(brandLabel)
contentView.addSubview(priceLabel)
contentView.addSubview(detailsLabel)
scrollView.addSubview(contentView)
view.backgroundColor = .white
view.addSubview(pulldownButton)
view.addSubview(separatorView)
view.addSubview(scrollView)
}
private func setupLayout() {
pulldownButton.snp.makeConstraints { make in
make.top.equalTo(view.safeAreaLayoutGuide.snp.topMargin).offset(10)
make.centerX.equalToSuperview()
make.width.equalTo(80)
make.height.equalTo(80)
}
separatorView.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(15)
make.trailing.equalToSuperview().offset(-15)
make.top.equalTo(pulldownButton.snp.bottom)
make.height.equalTo(1)
}
itemImageView.snp.makeConstraints { make in
make.leading.equalToSuperview()
make.trailing.equalToSuperview()
make.top.equalToSuperview()
make.height.equalTo(400)
}
nameLabel.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.leading.equalToSuperview().offset(20)
make.top.equalTo(itemImageView.snp.bottom).offset(10)
}
brandLabel.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.leading.equalToSuperview().offset(20)
make.top.equalTo(nameLabel.snp.bottom).offset(5)
}
priceLabel.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.leading.equalToSuperview().offset(20)
make.top.equalTo(brandLabel.snp.bottom).offset(5)
}
detailsLabel.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.leading.equalToSuperview().offset(20)
make.top.equalTo(priceLabel.snp.bottom).offset(20)
make.bottom.equalToSuperview().offset(-10)
}
contentView.snp.makeConstraints { make in
make.edges.equalToSuperview()
make.width.equalTo(view.snp.width)
}
scrollView.snp.makeConstraints { make in
make.top.equalTo(separatorView.snp.bottom).offset(10)
make.leading.equalToSuperview()
make.trailing.equalToSuperview()
make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-10)
}
}
public func setItem(item: Item) {
itemImageView.image = item.image
nameLabel.text = item.title
brandLabel.text = item.brand
priceLabel.text = "$\(item.price)"
detailsLabel.text = item.description
}
}
extension ItemModalViewController {
@objc func pulldownButtonTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| 33.181208 | 156 | 0.628236 |
297fbde1e27d7cf1c0616b74be1ac536e0067eee | 13,699 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import AVFoundation
protocol QRCodeReaderLifeCycleDelegate: class {
func readerDidStartScanning()
func readerDidStopScanning()
}
/// Reader object base on the `AVCaptureDevice` to read / scan 1D and 2D codes.
public final class QRCodeReader: NSObject, AVCaptureMetadataOutputObjectsDelegate {
private let sessionQueue = DispatchQueue(label: "session queue")
private let metadataObjectsQueue = DispatchQueue(label: "com.yannickloriot.qr", attributes: [], target: nil)
let defaultDevice: AVCaptureDevice? = AVCaptureDevice.default(for: .video)
let frontDevice: AVCaptureDevice? = {
if #available(iOS 10, *) {
return AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .front)
}
else {
for device in AVCaptureDevice.devices(for: AVMediaType.video) {
if device.position == .front {
return device
}
}
}
return nil
}()
lazy var defaultDeviceInput: AVCaptureDeviceInput? = {
guard let defaultDevice = defaultDevice else { return nil }
return try? AVCaptureDeviceInput(device: defaultDevice)
}()
lazy var frontDeviceInput: AVCaptureDeviceInput? = {
if let _frontDevice = self.frontDevice {
return try? AVCaptureDeviceInput(device: _frontDevice)
}
return nil
}()
let session = AVCaptureSession()
let metadataOutput = AVCaptureMetadataOutput()
weak var lifeCycleDelegate: QRCodeReaderLifeCycleDelegate?
// MARK: - Managing the Properties
/// CALayer that you use to display video as it is being captured by an input device.
public let previewLayer: AVCaptureVideoPreviewLayer
/// An array of object identifying the types of metadata objects to process.
public let metadataObjectTypes: [AVMetadataObject.ObjectType]
// MARK: - Managing the Code Discovery
/// Flag to know whether the scanner should stop scanning when a code is found.
public var stopScanningWhenCodeIsFound: Bool = true
/// Block is executed when a metadata object is found.
public var didFindCode: ((QRCodeReaderResult) -> Void)?
/// Block is executed when a found metadata object string could not be decoded.
public var didFailDecoding: (() -> Void)?
// MARK: - Creating the Code Reade
/**
Initializes the code reader with the QRCode metadata type object.
*/
public convenience override init() {
self.init(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: .back)
}
/**
Initializes the code reader with an array of metadata object types, and the default initial capture position
- parameter metadataObjectTypes: An array of objects identifying the types of metadata objects to process.
*/
public convenience init(metadataObjectTypes types: [AVMetadataObject.ObjectType]) {
self.init(metadataObjectTypes: types, captureDevicePosition: .back)
}
/**
Initializes the code reader with the starting capture device position, and the default array of metadata object types
- parameter captureDevicePosition: The capture position to use on start of scanning
*/
public convenience init(captureDevicePosition position: AVCaptureDevice.Position) {
self.init(metadataObjectTypes: [AVMetadataObject.ObjectType.qr], captureDevicePosition: position)
}
/**
Initializes the code reader with an array of metadata object types.
- parameter metadataObjectTypes: An array of objects identifying the types of metadata objects to process.
- parameter captureDevicePosition: The Camera to use on start of scanning.
*/
public init(metadataObjectTypes types: [AVMetadataObject.ObjectType], captureDevicePosition: AVCaptureDevice.Position) {
metadataObjectTypes = types
previewLayer = AVCaptureVideoPreviewLayer(session: session)
super.init()
sessionQueue.async {[weak self] in
guard let self = self else { return }
self.configureDefaultComponents(withCaptureDevicePosition: captureDevicePosition)
}
}
// MARK: - Initializing the AV Components
private func configureDefaultComponents(withCaptureDevicePosition: AVCaptureDevice.Position) {
for output in session.outputs {
session.removeOutput(output)
}
for input in session.inputs {
session.removeInput(input)
}
// Add video input
switch withCaptureDevicePosition {
case .front:
if let _frontDeviceInput = frontDeviceInput {
session.addInput(_frontDeviceInput)
}
default:
if let _defaultDeviceInput = defaultDeviceInput {
session.addInput(_defaultDeviceInput)
}
}
// Add metadata output
session.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: metadataObjectsQueue)
let allTypes = Set(metadataOutput.availableMetadataObjectTypes)
let filtered = metadataObjectTypes.filter { (mediaType) -> Bool in
allTypes.contains(mediaType)
}
metadataOutput.metadataObjectTypes = filtered
previewLayer.videoGravity = .resizeAspectFill
session.commitConfiguration()
}
/// Switch between the back and the front camera.
@discardableResult
public func switchDeviceInput() -> AVCaptureDeviceInput? {
if let _frontDeviceInput = frontDeviceInput {
session.beginConfiguration()
if let _currentInput = session.inputs.first as? AVCaptureDeviceInput {
session.removeInput(_currentInput)
let newDeviceInput = (_currentInput.device.position == .front) ? defaultDeviceInput : _frontDeviceInput
session.addInput(newDeviceInput!)
}
session.commitConfiguration()
}
return session.inputs.first as? AVCaptureDeviceInput
}
// MARK: - Controlling Reader
/**
Starts scanning the codes.
*Notes: if `stopScanningWhenCodeIsFound` is sets to true (default behaviour), each time the scanner found a code it calls the `stopScanning` method.*
*/
public func startScanning() {
sessionQueue.async {[weak self] in
guard let self = self, !self.session.isRunning else { return }
self.session.startRunning()
DispatchQueue.main.async {
self.lifeCycleDelegate?.readerDidStartScanning()
}
}
}
/// Stops scanning the codes.
public func stopScanning() {
sessionQueue.async {[weak self] in
guard let self = self, self.session.isRunning else { return }
self.session.stopRunning()
DispatchQueue.main.async {
self.lifeCycleDelegate?.readerDidStopScanning()
}
}
}
/**
Indicates whether the session is currently running.
The value of this property is a Bool indicating whether the receiver is running.
Clients can key value observe the value of this property to be notified when
the session automatically starts or stops running.
*/
public var isRunning: Bool {
return session.isRunning
}
/**
Indicates whether a front device is available.
- returns: true whether the device has a front device.
*/
public var hasFrontDevice: Bool {
return frontDevice != nil
}
/**
Indicates whether the torch is available.
- returns: true if a torch is available.
*/
public var isTorchAvailable: Bool {
return defaultDevice?.isTorchAvailable ?? false
}
/**
Toggles torch on the default device.
*/
public func toggleTorch() {
do {
try defaultDevice?.lockForConfiguration()
defaultDevice?.torchMode = defaultDevice?.torchMode == .on ? .off : .on
defaultDevice?.unlockForConfiguration()
}
catch _ { }
}
// MARK: - Managing the Orientation
/**
Returns the video orientation corresponding to the given device orientation.
- parameter orientation: The orientation of the app's user interface.
- parameter supportedOrientations: The supported orientations of the application.
- parameter fallbackOrientation: The video orientation if the device orientation is FaceUp or FaceDown.
*/
public class func videoOrientation(deviceOrientation orientation: UIDeviceOrientation, withSupportedOrientations supportedOrientations: UIInterfaceOrientationMask, fallbackOrientation: AVCaptureVideoOrientation? = nil) -> AVCaptureVideoOrientation {
let result: AVCaptureVideoOrientation
switch (orientation, fallbackOrientation) {
case (.landscapeLeft, _):
result = .landscapeRight
case (.landscapeRight, _):
result = .landscapeLeft
case (.portrait, _):
result = .portrait
case (.portraitUpsideDown, _):
result = .portraitUpsideDown
case (_, .some(let orientation)):
result = orientation
default:
result = .portrait
}
if supportedOrientations.contains(orientationMask(videoOrientation: result)) {
return result
}
else if let orientation = fallbackOrientation , supportedOrientations.contains(orientationMask(videoOrientation: orientation)) {
return orientation
}
else if supportedOrientations.contains(.portrait) {
return .portrait
}
else if supportedOrientations.contains(.landscapeLeft) {
return .landscapeLeft
}
else if supportedOrientations.contains(.landscapeRight) {
return .landscapeRight
}
else {
return .portraitUpsideDown
}
}
class func orientationMask(videoOrientation orientation: AVCaptureVideoOrientation) -> UIInterfaceOrientationMask {
switch orientation {
case .landscapeLeft:
return .landscapeLeft
case .landscapeRight:
return .landscapeRight
case .portraitUpsideDown:
return .portraitUpsideDown
default:
return .portrait
}
}
// MARK: - Checking the Reader Availabilities
/**
Checks whether the reader is available.
- returns: A boolean value that indicates whether the reader is available.
*/
public class func isAvailable() -> Bool {
guard let captureDevice = AVCaptureDevice.default(for: .video) else { return false }
return (try? AVCaptureDeviceInput(device: captureDevice)) != nil
}
/**
Checks and return whether the given metadata object types are supported by the current device.
- parameter metadataTypes: An array of objects identifying the types of metadata objects to check.
- returns: A boolean value that indicates whether the device supports the given metadata object types.
*/
public class func supportsMetadataObjectTypes(_ metadataTypes: [AVMetadataObject.ObjectType]? = nil) throws -> Bool {
guard let captureDevice = AVCaptureDevice.default(for: .video) else {
throw NSError(domain: "com.yannickloriot.error", code: -1001, userInfo: nil)
}
let deviceInput = try AVCaptureDeviceInput(device: captureDevice)
let output = AVCaptureMetadataOutput()
let session = AVCaptureSession()
session.addInput(deviceInput)
session.addOutput(output)
var metadataObjectTypes = metadataTypes
if metadataObjectTypes == nil || metadataObjectTypes?.count == 0 {
// Check the QRCode metadata object type by default
metadataObjectTypes = [.qr]
}
for metadataObjectType in metadataObjectTypes! {
if !output.availableMetadataObjectTypes.contains { $0 == metadataObjectType } {
return false
}
}
return true
}
// MARK: - AVCaptureMetadataOutputObjects Delegate Methods
public func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
sessionQueue.async { [weak self] in
guard let weakSelf = self else { return }
for current in metadataObjects {
if let _readableCodeObject = current as? AVMetadataMachineReadableCodeObject {
if _readableCodeObject.stringValue != nil {
if weakSelf.metadataObjectTypes.contains(_readableCodeObject.type) {
guard weakSelf.session.isRunning, let sVal = _readableCodeObject.stringValue else { return }
if weakSelf.stopScanningWhenCodeIsFound {
weakSelf.session.stopRunning()
DispatchQueue.main.async {
weakSelf.lifeCycleDelegate?.readerDidStopScanning()
}
}
let scannedResult = QRCodeReaderResult(value: sVal, metadataType:_readableCodeObject.type.rawValue)
DispatchQueue.main.async {
weakSelf.didFindCode?(scannedResult)
}
}
}
}
else {
weakSelf.didFailDecoding?()
}
}
}
}
}
| 33.169492 | 251 | 0.713994 |
757b2dc7b389523c16be3002f6ba13220d85e973 | 2,529 | //
// MainBusinessLogic.swift
// CameraDemo
//
// Created by Alan Roldán Maillo on 26/04/2019.
// Copyright © 2019 Alan Roldán Maillo. All rights reserved.
//
import UIKit
enum LoadMainResponse {
case success
case failure
}
protocol MainBusinessLogicDelegate: AnyObject {
func connectionUpdate(status: ConnectionStatus)
}
class MainBusinessLogic {
let backgroundColor = UIColor.background
let beginButtonProperties = ButtonPropertiesImpl()
let connectButtonProperties = ConnectButtonPropertiesImpl()
let disconnectButtonProperties = disconnectButtonPropertiesImpl()
let titleProperties = TitlePropertiesImpl()
let welcomeProperties = WelcomePropertiesImpl()
weak var delegate: MainBusinessLogicDelegate?
var connectionStatus: ConnectionStatus {
return ConnectorManager.shared.status
}
struct ButtonPropertiesImpl: ButtonProperties {
var tintColor: UIColor?
var background: UIColor? = .detail
var titleColor: UIColor? = .content
var title: String? = NSLocalizedString("begin", comment: "Begin")
}
struct ConnectButtonPropertiesImpl: ButtonProperties {
var tintColor: UIColor?
var background: UIColor? = .disconnected
var titleColor: UIColor? = .content
var title: String? = NSLocalizedString("reconnect_button", comment: "Reconnect")
}
struct disconnectButtonPropertiesImpl: ButtonProperties {
var tintColor: UIColor? = .content
var background: UIColor?
var titleColor: UIColor?
var title: String?
}
struct TitlePropertiesImpl: LabelProperties {
var textColor: UIColor? = UIColor.content
var text: String? = NSLocalizedString("title_project", comment: "PartnetPlayRobot")
}
struct WelcomePropertiesImpl: LabelProperties {
var textColor: UIColor? = TitlePropertiesImpl().textColor
var text: String? = NSLocalizedString("welcome_to", comment: "Welcome to")
}
func setup() {
ConnectorManager.shared.delegate = self
}
func connect() {
ConnectorManager.shared.connect()
}
func disconnect() {
ConnectorManager.shared.disconnect()
}
}
extension MainBusinessLogic: ConnectorManagerDelegate {
func received(message: String) {
}
func sended(message: String) {
}
func statusConnectionHasBeenUpdated(_ status: ConnectionStatus) {
delegate?.connectionUpdate(status: status)
}
}
| 28.41573 | 91 | 0.687228 |
62b2f6ddd5b7432a1e99e97eec1163e48660d1a7 | 1,473 | //
// Color.swift
// iOSBaseProject
//
// Created by admin on 16/5/19.
// Copyright © 2016年 Ding. All rights reserved.
//
import UIKit
public typealias Color = UIColor
public extension Color {
/**
Creates a color from an hex integer (e.g. 0x3498db).
- parameter hex: A hexa-decimal UInt32 that represents a color.
- parameter alpha: alpha, default is 1
*/
public convenience init(hex: UInt32, alpha: CGFloat = 1) {
let mask = 0x000000FF
let red = CGFloat(Int(hex >> 16) & mask) / 255
let green = CGFloat(Int(hex >> 8) & mask) / 255
let blue = CGFloat(Int(hex) & mask) / 255
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
/**
Creates a color from an hex string (e.g. "3498db" or "#3498db").
If the given hex string is invalid the initialiser will create a black color.
- parameter hexString: A hexa-decimal color string representation.
- parameter alpha: alpha, default is 1
*/
public convenience init(hexString: String, alpha: CGFloat = 1) {
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
if scanner.scanHexInt32(&color) {
self.init(hex: color, alpha: alpha)
} else {
self.init(hex: 0x000000, alpha: alpha)
}
}
}
| 25.842105 | 82 | 0.579769 |
093467e5fb51e53975ec2d73f320d1c3f3817912 | 496 | //
// SceneTableViewCell.swift
// SwiftPad-test
//
// Created by Sansi Mac on 2018/6/20.
// Copyright © 2018年 Sansi Mac. All rights reserved.
//
import UIKit
class SceneTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 19.84 | 65 | 0.667339 |
5b96822872ab40399c2b541fc5fb8f84ed451bb0 | 8,119 | //
// TableViewChart.swift
// PNChartSwift
//
// Created by Giovanni Pozzobon on 11/08/17.
//
//
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class tableViewChartController: UITableViewController {
var nameCharts = [String]()
var vc_StoryBoardID = [String]()
var datiScambiati : ExchageData = ExchageData()
var chartTypes : Array<String> = [];
//Indicatori di caricamento dei dati
var graphLoaded : Bool = false;
var topOrderLoaded : Bool = false;
var topUserLoaded : Bool = false;
var userDefault: UserDefaultUtility = UserDefaultUtility()
override func viewDidLoad() {
super.viewDidLoad()
// riempi l'array che poi saranno le righe della tabella
nameCharts = ["Line Chart", "Bar Chart", "Pie Chart", "Top Order", "Top User", "Dett Order"]
// anche se non usate per ora prepariamo la gestione di più ViewControll chiamati una per una ogni riga della tabella
vc_StoryBoardID = ["Chart", "Chart", "Chart", "Information", "Information", "Information"]
// inizializza le variabili flag che indicano il caricamenteo dei dati
datiScambiati.graphLoaded = false
datiScambiati.topUserLoaded = false
datiScambiati.topOrderLoaded = false
// carica gli URL utente
userDefault.readValueUser()
// carica i dati per i grafici
caricaJSONOrdini()
// carica i dati per il TopOrders
caricaJSONTopOrders()
// carica i dati per i TopUsers
caricaJSONTopUsers()
/* codice per uso di test per verificare le risposte dei vari WebServices
Alamofire.request(querypoint, method: .post, parameters: parameters, encoding: JSONEncoding.default).response { response in
//Alamofire.request("http://188.125.99.46:61862/QueryPoint/term.getOrdersAmount?qry={"startDate": "20100501","endDate": "20180505"}").response { response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("Error: \(String(describing: response.error))")
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)")
}*/
}
// MARK: -
// MARK: caricamento JSON
func caricaJSONOrdini() -> Void {
//let querypointGraph : String = String("http://88.36.205.44:61862/QueryPoint/term.getOrdersAmount?qry=")
//let querypointGraph : String = String("http://192.168.0.230:61862/QueryPoint/term.getOrdersAmount?qry=")
let querypointGraph = userDefault.urlOrder
print(querypointGraph)
let parametersGraph: Parameters = [
"startDate": "20170712",
"endDate": "20170801"
]
Alamofire.request(querypointGraph, method: .post, parameters: parametersGraph, encoding: JSONEncoding.default).responseJSON
{ (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["results"].arrayObject {
self.datiScambiati.arrGraphRes = resData as! [[String:AnyObject]]
print("datiScambiati.arrGraphRes: \(self.datiScambiati.arrGraphRes) \n")
}
self.datiScambiati.graphLoaded = true
}
}
}
func caricaJSONTopOrders() -> Void {
//let querypointTopOrder : String = String("http://88.36.205.44:61862/QueryPoint/term.getTopOrder?qry=")
//let querypointTopOrder : String = String("http://192.168.0.230:61862/QueryPoint/term.getTopOrder?qry=")
let querypointTopOrder = userDefault.urlCustomer
print(querypointTopOrder)
let parametersTopOrder: Parameters = [
"Date": "20170504"
]
// carica i dati del top order
Alamofire.request(querypointTopOrder, method: .post, parameters: parametersTopOrder, encoding: JSONEncoding.default).responseJSON
{ (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["results"].arrayObject {
self.datiScambiati.arrTopOrderRes = resData as! [[String:AnyObject]]
print("datiScambiati.arrTopOrderRes: \(self.datiScambiati.arrTopOrderRes)")
}
self.datiScambiati.topOrderLoaded = true
}
}
}
func caricaJSONTopUsers() -> Void {
//let querypointTopUser : String = String("http://88.36.205.44:61862/QueryPoint/term.getTopUser?qry=")
//let querypointTopUser : String = String("http://192.168.0.230:61862/QueryPoint/term.getTopUser?qry=")
let querypointTopUser = userDefault.urlSales
print(querypointTopUser)
let parametersTopUser: Parameters = [
"startDate": "20100501",
"endDate": "20180505"
]
// carica i dati del top user
Alamofire.request(querypointTopUser, method: .post, parameters: parametersTopUser, encoding: JSONEncoding.default).responseJSON
{ (responseData) -> Void in
if((responseData.result.value) != nil) {
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["results"].arrayObject {
self.datiScambiati.arrTopUserRes = resData as! [[String:AnyObject]]
print("datiScambiati.arrTopUserRes: \(self.datiScambiati.arrTopUserRes) \n")
}
self.datiScambiati.topUserLoaded = true
}
}
}
// MARK: -
// MARK: Lifecycle Tabella
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameCharts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = nameCharts[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc_Name = vc_StoryBoardID[indexPath.row]
let viewController = (storyboard?.instantiateViewController(withIdentifier: vc_Name) as! TemplateViewController)
viewController.exchangeData = datiScambiati
viewController.chartType = nameCharts[indexPath.row]
self.navigationController?.pushViewController(viewController, animated: true)
}
/* Questa funzione non viene chiamata perchè viene usata quella della ViewTable
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var indexPath : IndexPath = self.tableView.indexPathForSelectedRow!
let destViewController = segue.destination as! ChartViewController
destViewController.exchangeData = datiScambiati
destViewController.chartType = nameCharts[indexPath.row]
} */
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 35.609649 | 165 | 0.587264 |
0a62d103c28cf121765d203b4b1eedfb70c88f31 | 117 | class TokenRepository {
func save(_ token: Token) throws -> Token? {
try token.save()
return token
}
}
| 14.625 | 46 | 0.623932 |
6941d6bbd68a3bd31a9acea72ca1819cbf6f9e3f | 377 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C<3] = c<d {
extension NSSet {
}
class l {
protocol A {
func h: Any, k : b, y: AnyObject) {
typealias f = ")] {
}
}
}
protocol c : b {
typealias b b {
enum
| 18.85 | 87 | 0.676393 |
fe9afe127d59d8b2befe4b5d10ef63e9ee83e054 | 1,925 | // UINavigationControllerExtention.swift
// Libraryapp
// Created by Muhammad Abdullah Al Mamun on 21/2/20.
// Copyright © 2020 Muhammad Abdullah Al Mamun. All rights reserved.
import Foundation
#if canImport(UIKit)
import UIKit
extension UINavigationController {
open func pushViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void) {
pushViewController(viewController, animated: animated)
executeTransitionCoordinator(animated: animated, completion: completion)
}
@discardableResult
open func popViewController(animated: Bool, completion: @escaping () -> Void) -> UIViewController? {
let viewController = popViewController(animated: animated)
executeTransitionCoordinator(animated: animated, completion: completion)
return viewController
}
@discardableResult
open func popToViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void) -> [UIViewController]? {
let viewControllers = popToViewController(viewController, animated: animated)
executeTransitionCoordinator(animated: animated, completion: completion)
return viewControllers
}
@discardableResult
open func popToRootViewController(animated: Bool, completion: @escaping () -> Void) -> [UIViewController]? {
let viewControllers = popToRootViewController(animated: animated)
executeTransitionCoordinator(animated: animated, completion: completion)
return viewControllers
}
private func executeTransitionCoordinator(animated: Bool, completion: @escaping () -> Void) {
guard animated, let coordinator = transitionCoordinator else {
DispatchQueue.main.async(execute: completion)
return
}
coordinator.animate(alongsideTransition: nil) { _ in completion() }
}
}
#endif // canImport(UIKit)
| 40.957447 | 144 | 0.727273 |
c1a3feb99001ec88572aa779cb0e8e89fbe183cc | 2,164 | //
// AppDelegate.swift
// API Demo
//
// Created by Royce on 24/12/2016.
// Copyright © 2016 Ryetech. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.042553 | 285 | 0.754621 |
dd5026d8c2fb3491a9a66d2224b288b5d655f08d | 267 | //
// Settings.swift
// qrcoderly
//
// Created by Wasin Thonkaew on 3/30/18.
// Copyright © 2018 Wasin Thonkaew. All rights reserved.
//
import Foundation
final class Settings {
public static let COOLDOWN_UNTIL_NEXT_SCAN: TimeInterval = 4 // in seconds
}
| 19.071429 | 79 | 0.707865 |
161a2609331d38ca3360244b4ad15675f552a5d2 | 4,809 | //
// GonawinAPITournamentsTests.swift
// GonawinEngine
//
// Created by Remy JOURDE on 11/03/2016.
// Copyright © 2016 Remy Jourde. All rights reserved.
//
import Quick
import Nimble
import RxSwift
import GonawinEngine
class GonawinAPITournamentsTests: QuickSpec {
let disposeBag = DisposeBag()
override func spec() {
describe("Tournaments endpoint") {
var engine: AuthorizedGonawinEngine!
beforeEach {
engine = GonawinEngine.newStubbingAuthorizedGonawinEngine()
}
it("returns a list of tournaments") {
var tournaments: [Tournament]?
engine.getTournaments(1, count: 3)
.catchError(self.log)
.subscribe(onNext: {
tournaments = $0
})
.addDisposableTo(self.disposeBag)
expect(tournaments).toNot(beNil())
expect(tournaments?.count).to(equal(3))
expect(tournaments?[2].name).to(equal("2014 FIFA World Cup"))
}
}
describe("Tournament endpoint") {
var engine: AuthorizedGonawinEngine!
beforeEach {
engine = GonawinEngine.newStubbingAuthorizedGonawinEngine()
}
it("returns a tournament") {
var tournament: Tournament?
engine.getTournament(390036)
.catchError(self.log)
.subscribe(onNext: {
tournament = $0
})
.addDisposableTo(self.disposeBag)
expect(tournament).toNot(beNil())
expect(tournament?.name).to(equal("2014 FIFA World Cup"))
expect(tournament?.participantsCount).to(equal(2))
expect(tournament?.participants?[1].username).to(equal("jsmith"))
expect(tournament?.teams?[1].name).to(equal("Test Team 2"))
expect(tournament?.start).to(equal("12 June 2014"))
}
}
describe("Tournament Calendar endpoint") {
var engine: AuthorizedGonawinEngine!
beforeEach {
engine = GonawinEngine.newStubbingAuthorizedGonawinEngine()
}
it("returns a tournament calendar") {
var tournamentCalendar: TournamentCalendar?
engine.getTournamentCalendar(390036)
.catchError(self.log)
.subscribe(onNext: {
tournamentCalendar = $0
})
.addDisposableTo(self.disposeBag)
expect(tournamentCalendar).toNot(beNil())
expect(tournamentCalendar?.days.count).to(equal(1))
expect(tournamentCalendar?.days[0].matches.count).to(equal(1))
}
}
describe("Tournament Match Predict endpoint") {
var engine: AuthorizedGonawinEngine!
beforeEach {
engine = GonawinEngine.newStubbingAuthorizedGonawinEngine()
}
it("returns a results of a predict") {
var predict: Predict?
engine.getTournamentMatchPredict(390036, matchId: 11310001, homeTeamScore: 1, awayTeamScore: 2)
.catchError(self.log)
.subscribe(onNext: {
predict = $0
})
.addDisposableTo(self.disposeBag)
expect(predict).toNot(beNil())
expect(predict?.homeTeamScore).to(equal(1))
expect(predict?.awayTeamScore).to(equal(2))
}
}
}
func log(error: Error) -> Observable<[Tournament]> {
print("error : \(error)")
return Observable.empty()
}
func log(error: Error) -> Observable<Tournament> {
print("error : \(error)")
return Observable.empty()
}
func log(error: Error) -> Observable<TournamentCalendar> {
print("error : \(error)")
return Observable.empty()
}
func log(error: Error) -> Observable<Predict> {
print("error : \(error)")
return Observable.empty()
}
}
| 31.431373 | 111 | 0.472032 |
225656a874ae732e5355e053c0f07742e870b391 | 2,168 | //
// IndexHandler.swift
// PerfectPress
//
// Created by Ryan Collins on 6/9/16.
// Copyright (C) 2016 Ryan M. Collins.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the PerfectPress open source blog project
//
//===----------------------------------------------------------------------===//
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
struct IndexHandler {
func loadPageContent() -> String {
var post = "No matching post was found"
let randomContent = ContentGenerator().generate()
if let firstPost = randomContent["Test Post 1"] {
post = firstPost
}
let imageNumber = Int(arc4random_uniform(25) + 1)
var finalContent = "<section id=\"content\"><div class=\"container\"><div class=\"row\"><div class=\"banner center-block\"><div><img src=\"/img/[email protected]\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-1.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-2.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-3.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-4.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-5.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div></div></div><div class=\"row\"><div class=\"col-xs-12\"><h1>"
finalContent += "Test Post 1"
finalContent += "</h1><img src=\""
finalContent += "/img/random/random-\(imageNumber).jpg\" alt=\"Random Image \(imageNumber)\" class=\"alignleft feature-image img-responsive\" />"
finalContent += "<div class=\"content\">"
finalContent += post
finalContent += "</div>"
finalContent += "</div></div</div></section>"
return finalContent
}
}
| 46.12766 | 917 | 0.571956 |
fe9d7563ac27a9cf50c28c94ff821bb345cab27e | 8,617 | /// Copyright (c) 2018 Razeware LLC
///
/// 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.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import UIKit
import CoreData
private extension UIColor {
static func color(dict: [String : Any]) -> UIColor? {
guard let red = dict["red"] as? NSNumber,
let green = dict["green"] as? NSNumber,
let blue = dict["blue"] as? NSNumber else {
return nil
}
return UIColor(red: CGFloat(truncating: red) / 255.0, green: CGFloat(truncating: green) / 255.0, blue: CGFloat(truncating: blue) / 255.0, alpha: 1)
}
}
class ViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var timesWornLabel: UILabel!
@IBOutlet weak var lastWornLabel: UILabel!
@IBOutlet weak var favoriteLabel: UILabel!
// MARK: - Properties
var managedContext: NSManagedObjectContext!
var currentBowtie: Bowtie!
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
insertSampleData()
/// Tạo request
let request: NSFetchRequest<Bowtie> = Bowtie.fetchRequest()
let firstTitle = segmentedControl.titleForSegment(at: 0)!
request.predicate = NSPredicate(format: "%K = %@", argumentArray: [#keyPath(Bowtie.searchKey), firstTitle])
do {
/// Dùng context để fetch data
let results = try managedContext.fetch(request)
/// Update UI
currentBowtie = results.first
populate(bowtie: results.first!)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
func insertSampleData() {
/// Fetch lên với điều kiện searchKey phải khác nil
let fetch: NSFetchRequest<Bowtie> = Bowtie.fetchRequest()
fetch.predicate = NSPredicate(format: "searchKey != nil")
let count = try! managedContext.count(for: fetch)
if count > 0 {
/// Nếu có trong DB thì thôi
return
}
/// Load Plist => Insert vào vào CoreData
let path = Bundle.main.path(forResource: "SampleData", ofType: "plist")
let dataArray = NSArray(contentsOfFile: path!)!
for dict in dataArray {
/// Tạo ManagedObject từ Description
/// Mỗi lần mày tạo là context nó giữ object đó lại rồi
let entity = NSEntityDescription.entity(forEntityName: "Bowtie", in: managedContext)!
let bowtie = Bowtie(entity: entity, insertInto: managedContext)
/// Add infor
let btDict = dict as! [String: Any]
bowtie.id = UUID(uuidString: btDict["id"] as! String)
bowtie.name = btDict["name"] as? String
bowtie.searchKey = btDict["searchKey"] as? String
bowtie.rating = btDict["rating"] as! Double
let colorDict = btDict["tintColor"] as! [String: Any]
bowtie.tintColor = UIColor.color(dict: colorDict) /// Lưu trực tiếp UIColor
let imageName = btDict["imageName"] as? String
let image = UIImage(named: imageName!)
let photoData = UIImagePNGRepresentation(image!)!
bowtie.photoData = photoData /// lưu Data for photo
bowtie.lastWorn = btDict["lastWorn"] as? Date
let timesNumber = btDict["timesWorn"] as! NSNumber
bowtie.timesWorn = timesNumber.int32Value
bowtie.isFavorite = btDict["isFavorite"] as! Bool
bowtie.url = URL(string: btDict["url"] as! String)
}
/// Save những object hiện tại trên context
try! managedContext.save()
}
func populate(bowtie: Bowtie) {
guard let imageData = bowtie.photoData as Data?,
let lastWorn = bowtie.lastWorn as Date?,
let tintColor = bowtie.tintColor as? UIColor else {
return
}
/// Update UI with Bowtie object
imageView.image = UIImage(data: imageData)
nameLabel.text = bowtie.name
ratingLabel.text = "Rating: \(bowtie.rating)/5"
timesWornLabel.text = "# times worn: \(bowtie.timesWorn)"
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
lastWornLabel.text = "Last worn: " + dateFormatter.string(from: lastWorn)
favoriteLabel.isHidden = !bowtie.isFavorite
view.tintColor = tintColor
}
// MARK: - IBActions
@IBAction func segmentedControl(_ sender: Any) {
guard let control = sender as? UISegmentedControl,
let selectedValue = control.titleForSegment(at: control.selectedSegmentIndex) else {
return
}
/// Tạo Request với searchKey = <selectedValue>
let request: NSFetchRequest<Bowtie> = Bowtie.fetchRequest()
request.predicate = NSPredicate(format: "%K = %@",argumentArray: [#keyPath(Bowtie.searchKey), selectedValue])
do {
/// Fetch => Update UI
let results = try managedContext.fetch(request)
currentBowtie = results.first
populate(bowtie: currentBowtie)
}
catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func wear(_ sender: Any) {
/// Update data of currentBowtie
/// Mày chỉ cần update NSManagedObject thôi, context chắc có observer all NSManagedObject
/// Gọi save là nó save all changes, mày không cần chỉ rõ là save cái gì
/// Chắc là binding gì đó kinh lắm
let times = currentBowtie.timesWorn
currentBowtie.timesWorn = times + 1
currentBowtie.lastWorn = Date()
do {
/// Update CoreData
try managedContext.save()
/// UpdateUI
populate(bowtie: currentBowtie)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
@IBAction func rate(_ sender: Any) {
/// Tạo UIAlertController + textfiled
let alert = UIAlertController(title: "New Rating", message: "Rate this bow tie", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.keyboardType = .decimalPad
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
if let textField = alert.textFields?.first {
self.update(rating: textField.text)
}
}
alert.addAction(cancelAction)
alert.addAction(saveAction)
present(alert, animated: true)
}
/// Update rating cho currentBowtie
func update(rating: String?) {
guard let ratingString = rating,
let rating = Double(ratingString) else {
return
}
do {
currentBowtie.rating = rating
try managedContext.save()
populate(bowtie: currentBowtie)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain &&
(error.code == NSValidationNumberTooLargeError ||
error.code == NSValidationNumberTooSmallError) {
/// Mở lại rating
rate(currentBowtie)
} else {
print("Could not save \(error), \(error.userInfo)")
}
}
}
}
| 36.35865 | 151 | 0.670999 |
01f61ce31c0ef35782e7c38d79e7b07c0a5125cb | 464 | //
// NSStringExtension.swift
// RedBook
//
// Created by peng zhao on 2019/4/24.
// Copyright © 2019 mars. All rights reserved.
//
import UIKit
func StringSize(string:String,fontSize:CGFloat,maxSize:CGSize) -> CGSize {
let font = UIFont.systemFont(ofSize: fontSize)
let rect = NSString(string: string).boundingRect(with: maxSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [.font:font], context: nil)
return rect.size
}
| 29 | 163 | 0.732759 |
ebc902dfeba678775ea7ea57813f09854d0ea9d2 | 263 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b: d {
protocol c : Range<h> {
typealias h
| 26.3 | 87 | 0.73384 |
9187af3e07e7d3db2c02507f8d2a69bb2c745284 | 460 | //
// Constants.swift
// Wiki App
//
// Created by Mayank Gupta on 04/11/17.
// Copyright © 2017 Mayank Gupta. All rights reserved.
//
import Foundation
//MARK: - URLs
let ARTICLE_URL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&pithumbsize=120&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max"
//MARK: - Numeric
let RECENT_SAVE_LIMIT = 20
let MINIMUM_CHARACTER_FOR_SUGGESTION = 3
| 25.555556 | 197 | 0.752174 |
acbead57a53839d59ea5b7abbb8a3e6a625e6649 | 1,339 | //
// IQKeyboardManagerConstantsInternal.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-14 Iftekhar Qurashi.
//
// 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
let IQ_IS_IOS8_OR_GREATER = (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1)
| 47.821429 | 98 | 0.778193 |
6400bb0f476ca0d8da4171f24088600c3914220b | 21,384 | //Stub file made with Khrysalis 2 (by Lightning Kite)
import Foundation
import Alamofire
import AlamofireImage
import Photos
import AVKit
import MapKit
import EventKitUI
import DKImagePickerController
import MobileCoreServices
//--- ViewControllerAccess
public extension ViewControllerAccess {
//--- ViewControllerAccess image helpers
private static let imageDelegateExtension = ExtensionProperty<ViewControllerAccess, ImageDelegate>()
private static let documentDelegateExtension = ExtensionProperty<ViewControllerAccess, DocumentDelgate>()
private var imageDelegate: ImageDelegate {
if let existing = ViewControllerAccess.imageDelegateExtension.get(self) {
return existing
}
let new = ImageDelegate()
ViewControllerAccess.imageDelegateExtension.set(self, new)
return new
}
private var documentDelegate: DocumentDelgate {
if let existing = ViewControllerAccess.documentDelegateExtension.get(self) {
return existing
}
let new = DocumentDelgate()
ViewControllerAccess.documentDelegateExtension.set(self, new)
return new
}
private func withLibraryPermission(action: @escaping ()->Void) {
if PHPhotoLibrary.authorizationStatus() == .authorized {
action()
} else {
PHPhotoLibrary.requestAuthorization {_ in
DispatchQueue.main.async {
action()
}
}
}
}
//--- ViewControllerAccess.requestImageGallery((URL)->Unit)
func requestImageGallery(callback: @escaping (URL) -> Void) {
withLibraryPermission {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
let imageDelegate = self.imageDelegate
imageDelegate.forImages()
imageDelegate.onImagePicked = callback
imageDelegate.prepareGallery()
self.parentViewController.present(imageDelegate.imagePicker, animated: true, completion: nil)
}
}
}
//--- ViewControllerAccess.requestVideoGallery((URL)->Unit)
func requestVideoGallery(callback: @escaping (URL) -> Void) -> Void {
withLibraryPermission {if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
let imageDelegate = self.imageDelegate
imageDelegate.forVideo()
imageDelegate.onImagePicked = callback
imageDelegate.prepareGallery()
self.parentViewController.present(imageDelegate.imagePicker, animated: true, completion: nil)
}
}
}
//--- ViewControllerAccess.requestVideosGallery((List<URL>)->Unit)
func requestVideosGallery(callback: @escaping (Array<URL>) -> Void) -> Void {
if PHPhotoLibrary.authorizationStatus() == .authorized {
self.requestImagesGalleryRaw(type: .allVideos, callback: callback)
} else {
PHPhotoLibrary.requestAuthorization {_ in
DispatchQueue.main.async {
self.requestImagesGalleryRaw(type: .allVideos, callback: callback)
}
}
}
}
//--- ViewControllerAccess.requestVideoCamera(Boolean, (URL)->Unit)
func requestVideoCamera(front: Bool = false, callback: @escaping (URL) -> Void) -> Void {
withCameraPermission {
DispatchQueue.main.async {
if UIImagePickerController.isSourceTypeAvailable(.camera){
if(UIImagePickerController.availableMediaTypes(for: .camera)?.contains("public.movie") == true) {
let imageDelegate = self.imageDelegate
imageDelegate.onImagePicked = callback
imageDelegate.forVideo()
imageDelegate.prepareCamera(front: front)
self.parentViewController.present(imageDelegate.imagePicker, animated: true, completion: nil)
}
}
}
}
}
//--- ViewControllerAccess.requestMediasGallery((List<URL>)->Unit)
func requestMediasGallery(callback: @escaping (Array<URL>) -> Void) -> Void {
if PHPhotoLibrary.authorizationStatus() == .authorized {
self.requestImagesGalleryRaw(type: .allAssets, callback: callback)
} else {
PHPhotoLibrary.requestAuthorization {_ in
DispatchQueue.main.async {
self.requestImagesGalleryRaw(type: .allAssets, callback: callback)
}
}
}
}
//--- ViewControllerAccess.requestMediaGallery((URL)->Unit)
func requestMediaGallery(callback: @escaping (URL) -> Void) -> Void {
withLibraryPermission {
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
let imageDelegate = self.imageDelegate
imageDelegate.forAll()
imageDelegate.onImagePicked = callback
imageDelegate.prepareGallery()
self.parentViewController.present(imageDelegate.imagePicker, animated: true, completion: nil)
}
}
}
//--- ViewControllerAccess.requestImagesGallery((List<URL>)->Unit)
func requestImagesGallery(callback: @escaping (Array<URL>) -> Void) -> Void {
if PHPhotoLibrary.authorizationStatus() == .authorized {
self.requestImagesGalleryRaw(type: .allPhotos, callback: callback)
} else {
PHPhotoLibrary.requestAuthorization {_ in
DispatchQueue.main.async {
self.requestImagesGalleryRaw(type: .allPhotos, callback: callback)
}
}
}
}
private func requestImagesGalleryRaw(type: DKImagePickerControllerAssetType, callback: @escaping (Array<URL>) -> Void) {
let pickerController = DKImagePickerController()
pickerController.assetType = type
pickerController.didSelectAssets = { (assets: [DKAsset]) in
DKImageAssetExporter.sharedInstance.exportAssetsAsynchronously(assets: assets, completion: { info in
callback(assets.map { $0.localTemporaryPath! })
})
}
self.parentViewController.present(pickerController, animated: true){}
}
//--- ViewControllerAccess.requestImageCamera((URL)->Unit)
func requestImageCamera(front:Bool = false, callback: @escaping (URL) -> Void) {
withCameraPermission {
DispatchQueue.main.async {
if UIImagePickerController.isSourceTypeAvailable(.camera){
if(UIImagePickerController.availableMediaTypes(for: .camera)?.contains("public.image") == true) {
let imageDelegate = self.imageDelegate
imageDelegate.onImagePicked = callback
imageDelegate.forImages()
imageDelegate.prepareCamera(front: front)
self.parentViewController.present(imageDelegate.imagePicker, animated: true, completion: nil)
}
}
}
}
}
func getMimeType(uri:URL) -> String? {
let pathExtension = uri.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return nil
}
func requestDocuments(callback: @escaping (Array<URL>) -> Void){
let docDelegate = self.documentDelegate
docDelegate.onDocumentsPicked = callback
docDelegate.prepareMenu()
self.parentViewController.present(docDelegate.documentPicker, animated: true, completion: nil)
}
func requestDocument(callback: @escaping (URL) -> Void){
let docDelegate = self.documentDelegate
docDelegate.onDocumentPicked = callback
docDelegate.prepareMenu()
self.parentViewController.present(docDelegate.documentPicker, animated: true, completion: nil)
}
func requestFiles(callback: @escaping (Array<URL>) -> Void){
let optionMenu = UIAlertController(
title: nil,
message: "What kind of file?",
preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet
)
let image = UIAlertAction(title: "Images", style: .default, handler: { _ in
self.requestImagesGallery(callback: callback)
})
let video = UIAlertAction(title: "Videos", style: .default, handler: { _ in
self.requestVideosGallery(callback: callback)
})
let doc = UIAlertAction(title: "Documents", style: .default, handler: { _ in
self.requestDocuments(callback: callback)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
optionMenu.addAction(image)
optionMenu.addAction(video)
optionMenu.addAction(doc)
optionMenu.addAction(cancelAction)
if let b = self.parentViewController as? ButterflyViewController {
optionMenu.popoverPresentationController?.sourceRect = CGRect(x: b.lastTapPosition.x, y: b.lastTapPosition.y, width: 1, height: 1)
} else {
optionMenu.popoverPresentationController?.sourceRect = CGRect(x: self.parentViewController.view.frame.centerX(), y: self.parentViewController.view.frame.centerY(), width: 1, height: 1)
}
self.parentViewController.present(optionMenu, animated: true, completion: nil)
}
func requestFile(callback: @escaping (URL) -> Void){
let optionMenu = UIAlertController(
title: nil,
message: "What kind of file?",
preferredStyle: UIDevice.current.userInterfaceIdiom == .pad ? .alert : .actionSheet
)
let image = UIAlertAction(title: "Image", style: .default, handler: { _ in
self.requestImageGallery(callback: callback)
})
let video = UIAlertAction(title: "Video", style: .default, handler: { _ in
self.requestVideoGallery(callback: callback)
})
let doc = UIAlertAction(title: "Document", style: .default, handler: { _ in
self.requestDocument(callback: callback)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
optionMenu.addAction(image)
optionMenu.addAction(video)
optionMenu.addAction(doc)
optionMenu.addAction(cancelAction)
if let b = self.parentViewController as? ButterflyViewController {
optionMenu.popoverPresentationController?.sourceRect = CGRect(x: b.lastTapPosition.x, y: b.lastTapPosition.y, width: 1, height: 1)
} else {
optionMenu.popoverPresentationController?.sourceRect = CGRect(x: self.parentViewController.view.frame.centerX(), y: self.parentViewController.view.frame.centerY(), width: 1, height: 1)
}
self.parentViewController.present(optionMenu, animated: true, completion: nil)
}
func getFileName(uri:URL) -> String? {
return UUID().uuidString + uri.lastPathComponent
}
func getFileName(name: String, type: HttpMediaType) -> String? {
return UUID().uuidString + name
}
func downloadFile(url:String){
let url = URL(string: url)!
let documentsUrl:URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destinationFileUrl = documentsUrl?.appendingPathComponent(getFileName(uri: url)!)
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
if let localTemp = localURL, let destination = destinationFileUrl{
do {
try FileManager.default.copyItem(at: localTemp, to: destination)
DispatchQueue.main.sync {
let ac = UIActivityViewController(activityItems: [destination], applicationActivities: nil)
ac.popoverPresentationController?.sourceView = self.parentViewController.view
if let b = self.parentViewController as? ButterflyViewController {
ac.popoverPresentationController?.sourceRect = CGRect(x: b.lastTapPosition.x, y: b.lastTapPosition.y, width: 1, height: 1)
} else {
ac.popoverPresentationController?.sourceRect = CGRect(x: self.parentViewController.view.frame.centerX(), y: self.parentViewController.view.frame.centerY(), width: 1, height: 1)
}
self.parentViewController.present(ac, animated: true)
}
} catch (let writeError) {
print("Error creating a file \(destination) : \(writeError)")
}
}
}
task.resume()
}
func downloadFileData(data: Data, name: String, type: HttpMediaType){
let documentsUrl:URL? = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let destinationFileUrl = documentsUrl?.appendingPathComponent(getFileName(name: name, type: type)!)
if let destination = destinationFileUrl{
do {
try data.write(to: destination)
let ac = UIActivityViewController(activityItems: [destination], applicationActivities: nil)
ac.popoverPresentationController?.sourceView = self.parentViewController.view
if let b = self.parentViewController as? ButterflyViewController {
ac.popoverPresentationController?.sourceRect = CGRect(x: b.lastTapPosition.x, y: b.lastTapPosition.y, width: 1, height: 1)
} else {
ac.popoverPresentationController?.sourceRect = CGRect(x: self.parentViewController.view.frame.centerX(), y: self.parentViewController.view.frame.centerY(), width: 1, height: 1)
}
self.parentViewController.present(ac, animated: true)
} catch (let writeError) {
print("Error creating a file \(destination) : \(writeError)")
}
}
}
private func withCameraPermission(action: @escaping ()->Void) {
DispatchQueue.main.async {
if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
AVCaptureDevice.requestAccess(for: .video) { granted in
DispatchQueue.main.async {
if granted {
if PHPhotoLibrary.authorizationStatus() == .authorized {
action()
} else {
PHPhotoLibrary.requestAuthorization {_ in
action()
}
}
}
}
}
} else {
AVCaptureDevice.requestAccess(for: .video) { granted in
DispatchQueue.main.async {
if granted {
if PHPhotoLibrary.authorizationStatus() == .authorized {
action()
} else {
PHPhotoLibrary.requestAuthorization {_ in
action()
}
}
}
}
}
}
}
}
}
private class DocumentDelgate : NSObject, UIDocumentPickerDelegate, UINavigationControllerDelegate {
var documentPicker = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .import)
var onDocumentsPicked: ((Array<URL>) -> Void)? = nil
var onDocumentPicked: ((URL) -> Void)? = nil
func prepareMenu(){
documentPicker.delegate = self
}
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
self.onDocumentsPicked?(urls)
if let first = urls.first{
self.onDocumentPicked?(first)
}
}
public func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
//--- Image helpers
private class ImageDelegate : NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker = UIImagePickerController()
var onImagePicked: ((URL)->Void)? = nil
func forVideo(){
imagePicker.mediaTypes = ["public.movie"]
}
func forImages(){
imagePicker.mediaTypes = ["public.image"]
}
func forAll(){
imagePicker.mediaTypes = ["public.image", "public.movie"]
}
func prepareGallery(){
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
}
func prepareCamera(front:Bool){
imagePicker.delegate = self
imagePicker.sourceType = .camera
if imagePicker.mediaTypes.contains("public.image") {
imagePicker.cameraCaptureMode = .photo
} else {
imagePicker.cameraCaptureMode = .video
}
if front{
imagePicker.cameraDevice = .front
}else{
imagePicker.cameraDevice = .rear
}
imagePicker.allowsEditing = false
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if #available(iOS 11.0, *) {
if let image = info[.imageURL] as? URL ?? info[.mediaURL] as? URL {
print("Image retrieved directly using .imageURL")
DispatchQueue.main.async {
picker.dismiss(animated: true, completion: {
self.onImagePicked?(image)
self.onImagePicked = nil
})
}
return
}
}
if let originalImage = info[.editedImage] as? UIImage, let url = originalImage.saveTemp() {
print("Image retrieved using save as backup")
picker.dismiss(animated: true, completion: {
self.onImagePicked?(url)
self.onImagePicked = nil
})
} else if let originalImage = info[.originalImage] as? UIImage, let url = originalImage.saveTemp() {
print("Image retrieved using save as backup")
picker.dismiss(animated: true, completion: {
self.onImagePicked?(url)
self.onImagePicked = nil
})
} else {
picker.dismiss(animated: true, completion: {
self.onImagePicked = nil
})
}
}
}
// save
extension UIImage {
func saveTemp() -> URL? {
let id = UUID().uuidString
let tempDirectoryUrl = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("temp-butterfly-photos-\(id)")
guard let url2 = self.save(at: tempDirectoryUrl) else {
return nil
}
print(url2)
return url2
}
func save(at directory: FileManager.SearchPathDirectory,
pathAndImageName: String,
createSubdirectoriesIfNeed: Bool = true,
compressionQuality: CGFloat = 1.0) -> URL? {
do {
let documentsDirectory = try FileManager.default.url(for: directory, in: .userDomainMask,
appropriateFor: nil,
create: false)
return save(at: documentsDirectory.appendingPathComponent(pathAndImageName),
createSubdirectoriesIfNeed: createSubdirectoriesIfNeed,
compressionQuality: compressionQuality)
} catch {
print("-- Error: \(error)")
return nil
}
}
func save(at url: URL,
createSubdirectoriesIfNeed: Bool = true,
compressionQuality: CGFloat = 1.0) -> URL? {
do {
if createSubdirectoriesIfNeed {
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil)
}
guard let data = jpegData(compressionQuality: compressionQuality) else { return nil }
try data.write(to: url)
return url
} catch {
print("-- Error: \(error)")
return nil
}
}
}
// load from path
extension UIImage {
convenience init?(fileURLWithPath url: URL, scale: CGFloat = 1.0) {
do {
let data = try Data(contentsOf: url)
self.init(data: data, scale: scale)
} catch {
print("-- Error: \(error)")
return nil
}
}
}
| 41.847358 | 204 | 0.594837 |
871bb7ebed54828b1ae7b6b77cd566a3893c48e8 | 2,239 | //
// profileCell.swift
// Twitter
//
// Created by Shakeel Daswani on 3/8/16.
// Copyright © 2016 Shakeel Daswani. All rights reserved.
//
import UIKit
import AFNetworking
class profileCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var retweetcountLabel: UILabel!
@IBOutlet weak var favoritecountLabel: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
var tweet: Tweet! {
didSet {
profileImageView.setImageWithURL((tweet!.user!.profileUrl)!)
tweetLabel.text = tweet.text as? String
self.nameLabel.text = tweet.user?.name
self.usernameLabel.text = "@\(tweet.user!.screenname!)"
retweetcountLabel.text = "\(tweet.retweetCount)"
timestampLabel.text = "\(tweet!.timeStamp!)"
favoritecountLabel.text = "\(tweet.favoritesCount)"
if(tweet.liked == true) {
self.favoriteButton.setImage(UIImage(named: "like-action-on-pressed"), forState: UIControlState.Normal)
} else {
self.favoriteButton.setImage(UIImage(named: "like-action"), forState: UIControlState.Normal)
}
if(tweet.retweeted == true) {
self.retweetButton.setImage(UIImage(named: "retweet-action-on-pressed"), forState: UIControlState.Normal)
}
else {
self.retweetButton.setImage(UIImage(named: "retweet-action"), forState: UIControlState.Normal)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
profileImageView.layer.cornerRadius = 3
profileImageView.clipsToBounds = true
nameLabel.preferredMaxLayoutWidth = nameLabel.frame.width
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 33.924242 | 121 | 0.640464 |
76aae525a09bbf96371bf634b791c5c1d7f67b2e | 1,253 | //
// Alarm.swift
// SwiftUIAlarm
//
// Created by Tae joong Yoon on 2019/06/14.
// Copyright © 2019 Tae joong Yoon. All rights reserved.
//
import SwiftUI
struct Alarm: Hashable, Codable, Identifiable {
let id: UUID
var date: Date
var label: String
var repeatDay: [Int]
var isActive: Bool
var isSnooze: Bool
// Repeat Day String
var repeats: String {
guard repeatDay.count > 0 else { return "" }
return repeatDay.repeats
}
init(date: Date, label: String, repeatDay: [RepeatDay], isActive: Bool, isSnooze: Bool) {
self.id = UUID()
self.date = date
self.label = label
self.repeatDay = repeatDay.map { $0.rawValue }
self.isActive = isActive
self.isSnooze = isSnooze
}
// Default Alarms
static var defaultAlarm: [Alarm] {
get {
[
Alarm(date: Date().addingTimeInterval(-1000), label: "Alarm", repeatDay: [.sunday], isActive: true, isSnooze: true),
Alarm(date: Date(), label: "Alarm", repeatDay: [.sunday, .monday], isActive: true, isSnooze: false),
Alarm(date: Date().addingTimeInterval(+1000), label: "Alarm", repeatDay: [.sunday, .monday, .tuesday, .wednesday, .thursday, .friday, .saturday], isActive: false, isSnooze: false)
]
}
}
}
| 27.23913 | 187 | 0.644852 |
67a025861c7b7de3c6014d779f027f5938adab4c | 15,792 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -emit-ir -o - -primary-file %s | FileCheck %s
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// CHECK: [[B:%CSo1B]] = type
import ObjectiveC
import Foundation
import objc_ext
import TestProtocols
import ObjCIRExtras
// CHECK: @"\01L_selector_data(method:withFloat:)" = private global [18 x i8] c"method:withFloat:\00"
// CHECK: @"\01L_selector_data(method:withDouble:)" = private global [19 x i8] c"method:withDouble:\00"
// CHECK: @"\01L_selector_data(method:separateExtMethod:)" = private global [26 x i8] c"method:separateExtMethod:\00", section "__TEXT,__objc_methname,cstring_literals"
// Instance method invocation
// CHECK: define hidden void @_TF7objc_ir15instanceMethodsFCSo1BT_([[B]]*
func instanceMethods(_ b: B) {
// CHECK: load i8*, i8** @"\01L_selector(method:withFloat:)"
// CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
var i = b.method(1, with: 2.5 as Float)
// CHECK: load i8*, i8** @"\01L_selector(method:withDouble:)"
// CHECK: call i32 bitcast (void ()* @objc_msgSend to i32
i = i + b.method(1, with: 2.5 as Double)
}
// CHECK: define hidden void @_TF7objc_ir16extensionMethodsFT1bCSo1B_T_
func extensionMethods(b b: B) {
// CHECK: load i8*, i8** @"\01L_selector(method:separateExtMethod:)", align 8
// CHECK: [[T0:%.*]] = call i8* bitcast (void ()* @objc_msgSend to i8*
// CHECK-NEXT: [[T1:%.*]] = call i8* @objc_retainAutoreleasedReturnValue(i8* [[T0]])
// CHECK-NOT: [[T0]]
// CHECK: [[T1]]
b.method(1, separateExtMethod:1.5)
}
// CHECK: define hidden void @_TF7objc_ir19initCallToAllocInitFT1iVs5Int32_T_
func initCallToAllocInit(i i: CInt) {
// CHECK: call {{.*}} @_TFCSo1BCfT3intVs5Int32_GSQS__
B(int: i)
}
// CHECK: linkonce_odr hidden {{.*}} @_TFCSo1BCfT3intVs5Int32_GSQS__
// CHECK: load i8*, i8** @"\01L_selector(allocWithZone:)"
// CHECK: call [[OPAQUE:%.*]]* bitcast (void ()* @objc_msgSend
// Indexed subscripting
// CHECK: define hidden void @_TF7objc_ir19indexedSubscriptingFT1bCSo1B3idxSi1aCSo1A_T_
func indexedSubscripting(b b: B, idx: Int, a: A) {
// CHECK: load i8*, i8** @"\01L_selector(setObject:atIndexedSubscript:)", align 8
b[idx] = a
// CHECK: load i8*, i8** @"\01L_selector(objectAtIndexedSubscript:)"
var a2 = b[idx] as! A
}
// CHECK: define hidden void @_TF7objc_ir17keyedSubscriptingFT1bCSo1B3idxCSo1A1aS1__T_
func keyedSubscripting(b b: B, idx: A, a: A) {
// CHECK: load i8*, i8** @"\01L_selector(setObject:forKeyedSubscript:)"
b[a] = a
// CHECK: load i8*, i8** @"\01L_selector(objectForKeyedSubscript:)"
var a2 = b[a] as! A
}
// CHECK: define hidden void @_TF7objc_ir14propertyAccessFT1bCSo1B_T_
func propertyAccess(b b: B) {
// CHECK: load i8*, i8** @"\01L_selector(counter)"
// CHECK: load i8*, i8** @"\01L_selector(setCounter:)"
b.counter = b.counter + 1
// CHECK: call %swift.type* @_TMaCSo1B()
// CHECK: bitcast %swift.type* {{%.+}} to %objc_class*
// CHECK: load i8*, i8** @"\01L_selector(sharedCounter)"
// CHECK: load i8*, i8** @"\01L_selector(setSharedCounter:)"
B.sharedCounter = B.sharedCounter + 1
}
// CHECK: define hidden [[B]]* @_TF7objc_ir8downcastFT1aCSo1A_CSo1B(
func downcast(a a: A) -> B {
// CHECK: [[CLASS:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_B"
// CHECK: [[T0:%.*]] = call %objc_class* @rt_swift_getInitializedObjCClass(%objc_class* [[CLASS]])
// CHECK: [[T1:%.*]] = bitcast %objc_class* [[T0]] to i8*
// CHECK: call i8* @swift_dynamicCastObjCClassUnconditional(i8* [[A:%.*]], i8* [[T1]]) [[NOUNWIND:#[0-9]+]]
return a as! B
}
// CHECK: define hidden void @_TF7objc_ir19almostSubscriptableFT3as1CSo19AlmostSubscriptable1aCSo1A_T_
func almostSubscriptable(as1 as1: AlmostSubscriptable, a: A) {
as1.objectForKeyedSubscript(a)
}
// CHECK: define hidden void @_TF7objc_ir13protocolTypesFT1aCSo7NSMince1bPSo9NSRuncing__T_(%CSo7NSMince*, %objc_object*) {{.*}} {
func protocolTypes(a a: NSMince, b: NSRuncing) {
// - (void)eatWith:(id <NSRuncing>)runcer;
a.eat(with: b)
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(eatWith:)", align 8
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OPAQUE:%.*]]*, i8*, i8*)*)([[OPAQUE:%.*]]* {{%.*}}, i8* [[SEL]], i8* {{%.*}})
}
// CHECK-LABEL: define hidden void @_TF7objc_ir6getsetFT1pPSo8FooProto__T_(%objc_object*) {{.*}} {
func getset(p p: FooProto) {
// CHECK: load i8*, i8** @"\01L_selector(bar)"
// CHECK: load i8*, i8** @"\01L_selector(setBar:)"
let prop = p.bar
p.bar = prop
}
// CHECK-LABEL: define hidden %swift.type* @_TF7objc_ir16protocolMetatypeFT1pPSo8FooProto__PMPS0__(%objc_object*) {{.*}} {
func protocolMetatype(p: FooProto) -> FooProto.Type {
// CHECK: = call %swift.type* @swift_getObjectType(%objc_object* %0)
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processFooType(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK: call void @swift_unknownRelease(%objc_object* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processFooType(p.dynamicType)
return type
} // CHECK: }
class Impl: FooProto, AnotherProto {
@objc var bar: Int32 = 0
}
// CHECK-LABEL: define hidden %swift.type* @_TF7objc_ir27protocolCompositionMetatypeFT1pCS_4Impl_PMPSo12AnotherProtoSo8FooProto_(%C7objc_ir4Impl*) {{.*}} {
func protocolCompositionMetatype(p: Impl) -> (FooProto & AnotherProto).Type {
// CHECK: = getelementptr inbounds %C7objc_ir4Impl, %C7objc_ir4Impl* %0, i32 0, i32 0, i32 0
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK: call void bitcast (void (%swift.refcounted*)* @rt_swift_release to void (%C7objc_ir4Impl*)*)(%C7objc_ir4Impl* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processComboType(p.dynamicType)
return type
} // CHECK: }
// CHECK-LABEL: define hidden %swift.type* @_TF7objc_ir28protocolCompositionMetatype2FT1pCS_4Impl_PMPSo12AnotherProtoSo8FooProto_(%C7objc_ir4Impl*) {{.*}} {
func protocolCompositionMetatype2(p: Impl) -> (FooProto & AnotherProto).Type {
// CHECK: = getelementptr inbounds %C7objc_ir4Impl, %C7objc_ir4Impl* %0, i32 0, i32 0, i32 0
// CHECK-NOT: {{retain|release}}
// CHECK: [[RAW_RESULT:%.+]] = call i8* @processComboType2(i8* {{%.+}})
// CHECK: [[CASTED_RESULT:%.+]] = bitcast i8* [[RAW_RESULT]] to %objc_class*
// CHECK: [[SWIFT_RESULT:%.+]] = call %swift.type* @swift_getObjCClassMetadata(%objc_class* [[CASTED_RESULT]])
// CHECK: call void bitcast (void (%swift.refcounted*)* @rt_swift_release to void (%C7objc_ir4Impl*)*)(%C7objc_ir4Impl* %0)
// CHECK: ret %swift.type* [[SWIFT_RESULT]]
let type = processComboType2(p.dynamicType)
return type
} // CHECK: }
// CHECK-LABEL: define hidden void @_TF7objc_ir17pointerPropertiesFCSo14PointerWrapperT_(%CSo14PointerWrapper*) {{.*}} {
func pointerProperties(_ obj: PointerWrapper) {
// CHECK: load i8*, i8** @"\01L_selector(setVoidPtr:)"
// CHECK: load i8*, i8** @"\01L_selector(setIntPtr:)"
// CHECK: load i8*, i8** @"\01L_selector(setIdPtr:)"
obj.voidPtr = nil as UnsafeMutablePointer?
obj.intPtr = nil as UnsafeMutablePointer?
obj.idPtr = nil as AutoreleasingUnsafeMutablePointer?
}
// CHECK-LABEL: define hidden void @_TF7objc_ir20customFactoryMethodsFT_T_() {{.*}} {
func customFactoryMethods() {
// CHECK: call %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT10dummyParamT__S_
// CHECK: call %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT2ccGSqPs9AnyObject___S_
_ = SwiftNameTest(dummyParam: ())
_ = SwiftNameTest(cc: nil)
// CHECK: load i8*, i8** @"\01L_selector(testZ)"
// CHECK: load i8*, i8** @"\01L_selector(testY:)"
// CHECK: load i8*, i8** @"\01L_selector(testX:xx:)"
_ = SwiftNameTest.zz()
_ = SwiftNameTest.yy(aa: nil)
_ = SwiftNameTest.xx(nil, bb: nil)
do {
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject__5errorT__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject__5errorT_5blockFT_T__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT_5blockFT_T__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject___S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject__5blockFT_T__S_
// CHECK: call %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5blockFT_T__S_
_ = try SwiftNameTestError(error: ())
_ = try SwiftNameTestError(aa: nil, error: ())
_ = try SwiftNameTestError(aa: nil, error: (), block: {})
_ = try SwiftNameTestError(error: (), block: {})
_ = try SwiftNameTestError(aa: nil)
_ = try SwiftNameTestError(aa: nil, block: {})
_ = try SwiftNameTestError(block: {})
// CHECK: load i8*, i8** @"\01L_selector(testW:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testW2:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testV:)"
// CHECK: load i8*, i8** @"\01L_selector(testV2:)"
_ = try SwiftNameTestError.ww(nil)
_ = try SwiftNameTestError.w2(nil, error: ())
_ = try SwiftNameTestError.vv()
_ = try SwiftNameTestError.v2(error: ())
} catch _ {
}
}
// CHECK-LABEL: define linkonce_odr hidden %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT10dummyParamT__S_
// CHECK: load i8*, i8** @"\01L_selector(b)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo13SwiftNameTest* @_TTOFCSo13SwiftNameTestCfT2ccGSqPs9AnyObject___S_
// CHECK: load i8*, i8** @"\01L_selector(c:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err1:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject__5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject__5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject___S_
// CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT2aaGSqPs9AnyObject__5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo18SwiftNameTestError* @_TTOFCSo18SwiftNameTestErrorCfzT5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
// CHECK: }
// CHECK-LABEL: define hidden void @_TF7objc_ir29customFactoryMethodsInheritedFT_T_() {{.*}} {
func customFactoryMethodsInherited() {
// CHECK: call %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT10dummyParamT__S_
// CHECK: call %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT2ccGSqPs9AnyObject___S_
_ = SwiftNameTestSub(dummyParam: ())
_ = SwiftNameTestSub(cc: nil)
// CHECK: load i8*, i8** @"\01L_selector(testZ)"
// CHECK: load i8*, i8** @"\01L_selector(testY:)"
// CHECK: load i8*, i8** @"\01L_selector(testX:xx:)"
_ = SwiftNameTestSub.zz()
_ = SwiftNameTestSub.yy(aa: nil)
_ = SwiftNameTestSub.xx(nil, bb: nil)
do {
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject__5errorT__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject__5errorT_5blockFT_T__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT_5blockFT_T__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject___S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject__5blockFT_T__S_
// CHECK: call %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5blockFT_T__S_
_ = try SwiftNameTestErrorSub(error: ())
_ = try SwiftNameTestErrorSub(aa: nil, error: ())
_ = try SwiftNameTestErrorSub(aa: nil, error: (), block: {})
_ = try SwiftNameTestErrorSub(error: (), block: {})
_ = try SwiftNameTestErrorSub(aa: nil)
_ = try SwiftNameTestErrorSub(aa: nil, block: {})
_ = try SwiftNameTestErrorSub(block: {})
// CHECK: load i8*, i8** @"\01L_selector(testW:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testW2:error:)"
// CHECK: load i8*, i8** @"\01L_selector(testV:)"
// CHECK: load i8*, i8** @"\01L_selector(testV2:)"
_ = try SwiftNameTestErrorSub.ww(nil)
_ = try SwiftNameTestErrorSub.w2(nil, error: ())
_ = try SwiftNameTestErrorSub.vv()
_ = try SwiftNameTestErrorSub.v2(error: ())
} catch _ {
}
}
// CHECK-LABEL: define linkonce_odr hidden %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT10dummyParamT__S_
// CHECK: load i8*, i8** @"\01L_selector(b)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo16SwiftNameTestSub* @_TTOFCSo16SwiftNameTestSubCfT2ccGSqPs9AnyObject___S_
// CHECK: load i8*, i8** @"\01L_selector(c:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err1:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject__5errorT__S_
// CHECK: load i8*, i8** @"\01L_selector(err2:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject__5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err3:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5errorT_5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err4:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject___S_
// CHECK: load i8*, i8** @"\01L_selector(err5:error:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT2aaGSqPs9AnyObject__5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err6:error:callback:)"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden %CSo21SwiftNameTestErrorSub* @_TTOFCSo21SwiftNameTestErrorSubCfzT5blockFT_T__S_
// CHECK: load i8*, i8** @"\01L_selector(err7:callback:)"
// CHECK: }
// CHECK: linkonce_odr hidden {{.*}} @_TTOFCSo1BcfT3intVs5Int32_GSQS__
// CHECK: load i8*, i8** @"\01L_selector(initWithInt:)"
// CHECK: call [[OPAQUE:%.*]]* bitcast (void ()* @objc_msgSend
// CHECK: attributes [[NOUNWIND]] = { nounwind }
| 47.70997 | 168 | 0.718782 |
ef2ac56c1b83789b137862fcaebf6fc32b6a502e | 2,016 | // swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
//
// Package.swift
// CryptorRSA
//
// Copyright © 2017,2018 IBM. 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 PackageDescription
var dependencies: [Package.Dependency] = []
var targetDependencies: [Target.Dependency] = []
dependencies.append(.package(url: "https://github.com/IBM-Swift/HeliumLogger.git", from: "1.7.1"))
targetDependencies.append(.byName(name: "HeliumLogger"))
#if os(Linux)
dependencies.append(.package(url: "https://github.com/IBM-Swift/OpenSSL.git", from: "2.2.0"))
targetDependencies.append(.byName(name: "OpenSSL"))
#endif
let package = Package(
name: "CryptorRSA",
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "CryptorRSA",
targets: ["CryptorRSA"]
)
],
dependencies: dependencies,
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "CryptorRSA",
dependencies: targetDependencies
),
.testTarget(
name: "CryptorRSATests",
dependencies: ["CryptorRSA"]
)
]
)
| 33.6 | 122 | 0.681052 |
2372a5f281f0333ffb4d601248be32ecef8e70c3 | 3,393 | //
// NetworkHelper.swift
// PicPlay
//
// Created by Aleksey Orlov on 6/24/15.
// Copyright (c) 2015 Picsolve. All rights reserved.
//
import Foundation
public class NetworkHelper
{
static var deviceList: Dictionary <String, String>?
/**
Defines is HTTP response is successfull or not.
- parameter httpCode: HTTP code.
- returns: true if response is successfull, false otherwise.
*/
static func isHttpCodeSuccessful(httpCode: Int) -> Bool
{
return httpCode / 100 == 2
}
/**
Create task identifier from request type and request identifier.
- parameter requestType: Request type.
- parameter requestIdentifier: Request identifier.
- returns: Task identifier.
*/
public static func taskIdFrom(requestType:RequestType, requestIdentifier: String) -> String
{
return "\(requestType.rawValue), identifier=\(requestIdentifier)"
}
/**
Retrieves request type and request identifier from session task.
- parameter task: Session task description.
- returns: Request type and request identifier.
*/
static func requestTypeAndIdentifierFrom(task: NSURLSessionTask) -> (RequestType, String)
{
let components = task.taskDescription!.componentsSeparatedByString(", identifier=")
if components.count == 2
{
if let intValue = Int(components[0]),
type = RequestType(rawValue: intValue)
{
return (type, components[1])
}
}
assert(true, "Cannot extract request type and identifier from taskDescription")
return (.DownloadFile, "")
}
/**
Create dictionary from contents of file.
- parameter fileName: Name of a file.
- returns: Dictionary with contents of file.
*/
public static func dictionaryFromFile(fileName: String) -> AnyObject {
if let path = NSBundle.mainBundle().pathForResource(fileName, ofType: ""),
jsonData: AnyObject = try? NSData(contentsOfURL: NSURL(fileURLWithPath: path), options: NSDataReadingOptions.DataReadingMappedIfSafe) {
if let json: AnyObject = try? NSJSONSerialization.JSONObjectWithData(jsonData as! NSData, options: NSJSONReadingOptions.MutableContainers) {
return json
}
}
return Dictionary<String, AnyObject>()
}
/**
Convers JSON content into a dictionary.
- parameter rawData: Binary JSON content.
- returns: Dictionary with contents of JSON data.
*/
static func parseResponseData(rawData: NSData) -> Dictionary<String, AnyObject>?
{
if rawData.length > 0
{
// Parse JSON response.
if let content: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(rawData, options: .MutableContainers)
{
if let dictionary = content as? Dictionary<String, AnyObject>
{
return dictionary
}
else if let array = content as? Array<AnyObject>
{
return ["result": array]
}
}
}
//TODO: JSON parser
return Dictionary<String, AnyObject>()
}
}
| 29.504348 | 156 | 0.595638 |
0386a9223ac4ca306ea9d3d6458737e7dc8ccdd0 | 8,224 | //
// ViewController.swift
// EFQRCode
//
// Created by EyreFree on 2017/4/20.
//
// Copyright (c) 2017 EyreFree <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Cocoa
import EFQRCode
class ViewController: NSViewController {
let backgroundView: NSView = NSView()
let leftBarView: NSView = NSView()
let leftLineView: NSView = NSView()
let buttonRecognize: NSImageView = EFImageView()
let buttonGenerate: NSImageView = EFImageView()
let imageView: NSImageView = EFImageView()
var indexSelected = 0
// ViewController+Recognizer
let recognizerView = NSView()
let recognizerViewImage: DragDropImageView = DragDropImageView()
let recognizerViewPick: NSButton = NSButton()
let recognizerViewScan: NSButton = NSButton()
let recognizerViewResult: NSTextView = NSTextView()
// ViewController+Generator
let generatorView = NSView()
let generatorViewImage: NSImageView = NSImageView()
let generatorViewCreate: NSButton = NSButton()
let generatorViewSave: NSButton = NSButton()
let generatorViewContent: NSTextView = NSTextView()
let generatorViewTable = NSView()
lazy var generatorViewOptions: [EFDetailButton] = {
var buttons = [EFDetailButton]()
for index in 0 ..< titleArray.count {
buttons.append(EFDetailButton())
}
return buttons
}()
var result: Data?
// Param
var inputCorrectionLevel = EFInputCorrectionLevel.h
var mode: EFQRCodeMode = .none
var size: EFIntSize = EFIntSize(width: 1024, height: 1024)
var magnification: EFIntSize? = EFIntSize(width: 9, height: 9)
var backColor = NSColor.white
var frontColor = NSColor.black
var icon: NSImage? = nil
var iconSize: EFIntSize? = nil
var watermark: EFImage? = nil
var watermarkMode = EFWatermarkMode.scaleAspectFill
var foregroundPointOffset: CGFloat = 0
var allowTransparent: Bool = true
var binarizationThreshold: CGFloat = 0.5
var pointShape: EFPointShape = .square
let titleArray = [
"inputCorrectionLevel", "mode", "size", "magnification",
"backgroundColor", "foregroundColor", "icon", "iconSize",
"watermark", "watermarkMode", "foregroundPointOffset", "allowTransparent",
"binarizationThreshold", "pointShape"
]
override func viewDidLoad() {
super.viewDidLoad()
recognizerViewResult.string = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
generatorViewContent.string = "\n\n\n\n\n\n\n"
addControl()
refreshSelect()
}
override func viewDidAppear() {
super.viewDidAppear()
recognizerViewResult.string = ""
generatorViewContent.string = "https://github.com/EyreFree/EFQRCode"
self.view.window?.title = "EFQRCode"
self.view.window?.collectionBehavior = .fullScreenAuxiliary
}
func addControl() {
backgroundView.wantsLayer = true
backgroundView.layer?.backgroundColor = NSColor.theme.cgColor
self.view.addSubview(backgroundView)
backgroundView.snp.makeConstraints {
(make) in
make.top.left.right.bottom.equalTo(0)
make.width.equalTo(800)
make.height.equalTo(380)
}
backgroundView.addSubview(leftBarView)
leftBarView.snp.makeConstraints {
(make) in
make.top.left.bottom.equalTo(0)
make.width.equalTo(48)
}
leftLineView.wantsLayer = true
leftLineView.layer?.backgroundColor = NSColor.white.cgColor
backgroundView.addSubview(leftLineView)
leftLineView.snp.makeConstraints {
(make) in
make.top.bottom.equalTo(0)
make.left.equalTo(leftBarView.snp.right)
make.width.equalTo(1)
}
buttonRecognize.wantsLayer = true
buttonRecognize.imageAlignment = .alignCenter
buttonRecognize.imageScaling = .scaleAxesIndependently
buttonRecognize.image = NSImage(named: NSImage.Name("Recognizer"))
buttonRecognize.action = #selector(buttonRecognizeClicked)
leftBarView.addSubview(buttonRecognize)
buttonRecognize.snp.makeConstraints {
(make) in
make.left.right.top.equalTo(0)
make.height.equalTo(buttonRecognize.snp.width)
}
buttonGenerate.wantsLayer = true
buttonGenerate.imageAlignment = .alignCenter
buttonGenerate.imageScaling = .scaleAxesIndependently
buttonGenerate.image = NSImage(named: NSImage.Name("Generator"))
buttonGenerate.action = #selector(buttonGenerateClicked)
leftBarView.addSubview(buttonGenerate)
buttonGenerate.snp.makeConstraints {
(make) in
make.left.right.equalTo(0)
make.top.equalTo(buttonRecognize.snp.bottom)
make.height.equalTo(buttonGenerate.snp.width)
}
imageView.imageAlignment = .alignCenter
imageView.imageScaling = .scaleAxesIndependently
imageView.image = NSImage(named: NSImage.Name("launchimage"))
imageView.action = #selector(imageViewClicked)
leftBarView.addSubview(imageView)
imageView.snp.makeConstraints {
(make) in
make.left.right.bottom.equalTo(0)
make.height.equalTo(imageView.snp.width)
}
for tabView in [recognizerView, generatorView] {
tabView.wantsLayer = true
tabView.layer?.backgroundColor = NSColor.white.cgColor
tabView.isHidden = true
backgroundView.addSubview(tabView)
tabView.snp.makeConstraints {
(make) in
make.top.bottom.right.equalTo(0)
make.left.equalTo(leftLineView.snp.right)
}
}
addControlRecognizer()
addControlGenerator()
}
func refreshSelect() {
let imageArray = ["Recognizer", "Generator"]
let imageSelectedArray = ["Recognizer_D", "Generator_D"]
let views = [recognizerView, generatorView]
for (index, button) in [buttonRecognize, buttonGenerate].enumerated() {
button.image = NSImage(
named: NSImage.Name((index == indexSelected ? imageSelectedArray : imageArray)[index])
)
button.layer?.backgroundColor = (index == indexSelected ? NSColor.white : NSColor.theme).cgColor
views[index].isHidden = index != indexSelected
}
}
@objc func buttonRecognizeClicked() {
if 0 != indexSelected {
indexSelected = 0
refreshSelect()
}
}
@objc func buttonGenerateClicked() {
if 1 != indexSelected {
indexSelected = 1
refreshSelect()
}
}
@objc func imageViewClicked() {
if let url = URL(string: "https://github.com/EyreFree/EFQRCode") {
NSWorkspace.shared.open(url)
}
}
}
class EFImageView: NSImageView {
override func mouseDown(with event: NSEvent) {
if let action = self.action {
NSApp.sendAction(action, to: self.target, from: self)
}
}
}
| 35.448276 | 108 | 0.655885 |
5d881cd9164b0001d4695a6fd2d41e1be394fd8a | 3,100 | //
// ColorWithHSLTests.swift
// ColorWithHSLTests
//
// Created by GabrielMassana on 02/04/2016.
// Copyright © 2016 GabrielMassana. All rights reserved.
//
import XCTest
@testable import ColorWithHSL
class ColorWithHSLTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
//MARK: - Valid
func test_colorWithHex_newObjectReturned_minimum() {
let color = UIColor.colorWithHSL(hue: 0.0, saturation: 0.0, lightness: 0.0)
XCTAssertNotNil(color, "A valid Color object wasn't created");
}
func test_colorWithHex_newObjectReturned_maximum() {
let color = UIColor.colorWithHSL(hue: 360.0, saturation: 1.0, lightness: 1.0)
XCTAssertNotNil(color, "A valid Color object wasn't created");
}
//MARK: - NoValid
func test_colorWithHex_outOfRangeHue_over() {
let color = UIColor.colorWithHSL(hue: 361.0, saturation: 0.5, lightness: 0.5)
XCTAssertNil(color, "A valid Color object was created");
}
func test_colorWithHex_outOfRangeHue_under() {
let color = UIColor.colorWithHSL(hue: -1.0, saturation: 0.5, lightness: 0.5)
XCTAssertNil(color, "A valid Color object was created");
}
func test_colorWithHex_outOfRangeSaturation_over() {
let color = UIColor.colorWithHSL(hue: 180.0, saturation: 1.1, lightness: 0.5)
XCTAssertNil(color, "A valid Color object was created");
}
func test_colorWithHex_outOfRangeSaturation_under() {
let color = UIColor.colorWithHSL(hue: 180.0, saturation: -0.1, lightness: 0.5)
XCTAssertNil(color, "A valid Color object was created");
}
func test_colorWithHex_outOfRangeLightness_over() {
let color = UIColor.colorWithHSL(hue: 180.0, saturation: 0.5, lightness: 1.1)
XCTAssertNil(color, "A valid Color object was created");
}
func test_colorWithHex_outOfRangeLightness_under() {
let color = UIColor.colorWithHSL(hue: 180.0, saturation: 0.5, lightness: -0.1)
XCTAssertNil(color, "A valid Color object was created");
}
//MARK: - SpecificColor
func test_colorWithHex_red() {
let redColor = UIColor.colorWithHSL(hue: 0.0, saturation: 1.0, lightness: 0.5)
XCTAssertEqual(redColor, UIColor.redColor(), "A red Color object wasn't created");
}
func test_colorWithHex_green() {
let greenColor = UIColor.colorWithHSL(hue: 120.0, saturation: 1.0, lightness: 0.5)
XCTAssertEqual(greenColor, UIColor.greenColor(), "A green Color object wasn't created");
}
func test_colorWithHex_blue() {
let blueColor = UIColor.colorWithHSL(hue: 240.0, saturation: 1.0, lightness: 0.5)
XCTAssertEqual(blueColor, UIColor.blueColor(), "A blue Color object wasn't created");
}
}
| 28.440367 | 96 | 0.619355 |
ab3b88eba7a81644fc305fc556bdd23abb936ef1 | 6,104 | //
// AppDelegate.swift
// CalculatorTest
//
// Created by Yang Tian on 11/14/15.
// Copyright © 2015 Jiao Chu. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lw.2015.CalculatorTest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CalculatorTest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 54.5 | 291 | 0.720183 |
76254da89017865bda0f1173c9ed33f71b05d3dd | 3,668 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct ScheduleCreateOrUpdatePropertiesData : ScheduleCreateOrUpdatePropertiesProtocol {
public var description: String?
public var startTime: Date
public var expiryTime: Date?
public var interval: [String: String?]?
public var frequency: ScheduleFrequencyEnum
public var timeZone: String?
public var advancedSchedule: AdvancedScheduleProtocol?
enum CodingKeys: String, CodingKey {case description = "description"
case startTime = "startTime"
case expiryTime = "expiryTime"
case interval = "interval"
case frequency = "frequency"
case timeZone = "timeZone"
case advancedSchedule = "advancedSchedule"
}
public init(startTime: Date, frequency: ScheduleFrequencyEnum) {
self.startTime = startTime
self.frequency = frequency
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.description) {
self.description = try container.decode(String?.self, forKey: .description)
}
self.startTime = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .startTime)), format: .dateTime)!
if container.contains(.expiryTime) {
self.expiryTime = DateConverter.fromString(dateStr: (try container.decode(String?.self, forKey: .expiryTime)), format: .dateTime)
}
if container.contains(.interval) {
self.interval = try container.decode([String: String?]?.self, forKey: .interval)
}
self.frequency = try container.decode(ScheduleFrequencyEnum.self, forKey: .frequency)
if container.contains(.timeZone) {
self.timeZone = try container.decode(String?.self, forKey: .timeZone)
}
if container.contains(.advancedSchedule) {
self.advancedSchedule = try container.decode(AdvancedScheduleData?.self, forKey: .advancedSchedule)
}
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if self.description != nil {try container.encode(self.description, forKey: .description)}
try container.encode(DateConverter.toString(date: self.startTime, format: .dateTime), forKey: .startTime)
if self.expiryTime != nil {
try container.encode(DateConverter.toString(date: self.expiryTime!, format: .dateTime), forKey: .expiryTime)
}
if self.interval != nil {try container.encode(self.interval, forKey: .interval)}
try container.encode(self.frequency, forKey: .frequency)
if self.timeZone != nil {try container.encode(self.timeZone, forKey: .timeZone)}
if self.advancedSchedule != nil {try container.encode(self.advancedSchedule as! AdvancedScheduleData?, forKey: .advancedSchedule)}
}
}
extension DataFactory {
public static func createScheduleCreateOrUpdatePropertiesProtocol(startTime: Date, frequency: ScheduleFrequencyEnum) -> ScheduleCreateOrUpdatePropertiesProtocol {
return ScheduleCreateOrUpdatePropertiesData(startTime: startTime, frequency: frequency)
}
}
| 48.263158 | 165 | 0.716467 |
5086530fd22dac35d25ebfae2a02ebb086870873 | 2,086 | //
// VIPViewController.swift
// kankan
//
// Created by Xin on 16/10/19.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
class VIPViewController: UIViewController, WXNavigationProtocol {
var childVcs = [UIViewController]()
let titles:[String] = ["首页", "全部", "动作", "喜剧", "爱情", "科幻", "灾难", "恐怖", "悬疑", "魔幻", "战争", "罪案", "惊悚", "动画", "伦理", "纪录", "剧情"]
override func prefersStatusBarHidden() -> Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
self.configScrollView()
self.configNavigationBar()
let xScNavC = XScNavViewController(subViewControllers: childVcs)
xScNavC.addParentController(self)
}
func configNavigationBar() {
self.automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor.whiteColor()
addTitle("VIP影院")
addBottomImage()
}
//配置scrollview
func configScrollView() {
childVcs.append(VIPHomeViewController())
childVcs.append(VIPAllViewController())
childVcs.append(VIPActViewController())
childVcs.append(VIPFunnyViewController())
childVcs.append(VIPLoveViewController())
childVcs.append(VIPScienceViewController())
childVcs.append(VIPDisasterViewController())
childVcs.append(VIPTerrifyViewController())
childVcs.append(VIPSuspenseViewController())
childVcs.append(VIPMagicViewController())
childVcs.append(VIPWarViewController())
childVcs.append(VIPSinViewController())
childVcs.append(VIPPanicViewController())
childVcs.append(VIPAnimViewController())
childVcs.append(VIPRelationViewController())
childVcs.append(VIPDocuViewController())
childVcs.append(VIPStoryViewController())
for index in 0..<childVcs.count {
childVcs[index].title = titles[index]
}
}
}
| 25.753086 | 128 | 0.609779 |
d9a2b3ad32793d4253fd85ecb6e9ed66d7546353 | 4,656 | //
// CommonApis.swift
// YellowBook
//
// Created by mac on 2019/7/1.
// Copyright © 2019年 mac. All rights reserved.
//
import Foundation
import NicooNetwork
// MARK: - 设备号注册
class DeviceRegisterApi: XSVideoBaseAPI {
static let kInviteCode = "invite_code" // 剪切板内容
static let kUrlValue = "api/common/register-device"
override func loadData() -> Int {
if self.isLoading {
self.cancelAllRequests()
}
return super.loadData()
}
override func methodName() -> String {
return DeviceRegisterApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform(params)
}
}
// MARK: - 用户注册(手机号注册)
class UserRegisterApi: XSVideoBaseAPI {
static let kMobile = "mobile"
static let kPassword = "password"
static let kVerification_key = "verification_key"
static let kCode = "code"
static let kPassword_confirmation = "password_confirmation"
static let kInvite_code = "invite_code"
static let kUrlValue = "api/user/bind-mobile"
override func methodName() -> String {
return UserRegisterApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform(params)
}
}
// 用户登录
class UserLoginApi: XSVideoBaseAPI {
static let kMobile = "mobile"
static let kType = "type" // 登录方式:P:密码登录,C:验证码快捷登录
static let kVerification_key = "verification_key" // 验证码(如果是验证码登录必填)
static let kPassword = "password" // 用户密码(如果是密码登录必填
static let kCode = "code" // 验证码(如果是验证码登录必填)
static let kUrlValue = "/api/login"
override func loadData() -> Int {
if self.isLoading {
self.cancelAllRequests()
}
return super.loadData()
}
override func methodName() -> String {
return UserLoginApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform(params)
}
}
// MARK: - 发送验证码
class SendCodeApi: XSVideoBaseAPI {
static let kMobile = "mobile"
static let kUrlValue = "api/common/verify-code"
override func loadData() -> Int {
if self.isLoading {
self.cancelAllRequests()
}
return super.loadData()
}
override func methodName() -> String {
return SendCodeApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform(params)
}
}
// MARK: - 版本更新信息Api
class AppUpdateApi: XSVideoBaseAPI {
static let kUrlValue = "api/common/version"
static let kPlatform = "platform" // A [A:安卓版 I:IOS版]
static let kDefaultPlatform = "I"
override func loadData() -> Int {
if self.isLoading {
self.cancelAllRequests()
}
return super.loadData()
}
override func methodName() -> String {
return AppUpdateApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform( params)
}
}
// MARK: - 系统公告Api
class AppMessageApi: XSVideoBaseAPI {
static let kUrlValue = "api/common/notice"
override func loadData() -> Int {
if self.isLoading {
self.cancelAllRequests()
}
return super.loadData()
}
override func methodName() -> String {
return AppMessageApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform(params)
}
}
// MARK: - 闪屏广告
class AdvertismentApi: XSVideoBaseAPI {
static let kUrlValue = "api/common/startup"
override func loadData() -> Int {
if self.isLoading {
self.cancelAllRequests()
}
return super.loadData()
}
override func methodName() -> String {
return AdvertismentApi.kUrlValue
}
override func shouldCache() -> Bool {
return false
}
override func reform(_ params: [String: Any]?) -> [String: Any]? {
return super.reform(params)
}
}
| 22.935961 | 72 | 0.587199 |
331c40bb5ea41dedeb4dbf69c0ed61b2164e8c77 | 482 | //
// BlinkingLabel.swift
// BlinkingLabel
//
// Created by Nihal Khokhari on 04/04/19.
//
public class BlinkingLabel : UILabel {
public func startBlinking() {
let options : UIViewAnimationOptions = .Repeat | .Autoreverse
UIView.animateWithDuration(0.25, delay:0.0, options:options, animations: {
self.alpha = 0
}, completion: nil)
}
public func stopBlinking() {
alpha = 1
layer.removeAllAnimations()
}
}
| 22.952381 | 82 | 0.618257 |
dd8487724253b643f444a41fd31cc6b1782e67f5 | 958 | //
// MLCardForm.swift
// MLCardForm
//
// Created by Eric Ertl on 26/11/2019.
//
import Foundation
/**
Main class of this project.
It takes a `MLCardFormBuilder` object.
*/
@objcMembers
open class MLCardForm: NSObject {
internal var builder: MLCardFormBuilder
// MARK: Initialization
/**
Mandatory init. Based on `MLCardFormBuilder`
- parameter builder: MLCardFormBuilder object.
*/
public init(builder: MLCardFormBuilder) {
self.builder = builder
MLCardFormTracker.sharedInstance.startNewSession()
MLCardFormTracker.sharedInstance.trackEvent(path: "/card_form/init")
}
}
// MARK: Publics
extension MLCardForm {
/**
Setup MLCardForm settings and return main ViewController. Push this ViewController in your navigation stack.
*/
public func setupController() -> MLCardFormViewController {
return MLCardFormViewController.setupWithBuilder(builder)
}
}
| 24.564103 | 113 | 0.69833 |
5d71e44882edb2d1b0b1b77855a2f4fc60fde1c2 | 1,431 | //
// SwiftHttp2Tests.swift
// SwiftHttp2Tests
//
// Created by Scott Grosch on 1/2/18.
// Copyright © 2018 Gargoyle Software, LLC. All rights reserved.
//
import XCTest
@testable import SwiftHttp2
// TODO: Complete all test cases at https://github.com/http2jp/http2-frame-test-case
class SwiftHttp2Tests: XCTestCase {
static let nonConnectionStream = try! Http2StreamCache.shared.createStream(with: 1)
func testConversion16() {
let initial: UInt16 = 0b00100000_00000001
let ary = initial.toByteArray()
XCTAssertEqual(ary, [0b00100000, 0b00000001])
let back = UInt16(bytes: ary, startIndex: 0)
XCTAssertEqual(initial, back)
}
func testConversion32() {
let initial: UInt32 = 0b10000000_00010000_00100000_00000001
let ary = initial.toByteArray()
XCTAssertEqual(ary, [0b10000000, 0b00010000, 0b00100000, 0b00000001])
let back = UInt32(bytes: ary, startIndex: 0)
XCTAssertEqual(initial, back)
}
func testConversion64() {
let initial: UInt64 = 0b10000000_01000000_00100000_00010000_00001000_00000100_00000010_00000001
let ary = initial.toByteArray()
XCTAssertEqual(ary, [
0b10000000, 0b01000000, 0b00100000, 0b00010000, 0b00001000, 0b00000100, 0b00000010, 0b00000001
])
let back = UInt64(bytes: ary, startIndex: 0)
XCTAssertEqual(initial, back)
}
}
| 29.8125 | 106 | 0.686233 |
76bdafe64601c74dae7c32cef67a143671dc07ea | 1,250 | //
// JSON+ReadFromFile.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 28/10/2015.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
import edXCore
import edX
// This is just a class in the current bundle rather than in whatever bundle JSON is in.
// Which allows us to isolate test data to the test bundle
private class BundleClass {}
public extension JSON {
public init(resourceNamed fileName: String) {
guard let
url = Bundle(for: Swift.type(of: BundleClass())).url(forResource: fileName, withExtension: "json"),
let data = try? NSData(contentsOf: url, options: NSData.ReadingOptions.mappedIfSafe) else
{
assertionFailure("Couldn't load data from file")
self.init([:])
return
}
self.init(data:data as Data)
}
public init(plistResourceNamed fileName: String) {
guard let
url = Bundle(for: Swift.type(of: BundleClass())).url(forResource: fileName, withExtension: "plist"),
let data = NSDictionary(contentsOf: url) else
{
assertionFailure("Couldn't load data from file")
self.init([:])
return
}
self.init(data)
}
}
| 28.409091 | 112 | 0.6224 |
391c5a0cf1a2cc83a7f07eb7f6c9bf09e1e551bd | 478 | //
// BlockBackgroundColorAttribute.swift
// Down
//
// Created by John Nguyen on 11.08.19.
// Copyright © 2016-2019 Down. All rights reserved.
//
#if !os(watchOS)
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
struct BlockBackgroundColorAttribute {
var color: DownColor
var inset: CGFloat
}
extension NSAttributedString.Key {
static let blockBackgroundColor = NSAttributedString.Key("blockBackgroundColor")
}
#endif
| 14.484848 | 84 | 0.73431 |
f9533d8a9d4daab56ebafc6082476f2c7f561738 | 1,062 | //
// DexSortTypes.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 8/2/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
enum DexSort {
enum DTO {}
enum ViewModel {}
enum Event {
case readyView
case tapDeleteButton(IndexPath)
case dragModels(sourceIndexPath: IndexPath, destinationIndexPath: IndexPath)
case setModels([DTO.DexSortModel])
}
struct State: Mutating {
enum Action {
case none
case refresh
case delete
}
var isNeedRefreshing: Bool
var action: Action
var section: DexSort.ViewModel.Section
var deletedIndex: Int
}
}
extension DexSort.ViewModel {
struct Section: Mutating {
var items: [Row]
}
enum Row {
case model(DexSort.DTO.DexSortModel)
}
}
extension DexSort.DTO {
struct DexSortModel: Hashable, Mutating {
let id: String
let name: String
var sortLevel: Int
}
}
| 19.666667 | 84 | 0.588512 |
e8e11d0e2ee11f11344be3ab321bfe05e2e86d3f | 8,466 | // swiftlint:disable all
// Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen
#if os(macOS)
import AppKit
#elseif os(iOS)
import ARKit
import UIKit
#elseif os(tvOS) || os(watchOS)
import UIKit
#endif
// Deprecated typealiases
@available(*, deprecated, renamed: "ColorAsset.Color", message: "This typealias will be removed in SwiftGen 7.0")
internal typealias AssetColorTypeAlias = ColorAsset.Color
@available(*, deprecated, renamed: "ImageAsset.Image", message: "This typealias will be removed in SwiftGen 7.0")
internal typealias AssetImageTypeAlias = ImageAsset.Image
// swiftlint:disable superfluous_disable_command file_length implicit_return
// MARK: - Asset Catalogs
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Asset {
internal enum Files {
internal static let data = DataAsset(name: "Data")
internal enum Json {
internal static let data = DataAsset(name: "Json/Data")
}
internal static let readme = DataAsset(name: "README")
// swiftlint:disable trailing_comma
internal static let allResourceGroups: [ARResourceGroupAsset] = [
]
internal static let allColors: [ColorAsset] = [
]
internal static let allDataAssets: [DataAsset] = [
data,
Json.data,
readme,
]
internal static let allImages: [ImageAsset] = [
]
// swiftlint:enable trailing_comma
}
internal enum Food {
internal enum Exotic {
internal static let banana = ImageAsset(name: "Exotic/Banana")
internal static let mango = ImageAsset(name: "Exotic/Mango")
}
internal enum Round {
internal static let apricot = ImageAsset(name: "Round/Apricot")
internal static let apple = ImageAsset(name: "Round/Apple")
internal enum Double {
internal static let cherry = ImageAsset(name: "Round/Double/Cherry")
}
internal static let tomato = ImageAsset(name: "Round/Tomato")
}
internal static let `private` = ImageAsset(name: "private")
// swiftlint:disable trailing_comma
internal static let allResourceGroups: [ARResourceGroupAsset] = [
]
internal static let allColors: [ColorAsset] = [
]
internal static let allDataAssets: [DataAsset] = [
]
internal static let allImages: [ImageAsset] = [
Exotic.banana,
Exotic.mango,
Round.apricot,
Round.apple,
Round.Double.cherry,
Round.tomato,
`private`,
]
// swiftlint:enable trailing_comma
}
internal enum Other {
// swiftlint:disable trailing_comma
internal static let allResourceGroups: [ARResourceGroupAsset] = [
]
internal static let allColors: [ColorAsset] = [
]
internal static let allDataAssets: [DataAsset] = [
]
internal static let allImages: [ImageAsset] = [
]
// swiftlint:enable trailing_comma
}
internal enum Styles {
internal enum _24Vision {
internal static let background = ColorAsset(name: "24Vision/Background")
internal static let primary = ColorAsset(name: "24Vision/Primary")
}
internal static let orange = ImageAsset(name: "Orange")
internal enum Vengo {
internal static let primary = ColorAsset(name: "Vengo/Primary")
internal static let tint = ColorAsset(name: "Vengo/Tint")
}
// swiftlint:disable trailing_comma
internal static let allResourceGroups: [ARResourceGroupAsset] = [
]
internal static let allColors: [ColorAsset] = [
_24Vision.background,
_24Vision.primary,
Vengo.primary,
Vengo.tint,
]
internal static let allDataAssets: [DataAsset] = [
]
internal static let allImages: [ImageAsset] = [
orange,
]
// swiftlint:enable trailing_comma
}
internal enum Targets {
internal static let bottles = ARResourceGroupAsset(name: "Bottles")
internal static let paintings = ARResourceGroupAsset(name: "Paintings")
internal static let posters = ARResourceGroupAsset(name: "Posters")
// swiftlint:disable trailing_comma
internal static let allResourceGroups: [ARResourceGroupAsset] = [
bottles,
paintings,
posters,
]
internal static let allColors: [ColorAsset] = [
]
internal static let allDataAssets: [DataAsset] = [
]
internal static let allImages: [ImageAsset] = [
]
// swiftlint:enable trailing_comma
}
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
// MARK: - Implementation Details
internal struct ARResourceGroupAsset {
internal fileprivate(set) var name: String
#if os(iOS)
@available(iOS 11.3, *)
internal var referenceImages: Set<ARReferenceImage> {
return ARReferenceImage.referenceImages(in: self)
}
@available(iOS 12.0, *)
internal var referenceObjects: Set<ARReferenceObject> {
return ARReferenceObject.referenceObjects(in: self)
}
#endif
}
#if os(iOS)
@available(iOS 11.3, *)
internal extension ARReferenceImage {
static func referenceImages(in asset: ARResourceGroupAsset) -> Set<ARReferenceImage> {
let bundle = BundleToken.bundle
return referenceImages(inGroupNamed: asset.name, bundle: bundle) ?? Set()
}
}
@available(iOS 12.0, *)
internal extension ARReferenceObject {
static func referenceObjects(in asset: ARResourceGroupAsset) -> Set<ARReferenceObject> {
let bundle = BundleToken.bundle
return referenceObjects(inGroupNamed: asset.name, bundle: bundle) ?? Set()
}
}
#endif
internal final class ColorAsset {
internal fileprivate(set) var name: String
#if os(macOS)
internal typealias Color = NSColor
#elseif os(iOS) || os(tvOS) || os(watchOS)
internal typealias Color = UIColor
#endif
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
internal private(set) lazy var color: Color = {
guard let color = Color(asset: self) else {
fatalError("Unable to load color asset named \(name).")
}
return color
}()
fileprivate init(name: String) {
self.name = name
}
}
internal extension ColorAsset.Color {
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *)
convenience init?(asset: ColorAsset) {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
self.init(named: NSColor.Name(asset.name), bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal struct DataAsset {
internal fileprivate(set) var name: String
#if os(iOS) || os(tvOS) || os(macOS)
@available(iOS 9.0, macOS 10.11, *)
internal var data: NSDataAsset {
guard let data = NSDataAsset(asset: self) else {
fatalError("Unable to load data asset named \(name).")
}
return data
}
#endif
}
#if os(iOS) || os(tvOS) || os(macOS)
@available(iOS 9.0, macOS 10.11, *)
internal extension NSDataAsset {
convenience init?(asset: DataAsset) {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
self.init(name: asset.name, bundle: bundle)
#elseif os(macOS)
self.init(name: NSDataAsset.Name(asset.name), bundle: bundle)
#endif
}
}
#endif
internal struct ImageAsset {
internal fileprivate(set) var name: String
#if os(macOS)
internal typealias Image = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
internal typealias Image = UIImage
#endif
internal var image: Image {
let bundle = BundleToken.bundle
#if os(iOS) || os(tvOS)
let image = Image(named: name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
let image = bundle.image(forResource: NSImage.Name(name))
#elseif os(watchOS)
let image = Image(named: name)
#endif
guard let result = image else {
fatalError("Unable to load image asset named \(name).")
}
return result
}
}
internal extension ImageAsset.Image {
@available(macOS, deprecated,
message: "This initializer is unsafe on macOS, please use the ImageAsset.image property")
convenience init?(asset: ImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = BundleToken.bundle
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(macOS)
self.init(named: NSImage.Name(asset.name))
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
// swiftlint:disable convenience_type
private final class BundleToken {
static let bundle: Bundle = {
Bundle(for: BundleToken.self)
}()
}
// swiftlint:enable convenience_type
| 29.915194 | 113 | 0.688873 |
ef1710be5e08f918d22050b4a21960ae02e5fe74 | 2,807 |
import Advent
import Foundation
public enum Day11: Day {
public static let title = "Seating System"
public static func part1(_ input: Input) throws -> Int {
var matrix = try Matrix<Tile>(input: input)
var count = matrix.count(of: .occupied)
while true {
matrix = matrix.musicalChairs()
let newCount = matrix.count(of: .occupied)
guard newCount != count else { return count }
count = newCount
}
return count
}
public static func part2(_ input: Input) throws -> Int {
var matrix = try Matrix<Tile>(input: input)
var count = matrix.count(of: .occupied)
while true {
matrix = matrix.musicalChairs2()
let newCount = matrix.count(of: .occupied)
guard newCount != count else { return count }
count = newCount
}
return count
}
}
extension Day11 {
enum Tile: Character, RawRepresentable {
case floor = "."
case empty = "L"
case occupied = "#"
var isSeat: Bool { self == .empty || self == .occupied }
}
}
extension Day11.Tile: CustomStringConvertible {
var description: String { String(rawValue) }
}
extension Matrix where Element == Day11.Tile {
fileprivate func musicalChairs() -> Self {
func adjacent(to position: Position2D<Int>) -> [Day11.Tile] {
(position.orthogonallyAdjacent + position.diagonallyAdjacent)
.compactMap { self[$0] }
}
return map { (position: Position2D, tile: Day11.Tile) -> Day11.Tile in
switch tile {
case .empty where adjacent(to: position).count(of: .occupied) == 0: return .occupied
case .occupied where adjacent(to: position).count(of: .occupied) >= 4: return .empty
default: return tile
}
}
}
}
extension Matrix where Element == Day11.Tile {
fileprivate func musicalChairs2() -> Self {
func firstSeat(from position: Matrix<Day11.Tile>.Index, in direction: Vector2D<Int>) -> Element? {
indices(from: position, in: direction).first(where: \.isSeat)
}
func adjacent(to position: Matrix<Day11.Tile>.Index) -> [Element] {
(Vector2D<Int>.diagonal + Vector2D<Int>.orthogonal)
.compactMap { firstSeat(from: position, in: $0) }
}
return map { (position: Matrix<Day11.Tile>.Index, tile: Day11.Tile) -> Element in
switch tile {
case .empty where adjacent(to: position).count(where: { $0 == .occupied }) == 0: return .occupied
case .occupied where adjacent(to: position).count(where: { $0 == .occupied }) >= 5: return .empty
default: return tile
}
}
}
}
| 30.182796 | 109 | 0.580691 |
8975be266af2aa5011dd56850b161e4d086476e7 | 1,427 | //
// AppDelegate.swift
// SwiftUI Workshop
//
// Created by Rudrank Riyam on 19/10/19.
// Copyright © 2019 Rudrank Riyam. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.552632 | 179 | 0.748423 |
6773a0680b06defe7441f87785746741067995a4 | 838 | // Generated using Sourcery 0.16.1 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import Mirage
@testable import Example
import Foundation
class MockFuncClosuresReturns: FuncClosuresReturns {
//MARK: - VARIABLES
//MARK: - FUNCTIONS
//MARK: funcReturnClosure
lazy var mock_funcReturnClosure = FuncCallHandler<Void, (String) -> Int>(returnValue: anyClosureGettingStringReturningInt())
func funcReturnClosure() -> (String) -> Int {
return mock_funcReturnClosure.handle(())
}
//MARK: funcReturnClosureOptional
lazy var mock_funcReturnClosureOptional = FuncCallHandler<Void, ((String) -> Int)?>(returnValue: anyClosureOptGettingStringReturningInt())
func funcReturnClosureOptional() -> ((String) -> Int)? {
return mock_funcReturnClosureOptional.handle(())
}
}
| 38.090909 | 146 | 0.724344 |
ddaa71d4659d1e12165b983a40e52b7090efe821 | 277 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
func f {
var d = v ( {
{
}
protocol A {
enum S {
init {
struct A {
extension NSSet {
class
case ,
| 16.294118 | 87 | 0.703971 |
dd8330e1cb1cfeaf1cc76415d3493de673fb37ef | 2,348 | //
// CompliancePayload.swift
// AWProfileManager
//
// Copyright © 2016 VMware, Inc. All rights reserved. This product is protected
// by copyright and intellectual property laws in the United States and other
// countries as well as by international treaties. VMware products are covered
// by one or more patents listed at http://www.vmware.com/go/patents.
//
import Foundation
/**
* @brief Compliance payload that is contained in an 'AWProfile'.
* @details A profile payload that represents the compliance group of an SDK profile.
* @version 6.0
*/
@objc(AWCompliancePayload)
public class CompliancePayload: ProfilePayload {
public static let kComplianceStatusKey: String = "com.airwatch.compliance.compromisedPolicy"
/** A boolean indicating if compromised (jailbroken) devices should be prevented. */
public fileprivate (set) var preventCompromisedDevices: Bool = false
/** A boolean indicating if device restorations should be prevented. */
public fileprivate (set) var preventRestoringBackupDevices: Bool = false
/** An array of actions to be performed if the device is compromised. */
public fileprivate (set) var preventCompromisedDevicesActions: NSArray = []
/** A boolean indicating if compromised (jailbroken) devices should be prevented. */
public fileprivate (set) var enableCompromisedProtection: Bool = false
/** A string for the id of the compromised policy. */
public fileprivate (set) var compromisedPolicyID: String?
/// For constructing this payload in Objective-C UT. It should not be called for elsewhere
override init(dictionary: [String : Any]) {
super.init(dictionary: dictionary)
guard dictionary["PayloadType"] as? String == CompliancePayloadConstants.kCompliancePayloadType else {
log(error: "Failed to get Compliance Payload")
return
}
self.preventCompromisedDevices ??= dictionary.bool(for: CompliancePayloadConstants.kComplianceCompromisedProtectionKey)
self.enableCompromisedProtection = self.preventCompromisedDevices
self.compromisedPolicyID = dictionary[CompliancePayloadConstants.kCompliancePolicyID] as? String
}
override public class func payloadType() -> String {
return CompliancePayloadConstants.kCompliancePayloadType
}
}
| 42.690909 | 127 | 0.737649 |
7a24a9362f86058c371fd50a374fe323944a7b3f | 12,588 | //
// Extensions.swift
//
// Created by k1x
//
import Foundation
import XcodeEdit
import k2Utils
public extension String {
func swiftImportHeaderPath(module : String) -> String {
return "$(OBJROOT)/\(self).build/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/\(module).build/DerivedSources"
}
}
public struct ProjectPaths : Decodable {
public let spmProject : String
public let mainProject : String
public static func parse(from path: String) throws -> ProjectPaths {
return try PropertyListDecoder().decode(ProjectPaths.self, from: try Data(contentsOf: URL(fileURLWithPath: path)))
}
}
public extension PBXProject {
func group(where whereClosure : (PBXGroup) -> Bool) -> PBXGroup? {
for (_, obj) in allObjects.objects {
if let group = obj as? PBXGroup, whereClosure(group) {
return group
}
}
return nil
}
func loopBuildConfigurations(for targetName : String, element : (XCBuildConfiguration)->()) {
guard let configList = target(named: targetName)?.buildConfigurationList.value else {
return
}
for buildConfigRef in configList.buildConfigurations {
guard let buildConfig = buildConfigRef.value else {
return
}
element(buildConfig)
}
}
}
public extension PBXReference {
func nameWithoutExtension() throws -> String {
if let name = name {
return name
}
guard let path = path else {
throw "No path found".error()
}
let lastPathComponenet = path.substring(fromLast: "/") ?? path
return lastPathComponenet.substring(toLast: ".") ?? lastPathComponenet
}
}
public extension ProjectContext {
func frameworks(for targetName: String, to allObjects : AllObjects? = nil) throws -> [(TargetProcessing?, PBXFileReference)] {
guard let target = spmProject.project.target(named: targetName) else {
throw "Target not found!".error()
}
let frameworksPhase = target.buildPhase(of: PBXFrameworksBuildPhase.self)
return try frameworksPhase.files.compactMap({ buildFile -> (TargetProcessing?, PBXFileReference)? in
guard let fileRef = buildFile.value?.fileRef?.value as? PBXFileReference, let path = fileRef.path else {
return nil
}
let name = try fileRef.nameWithoutExtension()
let key = fileRef.key
if let framework = frameworks[key] {
return (targets[name], framework)
} else {
let guid : Guid
if let name = fileRef.lastPathComponentOrName {
guid = Guid("FREF-" + name.guidStyle)
} else {
guid = Guid.random
}
let clone = fileRef.clone(to: allObjects ?? spmProject.project.allObjects, guid: guid)
frameworks[key] = clone
return (targets[name], clone)
}
}).sorted(by: {
$0.1.lastPathComponentOrName < $1.1.lastPathComponentOrName
})
}
/// To be used in module dependencies for system frameworks
/// If create the reference directly the way as in this method must be used. Or better to create a new one here nearby.
func spmFramework(with path : String, sourceTree : SourceTree = .relativeTo(.sdkRoot), type : PBXFileType = .framework) -> PBXFileReference {
let reference = spmProject.project.newFrameworkReference(path: path, sourceTree: sourceTree, fileType: type)
let key = reference.key
if let framework = spmFrameworks[key] {
return framework
} else {
spmFrameworks[key] = reference
return reference
}
}
func deletePackageDescriptionTargets() {
var guids = [Guid]()
for targetRef in spmProject.project.targets {
guard let target = targetRef.value, target.name.hasSuffix("PackageDescription") else {
continue
}
for buildPhaseRef in target.buildPhases {
guard let buildPhase = buildPhaseRef.value else {
continue
}
buildPhase.files = buildPhase.files.filter { buildFileRef -> Bool in
guard let fileRef = buildFileRef.value?.fileRef?.value, fileRef.lastPathComponentOrName == "Package.swift" else {
return true
}
guids.append(buildFileRef.id)
// guids.append(fileRef.id)
return false
}
buildPhase.applyChanges()
}
}
for targetRef in spmProject.project.targets {
guard let target = targetRef.value, target.name.hasSuffix("PackageDescription") else {
continue
}
guids.append(targetRef.id)
if let buildConfigList = target.buildConfigurationList.value {
for configRef in buildConfigList.buildConfigurations {
guids.append(configRef.id)
}
}
target.deleteBuildPhases(where: { _ in true })
}
for guid in guids {
spmProject.project.allObjects.objects.removeValue(forKey: guid)
}
spmProject.project.targets = spmProject.project.targets.filter {
!$0.id.value.hasSuffix("PackageDescription")
}
spmProject.project.applyChanges()
}
}
public extension MainIosProjectRequirements {
@inlinable
func targetConfig(for target: String) -> XCBuildConfiguration? {
return iosContext.spmProject.project.target(named: target)?.buildConfigurationList.value?.buildConfigurations.first?.value
}
func removeLibraryLinkage(include : (PBXTarget)->Bool) {
var guids = [Guid]()
for targetRef in context.spmProject.project.targets {
guard let target = targetRef.value,
include(target),
let frameworksPhase = target.buildPhaseOptional(of: PBXFrameworksBuildPhase.self) else {
continue
}
for bfileRef in frameworksPhase.files {
guids.append(bfileRef.id)
}
frameworksPhase.files = []
}
for guid in guids {
context.spmProject.project.allObjects.objects.removeValue(forKey: guid)
}
}
func sortExternalGroup() {
externalGroup.children.sort(by: {
$0.value?.lastPathComponentOrName < $1.value?.lastPathComponentOrName
})
externalGroup.applyChanges()
}
func copyBuildSettings(from: String, to : [String]) throws {
guard let originalConfig = targetConfig(for: from),
let headerSearchPaths = originalConfig.buildSettings["HEADER_SEARCH_PATHS"] as? [String] else {
throw "Couldn't find an original configuration".error()
}
let targets = to.compactMap { iosContext.mainProject.project.target(named: $0) }
let sourceHeaderSearchPaths = headerSearchPaths.map {
$0.replacingOccurrences(of: "$(SRCROOT)/", with: "$(SRCROOT)/Dependencies/")
}
let otherSwiftFlags = try swiftFlags(from: from)
do {
for target in targets {
target.updateBuildSettings([
"OTHER_SWIFT_FLAGS" : otherSwiftFlags,
"HEADER_SEARCH_PATHS" : sourceHeaderSearchPaths
])
}
} catch {
print("Error with processing swift flags: \(error)")
}
}
func addSingleFramework(name: String, linkType : PBXProject.FrameworkType, from: String, to : [String]) throws {
let allObjects = iosContext.mainProject.project.allObjects
let frameworkObj = PBXFileReference(emptyObjectWithId: Guid("FREF-C-" + name.guidStyle), allObjects: allObjects)
frameworkObj.name = name
frameworkObj.path = name
frameworkObj.lastKnownFileType = .archive
frameworkObj.sourceTree = .relativeTo(.buildProductsDir)
let ref = allObjects.createReference(value: frameworkObj)
let targets = to.compactMap { iosContext.mainProject.project.target(named: $0) }
guard to.count == targets.count else {
throw "Not all targets '\(to)' were found!".error()
}
try iosContext.mainProject.project.addFramework(framework: frameworkObj, group: externalGroup, targets: targets.map { (linkType, $0) })
sortExternalGroup()
try copyBuildSettings(from: from, to: to)
}
func copyFrameworks(from: String, to : [String], linkType : (TargetProcessing?, PBXFileReference)->(PBXProject.FrameworkType?)) throws {
let frameworks = try context.frameworks(for: from, to: iosContext.mainProject.project.allObjects)
let targets = to.compactMap { iosContext.mainProject.project.target(named: $0) }
guard to.count == targets.count else {
throw "Not all targets '\(to)' were found!".error()
}
for (target, framework) in frameworks {
guard let fLinkType = linkType(target, framework) else {
continue
}
let targetsWithType = targets.map { (fLinkType, $0) }
try iosContext.mainProject.project.addFramework(framework: framework, group: externalGroup, targets: targetsWithType)
}
sortExternalGroup()
try copyBuildSettings(from: from, to: to)
}
func swiftFlags(from target : String) throws -> String {
guard let targetConfig = targetConfig(for: target) else {
throw "Swift flags not found for dependencies project".error()
}
var swiftFlags : String
if let stringValue = targetConfig.buildSettings["OTHER_SWIFT_FLAGS"] as? String {
swiftFlags = stringValue
} else if let array = targetConfig.buildSettings["OTHER_SWIFT_FLAGS"] as? [String] {
swiftFlags = array.joined(separator: " ")
} else {
swiftFlags = ""
}
print("Swift flags: \(swiftFlags)")
swiftFlags = swiftFlags.substring(fromFirst: " ") ?? swiftFlags
let smParsedConfig = swiftFlags
.replacingOccurrences(of: "-Xcc ", with: " ")
.replacingOccurrences(of: "$(SRCROOT)/", with: "$(SRCROOT)/Dependencies/")
.split(separator: " ")
return "$(inherited) $(DEFINES) -Xcc " + smParsedConfig.joined(separator: " -Xcc ")
}
}
public extension PBXTarget {
func addRswift(project : PBXProject, group : PBXGroup, path: String, shellScript: ((String)->String)? = nil, destTarget : PBXTarget? = nil) throws {
let name = path.lastPathComponent
let namePhase = "[ik2gen-R.swift] Generate \(name)"
let phase : PBXShellScriptBuildPhase = buildPhase(where: {
$0.name == namePhase
}, append: { phases, phase in
phases.insert(phase, at: 0)
})
phase.name = namePhase
phase.inputPaths = [ "$TEMP_DIR/rswift-lastrun" ]
phase.outputPaths = [ "$SRCROOT/\(path)" ]
phase.shellScript = shellScript?(path) ?? "\"$SRCROOT/../rswift\" generate \"$SRCROOT/\(path)\""
group.children = group.children.filter {
!($0.value?.path?.contains(name) ?? false)
}
try project.addSourceFiles(files: [
project.newFileReference(name: name, path: path, sourceTree: .relativeTo(.sourceRoot)),
], group: allObjects.createReference(value: group), targets: name.hasSuffix(".h") ? [] : [destTarget ?? self])
}
}
public extension ModuleRequirements {
static var targetsDictionary : [String : TargetProcessing] {
return Dictionary(uniqueKeysWithValues: Self.targets.map({ ($0.name, $0) }) )
}
}
public func shell(launchPath: String, arguments: [String], fromDirectory : String) -> (returnCode: Int32, output: String?) {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
task.currentDirectoryPath = fromDirectory
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let output = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)
task.waitUntilExit()
return (task.terminationStatus, output)
}
| 38.972136 | 152 | 0.60518 |
bf8f5f0444ea5c6a20c41fb51efd52d9952807d5 | 780 | //
// ConnectableObservableType.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence.
*/
public protocol ConnectableObservableType : ObservableType {
/**
Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established.
- returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence.
*/
func connect() -> Disposable
}
| 35.454545 | 178 | 0.767949 |
8f44dc4559ba412128a582db0bd8f0a964f76df7 | 6,520 | //
// ActionSheetPresenterBaseTests.swift
// SheeeeeeeeetTests
//
// Created by Daniel Saidi on 2018-10-18.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import UIKit
import Mockery
@testable import Sheeeeeeeeet
class ActionSheetPresenterBaseTests: QuickSpec {
override func spec() {
var presenter: TestClass!
var notificationCenter: MockNotificationCenter!
beforeEach {
notificationCenter = MockNotificationCenter()
presenter = TestClass(
notificationCenter: notificationCenter
)
}
// MARK: - Public Functions
describe("dismissing") {
it("does nothing") {}
}
describe("presenting action sheet") {
it("sets up system detection") {
let menu = Menu(items: [])
let sheet = menu.toActionSheet { _, _ in }
presenter.present(sheet, in: MockViewController(), completion: {})
let inv1 = presenter.recorder.invokations(of: presenter.setupDidEnterBackgroundDetection)
let inv2 = presenter.recorder.invokations(of: presenter.setupOrientationChangeDetection)
expect(inv1.count).to(equal(1))
expect(inv2.count).to(equal(1))
}
}
// MARK: - Notifications
describe("handling did enter background") {
func sheet(withConfig config: ActionSheet.Configuration) -> ActionSheet {
let menu = Menu(items: [])
return ActionSheet(menu: menu, configuration: config) { _, _ in }
}
it("aborts if presenter has no action sheet") {
presenter.handleDidEnterBackground()
let inv = presenter.recorder.invokations(of: presenter.dismiss)
expect(inv.count).to(equal(0))
}
it("aborts if action sheet is not dismissable") {
presenter.actionSheet = sheet(withConfig: .nonDismissable)
presenter.handleDidEnterBackground()
let inv = presenter.recorder.invokations(of: presenter.dismiss)
expect(inv.count).to(equal(0))
}
it("aborts if action sheet should not be dismissed") {
let config = ActionSheet.Configuration(isDismissable: true, shouldBeDismissedWhenEnteringBackground: false)
presenter.actionSheet = sheet(withConfig: config)
presenter.handleDidEnterBackground()
let inv = presenter.recorder.invokations(of: presenter.dismiss)
expect(inv.count).to(equal(0))
}
it("dismisses if action sheet can and should be dismissed") {
let config = ActionSheet.Configuration(isDismissable: true, shouldBeDismissedWhenEnteringBackground: true)
presenter.actionSheet = sheet(withConfig: config)
presenter.handleDidEnterBackground()
let inv = presenter.recorder.invokations(of: presenter.dismiss)
expect(inv.count).to(equal(1))
}
}
describe("handling orientation change") {
it("does nothing") {
presenter.handleOrientationChange()
}
}
describe("setting up didEnterBackgroundDetection") {
beforeEach {
presenter.setupDidEnterBackgroundDetection()
}
it("correctly unsubscribes from notification") {
let inv = notificationCenter.recorder.invokations(of: notificationCenter.removeObserverTest)
expect(inv.count).to(equal(1))
expect(inv[0].arguments.0).to(be(presenter))
expect(inv[0].arguments.1).to(equal(UIApplication.didEnterBackgroundNotification))
expect(inv[0].arguments.2).to(beNil())
}
it("correctly subscribes to notification") {
let inv = notificationCenter.recorder.invokations(of: notificationCenter.addObserverTest)
expect(inv.count).to(equal(1))
expect(inv[0].arguments.0).to(be(presenter))
expect(inv[0].arguments.1).to(equal(#selector(presenter.handleDidEnterBackground)))
expect(inv[0].arguments.2).to(equal(UIApplication.didEnterBackgroundNotification))
expect(inv[0].arguments.3).to(beNil())
}
}
describe("setting up willChangeStatusBarOrientationNotification") {
beforeEach {
presenter.setupOrientationChangeDetection()
}
it("correctly unsubscribes to notification") {
let inv = notificationCenter.recorder.invokations(of: notificationCenter.removeObserverTest)
expect(inv.count).to(equal(1))
expect(inv[0].arguments.0).to(be(presenter))
expect(inv[0].arguments.1).to(equal(UIApplication.willChangeStatusBarOrientationNotification))
expect(inv[0].arguments.2).to(beNil())
}
it("correctly subscribes to notification") {
let inv = notificationCenter.recorder.invokations(of: notificationCenter.addObserverTest)
expect(inv.count).to(equal(1))
expect(inv[0].arguments.0).to(be(presenter))
expect(inv[0].arguments.1).to(equal(#selector(presenter.handleOrientationChange)))
expect(inv[0].arguments.2).to(equal(UIApplication.willChangeStatusBarOrientationNotification))
expect(inv[0].arguments.3).to(beNil())
}
}
}
}
private class TestClass: ActionSheetPresenterBase {
var recorder = Mock()
override func dismiss(completion: @escaping () -> ()) {
recorder.invoke(dismiss, args: (completion))
}
override func setupDidEnterBackgroundDetection() {
super.setupDidEnterBackgroundDetection()
recorder.invoke(setupDidEnterBackgroundDetection, args: ())
}
override func setupOrientationChangeDetection() {
super.setupOrientationChangeDetection()
recorder.invoke(setupOrientationChangeDetection, args: ())
}
}
| 39.277108 | 123 | 0.583742 |
cc934a7723e9ba9af80eae5ddafcfc8d8e2d1cde | 6,878 | //
// MineViewController.swift
// MGDS_Swift
//
// Created by i-Techsys.com on 17/1/5.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
class MineViewController: UITableViewController {
@IBOutlet weak var loginStatusLabel: UILabel! // 登录状态
@IBOutlet weak var userHeaderView: UserHeaderView! // 用户头部信息View
override func viewDidLoad() {
super.viewDidLoad()
// let blurEccect = UIBlurEffect(style: .light)
// let effectView = UIVisualEffectView(effect: blurEccect)
// effectView.frame = tableView.frame
// view.addSubview(effectView)
// let blurEffect = UIBlurEffect(style: .light)
// let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
// self.tableView.separatorEffect = vibrancyEffect
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let user = SaveTools.mg_UnArchiver(path: MGUserPath) as? User
if (user != nil){
userHeaderView.user = user
}
}
}
// MARK: - 代理
extension MineViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
myFavourite()
break
case 1:
if indexPath.row == 0 {
giveFace()
}else if indexPath.row == 1 {
giveSuggest()
} else {
setUpWiFi()
}
case 2:
if indexPath.row == 0 {
aboutDouShi()
}else {
shareToFriend()
}
case 3:
aboutLogin()
default:
break
}
}
}
// MARK: - 方法封装
extension MineViewController {
// MARK: 第1️⃣页
/// 我的收藏
fileprivate func myFavourite() {
self.tabBarController?.selectedIndex = 2
}
// MARK: 第2️⃣页
/// 给个笑脸,就是评价的意思
fileprivate func giveFace() { // itms-apps://
let urlStr = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(appid)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"
guard let url = URL(string: urlStr) else { return }
if UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
// if #available(iOS 10.0, *) {
// let options = [UIApplicationOpenURLOptionUniversalLinksOnly : true]
// UIApplication.shared.open(url, options: options, completionHandler: nil)
// } else {
// UIApplication.shared.openURL(url)
// }
}
}
/// 意见反馈
fileprivate func giveSuggest() {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
self.present(mailComposeViewController, animated: true, completion: nil)
}
}
/// 设置WIFi
fileprivate func setUpWiFi() {
guard let url = URL(string: "app-Prefs:root=WIFI") else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
// MARK: 第3️⃣页
/// 关于逗视
fileprivate func aboutDouShi(){
let QRCodeVC = QRCodeViewController()
show(QRCodeVC, sender: self)
}
/// 盆友需要
fileprivate func shareToFriend() {
// https://itunes.apple.com/cn/app/id1044917946
let share = "https://github.com/LYM-mg"
UMSocialData.default().extConfig.title = "搞笑,恶搞视频全聚合,尽在逗视App"
UMSocialWechatHandler.setWXAppId("wxfd23fac852a54c97", appSecret: "d4624c36b6795d1d99dcf0547af5443d", url: "\(share)")
UMSocialQQHandler.setQQWithAppId("1104864621", appKey: "AQKpnMRxELiDWHwt", url: "\(share)")
UMSocialSinaHandler.openSSO(withRedirectURL: "https://github.com/LYM-mg/MGDS_Swift")
UMSocialConfig.setFollowWeiboUids([UMShareToSina:"2778589865",UMShareToTencent:"@liuyuanming6388"]) // 563b6bdc67e58e73ee002acd
let snsArray = [UMShareToWechatTimeline,UMShareToWechatSession,UMShareToTencent,UMShareToQQ,UMShareToQzone,UMShareToSina,UMShareToFacebook,UMShareToEmail]
UMSocialSnsService.presentSnsIconSheetView(self, appKey: "58f6d91fbbea834d7200178b", shareText:"搞笑,恶搞视频全聚合,尽在逗视App " + share, shareImage: UIImage(named: "doushi_icon"), shareToSnsNames: snsArray, delegate: nil)
}
// MARK: 第4️⃣页
/// 关于登录
func aboutLogin() {
//确定按钮
let alertController = UIAlertController(title: "确定要退出吗?", message: "", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
}
let OKAction = UIAlertAction(title: "确定", style: .default) { (action) in
self.loginStatusLabel.textColor = UIColor.green
//删除归档文件
let defaultManager = FileManager.default
if defaultManager.isDeletableFile(atPath: MGUserPath) {
try! defaultManager.removeItem(atPath: MGUserPath)
}
MGNotificationCenter.post(name: NSNotification.Name(KChange3DTouchNotification), object: nil)
MGKeyWindow?.rootViewController = UIStoryboard(name: "Login", bundle: nil).instantiateInitialViewController()
let transAnimation = CATransition()
transAnimation.type = kCATransitionPush
transAnimation.subtype = kCATransitionFromLeft
transAnimation.duration = 0.5
MGKeyWindow?.layer.add(transAnimation, forKey: nil)
}
alertController.addAction(cancelAction)
alertController.addAction(OKAction)
self.present(alertController, animated: true) {
}
}
}
// MARK: - MFMailComposeViewControllerDelegate
extension MineViewController: MFMailComposeViewControllerDelegate {
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self
//设置收件人
mailComposerVC.setToRecipients(["[email protected]","[email protected]"])
//设置主题
mailComposerVC.setSubject("逗视意见反馈")
//邮件内容
let info: [String: Any] = Bundle.main.infoDictionary!
let appName = info["CFBundleName"] as! String
let appVersion = info["CFBundleShortVersionString"] as! String
mailComposerVC.setMessageBody("</br></br></br></br></br>基本信息:</br></br>\(appName) \(appVersion)</br> \(UIDevice.current.name)</br>iOS \(UIDevice.current.systemVersion)", isHTML: true)
return mailComposerVC
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
| 38 | 220 | 0.635941 |
694727ed979eaba248a48f2ed68fb6981d9d8534 | 7,111 | //
// MovEncodeTool.swift
// MovEncodeTool
//
// Created by 刘超群 on 2021/1/26.
//
import Foundation
import Photos
/// Mov视频格式编码工具
public final class MovEncodeTool {
public typealias ResultClosure = (_ mp4FileUrl: URL, _ mp4Data: Data) -> ()
public typealias ErrorClosure = (_ errorMsg: String) -> ()
/// mov转码mp4
/// - Parameters:
/// - phAsset: PHAsset mov资源
/// - exportQuality: 预设输出质量
/// - resultClosure: 转码成功文件信息
/// - errorClosure: 转码失败信息
public static func convertMovToMp4(from phAsset: PHAsset,
exportPresetQuality exportQuality: MovEncodeExportPresetQuality,
resultClosure:@escaping ResultClosure,
errorClosure:@escaping ErrorClosure) {
print(MovEncodeTool.getVideoInfo(phAsset) ?? "")
let options = PHVideoRequestOptions()
options.version = .current
options.deliveryMode = .automatic
options.isNetworkAccessAllowed = true
let manager = PHImageManager.default()
// PHAsset转AVURLAsset
manager.requestAVAsset(forVideo: phAsset, options: options) { (asset, audioMix, info) in
guard let urlAsset: AVURLAsset = asset as? AVURLAsset else {
errorClosure("resource type error")
return
}
MovEncodeTool.convertMovToMp4(from: urlAsset, exportPresetQuality: exportQuality, resultClosure: resultClosure, errorClosure: errorClosure)
}
}
/// mov转码mp4
/// - Parameters:
/// - urlAsset: AVURLAsset mov资源
/// - exportQuality: 预设输出质量
/// - resultClosure: 转码成功文件信息
/// - errorClosure: 转码失败信息
public static func convertMovToMp4(from urlAsset: AVURLAsset,
exportPresetQuality exportQuality: MovEncodeExportPresetQuality,
resultClosure:@escaping ResultClosure,
errorClosure:@escaping ErrorClosure) {
let avAsset = AVURLAsset(url: urlAsset.url)
// 处理输出预设
let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: avAsset)
guard compatiblePresets.contains(MovEncodeTool.getAVAssetExportPresetQuality(exportQuality)) == true else {
errorClosure("没有匹配的预设")
return
}
// 处理路径
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!.appending("/Cache/VideoData")
let fileManager = FileManager.default
let isDirExist = fileManager.fileExists(atPath: path)
if isDirExist == false {
do {
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
} catch {
print("文件夹创建失败\(path)")
errorClosure("文件夹创建失败\(path)")
return
}
print("创建文件夹成功\(path)")
}
// 拼接文件最终路径
let dateFormat = DateFormatter()
dateFormat.locale = Locale(identifier: "zh_CN")
dateFormat.dateFormat = "yyyyMMddHHmmss"
let dateStr = dateFormat.string(from: Date())
let resultPath = path.appending("\(dateStr).mp4")
print("resultPath == \(resultPath)")
// 格式转换
guard let exportSession: AVAssetExportSession = AVAssetExportSession(asset: avAsset, presetName: MovEncodeTool.getAVAssetExportPresetQuality(exportQuality)) else {
errorClosure("AVAssetExportSession创建失败")
return
}
exportSession.outputURL = URL(fileURLWithPath: resultPath)
exportSession.outputFileType = .mp4
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously {
// 转换结果处理
switch (exportSession.status) {
case .completed:
do {
let mp4Data = try Data(contentsOf: exportSession.outputURL!)
resultClosure(exportSession.outputURL!, mp4Data)
} catch {
errorClosure("mp4Data创建失败")
}
case .exporting:
errorClosure("exporting")
case .cancelled:
errorClosure("cancelled")
case .unknown:
errorClosure("unknown")
case .waiting:
errorClosure("waiting")
case .failed:
errorClosure("failed")
@unknown default:
errorClosure("unknown default")
}
}
}
}
// MARK: - Public Func
public extension MovEncodeTool {
/// 获取视频信息
/// - Parameter asset: PHAsset相册视频文件
/// - Returns: 视频信息
static func getVideoInfo(_ asset: PHAsset) -> Dictionary<String, String>? {
guard let resource: PHAssetResource = PHAssetResource.assetResources(for: asset).first else {return nil}
var resourceArr: [String]
if #available(iOS 13.0, *) {
let temStr = resource.description.replacingOccurrences(of: " - ", with: " ").replacingOccurrences(of: ": ", with: "=").replacingOccurrences(of: "{", with: "").replacingOccurrences(of: "}", with: "").replacingOccurrences(of: ", ", with: " ")
resourceArr = temStr.components(separatedBy: " ")
resourceArr.removeFirst()
resourceArr.removeFirst()
} else {
let temStr = resource.description.replacingOccurrences(of: "{", with: "").replacingOccurrences(of: "}", with: "").replacingOccurrences(of: ", ", with: " ")
resourceArr = temStr.components(separatedBy: " ")
resourceArr.removeFirst()
resourceArr.removeFirst()
}
var videoInfo: [String: String] = [:]
resourceArr.forEach {
let temArr = $0.components(separatedBy: "=")
if temArr.count > 2 {
videoInfo[temArr[0]] = temArr[1]
}
}
videoInfo["duration"] = (asset.duration as NSNumber).description
return videoInfo
}
}
// MARK: - Private Func
private extension MovEncodeTool {
static func getAVAssetExportPresetQuality(_ exportPreset: MovEncodeExportPresetQuality) -> String {
switch exportPreset {
case .low:
return AVAssetExportPresetLowQuality
case .medium:
return AVAssetExportPresetMediumQuality
case .highest:
return AVAssetExportPresetHighestQuality
case .dpi640x480:
return AVAssetExportPreset640x480
case .dpi960x540:
return AVAssetExportPreset960x540
case .dpi1280x720:
return AVAssetExportPreset1280x720
case .dpi1920x1080:
return AVAssetExportPreset1920x1080
case .dpi3840x2160:
return AVAssetExportPreset3840x2160
}
}
}
// MARK: - MovEncodeExportPresetQuality
public enum MovEncodeExportPresetQuality {
case low
case medium
case highest
case dpi640x480
case dpi960x540
case dpi1280x720
case dpi1920x1080
case dpi3840x2160
}
| 38.646739 | 252 | 0.604838 |
71a9e69f62d6eb59348ea68ee0f5d92f098de86a | 874 | //
// SFTipsNavigationController.swift
// iOSTips
//
// Created by brian on 2018/1/8.
// Copyright © 2018年 brian. All rights reserved.
//
import UIKit
class SFTipsNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
}
| 24.277778 | 106 | 0.676201 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.