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
|
---|---|---|---|---|---|
22379cd14c0432dff1c8fe7bab04647296082124 | 741 | //
// Ra3yApp.swift
// Ra3y
//
// Created by Omar Elewa on 17/01/2022.
//
import SwiftUI
@main
struct Ra3yApp: App {
@StateObject var viewModel = HomeViewModel()
init() {
#if DEBUG
var injectionBundlePath = "/Applications/InjectionIII.app/Contents/Resources"
#if targetEnvironment(macCatalyst)
injectionBundlePath = "\(injectionBundlePath)/macOSInjection.bundle"
#elseif os(iOS)
injectionBundlePath = "\(injectionBundlePath)/iOSInjection.bundle"
#endif
Bundle(path: injectionBundlePath)?.load()
#endif
}
var body: some Scene {
WindowGroup {
HomeView().environmentObject(viewModel)
}
}
}
| 24.7 | 86 | 0.605938 |
8f430ebe1316b1fc0d125a534c3e5daa0c5b7d2d | 5,239 | public final class RingArray<Element>: Collection {
private var internalBuffer: UnsafeMutableBufferPointer<Element?> { didSet { oldValue.deallocate() } }
public private(set) var capacity: Int
public private(set) var count: Int = 0
private(set) var bufferStartOffset: Int = 0 {
didSet {
if self.bufferStartOffset >= self.capacity {
// If our offset is the whole buffer, wrap the offset back to the beginning
self.bufferStartOffset = 0
}
}
}
public let startIndex: Int = 0
public var endIndex: Int { count }
public init(startingSize: Int = 64) {
self.capacity = startingSize
self.internalBuffer = type(of: self).callocBuffer(capacity: self.capacity)
}
deinit {
self.internalBuffer.deallocate()
}
public subscript(index: Int) -> Element {
get {
ensureWithinCount(index)
return self.pointer(for: index).pointee!
}
set {
ensureWithinCount(index, gte: true)
self.ensureCapacity(for: index)
self.pointer(for: index).pointee = newValue
if index == self.count {
self.count += 1
}
}
}
public func append(_ element: Element) {
self[self.count] = element
}
@discardableResult
public func remove(at index: Int) -> Element {
ensureWithinCount(index)
let postState: UnsafeMutablePointer<Element?>.PostState
if index == 0 {
postState = .value(nil)
} else {
postState = .uninitialized
}
let ptr = self.pointer(for: index)
let outValue = ptr.move(replacingWith: postState)!
if index == 0 {
self.bufferStartOffset += 1
} else {
let shiftRange = self.index(after: index)..<self.endIndex
for src in shiftRange {
let dest = self.index(before: src)
self.internalBuffer.move(self.bufferIndex(for: src),
to: self.bufferIndex(for: dest),
srcPostState: .uninitialized)
}
if let i = shiftRange.last {
self.internalBuffer[self.bufferIndex(for: i)] = nil
}
}
self.count -= 1
return outValue
}
public func index(before i: Int) -> Int { i - 1 }
public func index(after i: Int) -> Int { i + 1 }
}
extension RingArray: ExpressibleByArrayLiteral {
public convenience init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
extension RingArray {
convenience public init<S: Sequence>(_ seq: S) where S.Element == Element {
self.init()
seq.forEach(self.append)
}
convenience public init(single: Element) {
self.init()
self.append(single)
}
@discardableResult
public func popFirst() -> Element? {
guard !self.isEmpty else { return nil }
return self.remove(at: 0)
}
@discardableResult
public func popLast() -> Element? {
guard !self.isEmpty else { return nil }
return self.remove(at: self.lastValidIndex)
}
public func append<S: Sequence>(contentsOf seq: S) where S.Element == Element {
seq.forEach(self.append)
}
}
extension RingArray {
@inline(__always)
private func ensureWithinCount(_ index: Int, gte: Bool = false) {
precondition(gte ? (index <= self.count) : (index < self.count), "Index \(index) out of bounds: \(self.count)")
}
private var lastValidIndex: Int { self.count - 1 }
private func bufferIndex(for index: Int) -> Int {
var outInd = self.bufferStartOffset + index
if outInd >= self.capacity {
outInd -= self.capacity
}
assert(outInd >= 0, "Buffer index \(outInd) out of bounds: \(self.capacity)")
assert(outInd < capacity, "Buffer index \(outInd) out of bounds: \(self.capacity)")
return outInd
}
private func pointer(for index: Int) -> UnsafeMutablePointer<Element?> {
self.internalBuffer.baseAddress!.advanced(by: self.bufferIndex(for: index))
}
}
extension RingArray {
private static func callocBuffer(capacity: Int) -> UnsafeMutableBufferPointer<Element?> {
let outBuf = UnsafeMutableBufferPointer<Element?>.allocate(capacity: capacity)
outBuf.initialize(repeating: nil)
return outBuf
}
private func ensureCapacity(for index: Int) {
guard index >= self.capacity else { return }
let newCapacity = self.capacity * 2
let newBuffer = type(of: self).callocBuffer(capacity: newCapacity)
let (firstChunk, secondChunk) = self.chunksToMove()
newBuffer.baseAddress!.moveAssign(from: firstChunk.first!, count: firstChunk.count)
if let secondChunk = secondChunk {
newBuffer.baseAddress!.advanced(by: firstChunk.count).moveAssign(from: secondChunk.first!, count: secondChunk.count)
}
self.internalBuffer = newBuffer
self.bufferStartOffset = 0
self.capacity = newCapacity
}
private func chunksToMove() -> (Range<UnsafeMutablePointer<Element?>>, Range<UnsafeMutablePointer<Element?>>?) {
let firstChunkStartPtr = self.internalBuffer.baseAddress!.advanced(by: self.bufferStartOffset)
let firstChunkEndPtr = Swift.min(firstChunkStartPtr.advanced(by: self.count), self.internalBuffer.endAddress!)
let firstChunk = firstChunkStartPtr..<firstChunkEndPtr
let remainingItems = self.count - firstChunk.count
guard remainingItems > 0 else { return (firstChunk, nil) }
let secondChunkStartPtr = self.internalBuffer.baseAddress!
let secondChunkEndPtr = secondChunkStartPtr.advanced(by: remainingItems)
let secondChunk = secondChunkStartPtr..<secondChunkEndPtr
return (firstChunk, secondChunk)
}
}
| 27.719577 | 119 | 0.704715 |
deb4c2d3c77767d5202066c1b29d4f7551f61f63 | 2,939 | import Foundation
public protocol Login {
var username: String { get }
var password: String { get }
func renew(prompt: Bool) -> Result<Login, Error>
}
final class LoginImpl: Login {
enum Error: Swift.Error {
case optOut, noPassword
}
lazy var username: String = {
switch getUsername() {
case let .success(success):
return success
case let .failure(failure):
Env.current.shell.write("\(failure)")
exit(EXIT_FAILURE)
}
}()
lazy var password: String = {
switch getPassword(for: username) {
case let .success(success):
return success
case let .failure(failure):
Env.current.shell.write("\(failure)")
exit(EXIT_FAILURE)
}
}()
func renew(prompt: Bool = true) -> Result<Login, Swift.Error> {
if prompt, !Env.current.shell.promptDecision("Want to reset the login?") {
return .failure(Error.optOut)
}
switch Env.current.keychain.delete(account: username) {
case let .failure(failure):
Env.current.shell.write("Error removing login from Keychain: \(failure)")
Env.current.shell.write("Will try to create a new login.")
default:
break
}
Env.current.defaults.removeObject(for: .username)
let login = LoginImpl()
_ = login.password
return .success(login)
}
private func getUsername() -> Result<String, Swift.Error> {
return Result<String, Swift.Error> {
if let username = Env.current.defaults[.username] as String? {
return username
} else {
guard let username = Env.current.shell.prompt("Enter your JIRA username", newline: false, silent: false),
!username.isEmpty else {
return try renew(prompt: false).get().username
}
Env.current.defaults[.username] = username
return username
}
}
}
private func getPassword(for username: String) -> Result<String, Swift.Error> {
let password = Env.current.keychain.read(account: username)
switch password {
case let .success(success?):
return .success(success)
case let .failure(failure):
if Env.current.debug {
Env.current.shell.write("\(failure)")
}
default:
break
}
if let newPassword = Env.current.shell.prompt("Enter your JIRA password", newline: false, silent: true), !newPassword.isEmpty {
return Env.current.keychain.create(password: newPassword, account: username)
.map { _ in newPassword }
.flatMapError { _ in renew(prompt: true).map { $0.password } }
}
return renew(prompt: true).map { $0.password }
}
}
| 31.602151 | 135 | 0.566519 |
89724265673a8c205e5fd1e49e58b31c3be933b3 | 1,460 | //
// VeilTests.swift
// PrimerSDKTests
//
// Created by Carl Eriksson on 09/01/2021.
//
import XCTest
@testable import PrimerSDK
class MaskTests: XCTestCase {
func test_card_number_formats_correctly() throws {
let numberMask = Mask(pattern: "#### #### #### #### ###")
let text = numberMask.apply(on: "4242424242424242")
XCTAssertEqual(text, "4242 4242 4242 4242")
}
func test_card_number_formats_length_correctly() throws {
let numberMask = Mask(pattern: "#### #### #### #### ###")
let text = numberMask.apply(on: "424242424242424242444")
XCTAssertEqual(text, "4242 4242 4242 4242 424")
}
func test_card_number_formats_only_digits() throws {
let numberMask = Mask(pattern: "#### #### #### #### ###")
let text = numberMask.apply(on: "bla")
XCTAssertEqual(text, " ")
}
func test_date_formats_correctly() throws {
let numberMask = Mask(pattern: "##/##")
let text = numberMask.apply(on: "1223")
XCTAssertEqual(text, "12/23")
}
func test_date_formats_length_correctly() throws {
let numberMask = Mask(pattern: "##/##")
let text = numberMask.apply(on: "122333333")
XCTAssertEqual(text, "12/23")
}
func test_date_formats_only_digits() throws {
let numberMask = Mask(pattern: "##/##")
let text = numberMask.apply(on: "bla")
XCTAssertEqual(text, "/")
}
}
| 26.071429 | 65 | 0.59863 |
3a8db392d868fdfac160412447f43a902b920d17 | 554 | //
// Nuke+.swift
// BOKiN
//
// Created by arabian9ts on 2018/11/21.
// Copyright © 2018 RedBottleCoffee. All rights reserved.
//
import Nuke
import UIKit
func loadImageWithNuke(url: String, imageView: UIImageView) {
let options = ImageLoadingOptions(
placeholder: UIImage(named: "placeholder"),
transition: .fadeIn(duration: 0.33)
)
Nuke.loadImage(
with: URL(string: url) ?? URL(string: "https://haginoryokkou.com/wp-content/uploads/2016/09/noimage.png")!,
options: options,
into: imageView)
}
| 25.181818 | 115 | 0.662455 |
5065d974695f9726567db17d7245fb3f21ad9863 | 2,013 | //
// CheckAuthEmailService.swift
// Storizy-iOS
//
// Created by 임수정 on 2021/11/12.
//
import Foundation
import Alamofire
struct CheckAuthEmailService {
static let shared = CheckAuthEmailService()
func checkAuthEmail(_ body: [String: String], completionHandler: @escaping (ResponseCode, Any) -> (Void)) {
let url = APIUrls.getAuthEmailURL
let header: HTTPHeaders = [ "Content-Type":"application/json"]
let dataRequest = AF.request(url,
method: .post,
parameters: body,
encoding: JSONEncoding.default,
headers: header)
dataRequest.responseData { (response) in
switch response.result {
case .success:
guard let status = response.response?.statusCode else { return }
guard let body = response.value else { return }
let str = String(decoding: body, as: UTF8.self)
print(str)
print(response.request)
// 상태 코드 처리
var responseCode: ResponseCode = .success
if status == 201 {
print("인증 번호 확인 성공")
responseCode = .success
} else {
print("인증 번호 확인 실패")
print(body)
print(status)
responseCode = .serverError
}
// response body 파싱
let decoder = JSONDecoder()
guard let responseBody = try? decoder.decode(ResponseData<String>.self, from: body) else { return }
// 응답 결과 전송
completionHandler(responseCode, responseBody)
case .failure(let error):
print(error)
completionHandler(.requestError, "request fail")
}
}
}
}
| 33 | 115 | 0.484848 |
56ad3ee35e2c0badad9ac9587223f27ff1471146 | 2,720 | //
// SearchViewController.swift
// GithubAPI
//
// Created by Jean-Baptiste Dominguez on 2019/10/28.
// Copyright © 2019 Jean-Baptiste Dominguez. All rights reserved.
//
import UIKit
class SearchViewController: UITableViewController {
var presenter: SearchPresenter?
private let _searchDebounce: Debounce = Debounce(minimumDelay: 0.5)
private let _cellId: String = "cellId"
private var _items: [RepoData]? {
didSet {
tableView.reloadData()
}
}
deinit {
#if DEBUG
print("deinit SearchViewController")
#endif
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
title = "Github Repository"
// Setup UI Search
let searchVC = UISearchController()
searchVC.searchBar.placeholder = "Search repository"
searchVC.searchResultsUpdater = self
navigationItem.searchController = searchVC
// Setup UI Table
tableView.register(UITableViewCell.self, forCellReuseIdentifier: _cellId)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _items?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: _cellId, for: indexPath)
if let item = _items?[indexPath.row] {
cell.textLabel?.text = item.name + " owned by " + item.owner.username
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension SearchViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
if let value = searchController.searchBar.text, value.count > 0 {
_searchDebounce.debounce { [weak self] in
self?.presenter?.updateSearchResults(value)
}
}
}
}
extension SearchViewController: SearchViewControllerDelegate {
func showSearchResults(_ results: [RepoData]) {
_items = results
}
func showError(_ title: String, message: String) {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Dismiss", style: .default))
present(alertVC, animated: true)
}
}
| 29.247312 | 109 | 0.642279 |
7aa331dee2092496fc93539235186ff8b18e5132 | 1,144 | //
import Foundation
//
import Foundation
import UInt256
fileprivate let Parameters = (
P: UInt256([0, UInt64.max, UInt64.max - 1, UInt64.max]),
a: UInt256([0, UInt64.max, UInt64.max - 1, UInt64.max - 3]),
b: UInt256([0, 0x64210519E59C80E7, 0x0FA7E9AB72243049, 0xFEB8DEECC146B9B1]),
G: (
x: UInt256([0, 0x188DA80EB03090F6, 0x7CBF20EB43A18800, 0xF4FF0AFD82FF1012]),
y: UInt256([0, 0x07192B95FFC8DA78, 0x631011ED6B24CDD5, 0x73F977A11E794811])
),
n: UInt256([0, UInt64.max, 0xFFFFFFFF99DEF836, 0x146BC9B1B4D22831])
)
public struct Secp192r1: EllipticCurveOverFiniteField {
public struct FFInt: FiniteFieldInteger {
public static var Characteristic: UInt256 = Parameters.P
public var value: UInt256
public init() {
value = 0
}
}
public static var Generator = Secp192r1(withCoordinates: Parameters.G)
public static var Order: UInt256 = Parameters.n
public static var a = FFInt(Parameters.a)
public static var b = FFInt(Parameters.b)
public var x: FFInt
public var y: FFInt?
public init() {
x = 0
}
}
| 22.88 | 84 | 0.663462 |
23cf3124eafdcfa472954400fe7a97735cc50135 | 7,007 | //
// BusinessesViewController.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Contributed by Pann Cherry 9/23/2018.
// Copyright (c) 2015 Timothy Lee and Pann Cherry. All rights reserved.
//
import UIKit
import MapKit
import AFNetworking
var allBusiness: [Business] = []
class BusinessesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UIScrollViewDelegate, FilterViewControllerDelegate{
var businesses: [Business]!
var filteredBusiness: [Business] = []
var loadingMoreViews: InfiniteScrollActivityView?
var isMoreDataLoading = false
var offset = 0
var term: String = "Restraunts"
var category: String = "All"
var refreshControl: UIRefreshControl!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(BusinessesViewController.didPullToRefresh(_:)), for: UIControl.Event.valueChanged)
tableView.insertSubview(refreshControl, at: 0)
let frame = CGRect(x: 0, y: tableView.contentSize.height, width: tableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight)
loadingMoreViews = InfiniteScrollActivityView(frame: frame)
loadingMoreViews!.isHidden = true
tableView.addSubview(loadingMoreViews!)
var insets = tableView.contentInset
insets.bottom += InfiniteScrollActivityView.defaultHeight
tableView.contentInset = insets
getBusinesses(forTerm: term, at: offset, categories: category)
/* Example of Yelp search with more search options specified
Business.searchWithTerm(term: "Restaurants", sort: .distance, categories: ["asianfusion", "burgers"]) { (businesses, error) in
self.businesses = businesses
for business in self.businesses {
print(business.name!)
print(business.address!)
}
}
*/
}
func getBusinesses(forTerm term: String, at offset: Int, categories category: String){
Business.searchWithTerm(term: term, offset: offset, category: [category], completion: { (businesses: [Business]?, error: Error?) -> Void in
if let businesses = businesses, businesses.count != 0 {
if offset == 0 {
self.businesses = businesses
}
else {
self.businesses += businesses
}
self.filteredBusiness = businesses
}
self.tableView.reloadData()
self.isMoreDataLoading = false
})
self.refreshControl.endRefreshing()
}
//code to fetch photos when pull to refresh
@objc func didPullToRefresh(_ refreshControl: UIRefreshControl) {
getBusinesses(forTerm: term, at: offset, categories: category)
}
//code to load more data
func loadMoreData() {
offset += businesses.count
Business.searchWithTerm(term: term, offset: offset, category: [category], completion: { (businesses: [Business]?, error: Error?) -> Void in
if self.isMoreDataLoading {
self.businesses = self.businesses + businesses!
} else {
self.businesses = businesses
}
self.isMoreDataLoading = false
self.loadingMoreViews!.stopAnimating()
self.tableView.reloadData()
if let businesses = businesses {
for business in businesses {
print(business.name!)
print(business.address!)
}
}
}
)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if businesses != nil {
return businesses!.count
}else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell
cell.business = businesses[indexPath.row]
return cell
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
businesses = searchText.isEmpty ? filteredBusiness : filteredBusiness.filter({ businesses -> Bool in
let dataString = businesses.name
return dataString?.lowercased().range(of: searchText.lowercased()) != nil
})
tableView.reloadData()
}
//code to display more posts when scrolling
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (!isMoreDataLoading) {
let scrollViewContentHeight = tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height
if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging) {
isMoreDataLoading = true
let frame = CGRect(x: 0, y: tableView.contentSize.height, width: tableView.bounds.size.width, height: InfiniteScrollActivityView.defaultHeight)
loadingMoreViews?.frame = frame
loadMoreData()
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
if let indexPath = tableView.indexPath(for: cell){
let business = businesses[indexPath.row]
let businessesDetailsViewController = segue.destination as! BusinessesDetailViewController
businessesDetailsViewController.business = business
}
}
/*
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navigationController = segue.destination as! UINavigationController
let filtersViewController = navigationController.topViewController as! FilterViewController
filtersViewController.delegate = self
}
func filterViewController(filterViewConfroller: FilterViewController, didUpdateFilters filters: [String : AnyObject]) {
var categories = filters["categories"] as? [String]
Business.searchWithTerm(term: "Restraunts", categories: categories){(businesses:[Business]!, error: NSError) -> Void in
self.businesses = businesses
self.tableView.reloadData()
}
}*/
}
| 39.8125 | 166 | 0.646354 |
ccda98d022fa704ac355bc6f81ba5b56ad404ad0 | 2,018 | import Foundation
func citeste()->[Float]//vector
{
print("a = ")
let s_o_a = readLine() //string, optional, variabila a
if let s_a = s_o_a{
let f_o_a = Float(s_a) //float, optional, a
if let f_a = f_o_a{
print("b = ")
let s_o_b = readLine() //string, optional, variabila a
if let s_b = s_o_b{
let f_o_b = Float(s_b) //float, optional, a
if let f_b = f_o_b{
print("c = ")
let s_o_c = readLine() //string, optional, variabila a
if let s_c = s_o_c{
let f_o_c = Float(s_c) //float, optional, a
if let f_c = f_o_c{
return[f_a, f_b, f_c]
}
else{
return[1, 2, 1]
}
}
else{
return[1, 2, 1]
}
}
else{
return[1, 2, 1]
}
}
else{
return[1, 2, 1]
}
}
else{
return[1, 2, 1]
}
}
else{
return[1, 2, 1]
}
}
func calculeaza(_ coef: [Float], _ x1: inout [Float], _ x2: inout [Float])
{
print("a = \(coef[0]) b = \(coef[1]) c = \(coef[2])")
let delta = coef[1] * coef[1] - 4 * coef[0] * coef[2]
if delta >= 0 {
x1.append ( (-coef[1] - sqrt(delta)/(2 * coef[0])))
x2.append ( (-coef[1] + sqrt(delta)/(2 * coef[0])))
x1.append ( 0)
x2.append ( 0)
}
else{
x1.append( -coef[1]/(2 * coef[0]))
x2.append( -coef[1]/(2 * coef[0]))
x1.append( -sqrt(-delta) / (2 * coef[0]))
x2.append( sqrt(-delta) / (2 * coef[0]))
}
}
func tipareste(_ x1: [Float], _ x2: [Float])
{
print("x1 = \(x1[0]) + \(x1[1])i")
print("x2 = \(x2[0]) + \(x2[1])i")
}
func tipareste_vector(_ v: [Float])
{
/*
for i in v {
print(i)
}
*/
/*
var i = 0
while (i < 3)
{
print(v[i])
i += 1
}
*/
var i = 0
repeat{
print(v[i])
i += 1
} while i<3
}
var x1 = [Float]()
var x2 = [Float]()
var coef = citeste()
tipareste_vector(coef)
calculeaza(coef, &x1, &x2)
tipareste(x1, x2)
| 19.784314 | 74 | 0.465312 |
d9a87a8edd7c73c54b2f091e95bea800db397b68 | 11,085 | //
// persoDataVC.swift
// RGPD
//
// Created by Thibault Deprez on 23/05/2018.
// Copyright © 2018 Thibault Deprez. All rights reserved.
//
import UIKit
class persoDataVC: UIViewController {
@IBOutlet weak var nextBtn: UIButton!
@IBOutlet weak var checkBackground: UIView!
@IBOutlet weak var checkImg: UIImageView!
@IBOutlet weak var descriptionLbl: UITextView!
@IBOutlet weak var titleView: UIView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var iconImg: UIImageView!
@IBOutlet weak var backBtn: UIButton!
@IBOutlet weak var iconView: UIView!
@IBOutlet weak var checkView: UIView!
@IBOutlet weak var descriptionView: UIView!
@IBOutlet weak var backImg: UIImageView!
@IBOutlet weak var backView: UIView!
private var checked = false
private var theme : RGPDStylePage!
@IBOutlet weak var backgroundView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
for item in RGPD.shared.theme.pages {
if item.pageName == RGPDPages.private_data.rawValue {
self.theme = item
}
}
descriptionLbl.text = RGPD.shared.texts.private_data
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
setView()
}
func setView() {
if theme.backgroundColor.count == 1 {
backgroundView.backgroundColor = colorGenerator.oneColor(theme.backgroundColor[0])
} else {
let layer = colorGenerator.gradient(theme.backgroundColor)
layer.frame = backgroundView.bounds
backgroundView.layer.insertSublayer(layer, at: 0)
}
if RGPD.shared.pagesShown.count == 1 {
nextBtn.setTitle("Valider", for: .normal)
}
checkBackground.layer.masksToBounds = true
nextBtn.layer.masksToBounds = true
iconImg.layer.masksToBounds = true
if theme.titleColor.count == 1 {
titleLbl.textColor = colorGenerator.oneColor(theme.titleColor[0])
} else {
let layer = colorGenerator.gradient(theme.titleColor)
layer.frame = titleView.bounds
titleView.layer.insertSublayer(layer, at: 0)
titleView.mask = titleLbl
}
if theme.iconColor.count == 1 {
iconImg.tintColor = colorGenerator.oneColor(theme.iconColor[0])
} else {
let layer = colorGenerator.gradient(theme.iconColor)
layer.frame = iconView.bounds
iconView.layer.insertSublayer(layer, at: 0)
iconView.mask = iconImg
}
if theme.checkColor.count == 1 {
checkImg.tintColor = colorGenerator.oneColor(theme.checkColor[0])
} else {
let layer = colorGenerator.gradient(theme.checkColor)
layer.frame = checkView.bounds
checkView.layer.insertSublayer(layer, at: 0)
checkView.mask = checkImg
}
if theme.textColor.count == 1 {
descriptionLbl.textColor = colorGenerator.oneColor(theme.textColor[0])
} else {
let layer = colorGenerator.gradient(theme.textColor)
layer.frame = descriptionView.bounds
descriptionView.layer.insertSublayer(layer, at: 0)
descriptionView.mask = descriptionLbl
}
if theme.backButtonColor.count == 1 {
backImg.tintColor = colorGenerator.oneColor(theme.backButtonColor[0])
} else {
let layer = colorGenerator.gradient(theme.backButtonColor)
layer.frame = backView.bounds
backView.layer.insertSublayer(layer, at: 0)
backView.mask = backImg
}
if checked {
if theme.fullButtonTextColor.count == 1 {
nextBtn.setTitleColor(colorGenerator.oneColor(theme.fullButtonTextColor[0]), for: .normal)
} else {
nextBtn.setTitleColor(UIColor.white, for: .normal)
}
nextBtn.isEnabled = true
if let array = nextBtn.layer.sublayers {
for item in array {
if item is CAGradientLayer || item is CAShapeLayer {
item.removeFromSuperlayer()
}
}
}
if let array = checkBackground.layer.sublayers {
for item in array {
if item is CAGradientLayer || item is CAShapeLayer {
item.removeFromSuperlayer()
}
}
}
checkImg.isHidden = false
if theme.fullCircleColor.count == 1 {
checkBackground.backgroundColor = colorGenerator.oneColor(theme.fullCircleColor[0])
checkBackground.layer.borderWidth = 0
} else {
checkBackground.layer.borderWidth = 0
let layer = colorGenerator.gradient(theme.fullCircleColor)
layer.frame = checkBackground.bounds
checkBackground.layer.insertSublayer(layer, at: 0)
}
if theme.fullButtonColor.count == 1 {
nextBtn.layer.borderWidth = 0
nextBtn.backgroundColor = colorGenerator.oneColor(theme.fullButtonColor[0])
} else {
nextBtn.layer.borderWidth = 0
let layer = colorGenerator.gradient(theme.fullButtonColor)
layer.frame = nextBtn.bounds
nextBtn.layer.insertSublayer(layer, at: 0)
}
} else {
if theme.emptyButtonTextColor.count == 1 {
nextBtn.setTitleColor(colorGenerator.oneColor(theme.emptyButtonTextColor[0]), for: .normal)
} else {
nextBtn.setTitleColor(UIColor.white, for: .normal)
}
nextBtn.isEnabled = false
if let array = nextBtn.layer.sublayers {
for item in array {
if item is CAGradientLayer || item is CAShapeLayer {
item.removeFromSuperlayer()
}
}
}
if let array = checkBackground.layer.sublayers {
for item in array {
if item is CAGradientLayer || item is CAShapeLayer {
item.removeFromSuperlayer()
}
}
}
checkImg.isHidden = true
if theme.emptyCircleColor.count == 1 {
checkBackground.backgroundColor = nil
checkBackground.layer.borderColor = colorGenerator.oneColor(theme.emptyCircleColor[0]).cgColor
checkBackground.layer.borderWidth = 1.0
} else {
// let layer = colorGenerator.gradient(theme.emptyCircleColor)
// layer.frame = checkBackground.bounds
// checkBackground.layer.insertSublayer(layer, at: 0)
checkBackground.backgroundColor = nil
var colors = [UIColor]()
for item in theme.emptyCircleColor {
colors.append(colorGenerator.oneColor(item))
}
checkBackground.setGradientBorder(width: 1, colors: colors)
}
if theme.emptyButtonColor.count == 1 {
nextBtn.backgroundColor = nil
nextBtn.layer.borderWidth = 1
nextBtn.layer.borderColor = colorGenerator.oneColor(theme.emptyButtonColor[0]).cgColor
} else {
nextBtn.backgroundColor = nil
let gradient = colorGenerator.gradient(theme.emptyButtonColor)
gradient.frame = nextBtn.bounds
let shape = CAShapeLayer()
shape.lineWidth = 1
shape.path = UIBezierPath(roundedRect: nextBtn.bounds, cornerRadius: 8).cgPath
shape.strokeColor = UIColor.black.cgColor
shape.fillColor = UIColor.clear.cgColor
gradient.mask = shape
nextBtn.layer.addSublayer(gradient)
// let layer = colorGenerator.gradient(theme.emptyButtonColor)
// layer.frame = nextBtn.bounds
// nextBtn.layer.insertSublayer(layer, at: 0)
}
}
}
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.
}
*/
@IBAction func AcceptedTapped(_ sender: Any) {
checked = !checked
setView()
}
@IBAction func ContinueTapped(_ sender: Any) {
if RGPD.shared.pagesShown.first == .private_data {
RGPD.shared.pagesAccepted.append(RGPD.shared.pagesShown.removeFirst())
}
if (RGPD.shared.pagesShown.count == 0) {
var str = "["
for i in 0..<RGPD.shared.pagesAccepted.count {
str += "\(i == 0 ? "" : ", ")\"\(RGPD.shared.pagesAccepted[i].rawValue)\""
}
str += "]"
Webservice.updateUserAuthorizations(authKeysString: str, completion: { data in
self.dismiss(animated: true, completion: nil)
guard let data = data else {
return
}
do {
let decoder = JSONDecoder()
let tmp = try decoder.decode(addUserAnswer.self, from: data)
print("RGPD POD Return from updateUserWebservice : \(tmp)")
} catch {
print(error)
// handle error
}
});
} else {
let storyboard = UIStoryboard(name: "main", bundle: Bundle(for: RGPD.self))
let nextPage = RGPD.shared.pagesShown.first
let controller = storyboard.instantiateViewController(withIdentifier: nextPage!.rawValue)
self.navigationController?.pushViewController(controller, animated: true)
}
}
@IBAction func backPressed(_ sender: Any) {
if RGPD.shared.pagesAccepted.contains(.private_data) {
RGPD.shared.pagesShown.insert(RGPD.shared.pagesAccepted.remove(at: RGPD.shared.pagesAccepted.firstIndex(of: .private_data)!), at: 0)
}
self.navigationController?.popViewController(animated: true)
}
}
| 39.448399 | 144 | 0.560668 |
1a7363effc0d4c37e4b870085c2320b18b529025 | 2,464 | //
// ViewController.swift
// MapSearch
//
// Created by Ian on 5/9/16.
// Copyright © 2016 ianchengtw_ios_30_apps_in_30_days. All rights reserved.
//
import UIKit
import GoogleMaps
class ViewController: UIViewController, UISearchBarDelegate, LocateOnTheMap
{
@IBOutlet weak var mapViewContainer: UIView!
var mapView: GMSMapView!
var searchResultController = SearchResultController()
var resultsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.mapView = GMSMapView(frame: self.mapViewContainer.frame)
self.view.addSubview(self.mapView)
self.searchResultController.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func searchWithAddress(sender: UIBarButtonItem) {
let searchController = UISearchController(searchResultsController: self.searchResultController)
searchController.searchBar.delegate = self
self.presentViewController(searchController, animated: true, completion: nil)
}
func locateWithLongitude(location: CLLocationCoordinate2D, bounds: GMSCoordinateBounds, title: String) {
dispatch_async(dispatch_get_main_queue()) {
guard let camera = self.mapView.cameraForBounds(bounds, insets: UIEdgeInsetsZero) else { return }
self.mapView.clear()
self.mapView.camera = camera
let marker = GMSMarker(position: location)
marker.title = title
marker.map = self.mapView
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let placeClient = GMSPlacesClient()
placeClient.autocompleteQuery(searchText, bounds: nil, filter: nil) { (results, error: NSError?) -> Void in
self.resultsArray.removeAll()
guard let results = results else { return }
for result in results {
self.resultsArray.append(result.attributedFullText.string)
}
self.searchResultController.reloadDataWithArray(self.resultsArray)
}
}
}
| 29.686747 | 115 | 0.634334 |
fb9fe9cce45951a15802913cd3f6f37711a33840 | 2,261 | import Foundation
/**
A response that contains a single Workflows resource.
Full documentation:
<https://developer.apple.com/documentation/appstoreconnectapi/ciworkflowresponse>
*/
public struct CiWorkflowResponse: Codable {
/// The resource data.
public let data: CiWorkflow
/// The included related resources.
@NullCodable public var included: [Included]?
/// Navigational links that include the self-link.
public let links: DocumentLinks
public init(data: CiWorkflow, included: [Included]? = nil, links: DocumentLinks) {
self.data = data
self.included = included
self.links = links
}
public enum Included: Codable {
case ciMacOsVersion(CiMacOsVersion)
case ciProduct(CiProduct)
case ciXcodeVersion(CiXcodeVersion)
case scmRepository(ScmRepository)
public init(from decoder: Decoder) throws {
if let ciMacOsVersion = try? CiMacOsVersion(from: decoder) {
self = .ciMacOsVersion(ciMacOsVersion)
} else if let ciProduct = try? CiProduct(from: decoder) {
self = .ciProduct(ciProduct)
} else if let ciXcodeVersion = try? CiXcodeVersion(from: decoder) {
self = .ciXcodeVersion(ciXcodeVersion)
} else if let scmRepository = try? ScmRepository(from: decoder) {
self = .scmRepository(scmRepository)
} else {
throw DecodingError.typeMismatch(Included.self, DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Unknown Included"))
}
}
public func encode(to encoder: Encoder) throws {
switch self {
case let .ciMacOsVersion(value):
try value.encode(to: encoder)
case let .ciProduct(value):
try value.encode(to: encoder)
case let .ciXcodeVersion(value):
try value.encode(to: encoder)
case let .scmRepository(value):
try value.encode(to: encoder)
}
}
private enum CodingKeys: String, CodingKey {
case type
}
}
}
| 36.467742 | 124 | 0.59487 |
61406eac99a202420b66aaf7a14b78a2ee935e43 | 5,142 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
protocol MatrixItemChooserDataSource {
func sections(with session: MXSession, completion: @escaping (Result<[MatrixListItemSectionData], Error>) -> Void)
var preselectedItemIds: Set<String>? { get }
}
protocol MatrixItemChooserProcessorProtocol {
var loadingText: String? { get }
var dataSource: MatrixItemChooserDataSource { get }
func computeSelection(withIds itemsIds:[String], completion: @escaping (Result<Void, Error>) -> Void)
func isItemIncluded(_ item: (MatrixListItemData)) -> Bool
}
@available(iOS 14.0, *)
class MatrixItemChooserService: MatrixItemChooserServiceProtocol {
// MARK: - Properties
// MARK: Private
private let processingQueue = DispatchQueue(label: "io.element.MatrixItemChooserService.processingQueue")
private let completionQueue = DispatchQueue.main
private let session: MXSession
private var sections: [MatrixListItemSectionData] = []
private var filteredSections: [MatrixListItemSectionData] = [] {
didSet {
sectionsSubject.send(filteredSections)
}
}
private var selectedItemIds: Set<String>
private let itemsProcessor: MatrixItemChooserProcessorProtocol
// MARK: Public
private(set) var sectionsSubject: CurrentValueSubject<[MatrixListItemSectionData], Never>
private(set) var selectedItemIdsSubject: CurrentValueSubject<Set<String>, Never>
var searchText: String = "" {
didSet {
refresh()
}
}
var loadingText: String? {
itemsProcessor.loadingText
}
// MARK: - Setup
init(session: MXSession, selectedItemIds: [String], itemsProcessor: MatrixItemChooserProcessorProtocol) {
self.session = session
self.sectionsSubject = CurrentValueSubject(self.sections)
self.selectedItemIds = Set(selectedItemIds)
self.selectedItemIdsSubject = CurrentValueSubject(self.selectedItemIds)
self.itemsProcessor = itemsProcessor
itemsProcessor.dataSource.sections(with: session) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let sections):
self.sections = sections
self.refresh()
if let preselectedItemIds = itemsProcessor.dataSource.preselectedItemIds {
for itemId in preselectedItemIds {
self.selectedItemIds.insert(itemId)
}
self.selectedItemIdsSubject.send(self.selectedItemIds)
}
case .failure(let error):
break
}
}
refresh()
}
// MARK: - Public
func reverseSelectionForItem(withId itemId: String) {
if selectedItemIds.contains(itemId) {
selectedItemIds.remove(itemId)
} else {
selectedItemIds.insert(itemId)
}
selectedItemIdsSubject.send(selectedItemIds)
}
func processSelection(completion: @escaping (Result<Void, Error>) -> Void) {
itemsProcessor.computeSelection(withIds: Array(selectedItemIds), completion: completion)
}
func refresh() {
self.processingQueue.async { [weak self] in
guard let self = self else { return }
let filteredSections = self.filter(sections: self.sections)
self.completionQueue.async {
self.filteredSections = filteredSections
}
}
}
// MARK: - Private
private func filter(sections: [MatrixListItemSectionData]) -> [MatrixListItemSectionData] {
var newSections: [MatrixListItemSectionData] = []
for section in sections {
let items: [MatrixListItemData]
if searchText.isEmpty {
items = section.items.filter {
itemsProcessor.isItemIncluded($0)
}
} else {
let lowercasedSearchText = self.searchText.lowercased()
items = section.items.filter {
itemsProcessor.isItemIncluded($0) && ($0.id.lowercased().contains(lowercasedSearchText) || ($0.displayName ?? "").lowercased().contains(lowercasedSearchText))
}
}
newSections.append(MatrixListItemSectionData(id: section.id, title: section.title, infoText: section.infoText, items: items))
}
return newSections
}
}
| 35.462069 | 178 | 0.639245 |
e432d289fa2d4d88680f6bd95a9bc4b95fff1700 | 4,482 | //
// OppDetailsViewController.swift
// VolunteeringManager
//
// Created by Julie Wei on 10/14/21.
//
import UIKit
class OppDetailsViewController: UIViewController {
@IBOutlet weak var labelOppTitle: UILabel!
@IBOutlet weak var labelOrgName: UILabel!
@IBOutlet weak var labelOppDetails: UILabel!
@IBOutlet weak var btnFavorite: UIButton!
@IBOutlet weak var labelVirtual: UILabel!
@IBOutlet weak var labelTimeZone: UILabel!
@IBOutlet weak var labelState: UILabel!
@IBOutlet weak var labelZipCode: UILabel!
var textOppTitle = ""
var textOppDetails = ""
var textOrgName = ""
var bFavorite = false
var bVirtual = false
var textTimeZone = ""
var textState = ""
var textZipCode = ""
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = false
self.tabBarController?.tabBar.isHidden = true
labelOppTitle.text = textOppTitle
labelOppDetails.text = textOppDetails
labelOrgName.text = textOrgName
if bVirtual {
labelVirtual.attributedText = makeAttributedString(title: labelVirtual.text!, subtitle: "Yes")
} else {
labelVirtual.attributedText = makeAttributedString(title: labelVirtual.text!, subtitle: "No")
}
labelTimeZone.attributedText = makeAttributedString(title: labelTimeZone.text!, subtitle: textTimeZone)
labelState.attributedText = makeAttributedString(title: labelState.text!, subtitle: textState)
labelZipCode.attributedText = makeAttributedString(title: labelZipCode.text!, subtitle: textZipCode)
if bFavorite {
if let image = UIImage(systemName: "heart.fill") {
btnFavorite.setImage(image, for: .normal)
}
} else {
if let image = UIImage(systemName: "heart") {
btnFavorite.setImage(image, for: .normal)
}
}
}
// Track if the favorite is changed for this opp
@IBAction func BtnFavoriteClicked(_ sender: Any) {
bFavorite.toggle()
bFavoriteChanged = (bFavoriteOriginal != bFavorite)
if bFavorite {
if let image = UIImage(systemName: "heart.fill") {
btnFavorite.setImage(image, for: .normal)
}
} else {
if let image = UIImage(systemName: "heart") {
btnFavorite.setImage(image, for: .normal)
}
}
}
@IBAction func BtnInquiryClicked(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let viewcontroller = storyboard.instantiateViewController(identifier: "InquiryViewController")
as? InquiryViewController {
viewcontroller.bInquiry = 0
self.navigationController?.pushViewController(viewcontroller, animated: false)
}
}
@IBAction func BtnApplyClicked(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let viewcontroller = storyboard.instantiateViewController(identifier: "InquiryViewController")
as? InquiryViewController {
viewcontroller.bInquiry = 1
self.navigationController?.pushViewController(viewcontroller, animated: false)
}
}
@IBAction func BtnLogActivityClicked(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let viewcontroller = storyboard.instantiateViewController(identifier: "InquiryViewController")
as? InquiryViewController {
viewcontroller.bInquiry = 2
self.navigationController?.pushViewController(viewcontroller, animated: false)
}
}
func makeAttributedString(title: String, subtitle: String) -> NSAttributedString {
let titleAttributes = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .headline), NSAttributedString.Key.foregroundColor: UIColor.purple]
let subtitleAttributes = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .subheadline)]
let titleString = NSMutableAttributedString(string: "\(title)", attributes: titleAttributes)
let subtitleString = NSAttributedString(string: subtitle, attributes: subtitleAttributes)
titleString.append(subtitleString)
return titleString
}
}
| 37.35 | 162 | 0.653057 |
f8fa720d68dd56e57893a8ed2d0145d63cdbbaaf | 1,147 | //
// WatchOS_3UITests.swift
// WatchOS_3UITests
//
// Created by ll on 2019/6/7.
// Copyright © 2019 ll. All rights reserved.
//
import XCTest
class WatchOS_3UITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 32.771429 | 182 | 0.687881 |
16c2716162cac02c306f679c77b6b7ed8bd12ad1 | 922 | //
// CWTextMessageDispatchOperation.swift
// CWWeChat
//
// Created by chenwei on 2017/3/30.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
/// 文字消息直接发送
class CWTextMessageDispatchOperation: CWMessageDispatchOperation {
override func sendMessage() {
let toId = message.targetId
let messageId = message.messageId
let textBody = message.messageBody as! CWTextMessageBody
let content = textBody.text
let _ = self.messageTransmitter.sendMessage(content: content,
targetId: toId,
messageId: messageId,
chatType: message.chatType.rawValue,
type: message.messageType.rawValue)
}
}
| 31.793103 | 97 | 0.510846 |
2f1a3491ec9e798b1e4beed8252d316c9db0a243 | 592 | //
// PlaidAPI+Transactions.swift
// Bank
//
// Created by Ayden Panhuyzen on 2017-12-02.
// Copyright © 2017 Ayden Panhuyzen. All rights reserved.
//
import Foundation
extension PlaidAPI {
func getTransactions(completionHandler: @escaping ([Transaction]?, [Account]?, Error?) -> Void) {
makeAuthedRequest(to: "transactions/get", body: ["start_date": "2000-01-01", "end_date": "9999-12-31", "options": ["count": 500]], type: TransactionsResponse.self) { (response, error) in
completionHandler(response?.transactions, response?.accounts, error)
}
}
}
| 32.888889 | 194 | 0.672297 |
acce8593aa6791c813599154d5d254daf9e8391c | 3,070 | //
// ShareViewController.swift
// Latergram
//
// Created by Satyam Jaiswal on 3/16/17.
// Copyright © 2017 Satyam Jaiswal. All rights reserved.
//
import UIKit
import Parse
import SVProgressHUD
protocol NewPostDelegate {
func onNewPostShare(newPost: Post) -> Void
}
class ShareViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var captionTextView: UITextView!
@IBOutlet weak var locationTextField: UITextField!
var captionPlaceholderLabel = UILabel()
var shareImage: UIImage?
var delegate: NewPostDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func setupUI(){
self.configureTextView()
if let image = self.shareImage{
self.postImageView.image = image
}
}
fileprivate func configureTextView(){
self.captionTextView.delegate = self
self.captionTextView.text = ""
self.captionPlaceholderLabel.text = "Add a caption"
self.captionPlaceholderLabel.font = UIFont.italicSystemFont(ofSize: (self.captionTextView.font?.pointSize)!)
self.captionPlaceholderLabel.sizeToFit()
self.captionPlaceholderLabel.textColor = UIColor(white: 0, alpha: 0.3)
self.captionPlaceholderLabel.frame.origin = CGPoint(x: 5, y: (self.captionTextView.font?.pointSize)!/2)
self.captionTextView.addSubview(self.captionPlaceholderLabel)
}
func textViewDidChange(_ textView: UITextView) {
self.captionPlaceholderLabel.isHidden = !textView.text.isEmpty
}
@IBAction func onShareButtonTapped(_ sender: Any) {
self.closeKeypad()
SVProgressHUD.show()
Post.createNewPost(picture: self.shareImage, caption: self.captionTextView.text, location: self.locationTextField.text ,success: { (response: PFObject) in
print("Posted successfully. Post ID: \(response.objectId)")
self.delegate?.onNewPostShare(newPost: Post(postPFPbject: response))
SVProgressHUD.dismiss()
self.dismiss(animated: true, completion: nil)
}) { (error: Error) in
print(error.localizedDescription)
SVProgressHUD.dismiss()
}
}
fileprivate func closeKeypad(){
self.captionTextView.resignFirstResponder()
self.locationTextField.resignFirstResponder()
}
@IBAction func onBackgroundTapped(_ sender: Any) {
self.closeKeypad()
}
/*
// 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.
}
*/
}
| 33.010753 | 162 | 0.677524 |
d7cad2e3b6f52e1b8a1890e796b497726432a747 | 1,429 | // Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
import UIKit
class DynamicTableViewIconCell: UITableViewCell {
// MARK: - Overrides
override func awakeFromNib() {
super.awakeFromNib()
imageView?.tintColor = tintColor
}
// MARK: - Internal
func configure(image: UIImage?, text: String, tintColor: UIColor?, style: ENAFont = .body, iconWidth: CGFloat) {
if let tintColor = tintColor {
imageView?.tintColor = tintColor
imageView?.image = image?.withRenderingMode(.alwaysTemplate)
} else {
imageView?.image = image?.withRenderingMode(.alwaysOriginal)
}
(textLabel as? ENALabel)?.style = style.labelStyle
textLabel?.text = text
imageViewWidthConstraint.constant = iconWidth
}
// MARK: - Private
@IBOutlet private weak var imageViewWidthConstraint: NSLayoutConstraint!
}
| 28.019608 | 113 | 0.739678 |
67fe41b6f744b86670d88b49afeed0ca059edeca | 21,460 | ////
// 🦠 Corona-Warn-App
//
import Foundation
import OpenCombine
protocol PPAnalyticsSubmitting {
/// Triggers the submission of all collected analytics data. Only if all checks success, the submission is done. Otherwise, the submission is aborted. The completion calls are passed through to test the component.
/// ⚠️ This method should ONLY be called by the PPAnalyticsCollector ⚠️
func triggerSubmitData(ppacToken: PPACToken?, completion: ((Result<Void, PPASError>) -> Void)?)
#if !RELEASE
/// ONLY FOR TESTING. Triggers for the dev menu a forced submission of the data, whithout any checks.
/// This method should only be called by the PPAnalyticsCollector
func forcedSubmitData(completion: @escaping (Result<Void, PPASError>) -> Void)
/// ONLY FOR TESTING. Return the constructed proto-file message to look into the data we would submit.
/// This method should only be called by the PPAnalyticsCollector
func getPPADataMessage() -> SAP_Internal_Ppdd_PPADataIOS
#endif
}
// swiftlint:disable:next type_body_length
final class PPAnalyticsSubmitter: PPAnalyticsSubmitting {
// MARK: - Init
init(
store: Store,
client: Client,
appConfig: AppConfigurationProviding,
coronaTestService: CoronaTestService
) {
guard let store = store as? (Store & PPAnalyticsData) else {
Log.error("I will never submit any analytics data. Could not cast to correct store protocol", log: .ppa)
fatalError("I will never submit any analytics data. Could not cast to correct store protocol")
}
self.store = store
self.client = client
self.submissionState = .readyForSubmission
self.configurationProvider = appConfig
self.coronaTestService = coronaTestService
}
// MARK: - Protocol PPAnalyticsSubmitting
func triggerSubmitData(
ppacToken: PPACToken? = nil,
completion: ((Result<Void, PPASError>) -> Void)? = nil
) {
Log.info("Analytics submission was triggered. Checking now if we can submit...", log: .ppa)
// Check if a submission is already in progress
guard submissionState == .readyForSubmission else {
Log.warning("Analytics submission abord due to submission is already in progress", log: .ppa)
completion?(.failure(.submissionInProgress))
return
}
submissionState = .submissionInProgress
// Check if user has given his consent to collect data
if userDeclinedAnalyticsCollectionConsent {
Log.warning("Analytics submission abord due to missing users consent", log: .ppa)
submissionState = .readyForSubmission
completion?(.failure(.userConsentError))
return
}
Log.debug("PPAnayticsSubmitter requesting AppConfig…", log: .ppa)
// Sink on the app configuration if something has changed. But do this in background.
self.configurationProvider.appConfiguration().sink { [ weak self] configuration in
Log.debug("PPAnayticsSubmitter recieved AppConfig", log: .ppa)
let ppaConfigData = configuration.privacyPreservingAnalyticsParameters.common
self?.probabilityToSubmitPPAUsageData = ppaConfigData.probabilityToSubmit
self?.hoursSinceTestResultToSubmitKeySubmissionMetadata = ppaConfigData.hoursSinceTestResultToSubmitKeySubmissionMetadata
self?.hoursSinceTestRegistrationToSubmitTestResultMetadata = ppaConfigData.hoursSinceTestRegistrationToSubmitTestResultMetadata
self?.probabilityToSubmitExposureWindows = ppaConfigData.probabilityToSubmitExposureWindows
guard let strongSelf = self else {
Log.warning("Analytics submission abord due fail at creating strong self", log: .ppa)
self?.submissionState = .readyForSubmission
completion?(.failure(.generalError))
return
}
// Check configuration parameter
let random = Double.random(in: 0...1)
if random > strongSelf.probabilityToSubmitPPAUsageData {
Log.warning("Analytics submission abord due to randomness. Random is: \(random), probabilityToSubmit is: \(strongSelf.probabilityToSubmitPPAUsageData)", log: .ppa)
strongSelf.submissionState = .readyForSubmission
completion?(.failure(.probibilityError))
return
}
// Last submission check
if strongSelf.submissionWithinLast23Hours {
Log.warning("Analytics submission abord due to submission last 23 hours", log: .ppa)
strongSelf.submissionState = .readyForSubmission
completion?(.failure(.submission23hoursError))
return
}
// Onboarding check
if strongSelf.onboardingCompletedWithinLast24Hours {
Log.warning("Analytics submission abord due to onboarding completed last 24 hours", log: .ppa)
strongSelf.submissionState = .readyForSubmission
completion?(.failure(.onboardingError))
return
}
// App Reset check
if strongSelf.appResetWithinLast24Hours {
Log.warning("Analytics submission abord due to app resetted last 24 hours", log: .ppa)
strongSelf.submissionState = .readyForSubmission
completion?(.failure(.appResetError))
return
}
if let token = ppacToken {
Log.info("Analytics submission has an injected ppac token.", log: .ppa)
strongSelf.submitData(with: token, completion: completion)
} else {
Log.info("Analytics submission needs to generate new ppac token.", log: .ppa)
strongSelf.generatePPACAndSubmitData(completion: completion)
}
}.store(in: &subscriptions)
}
#if !RELEASE
func forcedSubmitData(completion: @escaping (Result<Void, PPASError>) -> Void) {
generatePPACAndSubmitData(
disableExposureWindowsProbability: true,
completion: completion
)
}
func getPPADataMessage() -> SAP_Internal_Ppdd_PPADataIOS {
return obtainUsageData(disableExposureWindowsProbability: true)
}
#endif
// MARK: - Private
private let store: (Store & PPAnalyticsData)
private let client: Client
private let configurationProvider: AppConfigurationProviding
private let coronaTestService: CoronaTestService
private var submissionState: PPASubmissionState
private var subscriptions: Set<AnyCancellable> = []
private var probabilityToSubmitPPAUsageData: Double = 0
private var hoursSinceTestRegistrationToSubmitTestResultMetadata: Int32 = 0
private var probabilityToSubmitExposureWindows: Double = 0
private var hoursSinceTestResultToSubmitKeySubmissionMetadata: Int32 = 0
private var userDeclinedAnalyticsCollectionConsent: Bool {
return !store.isPrivacyPreservingAnalyticsConsentGiven
}
private var submissionWithinLast23Hours: Bool {
guard let lastSubmission = store.lastSubmissionAnalytics,
let twentyThreeHoursAgo = Calendar.current.date(byAdding: .hour, value: -23, to: Date()) else {
return false
}
let lastTwentyThreeHours = twentyThreeHoursAgo...Date()
return lastTwentyThreeHours.contains(lastSubmission)
}
private var onboardingCompletedWithinLast24Hours: Bool {
// why the date of acceptedPrivacyNotice? See https://github.com/corona-warn-app/cwa-app-tech-spec/pull/19#discussion_r572826236
guard let onbaordedDate = store.dateOfAcceptedPrivacyNotice,
let twentyFourHoursAgo = Calendar.current.date(byAdding: .hour, value: -24, to: Date()) else {
return false
}
let lastTwentyFourHours = twentyFourHoursAgo...Date()
return lastTwentyFourHours.contains(onbaordedDate)
}
private var appResetWithinLast24Hours: Bool {
guard let lastResetDate = store.lastAppReset,
let twentyFourHoursAgo = Calendar.current.date(byAdding: .hour, value: -24, to: Date()) else {
return false
}
let lastTwentyFourHours = twentyFourHoursAgo...Date()
return lastTwentyFourHours.contains(lastResetDate)
}
private var shouldIncludeKeySubmissionMetadata: Bool {
/* Conditions for submitting the data:
submitted is true
OR
- differenceBetweenTestResultAndCurrentDateInHours >= hoursSinceTestResultToSubmitKeySubmissionMetadata
*/
var isSubmitted = false
var timeDifferenceFulfillsCriteria = false
// if submitted is true
if store.keySubmissionMetadata?.submitted == true {
isSubmitted = true
} else {
isSubmitted = false
}
// if there is no test result time stamp
guard let testResultReceivedDate = coronaTestService.pcrTest?.finalTestResultReceivedDate else {
return isSubmitted
}
let differenceBetweenTestResultAndCurrentDate = Calendar.current.dateComponents([.hour], from: testResultReceivedDate, to: Date())
if let differenceBetweenTestResultAndCurrentDateInHours = differenceBetweenTestResultAndCurrentDate.hour,
differenceBetweenTestResultAndCurrentDateInHours >= hoursSinceTestResultToSubmitKeySubmissionMetadata {
timeDifferenceFulfillsCriteria = true
}
return isSubmitted || timeDifferenceFulfillsCriteria
}
private var shouldIncludeTestResultMetadata: Bool {
/* Conditions for submitting the data:
- testResult = positive
OR
- testResult = negative
OR
- differenceBetweenRegistrationAndCurrentDateInHours "Registration is stored In TestMetadata" >= hoursSinceTestRegistrationToSubmitTestResultMetadata "stored in appConfiguration"
*/
// If for some reason there is no registrationDate we should not submit the testMetadata
guard let registrationDate = store.testResultMetadata?.testRegistrationDate else {
return false
}
switch store.testResultMetadata?.testResult {
case .positive, .negative:
return true
default:
break
}
let differenceBetweenRegistrationAndCurrentDate = Calendar.current.dateComponents([.hour], from: registrationDate, to: Date())
if let differenceBetweenRegistrationAndCurrentDateInHours = differenceBetweenRegistrationAndCurrentDate.hour,
differenceBetweenRegistrationAndCurrentDateInHours >= hoursSinceTestRegistrationToSubmitTestResultMetadata {
return true
}
return false
}
private func generatePPACAndSubmitData(disableExposureWindowsProbability: Bool = false, completion: ((Result<Void, PPASError>) -> Void)? = nil) {
// Obtain authentication data
let deviceCheck = PPACDeviceCheck()
let ppacService = PPACService(store: self.store, deviceCheck: deviceCheck)
// Submit analytics data with generated ppac token
ppacService.getPPACToken { [weak self] result in
switch result {
case let .success(token):
Log.info("Succesfully created new ppac token to submit analytics data.", log: .ppa)
self?.submitData(with: token, disableExposureWindowsProbability: disableExposureWindowsProbability, completion: completion)
case let .failure(error):
Log.error("Could not submit analytics data due to ppac authorization error", log: .ppa, error: error)
self?.submissionState = .readyForSubmission
completion?(.failure(.ppacError(error)))
return
}
}
}
private func obtainUsageData(disableExposureWindowsProbability: Bool = false) -> SAP_Internal_Ppdd_PPADataIOS {
Log.info("Obtaining now all usage data for analytics submission...", log: .ppa)
let exposureRiskMetadata = gatherExposureRiskMetadata()
let userMetadata = gatherUserMetadata()
let clientMetadata = gatherClientMetadata()
let keySubmissionMetadata = gatherKeySubmissionMetadata()
let testResultMetadata = gatherTestResultMetadata()
let newExposureWindows = gatherNewExposureWindows()
let payload = SAP_Internal_Ppdd_PPADataIOS.with {
$0.exposureRiskMetadataSet = exposureRiskMetadata
$0.userMetadata = userMetadata
$0.clientMetadata = clientMetadata
$0.userMetadata = userMetadata
if shouldIncludeKeySubmissionMetadata {
$0.keySubmissionMetadataSet = keySubmissionMetadata
}
if shouldIncludeTestResultMetadata {
$0.testResultMetadataSet = testResultMetadata
}
/*
Exposure Windows are included in the next submission if:
- a generated random number between 0 and 1 is lower than or equal the value of Configuration Parameter .probabilityToSubmitExposureWindows.
- This shall be logged as warning.
*/
if disableExposureWindowsProbability {
$0.newExposureWindows = newExposureWindows
} else {
let randomProbability = Double.random(in: 0...1)
if randomProbability <= probabilityToSubmitExposureWindows {
$0.newExposureWindows = newExposureWindows
}
Log.warning("generated probability to submit New Exposure Windows: \(randomProbability)", log: .ppa)
Log.warning("configuration probability to submit New Exposure Windows: \(probabilityToSubmitExposureWindows)", log: .ppa)
}
}
return payload
}
private func submitData(with ppacToken: PPACToken, disableExposureWindowsProbability: Bool = false, completion: ((Result<Void, PPASError>) -> Void)? = nil) {
Log.info("All checks passed succesfully to submit ppa. Obtaining usage data right now...", log: .ppa)
let payload = obtainUsageData(disableExposureWindowsProbability: disableExposureWindowsProbability)
Log.info("Completed obtaining all usage data for analytics submission. Sending right now to server...", log: .ppa)
var forceApiTokenHeader = false
#if !RELEASE
forceApiTokenHeader = store.forceAPITokenAuthorization
#endif
#if DEBUG
if isUITesting {
Log.info("While UI Testing, we do not submit analytics data", log: .ppa)
submissionState = .readyForSubmission
completion?(.failure(.generalError))
return
}
#endif
client.submit(
payload: payload,
ppacToken: ppacToken,
isFake: false,
forceApiTokenHeader: forceApiTokenHeader,
completion: { [weak self] result in
switch result {
case .success:
Log.info("Analytics data succesfully submitted", log: .ppa)
// after succesful submission, store the current risk exposure metadata as the previous one to get the next time a comparison.
self?.store.previousRiskExposureMetadata = self?.store.currentRiskExposureMetadata
self?.store.currentRiskExposureMetadata = nil
if let shouldIncludeTestResultMetadata = self?.shouldIncludeTestResultMetadata, shouldIncludeTestResultMetadata {
self?.store.testResultMetadata = nil
}
if let shouldIncludeKeySubmissionMetadata = self?.shouldIncludeKeySubmissionMetadata, shouldIncludeKeySubmissionMetadata {
self?.store.keySubmissionMetadata = nil
}
self?.store.lastSubmittedPPAData = payload.textFormatString()
self?.store.exposureWindowsMetadata?.newExposureWindowsQueue.removeAll()
self?.store.lastSubmissionAnalytics = Date()
self?.submissionState = .readyForSubmission
completion?(result)
case let .failure(error):
Log.error("Analytics data were not submitted. Error: \(error)", log: .ppa, error: error)
self?.submissionState = .readyForSubmission
completion?(result)
}
}
)
}
func gatherExposureRiskMetadata() -> [SAP_Internal_Ppdd_ExposureRiskMetadata] {
guard let storedUsageData = store.currentRiskExposureMetadata else {
return []
}
return [SAP_Internal_Ppdd_ExposureRiskMetadata.with {
$0.riskLevel = storedUsageData.riskLevel.protobuf
$0.riskLevelChangedComparedToPreviousSubmission = storedUsageData.riskLevelChangedComparedToPreviousSubmission
$0.mostRecentDateAtRiskLevel = formatToUnixTimestamp(for: storedUsageData.mostRecentDateAtRiskLevel)
$0.dateChangedComparedToPreviousSubmission = storedUsageData.dateChangedComparedToPreviousSubmission
}]
}
func gatherNewExposureWindows() -> [SAP_Internal_Ppdd_PPANewExposureWindow] {
guard let exposureWindowsMetadata = store.exposureWindowsMetadata else {
return []
}
let exposureWindowsMetadataProto: [SAP_Internal_Ppdd_PPANewExposureWindow] = exposureWindowsMetadata.newExposureWindowsQueue.map { windowMetadata in
SAP_Internal_Ppdd_PPANewExposureWindow.with {
$0.normalizedTime = windowMetadata.normalizedTime
$0.transmissionRiskLevel = Int32(windowMetadata.transmissionRiskLevel)
$0.exposureWindow = SAP_Internal_Ppdd_PPAExposureWindow.with({ protobufWindow in
if let infectiousness = windowMetadata.exposureWindow.infectiousness.protobuf {
protobufWindow.infectiousness = infectiousness
}
if let reportType = windowMetadata.exposureWindow.reportType.protobuf {
protobufWindow.reportType = reportType
}
protobufWindow.calibrationConfidence = Int32(windowMetadata.exposureWindow.calibrationConfidence.rawValue)
protobufWindow.date = Int64(windowMetadata.date.timeIntervalSince1970)
protobufWindow.scanInstances = windowMetadata.exposureWindow.scanInstances.map({ scanInstance in
SAP_Internal_Ppdd_PPAExposureWindowScanInstance.with { protobufScanInstance in
protobufScanInstance.secondsSinceLastScan = Int32(scanInstance.secondsSinceLastScan)
protobufScanInstance.typicalAttenuation = Int32(scanInstance.typicalAttenuation)
protobufScanInstance.minAttenuation = Int32(scanInstance.minAttenuation)
}
})
})
}
}
return exposureWindowsMetadataProto
}
func gatherUserMetadata() -> SAP_Internal_Ppdd_PPAUserMetadata {
// According to the tech spec, grap the user metadata right before the submission. We do not use "Analytics.collect()" here because we are probably already inside this call. So if we would use the call here, we could produce a infinite loop.
store.userMetadata = store.userData
guard let storedUserData = store.userMetadata else {
return SAP_Internal_Ppdd_PPAUserMetadata.with { _ in }
}
return SAP_Internal_Ppdd_PPAUserMetadata.with {
if let federalState = storedUserData.federalState {
$0.federalState = federalState.protobuf
}
if let administrativeUnit = storedUserData.administrativeUnit {
$0.administrativeUnit = Int32(administrativeUnit)
}
if let ageGroup = storedUserData.ageGroup {
$0.ageGroup = ageGroup.protobuf
}
}
}
func gatherClientMetadata() -> SAP_Internal_Ppdd_PPAClientMetadataIOS {
// According to the tech spec, grap the client metadata right before the submission. We do not use "Analytics.collect()" here because we are probably already inside this call. So if we would use the call here, we could produce a infinite loop.
let eTag = store.appConfigMetadata?.lastAppConfigETag
store.clientMetadata = ClientMetadata(etag: eTag)
guard let clientData = store.clientMetadata else {
return SAP_Internal_Ppdd_PPAClientMetadataIOS.with { _ in }
}
return SAP_Internal_Ppdd_PPAClientMetadataIOS.with {
if let cwaVersion = clientData.cwaVersion {
$0.cwaVersion = cwaVersion.protobuf
}
if let eTag = clientData.eTag {
$0.appConfigEtag = eTag
}
$0.iosVersion = clientData.iosVersion.protobuf
}
}
// swiftlint:disable:next cyclomatic_complexity
func gatherKeySubmissionMetadata() -> [SAP_Internal_Ppdd_PPAKeySubmissionMetadata] {
guard let storedUsageData = store.keySubmissionMetadata else {
return []
}
return [SAP_Internal_Ppdd_PPAKeySubmissionMetadata.with {
if let submitted = storedUsageData.submitted {
$0.submitted = submitted
}
if let submittedInBackground = storedUsageData.submittedInBackground {
$0.submittedInBackground = submittedInBackground
}
if let submittedAfterCancel = storedUsageData.submittedAfterCancel {
$0.submittedAfterCancel = submittedAfterCancel
}
if let submittedAfterSymptomFlow = storedUsageData.submittedAfterSymptomFlow {
$0.submittedAfterSymptomFlow = submittedAfterSymptomFlow
}
if let advancedConsentGiven = storedUsageData.advancedConsentGiven {
$0.advancedConsentGiven = advancedConsentGiven
}
if let lastSubmissionFlowScreen = storedUsageData.lastSubmissionFlowScreen?.protobuf {
$0.lastSubmissionFlowScreen = lastSubmissionFlowScreen
}
if let hoursSinceTestResult = storedUsageData.hoursSinceTestResult {
$0.hoursSinceTestResult = hoursSinceTestResult
}
if let hoursSinceTestRegistration = storedUsageData.hoursSinceTestRegistration {
$0.hoursSinceTestRegistration = hoursSinceTestRegistration
}
if let daysSinceMostRecentDateAtRiskLevelAtTestRegistration = storedUsageData.daysSinceMostRecentDateAtRiskLevelAtTestRegistration {
$0.daysSinceMostRecentDateAtRiskLevelAtTestRegistration = daysSinceMostRecentDateAtRiskLevelAtTestRegistration
}
if let hoursSinceHighRiskWarningAtTestRegistration = storedUsageData.hoursSinceHighRiskWarningAtTestRegistration {
$0.hoursSinceHighRiskWarningAtTestRegistration = hoursSinceHighRiskWarningAtTestRegistration
}
$0.submittedWithTeleTan = !store.submittedWithQR
}]
}
func gatherTestResultMetadata() -> [SAP_Internal_Ppdd_PPATestResultMetadata] {
let metadata = store.testResultMetadata
let resultProtobuf = SAP_Internal_Ppdd_PPATestResultMetadata.with {
if let testResult = metadata?.testResult?.protobuf {
$0.testResult = testResult
}
if let hoursSinceTestRegistration = metadata?.hoursSinceTestRegistration {
$0.hoursSinceTestRegistration = Int32(hoursSinceTestRegistration)
}
if let riskLevel = metadata?.riskLevelAtTestRegistration?.protobuf {
$0.riskLevelAtTestRegistration = riskLevel
}
if let daysSinceMostRecentDateAtRiskLevelAtTestRegistration = metadata?.daysSinceMostRecentDateAtRiskLevelAtTestRegistration {
$0.daysSinceMostRecentDateAtRiskLevelAtTestRegistration = Int32(daysSinceMostRecentDateAtRiskLevelAtTestRegistration)
}
if let hoursSinceHighRiskWarningAtTestRegistration = metadata?.hoursSinceHighRiskWarningAtTestRegistration {
$0.hoursSinceHighRiskWarningAtTestRegistration = Int32(hoursSinceHighRiskWarningAtTestRegistration)
}
}
return [resultProtobuf]
}
private func formatToUnixTimestamp(for date: Date?) -> Int64 {
guard let date = date else {
Log.warning("mostRecentDate is nil", log: .ppa)
return -1
}
return Int64(date.timeIntervalSince1970)
}
}
| 41.348748 | 245 | 0.774884 |
2f6cdebe78a474b6c013057e11b97c2fa65aa819 | 396 | // 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
// LabCostProtocol is a cost item.
public protocol LabCostProtocol : ResourceProtocol {
var properties: LabCostPropertiesProtocol { get set }
}
| 39.6 | 96 | 0.757576 |
118c61d24292e3906d0dd2e6a2f1e6de2db8c772 | 1,175 | //
// BaseFormItemComposite.swift
// ALFormBuilder
//
// Created by Lobanov Aleksey on 26/10/2017.
// Copyright © 2017 Lobanov Aleksey. All rights reserved.
//
import Foundation
/// Base implementation of FormItemCompositeProtocol
/// For creation new model you should use Decorator pattern for
/// extended it
public class TableModelComposite: TableModelCompositeProtocol {
public var children: [TableModelCompositeProtocol] = []
public var level: Int = 0
public var identifier: String = "root"
public var datasource: [TableModelCompositeProtocol] {
return children
}
public var customData: Any?
public required init() {}
public init(identifier: String, level: Int) {
self.identifier = identifier
self.level = level
}
public func add(_ model: TableModelCompositeProtocol...) {
children.append(contentsOf: model)
}
public func remove(_ model: TableModelCompositeProtocol) {
if let index = self.children.index(where: { $0 == model }) {
children.remove(at: index)
}
}
}
public func == (lhs: TableModelCompositeProtocol, rhs: TableModelCompositeProtocol) -> Bool {
return lhs.identifier == rhs.identifier
}
| 25.543478 | 93 | 0.72 |
9cab0f6ca06e992a1ea6628b34e9a2dd47b158a5 | 13,990 | public extension Request {
/**
# Read App Information for an Xcode Cloud Product
Get the app in App Store Connect that’s related to an Xcode Cloud product.
Full documentation:
<https://developer.apple.com/documentation/appstoreconnectapi/read_app_information_for_an_xcode_cloud_product>
- Parameter id: The id of the requested resource
- Parameter fields: Fields to return for included related types
- Parameter includes: Relationship data to include in the response
- Parameter limits: Number of resources to return
- Returns: A `Request` with to send to an instance of `BagbutikService`
*/
static func getAppForCiProduct(id: String,
fields: [GetAppForCiProduct.Field]? = nil,
includes: [GetAppForCiProduct.Include]? = nil,
limits: [GetAppForCiProduct.Limit]? = nil) -> Request<AppResponse, ErrorResponse>
{
return .init(path: "/v1/ciProducts/\(id)/app", method: .get, parameters: .init(fields: fields,
includes: includes,
limits: limits))
}
}
public enum GetAppForCiProduct {
/**
Fields to return for included related types.
*/
public enum Field: FieldParameter {
/// The fields to include for returned resources of type appClips
case appClips([AppClips])
/// The fields to include for returned resources of type appCustomProductPages
case appCustomProductPages([AppCustomProductPages])
/// The fields to include for returned resources of type appEvents
case appEvents([AppEvents])
/// The fields to include for returned resources of type appInfos
case appInfos([AppInfos])
/// The fields to include for returned resources of type appPreOrders
case appPreOrders([AppPreOrders])
/// The fields to include for returned resources of type appPrices
case appPrices([AppPrices])
/// The fields to include for returned resources of type appStoreVersions
case appStoreVersions([AppStoreVersions])
/// The fields to include for returned resources of type apps
case apps([Apps])
/// The fields to include for returned resources of type betaAppLocalizations
case betaAppLocalizations([BetaAppLocalizations])
/// The fields to include for returned resources of type betaAppReviewDetails
case betaAppReviewDetails([BetaAppReviewDetails])
/// The fields to include for returned resources of type betaGroups
case betaGroups([BetaGroups])
/// The fields to include for returned resources of type betaLicenseAgreements
case betaLicenseAgreements([BetaLicenseAgreements])
/// The fields to include for returned resources of type builds
case builds([Builds])
/// The fields to include for returned resources of type ciProducts
case ciProducts([CiProducts])
/// The fields to include for returned resources of type endUserLicenseAgreements
case endUserLicenseAgreements([EndUserLicenseAgreements])
/// The fields to include for returned resources of type gameCenterEnabledVersions
case gameCenterEnabledVersions([GameCenterEnabledVersions])
/// The fields to include for returned resources of type inAppPurchases
case inAppPurchases([InAppPurchases])
/// The fields to include for returned resources of type preReleaseVersions
case preReleaseVersions([PreReleaseVersions])
/// The fields to include for returned resources of type reviewSubmissions
case reviewSubmissions([ReviewSubmissions])
/// The fields to include for returned resources of type territories
case territories([Territories])
public enum AppClips: String, ParameterValue, CaseIterable {
case app
case appClipAdvancedExperiences
case appClipDefaultExperiences
case bundleId
}
public enum AppCustomProductPages: String, ParameterValue, CaseIterable {
case app
case appCustomProductPageVersions
case appStoreVersionTemplate
case customProductPageTemplate
case name
case url
case visible
}
public enum AppEvents: String, ParameterValue, CaseIterable {
case app
case archivedTerritorySchedules
case badge
case deepLink
case eventState
case localizations
case primaryLocale
case priority
case purchaseRequirement
case purpose
case referenceName
case territorySchedules
}
public enum AppInfos: String, ParameterValue, CaseIterable {
case ageRatingDeclaration
case app
case appInfoLocalizations
case appStoreAgeRating
case appStoreState
case brazilAgeRating
case kidsAgeBand
case primaryCategory
case primarySubcategoryOne
case primarySubcategoryTwo
case secondaryCategory
case secondarySubcategoryOne
case secondarySubcategoryTwo
}
public enum AppPreOrders: String, ParameterValue, CaseIterable {
case app
case appReleaseDate
case preOrderAvailableDate
}
public enum AppPrices: String, ParameterValue, CaseIterable {
case app
case priceTier
}
public enum AppStoreVersions: String, ParameterValue, CaseIterable {
case ageRatingDeclaration
case app
case appClipDefaultExperience
case appStoreReviewDetail
case appStoreState
case appStoreVersionExperiments
case appStoreVersionLocalizations
case appStoreVersionPhasedRelease
case appStoreVersionSubmission
case build
case copyright
case createdDate
case downloadable
case earliestReleaseDate
case idfaDeclaration
case platform
case releaseType
case routingAppCoverage
case usesIdfa
case versionString
}
public enum Apps: String, ParameterValue, CaseIterable {
case appClips
case appCustomProductPages
case appEvents
case appInfos
case appStoreVersions
case availableInNewTerritories
case availableTerritories
case betaAppLocalizations
case betaAppReviewDetail
case betaGroups
case betaLicenseAgreement
case betaTesters
case builds
case bundleId
case ciProduct
case contentRightsDeclaration
case endUserLicenseAgreement
case gameCenterEnabledVersions
case inAppPurchases
case isOrEverWasMadeForKids
case name
case perfPowerMetrics
case preOrder
case preReleaseVersions
case pricePoints
case prices
case primaryLocale
case reviewSubmissions
case sku
case subscriptionStatusUrl
case subscriptionStatusUrlForSandbox
case subscriptionStatusUrlVersion
case subscriptionStatusUrlVersionForSandbox
}
public enum BetaAppLocalizations: String, ParameterValue, CaseIterable {
case app
case description
case feedbackEmail
case locale
case marketingUrl
case privacyPolicyUrl
case tvOsPrivacyPolicy
}
public enum BetaAppReviewDetails: String, ParameterValue, CaseIterable {
case app
case contactEmail
case contactFirstName
case contactLastName
case contactPhone
case demoAccountName
case demoAccountPassword
case demoAccountRequired
case notes
}
public enum BetaGroups: String, ParameterValue, CaseIterable {
case app
case betaTesters
case builds
case createdDate
case feedbackEnabled
case hasAccessToAllBuilds
case iosBuildsAvailableForAppleSiliconMac
case isInternalGroup
case name
case publicLink
case publicLinkEnabled
case publicLinkId
case publicLinkLimit
case publicLinkLimitEnabled
}
public enum BetaLicenseAgreements: String, ParameterValue, CaseIterable {
case agreementText
case app
}
public enum Builds: String, ParameterValue, CaseIterable {
case app
case appEncryptionDeclaration
case appStoreVersion
case betaAppReviewSubmission
case betaBuildLocalizations
case betaGroups
case buildAudienceType
case buildBetaDetail
case buildBundles
case computedMinMacOsVersion
case diagnosticSignatures
case expirationDate
case expired
case iconAssetToken
case icons
case individualTesters
case lsMinimumSystemVersion
case minOsVersion
case perfPowerMetrics
case preReleaseVersion
case processingState
case uploadedDate
case usesNonExemptEncryption
case version
}
public enum CiProducts: String, ParameterValue, CaseIterable {
case additionalRepositories
case app
case buildRuns
case bundleId
case createdDate
case name
case primaryRepositories
case productType
case workflows
}
public enum EndUserLicenseAgreements: String, ParameterValue, CaseIterable {
case agreementText
case app
case territories
}
public enum GameCenterEnabledVersions: String, ParameterValue, CaseIterable {
case app
case compatibleVersions
case iconAsset
case platform
case versionString
}
public enum InAppPurchases: String, ParameterValue, CaseIterable {
case apps
case inAppPurchaseType
case productId
case referenceName
case state
}
public enum PreReleaseVersions: String, ParameterValue, CaseIterable {
case app
case builds
case platform
case version
}
public enum ReviewSubmissions: String, ParameterValue, CaseIterable {
case app
case appStoreVersionForReview
case canceled
case items
case platform
case state
case submitted
case submittedDate
}
public enum Territories: String, ParameterValue, CaseIterable {
case currency
}
}
/**
Relationship data to include in the response.
*/
public enum Include: String, IncludeParameter {
case appClips, appCustomProductPages, appEvents, appInfos, appStoreVersions, availableTerritories, betaAppLocalizations, betaAppReviewDetail, betaGroups, betaLicenseAgreement, builds, ciProduct, endUserLicenseAgreement, gameCenterEnabledVersions, inAppPurchases, preOrder, preReleaseVersions, prices, reviewSubmissions
}
/**
Number of included related resources to return.
*/
public enum Limit: LimitParameter {
/// Maximum number of related betaGroups returned (when they are included) - maximum 50
case betaGroups(Int)
/// Maximum number of related appStoreVersions returned (when they are included) - maximum 50
case appStoreVersions(Int)
/// Maximum number of related preReleaseVersions returned (when they are included) - maximum 50
case preReleaseVersions(Int)
/// Maximum number of related betaAppLocalizations returned (when they are included) - maximum 50
case betaAppLocalizations(Int)
/// Maximum number of related builds returned (when they are included) - maximum 50
case builds(Int)
/// Maximum number of related appInfos returned (when they are included) - maximum 50
case appInfos(Int)
/// Maximum number of related appClips returned (when they are included) - maximum 50
case appClips(Int)
/// Maximum number of related prices returned (when they are included) - maximum 50
case prices(Int)
/// Maximum number of related availableTerritories returned (when they are included) - maximum 50
case availableTerritories(Int)
/// Maximum number of related inAppPurchases returned (when they are included) - maximum 50
case inAppPurchases(Int)
/// Maximum number of related gameCenterEnabledVersions returned (when they are included) - maximum 50
case gameCenterEnabledVersions(Int)
/// Maximum number of related appCustomProductPages returned (when they are included) - maximum 50
case appCustomProductPages(Int)
/// Maximum number of related appEvents returned (when they are included) - maximum 50
case appEvents(Int)
/// Maximum number of related reviewSubmissions returned (when they are included) - maximum 50
case reviewSubmissions(Int)
}
}
| 38.969359 | 326 | 0.625661 |
d5767bc4d23e9cac980e9a1b13b7c433b168a0e8 | 266 | //
// Day25Test.swift
// Year2018Tests
//
// Created by Gordon Tucker on 12/3/18.
// Copyright © 2018 Gordon Tucker. All rights reserved.
//
import XCTest
import Year2018
class Day25Test: XCTestCase {
func testDay25() {
let day = Day25()
}
}
| 14 | 56 | 0.642857 |
ed3742002447a720e654dc4a46f3f8f90ce7e55a | 313 | // 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<{class a{class a<T where h:a{class a<T:e}}}class A{class a{let a={{}struct{{}:{{{}{}b{let a{{{{S{}{{}struct{(f{{}struct Q{struct Q{struct S | 62.6 | 144 | 0.699681 |
dd6eb174e5ff5914b889a603b77face01bf3b4d7 | 466 | import UIKit
class Solution {
func missingNumber(_ nums: [Int]) -> Int {
let nCount = nums.count
var start = 0
var end = nCount - 1
while start <= end {
let middle = start + (end - start) / 2
if nums[middle] == middle {
start = middle + 1
}
else {
end = middle - 1
}
}
return start
}
}
Solution().missingNumber([0])
| 21.181818 | 50 | 0.439914 |
e9c3c16ec9516a56e96aa39741f8a336e904557c | 3,801 | /*
SQLiteDatabase.swift
Copyright (c) 2020, Valentin Debon
This file is part of SQLiteCodable
subject the BSD 3-Clause License, see LICENSE
*/
import SQLCodable
import CSQLite
/**
SQLite Database.
`SQLDatabase` implemented using the `CSQLite` C-interface.
*/
public final class SQLiteDatabase : SQLDatabase {
private var preparedStatements: [String : OpaquePointer]
private let connection: OpaquePointer
/**
Create an sqlite database from a file or in-memory.
- Parameter filename: File in which the database is created, or `:memory:` for an in-memory database. Default is `:memory:`.
- Throws: `SQLiteError` if unable to open `filename`.
*/
public init(filename: String = ":memory:") throws {
var connection: OpaquePointer?
guard sqlite3_open(filename, &connection) == SQLITE_OK else {
defer { sqlite3_close(connection) }
throw SQLiteError(rawValue: sqlite3_extended_errcode(connection))!
}
self.preparedStatements = [:]
self.connection = connection!
sqlite3_extended_result_codes(self.connection, 1)
}
deinit {
self.removePreparedStatements()
sqlite3_close(self.connection)
}
/**
Access or create the `sqlite3_stmt` associated with the given query.
- Parameter queryString: The query string for `sqlite3_stmt`.
- Throws: `SQLiteError` if unable to create the `sqlite3_stmt`.
- Note: Before iOS 12.0, tvOS 12.0 and watchOS 5.0 if the statement was not previously created,
it will be created using `sqlite3_prepare_v2` and not `sqlite3_prepare_v3`, which is the default behaviour.
*/
func preparedStatement(forQuery queryString: String) throws -> OpaquePointer {
if let preparedStatement = self.preparedStatements[queryString] {
return preparedStatement
} else {
var pStmt: OpaquePointer?
let errorCode: Int32 = queryString.withCString { queryCString in
if #available(iOS 12.0, tvOS 12.0, watchOS 5.0, *) {
return sqlite3_prepare_v3(self.connection, queryCString,
Int32(queryString.utf8.count + 1), UInt32(SQLITE_PREPARE_PERSISTENT),
&pStmt, nil)
} else {
return sqlite3_prepare_v2(self.connection, queryCString,
Int32(queryString.utf8.count + 1), &pStmt, nil)
}
}
guard errorCode == SQLITE_OK else {
throw SQLiteError(rawValue: errorCode)!
}
guard let preparedStatement = pStmt else {
fatalError("Invalid null valid prepared statement for query: \(queryString)")
}
if let replaced = self.preparedStatements.updateValue(preparedStatement, forKey: queryString) {
fatalError("\(Self.self): invalid previous query in prepared statements: \(replaced) for query: \(queryString)")
}
return preparedStatement
}
}
/**
Removes all previously prepared `sqlite3_stmt`.
Empties the `sqlite3_stmt` internal cache. SQLite usually keeps locks on tables while prepared statements
use them (eg. create table). This function allows you to purge the cache and thus remove these locks.
- Note: `SQLStatement`s created from this object are safe from cache purge, as they pick them only when required.
- SeeAlso: `statement(query:)`.
*/
public func removePreparedStatements() {
for preparedStatement in self.preparedStatements.values {
sqlite3_finalize(preparedStatement)
}
self.preparedStatements.removeAll()
}
/**
Acquire an `SQLStatement` from this database. The `SQLiteDatabase` handles its cache directly
with the `sqlite3_stmt`, but every of these statements hold a strong reference to the database to avoid
any misuse.
- Parameter query: Query source code.
- Returns: A newly created `SQLStatement` associated with this object and `query`.
*/
public func statement(_ query: StaticString) -> SQLStatement {
SQLiteStatement(database: self, queryString: String(cString: query.utf8Start))
}
}
| 32.767241 | 126 | 0.736385 |
76455cf0b054c4c554d3dee767f4bf8f526135d0 | 3,365 | //
// HPLabel.swift
// Pods
//
// Created by Huy Pham on 11/2/15.
//
//
import UIKit
@IBDesignable
public class HPLabel: UILabel {
var internalProxy: UIInternalProxy?
// MARK: Init
override init(frame: CGRect) {
super.init(frame: frame)
internalProxy = UIInternalProxy(subjectView: self)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
internalProxy = UIInternalProxy(subjectView: self)
}
// MARK: Text
override public var text: String? {
get {
return super.text
}
set(newText) {
super.text = Utils.localizeWithDefinedMode(text: newText)
}
}
// MARK: Border
@IBInspectable public var borderColor: UIColor? {
didSet {
self.internalProxy?.borderColor = self.borderColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
self.internalProxy?.borderWidth = self.borderWidth
}
}
// MARK: Corner
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
self.internalProxy?.cornerRadius = self.cornerRadius
}
}
@IBInspectable public var topLeftRounded: Bool = true {
didSet {
self.internalProxy?.topLeftRounded = self.topLeftRounded
}
}
@IBInspectable public var topRightRounded: Bool = true {
didSet {
self.internalProxy?.topRightRounded = self.topRightRounded
}
}
@IBInspectable public var botLeftRounded: Bool = true {
didSet {
self.internalProxy?.botLeftRounded = self.botLeftRounded
}
}
@IBInspectable public var botRightRounded: Bool = true {
didSet {
self.internalProxy?.botRightRounded = self.botRightRounded
}
}
// MARK: Padding
@IBInspectable public var paddingStart: Float = 0
@IBInspectable public var paddingEnd: Float = 0
@IBInspectable public var paddingTop: Float = 0
@IBInspectable public var paddingBottom: Float = 0
override public func drawText(in rect: CGRect) {
super.drawText(in: makeRectInset(bounds: bounds))
}
override public func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
return super.textRect(forBounds: makeRectInset(bounds: bounds), limitedToNumberOfLines: numberOfLines)
}
private func makeRectInset(bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, UIEdgeInsetsMake(CGFloat(paddingTop), CGFloat(paddingStart), CGFloat(paddingBottom), CGFloat(paddingEnd)))
}
public override func didMoveToWindow() {
for ct: NSLayoutConstraint in self.constraints {
if type(of: ct) !== NSLayoutConstraint.self {
continue
}
if (ct.firstAttribute == NSLayoutAttribute.height && ct.firstItem as? HPLabel == self) || (ct.secondAttribute == NSLayoutAttribute.height && ct.secondItem as? HPLabel == self) {
print(ct.constant)
ct.constant += (CGFloat(paddingTop) + CGFloat(paddingBottom))
break
}
}
}
}
| 26.706349 | 189 | 0.599703 |
e254d601624613c87c0be29f406a3e0fe02fb00f | 700 | import Fluent
import Vapor
final class Message: Model {
static let schema = "messages"
@ID(key: .id)
var id: UUID?
@Field(key: "title")
var title: String
@Field(key: "body")
var body: String
@Field(key: "color")
var color: String?
@Parent(key: "channel_id")
var channel: Channel
@Timestamp(key: "created_at", on: .create)
var createdAt: Date?
init() {}
init(id: UUID? = nil, channel: Channel, title: String, body: String, color: String?) throws {
self.id = id
$channel.id = try channel.requireID()
$channel.value = channel
self.title = title
self.body = body
self.color = color
}
}
| 21.212121 | 97 | 0.584286 |
bb0dd4218fe433363b0d405ee085ce826e9b2400 | 13,299 | //
// SearchSettings.swift
// Yelp
//
// Created by Auster Chen on 9/23/17.
// Copyright © 2017 Auster Chen. All rights reserved.
//
import Foundation
class SearchSettings {
static let instance = SearchSettings()
let searchRadiusesMap: [[String: Any]] = [
["name": "5 miles", "value": 8046],
["name": "10 miles", "value": 16093],
["name": "15 miles", "value": 24140],
["name": "20 miles", "value": 32186],
["name": "25 miles", "value": 40000],
]
let sortValuesMap: [[String: Any]] = [
["name": "Best Matched", "value": YelpSortMode.bestMatched],
["name": "Distance", "value": YelpSortMode.distance],
["name": "Highest Rated", "value": YelpSortMode.highestRated],
]
let categories: [[String: String]] = [["name" : "Afghan", "code": "afghani"],
["name" : "African", "code": "african"],
["name" : "American, New", "code": "newamerican"],
["name" : "American, Traditional", "code": "tradamerican"],
["name" : "Arabian", "code": "arabian"],
["name" : "Argentine", "code": "argentine"],
["name" : "Armenian", "code": "armenian"],
["name" : "Asian Fusion", "code": "asianfusion"],
["name" : "Asturian", "code": "asturian"],
["name" : "Australian", "code": "australian"],
["name" : "Austrian", "code": "austrian"],
["name" : "Baguettes", "code": "baguettes"],
["name" : "Bangladeshi", "code": "bangladeshi"],
["name" : "Barbeque", "code": "bbq"],
["name" : "Basque", "code": "basque"],
["name" : "Bavarian", "code": "bavarian"],
["name" : "Beer Garden", "code": "beergarden"],
["name" : "Beer Hall", "code": "beerhall"],
["name" : "Beisl", "code": "beisl"],
["name" : "Belgian", "code": "belgian"],
["name" : "Bistros", "code": "bistros"],
["name" : "Black Sea", "code": "blacksea"],
["name" : "Brasseries", "code": "brasseries"],
["name" : "Brazilian", "code": "brazilian"],
["name" : "Breakfast & Brunch", "code": "breakfast_brunch"],
["name" : "British", "code": "british"],
["name" : "Buffets", "code": "buffets"],
["name" : "Bulgarian", "code": "bulgarian"],
["name" : "Burgers", "code": "burgers"],
["name" : "Burmese", "code": "burmese"],
["name" : "Cafes", "code": "cafes"],
["name" : "Cafeteria", "code": "cafeteria"],
["name" : "Cajun/Creole", "code": "cajun"],
["name" : "Cambodian", "code": "cambodian"],
["name" : "Canadian", "code": "New)"],
["name" : "Canteen", "code": "canteen"],
["name" : "Caribbean", "code": "caribbean"],
["name" : "Catalan", "code": "catalan"],
["name" : "Chech", "code": "chech"],
["name" : "Cheesesteaks", "code": "cheesesteaks"],
["name" : "Chicken Shop", "code": "chickenshop"],
["name" : "Chicken Wings", "code": "chicken_wings"],
["name" : "Chilean", "code": "chilean"],
["name" : "Chinese", "code": "chinese"],
["name" : "Comfort Food", "code": "comfortfood"],
["name" : "Corsican", "code": "corsican"],
["name" : "Creperies", "code": "creperies"],
["name" : "Cuban", "code": "cuban"],
["name" : "Curry Sausage", "code": "currysausage"],
["name" : "Cypriot", "code": "cypriot"],
["name" : "Czech", "code": "czech"],
["name" : "Czech/Slovakian", "code": "czechslovakian"],
["name" : "Danish", "code": "danish"],
["name" : "Delis", "code": "delis"],
["name" : "Diners", "code": "diners"],
["name" : "Dumplings", "code": "dumplings"],
["name" : "Eastern European", "code": "eastern_european"],
["name" : "Ethiopian", "code": "ethiopian"],
["name" : "Fast Food", "code": "hotdogs"],
["name" : "Filipino", "code": "filipino"],
["name" : "Fish & Chips", "code": "fishnchips"],
["name" : "Fondue", "code": "fondue"],
["name" : "Food Court", "code": "food_court"],
["name" : "Food Stands", "code": "foodstands"],
["name" : "French", "code": "french"],
["name" : "French Southwest", "code": "sud_ouest"],
["name" : "Galician", "code": "galician"],
["name" : "Gastropubs", "code": "gastropubs"],
["name" : "Georgian", "code": "georgian"],
["name" : "German", "code": "german"],
["name" : "Giblets", "code": "giblets"],
["name" : "Gluten-Free", "code": "gluten_free"],
["name" : "Greek", "code": "greek"],
["name" : "Halal", "code": "halal"],
["name" : "Hawaiian", "code": "hawaiian"],
["name" : "Heuriger", "code": "heuriger"],
["name" : "Himalayan/Nepalese", "code": "himalayan"],
["name" : "Hong Kong Style Cafe", "code": "hkcafe"],
["name" : "Hot Dogs", "code": "hotdog"],
["name" : "Hot Pot", "code": "hotpot"],
["name" : "Hungarian", "code": "hungarian"],
["name" : "Iberian", "code": "iberian"],
["name" : "Indian", "code": "indpak"],
["name" : "Indonesian", "code": "indonesian"],
["name" : "International", "code": "international"],
["name" : "Irish", "code": "irish"],
["name" : "Island Pub", "code": "island_pub"],
["name" : "Israeli", "code": "israeli"],
["name" : "Italian", "code": "italian"],
["name" : "Japanese", "code": "japanese"],
["name" : "Jewish", "code": "jewish"],
["name" : "Kebab", "code": "kebab"],
["name" : "Korean", "code": "korean"],
["name" : "Kosher", "code": "kosher"],
["name" : "Kurdish", "code": "kurdish"],
["name" : "Laos", "code": "laos"],
["name" : "Laotian", "code": "laotian"],
["name" : "Latin American", "code": "latin"],
["name" : "Live/Raw Food", "code": "raw_food"],
["name" : "Lyonnais", "code": "lyonnais"],
["name" : "Malaysian", "code": "malaysian"],
["name" : "Meatballs", "code": "meatballs"],
["name" : "Mediterranean", "code": "mediterranean"],
["name" : "Mexican", "code": "mexican"],
["name" : "Middle Eastern", "code": "mideastern"],
["name" : "Milk Bars", "code": "milkbars"],
["name" : "Modern Australian", "code": "modern_australian"],
["name" : "Modern European", "code": "modern_european"],
["name" : "Mongolian", "code": "mongolian"],
["name" : "Moroccan", "code": "moroccan"],
["name" : "New Zealand", "code": "newzealand"],
["name" : "Night Food", "code": "nightfood"],
["name" : "Norcinerie", "code": "norcinerie"],
["name" : "Open Sandwiches", "code": "opensandwiches"],
["name" : "Oriental", "code": "oriental"],
["name" : "Pakistani", "code": "pakistani"],
["name" : "Parent Cafes", "code": "eltern_cafes"],
["name" : "Parma", "code": "parma"],
["name" : "Persian/Iranian", "code": "persian"],
["name" : "Peruvian", "code": "peruvian"],
["name" : "Pita", "code": "pita"],
["name" : "Pizza", "code": "pizza"],
["name" : "Polish", "code": "polish"],
["name" : "Portuguese", "code": "portuguese"],
["name" : "Potatoes", "code": "potatoes"],
["name" : "Poutineries", "code": "poutineries"],
["name" : "Pub Food", "code": "pubfood"],
["name" : "Rice", "code": "riceshop"],
["name" : "Romanian", "code": "romanian"],
["name" : "Rotisserie Chicken", "code": "rotisserie_chicken"],
["name" : "Rumanian", "code": "rumanian"],
["name" : "Russian", "code": "russian"],
["name" : "Salad", "code": "salad"],
["name" : "Sandwiches", "code": "sandwiches"],
["name" : "Scandinavian", "code": "scandinavian"],
["name" : "Scottish", "code": "scottish"],
["name" : "Seafood", "code": "seafood"],
["name" : "Serbo Croatian", "code": "serbocroatian"],
["name" : "Signature Cuisine", "code": "signature_cuisine"],
["name" : "Singaporean", "code": "singaporean"],
["name" : "Slovakian", "code": "slovakian"],
["name" : "Soul Food", "code": "soulfood"],
["name" : "Soup", "code": "soup"],
["name" : "Southern", "code": "southern"],
["name" : "Spanish", "code": "spanish"],
["name" : "Steakhouses", "code": "steak"],
["name" : "Sushi Bars", "code": "sushi"],
["name" : "Swabian", "code": "swabian"],
["name" : "Swedish", "code": "swedish"],
["name" : "Swiss Food", "code": "swissfood"],
["name" : "Tabernas", "code": "tabernas"],
["name" : "Taiwanese", "code": "taiwanese"],
["name" : "Tapas Bars", "code": "tapas"],
["name" : "Tapas/Small Plates", "code": "tapasmallplates"],
["name" : "Tex-Mex", "code": "tex-mex"],
["name" : "Thai", "code": "thai"],
["name" : "Traditional Norwegian", "code": "norwegian"],
["name" : "Traditional Swedish", "code": "traditional_swedish"],
["name" : "Trattorie", "code": "trattorie"],
["name" : "Turkish", "code": "turkish"],
["name" : "Ukrainian", "code": "ukrainian"],
["name" : "Uzbek", "code": "uzbek"],
["name" : "Vegan", "code": "vegan"],
["name" : "Vegetarian", "code": "vegetarian"],
["name" : "Venison", "code": "venison"],
["name" : "Vietnamese", "code": "vietnamese"],
["name" : "Wok", "code": "wok"],
["name" : "Wraps", "code": "wraps"],
["name" : "Yugoslav", "code": "yugoslav"]]
fileprivate var selectedCategories: [String]?
fileprivate var searchRadiusInMeters: Int?
fileprivate var hasDeals: Bool = false
fileprivate var sort: YelpSortMode = YelpSortMode.bestMatched
fileprivate var searchTerm: String = ""
func updateDealsSwitch(_ newValue: Bool) {
hasDeals = newValue
}
func getDealsValue() -> Bool {
return hasDeals
}
func updateSearchTerm(_ newSearchTerm: String) -> Void {
searchTerm = newSearchTerm
}
func getSearchTerm() -> String {
return searchTerm
}
func updateSearchRadius(_ searchRadius: Int?) {
searchRadiusInMeters = searchRadius
}
func getSearchRadius() -> Int? {
return searchRadiusInMeters
}
func updateSort(_ newSortValue: YelpSortMode) -> Void {
sort = newSortValue
}
func getSort() -> YelpSortMode {
return sort
}
func updateCategories(_ newCategories: [String:Bool]) {
var categoryCodes = [String]()
newCategories.forEach { (key, value) in
if value {
categoryCodes.append(key)
}
}
selectedCategories = categoryCodes
}
func getCategories() -> [String]? {
return selectedCategories
}
}
| 52.984064 | 86 | 0.412211 |
d7379cccfe3db6e28c8088276beaa17098553c28 | 404 | let ssidHeaderName = "S"
let encryptionTypeHeaderName = "T"
let passwordHeaderName = "P"
let hiddenHeaderName = "H"
let doubleQuote = "\"".first!
let terminator = ";".first!
let separator = ":".first!
let comma = ",".first!
let backslash = "\\".first!
let meCardEscapingPrefix = backslash
let meCardSpecialCharacters = Set([
doubleQuote,
terminator,
separator,
comma,
backslash,
])
| 20.2 | 36 | 0.685644 |
2fde9640a749421026316628bed25fd16bc75a89 | 3,050 | //
// Copyright (c) 2016 Keun young Kim <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var currentModeLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var toggleSwitch: UISwitch!
func updateContentModeName() {
let modeNames = ["UIViewContentMode.ScaleToFill",
"UIViewContentMode.ScaleAspectFit",
"UIViewContentMode.ScaleAspectFill",
"UIViewContentMode.Redraw",
"UIViewContentMode.Center",
"UIViewContentMode.Top",
"UIViewContentMode.Bottom",
"UIViewContentMode.Left",
"UIViewContentMode.Right",
"UIViewContentMode.TopLeft",
"UIViewContentMode.TopRight",
"UIViewContentMode.BottomLeft",
"UIViewContentMode.BottomRight"]
currentModeLabel.text = modeNames[imageView.contentMode.rawValue]
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.borderWidth = 2.0
imageView.layer.borderColor = UIColor.blackColor().CGColor
toggleSwitch.on = imageView.clipsToBounds
updateContentModeName()
}
@IBAction func toggleClipsToBounds(sender: UISwitch) {
imageView.clipsToBounds = sender.on
}
@IBAction func changeContentMode(sender: AnyObject) {
var currentMode = imageView.contentMode.rawValue
if currentMode == UIViewContentMode.BottomRight.rawValue {
currentMode = 0
} else {
currentMode += 1
}
if let mode = UIViewContentMode(rawValue: currentMode) {
imageView.contentMode = mode
}
updateContentModeName()
}
}
| 38.607595 | 81 | 0.636393 |
01a39648f2f4c251f2eb522aa8d8389361c1166d | 2,020 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
window = UIWindow(frame: Device.bounds)
window!.rootViewController = AppSnackbarController(rootViewController: RootViewController())
window!.makeKeyAndVisible()
}
}
| 43.913043 | 100 | 0.760891 |
4a306110bc568630d2956b40e50c9ef5a26045e1 | 1,628 | import Foundation
import ProjectDescription
import TSCBasic
import TuistCore
import TuistGraph
import TuistSupport
import XCTest
@testable import TuistLoader
@testable import TuistSupportTesting
final class AutogenerationOptionsManifestMapperTests: TuistUnitTestCase {
private typealias Manifest = ProjectDescription.Config.GenerationOptions.AutogenerationOptions
func test_disableAutogeneratedSchemes_is_mapped_correctly() throws {
// Given
let manifest: ProjectDescription.Config.GenerationOptions = .disableAutogeneratedSchemes
let temporaryPath = try temporaryPath()
let generatorPaths = GeneratorPaths(manifestDirectory: temporaryPath)
// When
let got = try TuistGraph.Config.GenerationOption.from(manifest: manifest, generatorPaths: generatorPaths)
// Then
XCTAssertEqual(TuistGraph.Config.GenerationOption.autogenerationOptions(.disabled), got)
}
func test_from_returnsTheCorrectValue_whenManifestIncludesAllOptions() throws {
// Given
let manifest: Manifest = .enabled([.parallelizable, .randomExecutionOrdering])
// When
let got = try TuistGraph.AutogenerationOptions.from(manifest: manifest)
// Then
XCTAssertEqual(.enabled([.parallelizable, .randomExecutionOrdering]), got)
}
func test_from_returnsTheCorrectValue_whenManifestIsEmpty() throws {
// Given
let manifest: Manifest = .enabled([])
// When
let got = try TuistGraph.AutogenerationOptions.from(manifest: manifest)
// Then
XCTAssertEqual(.enabled([]), got)
}
}
| 32.56 | 113 | 0.734029 |
0973c9dd86c47249997b175ab8b10153c21cf4ff | 3,190 | import Quick
import Nimble
@testable import MiniApp
class MASDKErrorTests: QuickSpec {
override func spec() {
describe("MASDKError tests") {
context("when converting an NSError") {
it("will convert server error") {
let originalError = NSError.serverError(code: 400, message: "test")
let newError = MASDKError.serverError(code: 400, message: "test")
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert invalid URL error") {
let originalError = NSError.invalidURLError()
let newError = MASDKError.invalidURLError
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert invalid App ID error") {
let originalError = NSError.invalidAppId()
let newError = MASDKError.invalidAppId
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert invalid response data error") {
let originalError = NSError.invalidResponseData()
let newError = MASDKError.invalidResponseData
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert invalid downloading failed error") {
let originalError = NSError.downloadingFailed()
let newError = MASDKError.downloadingFailed
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert invalid no published version error") {
let originalError = NSError.noPublishedVersion()
let newError = MASDKError.noPublishedVersion
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert invalid no mini app not found error") {
let originalError = NSError.miniAppNotFound(message: "")
let newError = MASDKError.miniAppNotFound
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
it("will convert return unknown error") {
let originalError = NSError(domain: "test_domain", code: 1, userInfo: [NSLocalizedDescriptionKey: "test_description"])
let newError = MASDKError.unknownError(domain: "test_domain", code: 1, description: "test_description")
expect(MASDKError.fromError(error: originalError).localizedDescription).to(equal(newError.localizedDescription))
}
}
}
}
}
| 46.911765 | 138 | 0.609404 |
ac26b016f030655bb4ee906591fc7e40ead97f18 | 1,022 | // ********************************************************************************
//
// This source file is part of the Open Banking Connector project
// ( https://github.com/finlabsuk/open-banking-connector ).
//
// Copyright (C) 2019 Finnovation Labs and the Open Banking Connector project authors.
//
// Licensed under Apache License v2.0. See LICENSE.txt for licence information.
// SPDX-License-Identifier: Apache-2.0
//
// ********************************************************************************
import AccountTransactionTypeRequirements
public typealias OBApiReadAccountAlias = OBReadAccount3
public typealias OBApiReadAccountDataAlias = OBReadAccount3Data
public typealias OBApiAccountAlias = OBAccount3
extension OBApiReadAccountAlias: OBReadAccountProtocol {
public typealias OBReadResourceData = OBApiReadAccountDataAlias
}
extension OBApiReadAccountDataAlias: OBReadAccountDataProtocol {
public typealias OBResource = OBApiAccountAlias
}
extension OBApiAccountAlias: OBAccountProtocol { }
| 39.307692 | 86 | 0.683953 |
f878f3964b34cf52a4f79ba69bd5759d758d046f | 6,520 | /* file: geometric_tolerance_auxiliary_classification_enum.swift generated: Mon Jan 3 16:32:52 2022 */
/* This file was generated by the EXPRESS to Swift translator "exp2swift",
derived from STEPcode (formerly NIST's SCL).
exp2swift version: v.1.0.1, derived from stepcode v0.8 as of 2019/11/23
WARNING: You probably don't want to edit it since your modifications
will be lost if exp2swift is used to regenerate it.
*/
import SwiftSDAIcore
extension AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF {
//MARK: -TYPE DEFINITION in EXPRESS
/*
TYPE geometric_tolerance_auxiliary_classification_enum = ENUMERATION OF
( all_over,
unless_otherwise_specified );
END_TYPE; -- geometric_tolerance_auxiliary_classification_enum (line:3364 file:ap242ed2_mim_lf_v1.101.TY.exp)
*/
/** ENUMERATION type
- EXPRESS:
```express
TYPE geometric_tolerance_auxiliary_classification_enum = ENUMERATION OF
( all_over,
unless_otherwise_specified );
END_TYPE; -- geometric_tolerance_auxiliary_classification_enum (line:3364 file:ap242ed2_mim_lf_v1.101.TY.exp)
```
*/
public enum nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM : SDAI.ENUMERATION, SDAIValue, AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM__type {
/// ENUMERATION case in ``nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM``
case ALL_OVER
/// ENUMERATION case in ``nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM``
case UNLESS_OTHERWISE_SPECIFIED
// SDAIGenericType
public var typeMembers: Set<SDAI.STRING> {
var members = Set<SDAI.STRING>()
members.insert(SDAI.STRING(Self.typeName))
return members
}
public var entityReference: SDAI.EntityReference? {nil}
public var stringValue: SDAI.STRING? {nil}
public var binaryValue: SDAI.BINARY? {nil}
public var logicalValue: SDAI.LOGICAL? {nil}
public var booleanValue: SDAI.BOOLEAN? {nil}
public var numberValue: SDAI.NUMBER? {nil}
public var realValue: SDAI.REAL? {nil}
public var integerValue: SDAI.INTEGER? {nil}
public var genericEnumValue: SDAI.GenericEnumValue? { SDAI.GenericEnumValue(self) }
public func arrayOptionalValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY_OPTIONAL<ELEM>? {nil}
public func arrayValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY<ELEM>? {nil}
public func listValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.LIST<ELEM>? {nil}
public func bagValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.BAG<ELEM>? {nil}
public func setValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.SET<ELEM>? {nil}
public func enumValue<ENUM:SDAIEnumerationType>(enumType:ENUM.Type) -> ENUM? { return self as? ENUM }
// SDAIUnderlyingType
public typealias FundamentalType = Self
public static var typeName: String =
"AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF.GEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM"
public var asFundamentalType: FundamentalType { return self }
public init(fundamental: FundamentalType) {
self = fundamental
}
public init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let enumval = generic?.enumValue(enumType: Self.self) else { return nil }
self = enumval
}
// InitializableByP21Parameter
public static var bareTypeName: String = "GEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM"
public init?(p21untypedParam: P21Decode.ExchangeStructure.UntypedParameter, from exchangeStructure: P21Decode.ExchangeStructure) {
switch p21untypedParam {
case .enumeration(let enumcase):
switch enumcase {
case "ALL_OVER": self = .ALL_OVER
case "UNLESS_OTHERWISE_SPECIFIED": self = .UNLESS_OTHERWISE_SPECIFIED
default:
exchangeStructure.error = "unexpected p21parameter enum case(\(enumcase)) while resolving \(Self.bareTypeName) value"
return nil
}
case .rhsOccurenceName(let rhsname):
switch rhsname {
case .constantValueName(let name):
guard let generic = exchangeStructure.resolve(constantValueName: name) else {exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) value"); return nil }
guard let enumValue = generic.enumValue(enumType:Self.self) else { exchangeStructure.error = "constant value(\(name): \(generic)) is not compatible with \(Self.bareTypeName)"; return nil }
self = enumValue
case .valueInstanceName(let name):
guard let param = exchangeStructure.resolve(valueInstanceName: name) else {exchangeStructure.add(errorContext: "while resolving \(Self.bareTypeName) value from \(rhsname)"); return nil }
self.init(p21param: param, from: exchangeStructure)
default:
exchangeStructure.error = "unexpected p21parameter(\(p21untypedParam)) while resolving \(Self.bareTypeName) value"
return nil
}
case .noValue:
return nil
default:
exchangeStructure.error = "unexpected p21parameter(\(p21untypedParam)) while resolving \(Self.bareTypeName) value"
return nil
}
}
public init(p21omittedParamfrom exchangeStructure: P21Decode.ExchangeStructure) {
self = .ALL_OVER
}
//WHERE RULE VALIDATION (ENUMERATION TYPE)
public static func validateWhereRules(instance:Self?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] {
return [:]
}
}
//MARK: -enum case symbol promotions
/// promoted ENUMERATION case in ``nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM``
public static let ALL_OVER = nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM.ALL_OVER
/// promoted ENUMERATION case in ``nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM``
public static let UNLESS_OTHERWISE_SPECIFIED = nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM
.UNLESS_OTHERWISE_SPECIFIED
}
//MARK: - ENUMERATION TYPE HIERARCHY
public protocol AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM__type:
SDAIEnumerationType {}
public protocol AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM__subtype: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM__type, SDAIDefinedType
where Supertype: AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF__nGEOMETRIC_TOLERANCE_AUXILIARY_CLASSIFICATION_ENUM__type
{}
| 45.277778 | 248 | 0.759816 |
72d60b2af513eebd383608be12504973d97e984d | 13,293 | //
// ServerTrustPolicy.swift
// NetService
//
// Created by steven on 2021/1/8.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
public class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/// Initializes the `ServerTrustPolicyManager` instance with the given policies.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
/// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
/// pinning for host3 and disabling evaluation for host4.
///
/// - parameter policies: A dictionary of all policies mapped to a particular host.
///
/// - returns: The new `ServerTrustPolicyManager` instance.
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/// Returns the `ServerTrustPolicy` for the given host if applicable.
///
/// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
/// this method and implement more complex mapping implementations such as wildcards.
///
/// - parameter host: The host to use when searching for a matching policy.
///
/// - returns: The server trust policy for the given host if found.
open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension URLSession {
private struct AssociatedKeys {
static var managerKey = "URLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
/// with a given set of criteria to determine whether the server trust is valid and the connection should be made.
///
/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
/// to route all communication over an HTTPS connection with pinning enabled.
///
/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
/// validate the host provided by the challenge. Applications are encouraged to always
/// validate the host in production environments to guarantee the validity of the server's
/// certificate chain.
///
/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to
/// validate the host provided by the challenge as well as specify the revocation flags for
/// testing for revoked certificates. Apple platforms did not start testing for revoked
/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is
/// demonstrated in our TLS tests. Applications are encouraged to always validate the host
/// in production environments to guarantee the validity of the server's certificate chain.
///
/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
/// considered valid if one of the pinned certificates match one of the server certificates.
/// By validating both the certificate chain and host, certificate pinning provides a very
/// secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate
/// chain in production environments.
///
/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
/// valid if one of the pinned public keys match one of the server certificate public keys.
/// By validating both the certificate chain and host, public key pinning provides a very
/// secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate
/// chain in production environments.
///
/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
///
/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust.
public enum ServerTrustPolicy {
case performDefaultEvaluation(validateHost: Bool)
case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags)
case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case disableEvaluation
case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool)
// MARK: - Bundle Location
/// Returns all certificates within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `.cer` files.
///
/// - returns: All certificates within the given bundle.
public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil)
}.joined())
for path in paths {
if
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/// Returns all public keys within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `*.cer` files.
///
/// - returns: All public keys within the given bundle.
public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificates(in: bundle) {
if let publicKey = publicKey(for: certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/// Evaluates whether the server trust is valid for the given host.
///
/// - parameter serverTrust: The server trust to evaluate.
/// - parameter host: The host of the challenge protection space.
///
/// - returns: Whether the server trust is valid.
public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .performDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
serverTrustIsValid = trustIsValid(serverTrust)
case let .performRevokedEvaluation(validateHost, revocationFlags):
let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
let revokedPolicy = SecPolicyCreateRevocation(revocationFlags)
SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef)
serverTrustIsValid = trustIsValid(serverTrust)
case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateData(for: serverTrust)
let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData == pinnedCertificateData {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .disableEvaluation:
serverTrustIsValid = true
case let .customEvaluation(closure):
serverTrustIsValid = closure(serverTrust, host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(_ trust: SecTrust) -> Bool {
var isValid = false
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) {
isValid = SecTrustEvaluateWithError(trust, nil)
} else {
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType.unspecified
let proceed = SecTrustResultType.proceed
isValid = result == unspecified || result == proceed
}
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateData(for trust: SecTrust) -> [Data] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateData(for: certificates)
}
private func certificateData(for certificates: [SecCertificate]) -> [Data] {
return certificates.map { SecCertificateCopyData($0) as Data }
}
// MARK: - Private - Public Key Extraction
private static func publicKeys(for trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if
let certificate = SecTrustGetCertificateAtIndex(trust, index),
let publicKey = publicKey(for: certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKey(for certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust, trustCreationStatus == errSecSuccess {
if #available(iOS 14, macOS 11, *) {
publicKey = SecTrustCopyKey(trust)
} else {
publicKey = SecTrustCopyPublicKey(trust)
}
}
return publicKey
}
}
| 44.607383 | 120 | 0.642368 |
095c4b313ef90b04f34ba5a3625825062016ec70 | 2,386 | // Copyright 2022 Pera Wallet, LDA
// 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.
// ActionableBannerViewTheme.swift
import Foundation
import MacaroonUIKit
import UIKit
struct ActionableBannerViewTheme: LayoutSheet, StyleSheet {
let contentMinWidthRatio: LayoutMetric
let contentPaddings: LayoutPaddings
var background: ViewStyle
let icon: ImageStyle
let iconContentEdgeInsets: LayoutOffset
let iconSize: LayoutSize
var title: TextStyle
var message: TextStyle
let messageContentEdgeInsets: LayoutPaddings
let actionHorizontalPaddings: LayoutHorizontalPaddings
let action: ButtonStyle
let actionCorner: Corner
let actionContentEdgeInsets: LayoutPaddings
init(
_ family: LayoutFamily,
contentBottomPadding: LayoutMetric = 20
) {
contentMinWidthRatio = 0.5
contentPaddings = (20, 24, contentBottomPadding, .noMetric)
background = [
.backgroundColor(AppColors.Shared.Helpers.negative)
]
icon = [
.contentMode(.bottomLeft),
]
iconContentEdgeInsets = (12, 12)
iconSize = (24, 24)
title = [
.textOverflow(FittingText()),
.textColor(AppColors.Shared.System.background)
]
message = [
.textOverflow(FittingText()),
.textColor(AppColors.Shared.System.background)
]
messageContentEdgeInsets = (4, 0, 0, 0)
actionHorizontalPaddings = (20, 24)
action = [
.titleColor([.normal(AppColors.Components.Button.Primary.text)]),
.backgroundColor(UIColor(red: 1, green: 1, blue: 1, alpha: 0.12))
]
actionCorner = Corner(radius: 4)
actionContentEdgeInsets = (8, 16, 8, 16)
}
init(_ family: LayoutFamily) {
self.init(family, contentBottomPadding: 20)
}
}
| 29.45679 | 77 | 0.668483 |
1dd1a581517d2e5061d3f451e9a3447098af01e0 | 751 | import XCTest
import eNotesSDKLukso
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.896552 | 111 | 0.603196 |
fbfcf881b34028bb5ca17bf26845e9428bf3d74f | 1,004 | //
// SearchErrorTests.swift
// BookStoreKitTests
//
// Created by Soojin Ro on 17/08/2019.
// Copyright © 2019 Soojin Ro. All rights reserved.
//
import XCTest
@testable import BookStoreKit
class SearchErrorTests: XCTestCase {
func testEquatable() {
let notFound1 = SearchError.notFound
let notFound2 = SearchError.notFound
let endOfResult1 = SearchError.endOfResult
let endOfResult2 = SearchError.endOfResult
let apiError = SearchError.apiFailure(NSError(domain: "test", code: 0, userInfo: nil))
let apiError1 = SearchError.apiFailure(NSError(domain: "test", code: 0, userInfo: nil))
let apiError2 = SearchError.apiFailure(NSError(domain: "test-1", code: 9999, userInfo: nil))
XCTAssertEqual(notFound1, notFound2)
XCTAssertEqual(endOfResult1, endOfResult2)
XCTAssertNotEqual(notFound1, endOfResult1)
XCTAssertNotEqual(apiError, apiError1)
XCTAssertNotEqual(apiError1, apiError2)
}
}
| 34.62069 | 100 | 0.700199 |
f97ae5ad0865d60d99e20ade0f2b03699117dfad | 7,240 | //===--- StdlibCoreExtras.swift -------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftPrivate
import SwiftPrivateLibcExtras
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
#if _runtime(_ObjC)
import Foundation
#endif
//
// These APIs don't really belong in a unit testing library, but they are
// useful in tests, and stdlib does not have such facilities yet.
//
func findSubstring(_ string: String, _ substring: String) -> String.Index? {
if substring.isEmpty {
return string.startIndex
}
#if _runtime(_ObjC)
return string.range(of: substring)?.lowerBound
#else
// FIXME(performance): This is a very non-optimal algorithm, with a worst
// case of O((n-m)*m). When non-objc String has a match function that's better,
// this should be removed in favor of using that.
// Operate on unicode scalars rather than codeunits.
let haystack = string.unicodeScalars
let needle = substring.unicodeScalars
for matchStartIndex in haystack.indices {
var matchIndex = matchStartIndex
var needleIndex = needle.startIndex
while true {
if needleIndex == needle.endIndex {
// if we hit the end of the search string, we found the needle
return matchStartIndex.samePosition(in: string)
}
if matchIndex == haystack.endIndex {
// if we hit the end of the string before finding the end of the needle,
// we aren't going to find the needle after that.
return nil
}
if needle[needleIndex] == haystack[matchIndex] {
// keep advancing through both the string and search string on match
matchIndex = haystack.index(after: matchIndex)
needleIndex = haystack.index(after: needleIndex)
} else {
// no match, go back to finding a starting match in the string.
break
}
}
}
return nil
#endif
}
public func createTemporaryFile(
_ fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String
) -> String {
#if _runtime(_ObjC)
let tempDir: NSString = NSTemporaryDirectory() as NSString
var fileName = tempDir.appendingPathComponent(
fileNamePrefix + "XXXXXX" + fileNameSuffix)
#else
var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix
#endif
let fd = _stdlib_mkstemps(
&fileName, CInt(fileNameSuffix.utf8.count))
if fd < 0 {
fatalError("mkstemps() returned an error")
}
var stream = _FDOutputStream(fd: fd)
stream.write(contents)
if close(fd) != 0 {
fatalError("close() return an error")
}
return fileName
}
public final class Box<T> {
public init(_ value: T) { self.value = value }
public var value: T
}
infix operator <=>
public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult {
return lhs < rhs
? .lt
: lhs > rhs ? .gt : .eq
}
public struct TypeIdentifier : Hashable, Comparable {
public init(_ value: Any.Type) {
self.value = value
}
public var hashValue: Int { return objectID.hashValue }
public var value: Any.Type
internal var objectID : ObjectIdentifier { return ObjectIdentifier(value) }
}
public func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool {
return lhs.objectID < rhs.objectID
}
public func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool {
return lhs.objectID == rhs.objectID
}
extension TypeIdentifier
: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return String(describing: value)
}
public var debugDescription: String {
return "TypeIdentifier(\(description))"
}
}
enum FormNextPermutationResult {
case success
case formedFirstPermutation
}
extension MutableCollection
where
Self : BidirectionalCollection,
Iterator.Element : Comparable
{
mutating func _reverseSubrange(_ subrange: Range<Index>) {
if subrange.isEmpty { return }
var f = subrange.lowerBound
var l = index(before: subrange.upperBound)
while f < l {
swap(&self[f], &self[l])
formIndex(after: &f)
formIndex(before: &l)
}
}
mutating func formNextPermutation() -> FormNextPermutationResult {
if isEmpty {
// There are 0 elements, only one permutation is possible.
return .formedFirstPermutation
}
do {
var i = startIndex
formIndex(after: &i)
if i == endIndex {
// There is only element, only one permutation is possible.
return .formedFirstPermutation
}
}
var i = endIndex
formIndex(before: &i)
var beforeI = i
formIndex(before: &beforeI)
var elementAtI = self[i]
var elementAtBeforeI = self[beforeI]
while true {
if elementAtBeforeI < elementAtI {
// Elements at `i..<endIndex` are in non-increasing order. To form the
// next permutation in lexicographical order we need to replace
// `self[i-1]` with the next larger element found in the tail, and
// reverse the tail. For example:
//
// i-1 i endIndex
// V V V
// 6 2 8 7 4 1 [ ] // Input.
// 6 (4) 8 7 (2) 1 [ ] // Exchanged self[i-1] with the
// ^--------^ // next larger element
// // from the tail.
// 6 4 (1)(2)(7)(8)[ ] // Reversed the tail.
// <-------->
var j = endIndex
repeat {
formIndex(before: &j)
} while !(elementAtBeforeI < self[j])
swap(&self[beforeI], &self[j])
_reverseSubrange(i..<endIndex)
return .success
}
if beforeI == startIndex {
// All elements are in non-increasing order. Reverse to form the first
// permutation, where all elements are sorted (in non-increasing order).
reverse()
return .formedFirstPermutation
}
i = beforeI
formIndex(before: &beforeI)
elementAtI = elementAtBeforeI
elementAtBeforeI = self[beforeI]
}
}
}
/// Generate all permutations.
public func forAllPermutations(_ size: Int, _ body: ([Int]) -> Void) {
var data = Array(0..<size)
repeat {
body(data)
} while data.formNextPermutation() != .formedFirstPermutation
}
/// Generate all permutations.
public func forAllPermutations<S : Sequence>(
_ sequence: S, _ body: ([S.Iterator.Element]) -> Void
) {
let data = Array(sequence)
forAllPermutations(data.count) {
(indices: [Int]) in
body(indices.map { data[$0] })
return ()
}
}
public func cartesianProduct<C1 : Collection, C2 : Collection>(
_ c1: C1, _ c2: C2
) -> [(C1.Iterator.Element, C2.Iterator.Element)] {
var result: [(C1.Iterator.Element, C2.Iterator.Element)] = []
for e1 in c1 {
for e2 in c2 {
result.append((e1, e2))
}
}
return result
}
| 29.193548 | 81 | 0.635912 |
5089960b5713b470b2e185daf033854bc3970c02 | 11,159 | import UIKit
public protocol AnnouncementCollectionViewCellDelegate: NSObjectProtocol {
func announcementCellDidTapDismiss(_ cell: AnnouncementCollectionViewCell)
func announcementCellDidTapActionButton(_ cell: AnnouncementCollectionViewCell)
func announcementCell(_ cell: AnnouncementCollectionViewCell, didTapLinkURL: URL)
}
open class AnnouncementCollectionViewCell: CollectionViewCell {
public weak var delegate: AnnouncementCollectionViewCellDelegate?
public let imageView = UIImageView()
private let messageTextView = UITextView()
public let actionButton = UIButton()
public let dismissButton = UIButton()
private let captionTextView = UITextView()
public let captionSeparatorView = UIView()
public let messageSpacing: CGFloat = 20
public let buttonMargin: CGFloat = 40
public let actionButtonHeight: CGFloat = 40
public let dismissButtonSpacing: CGFloat = 8
public let dismissButtonHeight: CGFloat = 32
public var imageViewDimension: CGFloat = 150
public let captionSpacing: CGFloat = 20
open override func setup() {
layoutMargins = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
contentView.addSubview(imageView)
messageTextView.isScrollEnabled = false
messageTextView.isEditable = false
messageTextView.delegate = self
contentView.addSubview(messageTextView)
contentView.addSubview(actionButton)
contentView.addSubview(dismissButton)
contentView.addSubview(captionSeparatorView)
captionTextView.isScrollEnabled = false
captionTextView.isEditable = false
captionTextView.delegate = self
contentView.addSubview(captionTextView)
actionButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)
actionButton.titleLabel?.numberOfLines = 0
actionButton.addTarget(self, action: #selector(actionButtonPressed), for: .touchUpInside)
dismissButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 15, bottom: 8, right: 15)
dismissButton.titleLabel?.numberOfLines = 0
dismissButton.addTarget(self, action: #selector(dismissButtonPressed), for: .touchUpInside)
super.setup()
}
@objc func actionButtonPressed() {
delegate?.announcementCellDidTapActionButton(self)
}
@objc func dismissButtonPressed() {
delegate?.announcementCellDidTapDismiss(self)
}
// This method is called to reset the cell to the default configuration. It is called on initial setup and prepareForReuse. Subclassers should call super.
override open func reset() {
super.reset()
imageView.wmf_reset()
imageViewDimension = 150
updateFonts(with: traitCollection)
captionHTML = nil
messageHTML = nil
isImageViewHidden = true
isUrgent = false
dismissButtonTitle = nil
}
open override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
actionButton.titleLabel?.font = UIFont.wmf_font(.semiboldSubheadline, compatibleWithTraitCollection: traitCollection)
dismissButton.titleLabel?.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection)
updateCaptionTextViewWithAttributedCaption()
}
public var isImageViewHidden = false {
didSet {
imageView.isHidden = isImageViewHidden
setNeedsLayout()
}
}
fileprivate var isCaptionHidden = false {
didSet {
captionSeparatorView.isHidden = isCaptionHidden
captionTextView.isHidden = isCaptionHidden
setNeedsLayout()
}
}
fileprivate func updateCaptionTextViewWithAttributedCaption() {
guard let html = captionHTML else {
isCaptionHidden = true
return
}
let attributedText = html.byAttributingHTML(with: .footnote, matching: traitCollection, color: captionTextView.textColor)
let pStyle = NSMutableParagraphStyle()
pStyle.lineBreakMode = .byWordWrapping
pStyle.baseWritingDirection = .natural
let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle: pStyle]
attributedText.addAttributes(attributes, range: NSMakeRange(0, attributedText.length))
captionTextView.attributedText = attributedText
isCaptionHidden = false
}
public var captionHTML: String? {
didSet {
updateCaptionTextViewWithAttributedCaption()
}
}
public var isUrgent: Bool = false
private var messageUnderlineColor: UIColor = UIColor.black
private var messageEmphasisColor: UIColor = UIColor.black
private var messageLineHeightMultiple: CGFloat = 1
private func updateMessageTextViewWithAttributedMessage() {
guard let html = messageHTML else {
messageTextView.attributedText = nil
return
}
let attributedText = html.byAttributingHTML(with: .subheadline,
boldWeight: .bold,
matching: traitCollection,
color: messageTextView.textColor,
tagMapping: ["em": "i"], // em tags are generally italicized by default, match this behavior
additionalTagAttributes: [
"u": [
NSAttributedString.Key.underlineColor: messageUnderlineColor,
NSAttributedString.Key.underlineStyle: NSNumber(value: NSUnderlineStyle.single.rawValue)
],
"strong": [
NSAttributedString.Key.foregroundColor: messageEmphasisColor
]
])
let pStyle = NSMutableParagraphStyle()
pStyle.lineHeightMultiple = messageLineHeightMultiple
let attributes: [NSAttributedString.Key : Any] = [NSAttributedString.Key.paragraphStyle: pStyle]
attributedText.addAttributes(attributes, range: NSMakeRange(0, attributedText.length))
messageTextView.attributedText = attributedText
}
public var messageHTML: String? {
didSet {
updateMessageTextViewWithAttributedMessage()
}
}
public var dismissButtonTitle: String? {
didSet {
let newTitle = dismissButtonTitle ?? CommonStrings.dismissButtonTitle
dismissButton.setTitle(newTitle, for: .normal)
setNeedsLayout()
}
}
open override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let widthMinusMargins = layoutWidth(for: size)
let displayScale = traitCollection.displayScale > 0 ? traitCollection.displayScale : 2.0
var origin = CGPoint(x: layoutMargins.left + layoutMarginsAdditions.left, y: 0)
if !isImageViewHidden {
if (apply) {
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: imageViewDimension)
}
origin.y += imageViewDimension
}
origin.y += messageSpacing
let messageTextSize = messageTextView.sizeThatFits(CGSize(width: widthMinusMargins, height: CGFloat.greatestFiniteMagnitude))
let messageFrame = CGRect(origin: origin, size: CGSize(width: widthMinusMargins, height: messageTextSize.height))
if (apply) {
messageTextView.frame = messageFrame
}
origin.y += messageFrame.layoutHeight(with: messageSpacing)
let buttonMinimumWidth = min(250, widthMinusMargins)
origin.y += actionButton.wmf_preferredHeight(at: origin, maximumWidth: widthMinusMargins, minimumWidth: buttonMinimumWidth, horizontalAlignment: .center, spacing: dismissButtonSpacing, apply: apply)
origin.y += dismissButton.wmf_preferredHeight(at: origin, maximumWidth: widthMinusMargins, minimumWidth: buttonMinimumWidth, horizontalAlignment: .center, spacing: 0, apply: apply)
if !isCaptionHidden {
origin.y += dismissButtonSpacing
let separatorFrame = CGRect(x: origin.x, y: origin.y, width: widthMinusMargins, height: 1.0 / displayScale)
if (apply) {
captionSeparatorView.frame = separatorFrame
}
origin.y += separatorFrame.height
origin.y += captionSpacing
let captionTextViewSize = captionTextView.sizeThatFits(CGSize(width: widthMinusMargins, height: CGFloat.greatestFiniteMagnitude))
let captionFrame = CGRect(origin: origin, size: CGSize(width: widthMinusMargins, height: captionTextViewSize.height))
if (apply) {
captionTextView.frame = captionFrame
}
origin.y += captionFrame.height
origin.y += captionSpacing
} else {
origin.y += layoutMargins.bottom
}
return CGSize(width: size.width, height: origin.y)
}
}
extension AnnouncementCollectionViewCell: UITextViewDelegate {
public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
delegate?.announcementCell(self, didTapLinkURL: URL)
return false
}
}
extension AnnouncementCollectionViewCell: Themeable {
@objc(applyTheme:)
public func apply(theme: Theme) {
setBackgroundColors(theme.colors.cardBackground, selected: theme.colors.selectedCardBackground)
messageTextView.textColor = theme.colors.primaryText
messageTextView.backgroundColor = .clear
dismissButton.setTitleColor(theme.colors.secondaryText, for: .normal)
imageView.backgroundColor = theme.colors.midBackground
imageView.alpha = theme.imageOpacity
actionButton.setTitleColor(theme.colors.link, for: .normal)
actionButton.backgroundColor = theme.colors.cardButtonBackground
messageLineHeightMultiple = 1.25
if isUrgent {
messageUnderlineColor = theme.colors.error
messageEmphasisColor = theme.colors.error
layer.borderWidth = 3
layer.borderColor = theme.colors.error.cgColor
layer.cornerRadius = Theme.exploreCardCornerRadius
} else {
layer.borderWidth = 0
layer.cornerRadius = 0
messageUnderlineColor = messageTextView.textColor ?? theme.colors.primaryText
messageEmphasisColor = messageTextView.textColor ?? theme.colors.primaryText
}
actionButton.layer.cornerRadius = 5
captionSeparatorView.backgroundColor = theme.colors.border
captionTextView.textColor = theme.colors.secondaryText
captionTextView.backgroundColor = .clear
updateCaptionTextViewWithAttributedCaption()
updateMessageTextViewWithAttributedMessage()
}
}
| 43.251938 | 206 | 0.667712 |
b9b6948804553342c6cc45e01747e487f1aaaf9b | 12,979 | //
// GameViewController.swift
// WildWest
//
// Created by Hugues Stephano Telolahy on 24/01/2020.
// Copyright © 2020 creativeGames. All rights reserved.
//
// swiftlint:disable implicitly_unwrapped_optional
import UIKit
import RxSwift
import WildWestEngine
class GameViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet private weak var endTurnButton: UIButton!
@IBOutlet private weak var otherMovesButton: UIButton!
@IBOutlet private weak var playersCollectionView: UICollectionView!
@IBOutlet private weak var handCollectionView: UICollectionView!
@IBOutlet private weak var messageTableView: UITableView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var discardImageView: UIImageView!
@IBOutlet private weak var deckImageView: UIImageView!
@IBOutlet private weak var deckCountLabel: UILabel!
// MARK: - Dependencies
var router: RouterProtocol!
var userManager: UserManagerProtocol!
var environment: GameEnvironment!
var analyticsManager: AnalyticsManager!
var animationMatcher: AnimationEventMatcherProtocol!
var mediaMatcher: MediaEventMatcherProtocol!
var soundPlayer: SoundPlayerProtocol!
var moveSegmenter: MoveSegmenterProtocol!
var moveSelector: GameMoveSelectorWidget!
var preferences: UserPreferencesProtocol!
private lazy var animationRenderer: AnimationRendererProtocol = {
AnimationRenderer(viewController: self,
cardPositions: buildCardPositions(),
cardSize: discardImageView.bounds.size,
cardBackImage: #imageLiteral(resourceName: "01_back"))
}()
// MARK: - Data
private var state: StateProtocol!
private var playerItems: [PlayerItem] = []
private var handCards: [CardProtocol] = []
private var segmentedMoves: [String: [GMove]] = [:]
private var messages: [String] = []
private let disposeBag = DisposeBag()
private lazy var assistantAI: AIProtocol = {
let sheriff = state.players.values.first(where: { $0.role == .sheriff })!.identifier
let abilityEvaluator = AbilityEvaluator()
let roleEstimator = RoleEstimator(sheriff: sheriff, abilityEvaluator: abilityEvaluator)
let roleStrategy = RoleStrategy()
let moveEvaluator = MoveEvaluator(abilityEvaluator: abilityEvaluator, roleEstimator: roleEstimator, roleStrategy: roleStrategy)
return RandomWithRoleAi(moveEvaluator: moveEvaluator)
}()
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let layout = playersCollectionView.collectionViewLayout as? GameCollectionViewLayout
layout?.delegate = self
environment.database.state(observedBy: environment.controlledId).subscribe(onNext: { [weak self] state in
self?.processState(state)
})
.disposed(by: disposeBag)
environment.database.event.subscribe(onNext: { [weak self] update in
self?.processEvent(update)
})
.disposed(by: disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
router.toGameRoles(state.players.count) { [weak self] in
self?.environment.engine.execute(nil, completion: nil)
}
}
// MARK: - IBAction
@IBAction private func refreshButtonTapped(_ sender: Any) {
environment.engine.execute(nil, completion: nil)
}
@IBAction private func menuButtonTapped(_ sender: Any) {
userManager.setStatusIdle()
router.toMenu()
}
@IBAction private func endTurnTapped(_ sender: Any) {
guard let moves = segmentedMoves["endTurn"] else {
return
}
moveSelector.selectMove(among: moves, title: nil, cancelable: true) { [weak self] move in
self?.environment.engine.execute(move, completion: nil)
}
}
@IBAction private func otherMovesTapped(_ sender: Any) {
guard let moves = segmentedMoves["*"] else {
return
}
moveSelector.selectMove(among: moves, title: nil, cancelable: true) { [weak self] move in
self?.environment.engine.execute(move, completion: nil)
}
}
}
private extension GameViewController {
func processState(_ state: StateProtocol) {
self.state = state
playerItems = state.playerItems(users: environment.users)
playersCollectionView.reloadData()
if let controlledId = environment.controlledId,
let player = state.players[controlledId] {
handCards = player.hand
handCollectionView.reloadData()
}
discardImageView.image = state.topDiscardImage
deckCountLabel.text = "[] \(state.deck.count)"
titleLabel.text = state.instruction(for: environment.controlledId)
}
func processEvent(_ event: GEvent) {
switch event {
case let .activate(moves):
let moves = moves.filter { $0.actor == environment.controlledId }
processMoves(moves)
case let .gameover(winner):
router.toGameOver(winner)
userManager.setStatusIdle()
analyticsManager.tagEventGameOver(state)
case let .run(move):
messages.append("\(mediaMatcher.emoji(on: event) ?? "") \(move.ability)")
messageTableView.reloadDataScrollingAtBottom()
default:
break
}
#if DEBUG
print("\(mediaMatcher.emoji(on: event) ?? "") \(event)")
#endif
if let animation = animationMatcher.animation(on: event) {
animationRenderer.execute(animation, in: state)
}
if let sfx = mediaMatcher.sfx(on: event) {
soundPlayer.play(sfx)
}
}
func processMoves(_ moves: [GMove]) {
segmentedMoves = moveSegmenter.segment(moves)
handCollectionView.reloadData()
endTurnButton.isEnabled = segmentedMoves["endTurn"] != nil
otherMovesButton.isEnabled = segmentedMoves["*"] != nil
// Select reaction moves
if !moves.isEmpty,
let hit = state.hit {
if preferences.assistedMode {
let move = assistantAI.bestMove(among: moves, in: state)
environment.engine.execute(move, completion: nil)
} else {
moveSelector.selectMove(among: moves, title: hit.name, cancelable: false) { [weak self] move in
self?.environment.engine.execute(move, completion: nil)
}
}
}
}
func buildCardPositions() -> [CardArea: CGPoint] {
var result: [CardArea: CGPoint] = [:]
guard let discardCenter = discardImageView.superview?.convert(discardImageView.center, to: view),
let deckCenter = deckImageView.superview?.convert(deckImageView.center, to: view) else {
fatalError("Illegal state")
}
result[.deck] = deckCenter
result[.store] = deckCenter
result[.discard] = discardCenter
let playerIds = state.initialOrder
for (index, playerId) in playerIds.enumerated() {
guard let attribute = playersCollectionView.collectionViewLayout
.layoutAttributesForItem(at: IndexPath(row: index, section: 0)) else {
fatalError("Illegal state")
}
let cellCenter = playersCollectionView.convert(attribute.center, to: view)
let handPosition = cellCenter
let inPlayPosition = cellCenter.applying(CGAffineTransform(translationX: attribute.bounds.size.height / 2, y: 0))
result[.hand(playerId)] = handPosition
result[.inPlay(playerId)] = inPlayPosition
}
return result
}
}
extension GameViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(with: MessageCell.self, for: indexPath)
cell.update(with: messages[indexPath.row])
return cell
}
}
extension GameViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
if collectionView == playersCollectionView {
return playersCollectionViewNumberOfItems()
} else {
return handCollectionViewNumberOfItems()
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == playersCollectionView {
return playersCollectionView(collectionView, cellForItemAt: indexPath)
} else {
return handCollectionView(collectionView, cellForItemAt: indexPath)
}
}
private func playersCollectionViewNumberOfItems() -> Int {
playerItems.count
}
private func handCollectionViewNumberOfItems() -> Int {
handCards.count
}
private func playersCollectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(with: PlayerCell.self, for: indexPath)
cell.update(with: playerItems[indexPath.row])
return cell
}
private func handCollectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(with: HandCell.self, for: indexPath)
let card = handCards[indexPath.row]
let active = segmentedMoves[card.identifier] != nil
cell.update(with: card, active: active)
return cell
}
}
extension GameViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == playersCollectionView {
playersCollectionViewDidSelectItem(at: indexPath)
} else {
handCollectionViewDidSelectItem(at: indexPath)
}
}
private func playersCollectionViewDidSelectItem(at indexPath: IndexPath) {
let player = playerItems[indexPath.row].player
router.toGamePlayer(player)
analyticsManager.tageEventPlayerDescriptor(player)
}
private func handCollectionViewDidSelectItem(at indexPath: IndexPath) {
guard let moves = segmentedMoves[handCards[indexPath.row].identifier] else {
return
}
moveSelector.selectMove(among: moves, title: nil, cancelable: true) { [weak self] move in
self?.environment.engine.execute(move, completion: nil)
}
}
}
extension GameViewController: GameCollectionViewLayoutDelegate {
func numberOfItemsForGameCollectionViewLayout(layout: GameCollectionViewLayout) -> Int {
state.players.count
}
}
private extension StateProtocol {
var topDiscardImage: UIImage? {
guard let topDiscard = discard.first else {
return UIImage(color: .gold)
}
return UIImage(named: topDiscard.name)
}
func instruction(for controlledPlayerId: String?) -> String {
if let hit = hit {
return hit.name
} else if controlledPlayerId == turn {
return "your turn"
} else {
return "..."
}
}
func playerItems(users: [String: UserInfo]?) -> [PlayerItem] {
initialOrder.map { player in
PlayerItem(player: players[player]!,
isTurn: player == turn,
isHitLooseHealth: isHitLooseHealth(player),
isHitSomeAction: isHitSomeAction(player),
user: users?[player])
}
}
private func isHitLooseHealth(_ player: String) -> Bool {
if let hit = hit,
hit.abilities.contains("looseHealth"),
hit.players.contains(player) {
return true
} else {
return false
}
}
private func isHitSomeAction(_ player: String) -> Bool {
if let hit = hit,
!hit.abilities.contains("looseHealth"),
hit.players.contains(player) {
return true
} else {
return false
}
}
}
| 35.269022 | 135 | 0.626319 |
d5e88e9d10ce2faec556028a13e333a7a5dee9a7 | 1,270 | import Foundation
/// Credit card info
@objc open class CardInfo: NSObject, Serializable {
/// The credit card number, also known as a Primary Account Number (PAN)
@objc open var pan: String?
/// The credit card expiration month
open var expMonth: Int?
/// The credit card expiration year in 4 digits
open var expYear: Int?
/// The credit card cvv2 code
@objc open var cvv: String?
/// Card holder name
@objc open var name: String?
/// Credit card language. Should use the format [language designator ISO-639-1]
@objc open var language: String?
/// Card holder billing address
@objc open var address: Address?
/// Card holder risk data
@objc open var riskData: IdVerification?
/// Initialize class with all variables
public init(pan: String?, expMonth: Int?, expYear: Int?, cvv: String?, name: String?, language: String? = nil, address: Address?, riskData: IdVerification?) {
super.init()
self.pan = pan
self.expMonth = expMonth
self.expYear = expYear
self.cvv = cvv
self.name = name
self.language = language
self.address = address
self.riskData = riskData
}
}
| 28.222222 | 162 | 0.618898 |
e6066971137f308fbc2f5c36dec7b6b26e645e35 | 536 | //
// SubtitleProfile.swift
// EmbyApiClient
//
import Foundation
public struct SubtitleProfile {
let format: String?
let method: SubtitleDeliveryMethod?
let didlMode: String?
let language: String?
var languages: [String] {
get {
return splitToArray(stringToSplit: language, delimiter: ",")
}
}
public func supportsLanguage(subLanguage: String) -> Bool {
return language == nil || languages.contains(where: { $0.lowercased() == subLanguage.lowercased()})
}
}
| 23.304348 | 107 | 0.639925 |
ac67b7e04bf254bee552f927fce31167ecd657e4 | 1,783 | //
// NetworkManager.swift
// Moviest
//
// Created by Bilal Arslan on 15.05.2018.
// Copyright © 2018 Bilal Arslan. All rights reserved.
//
import Foundation
import Alamofire
public enum NetworkError: Error {
case unknown
case connection(Error)
case corruptedData
}
typealias Completion<T: Codable> = (_ responseObject: Response<T>) -> Void
typealias NetworkManagerRequest = DataRequest
class RequestManager {
static var shared = RequestManager()
private let manager = Session.default
private init() {
}
@discardableResult func perform<T : Codable>(_ request: MovieRequest, handleCompletion: @escaping (Response<T>) -> Void) -> NetworkManagerRequest? {
let dataRequest = manager.request(request)
dataRequest.responseData { (dataResponse: AFDataResponse<Data>) in
let result: Result<T, NetworkError>
let statusCode = dataResponse.response?.statusCode ?? 0
if statusCode == 0 {
result = .failure(NetworkError.unknown)
} else {
switch dataResponse.result {
case .success(let value):
if let object = T(jsonData: value) {
result = .success(object)
} else {
result = .failure(NetworkError.corruptedData)
}
case .failure(let error):
result = .failure(NetworkError.connection(error))
}
}
handleCompletion(Response<T>(request: dataRequest.request,
response: dataResponse.response,
data: dataResponse.data, result: result))
}
return dataRequest
}
}
| 31.280702 | 152 | 0.576556 |
62c9907e166f3e48638dd684c3a8f5984f6217c2 | 3,376 | //
// ImageContainer.swift
// TetherViewer
//
// Created by Matthew Martin on 3/17/21.
//
import AppKit
import QuickLookThumbnailing
import CoreImage
class ImageModel: Identifiable, Equatable, ObservableObject {
static func == (lhs: ImageModel, rhs: ImageModel) -> Bool {
return lhs.id == rhs.id
}
let id : Int
@Published var clippedImage : NSImage
@Published var fullImage : NSImage
@Published var thumbnail : NSImage?
@Published var showClipping = false
let imageFilename : String
let exif : ExifData?
static let colorCubeFilter = ImageModel.colorCubeFilterForHighlights(threshold: 0.98)
init(id: Int, imageUrl: URL) {
self.id = id
let img = NSImage(byReferencingFile: imageUrl.path)!
self.fullImage = img
self.clippedImage = ImageModel.buildClippingImage(input: img)
self.imageFilename = imageUrl.lastPathComponent
if let imageSource = CGImageSourceCreateWithURL(imageUrl as CFURL, nil) {
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)
if let exif = imageProperties as? [String: Any] {
if let e = exif["{Exif}"] as? NSMutableDictionary {
self.exif = ExifData(from: e);
} else {
self.exif = nil
}
} else {
self.exif = nil
}
} else {
self.exif = nil
}
let previewGenerator = QLThumbnailGenerator()
let thumbnailSize = CGSize(width: 256, height: 256)
let scale = NSScreen.main?.backingScaleFactor ?? 1.0
let group = DispatchGroup()
group.enter()
let request = QLThumbnailGenerator.Request(fileAt: imageUrl, size: thumbnailSize, scale: scale, representationTypes: .thumbnail)
previewGenerator.generateBestRepresentation(for: request) { (thumbnail, error) in
if let error = error {
print(error.localizedDescription)
} else if let thumb = thumbnail {
self.thumbnail = thumb.nsImage
}
group.leave()
}
group.wait()
}
static func buildClippingImage(input : NSImage) -> NSImage {
let cgImage = input.cgImage(forProposedRect: nil, context: nil, hints: [:])!
let inputImage = CIImage(cgImage: cgImage)
colorCubeFilter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage = colorCubeFilter.outputImage!
let rep = NSBitmapImageRep(ciImage: outputImage)
let newImage = NSImage()
newImage.addRepresentation(rep)
return newImage
}
static func colorCubeFilterForHighlights(threshold: Float) -> CIFilter {
let size = 64
var cubeData = [Float](repeating: 0, count: size * size * size * 4)
var rgb: [Float] = [0, 0, 0]
var offset = 0
for z in 0 ..< size {
rgb[2] = Float(z) / Float(size) // blue value
for y in 0 ..< size {
rgb[1] = Float(y) / Float(size) // green value
for x in 0 ..< size {
rgb[0] = Float(x) / Float(size) // red value
if(rgb[0] > threshold || rgb[1] > threshold || rgb[2] > threshold) {
cubeData[offset] = 1.0
cubeData[offset + 1] = 0.0
cubeData[offset + 2] = 0.0
cubeData[offset + 3] = 1.0
} else {
cubeData[offset] = rgb[0]
cubeData[offset + 1] = rgb[1]
cubeData[offset + 2] = rgb[2]
cubeData[offset + 3] = 1.0
}
offset += 4
}
}
}
let b = cubeData.withUnsafeBufferPointer { Data(buffer: $0) }
let data = b as NSData
let colorCube = CIFilter(name: "CIColorCube", parameters: [
"inputCubeDimension": size,
"inputCubeData": data
])
return colorCube!
}
}
| 29.356522 | 130 | 0.673282 |
898ca6094a203882ec77a83fa0902b972bb44d2e | 17,418 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import CoreGraphics
import Darwin
//===----------------------------------------------------------------------===//
// CGAffineTransform
//===----------------------------------------------------------------------===//
extension CGAffineTransform: Equatable {}
public func ==(lhs: CGAffineTransform, rhs: CGAffineTransform) -> Bool {
return lhs.__equalTo(rhs)
}
//===----------------------------------------------------------------------===//
// CGColor
//===----------------------------------------------------------------------===//
extension CGColor {
@available(OSX 10.3, iOS 2.0, *)
public var components: [CGFloat]? {
guard let pointer = self.__unsafeComponents else { return nil }
let buffer = UnsafeBufferPointer(start: pointer, count: self.numberOfComponents)
return Array(buffer)
}
#if os(macOS)
public class var white: CGColor
{ return CGColor.__constantColor(for: CGColor.__whiteColorName)! }
public class var black: CGColor
{ return CGColor.__constantColor(for: CGColor.__blackColorName)! }
public class var clear: CGColor
{ return CGColor.__constantColor(for: CGColor.__clearColorName)! }
#endif
}
extension CGColor: Equatable {}
public func ==(lhs: CGColor, rhs: CGColor) -> Bool {
return lhs.__equalTo(rhs)
}
//===----------------------------------------------------------------------===//
// CGColorSpace
//===----------------------------------------------------------------------===//
extension CGColorSpace {
public var colorTable: [UInt8]? {
guard self.model == .indexed else { return nil }
var table = [UInt8](repeating: 0, count: self.__colorTableCount)
self.__unsafeGetColorTable(&table)
return table
}
}
//===----------------------------------------------------------------------===//
// CGContext
//===----------------------------------------------------------------------===//
extension CGContext {
public func setLineDash(phase: CGFloat, lengths: [CGFloat]) {
self.__setLineDash(phase: phase, lengths: lengths, count: lengths.count)
}
public func move(to point: CGPoint) {
self.__moveTo(x: point.x, y: point.y)
}
public func addLine(to point: CGPoint) {
self.__addLineTo(x: point.x, y: point.y)
}
public func addCurve(to end: CGPoint, control1: CGPoint, control2: CGPoint) {
self.__addCurveTo(cp1x: control1.x, cp1y: control1.y,
cp2x: control2.x, cp2y: control2.y, endingAtX: end.x, y: end.y)
}
public func addQuadCurve(to end: CGPoint, control: CGPoint) {
self.__addQuadCurveTo(cpx: control.x, cpy: control.y,
endingAtX: end.x, y: end.y)
}
public func addRects(_ rects: [CGRect]) {
self.__addRects(rects, count: rects.count)
}
public func addLines(between points: [CGPoint]) {
self.__addLines(between: points, count: points.count)
}
public func addArc(center: CGPoint, radius: CGFloat, startAngle: CGFloat,
endAngle: CGFloat, clockwise: Bool) {
self.__addArc(centerX: center.x, y: center.y, radius: radius,
startAngle: startAngle, endAngle: endAngle, clockwise: clockwise ? 1 : 0)
}
public func addArc(tangent1End: CGPoint, tangent2End: CGPoint,
radius: CGFloat) {
self.__addArc(x1: tangent1End.x, y1: tangent1End.y,
x2: tangent2End.x, y2: tangent2End.y, radius: radius)
}
/// Fills the current path using the specified rule (winding by default).
///
/// Any open subpath is implicitly closed.
public func fillPath(using rule: CGPathFillRule = .winding) {
switch rule {
case .winding: self.__fillPath()
case .evenOdd: self.__eoFillPath()
}
}
/// Intersects the current path with the current clipping region and uses the
/// result as the new clipping region for subsequent drawing.
///
/// Uses the specified fill rule (winding by default) to determine which
/// areas to treat as the interior of the clipping region. When evaluating
/// the path, any open subpath is implicitly closed.
public func clip(using rule: CGPathFillRule = .winding) {
switch rule {
case .winding: self.__clip()
case .evenOdd: self.__eoClip()
}
}
public func fill(_ rects: [CGRect]) {
self.__fill(rects, count: rects.count)
}
public func strokeLineSegments(between points: [CGPoint]) {
self.__strokeLineSegments(between: points, count: points.count)
}
public func clip(to rects: [CGRect]) {
self.__clip(to: rects, count: rects.count)
}
public func draw(_ image: CGImage, in rect: CGRect, byTiling: Bool = false) {
if byTiling {
self.__draw(in: rect, byTiling: image)
} else {
self.__draw(in: rect, image: image)
}
}
public var textPosition: CGPoint {
get { return self.__textPosition }
set { self.__setTextPosition(x: newValue.x, y: newValue.y) }
}
public func showGlyphs(_ glyphs: [CGGlyph], at positions: [CGPoint]) {
precondition(glyphs.count == positions.count)
self.__showGlyphs(glyphs, atPositions: positions, count: glyphs.count)
}
}
//===----------------------------------------------------------------------===//
// CGDataProvider
//===----------------------------------------------------------------------===//
// TODO: replace init(UnsafePointer<UInt8>) with init(String)
// blocked on rdar://problem/27444567
//===----------------------------------------------------------------------===//
// CGDirectDisplay
//===----------------------------------------------------------------------===//
#if os(macOS)
public func CGGetLastMouseDelta() -> (x: Int32, y: Int32) {
var pair: (x: Int32, y: Int32) = (0, 0)
__CGGetLastMouseDelta(&pair.x, &pair.y)
return pair
}
#endif
//===----------------------------------------------------------------------===//
// CGGeometry
//===----------------------------------------------------------------------===//
public extension CGPoint {
static var zero: CGPoint {
@_transparent // @fragile
get { return CGPoint(x: 0, y: 0) }
}
@_transparent // @fragile
init(x: Int, y: Int) {
self.init(x: CGFloat(x), y: CGFloat(y))
}
@_transparent // @fragile
init(x: Double, y: Double) {
self.init(x: CGFloat(x), y: CGFloat(y))
}
init?(dictionaryRepresentation dict: CFDictionary) {
var point = CGPoint()
if CGPoint.__setFromDictionaryRepresentation(dict, &point) {
self = point
} else {
return nil
}
}
}
extension CGPoint : CustomReflectable, CustomPlaygroundQuickLookable {
public var customMirror: Mirror {
return Mirror(self, children: ["x": x, "y": y], displayStyle: .`struct`)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .point(Double(x), Double(y))
}
}
extension CGPoint : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(x), \(y))"
}
}
extension CGPoint : Equatable {}
@_transparent // @fragile
public func == (lhs: CGPoint, rhs: CGPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public extension CGSize {
static var zero: CGSize {
@_transparent // @fragile
get { return CGSize(width: 0, height: 0) }
}
@_transparent // @fragile
init(width: Int, height: Int) {
self.init(width: CGFloat(width), height: CGFloat(height))
}
@_transparent // @fragile
init(width: Double, height: Double) {
self.init(width: CGFloat(width), height: CGFloat(height))
}
init?(dictionaryRepresentation dict: CFDictionary) {
var size = CGSize()
if CGSize.__setFromDictionaryRepresentation(dict, &size) {
self = size
} else {
return nil
}
}
}
extension CGSize : CustomReflectable, CustomPlaygroundQuickLookable {
public var customMirror: Mirror {
return Mirror(
self,
children: ["width": width, "height": height],
displayStyle: .`struct`)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .size(Double(width), Double(height))
}
}
extension CGSize : CustomDebugStringConvertible {
public var debugDescription : String {
return "(\(width), \(height))"
}
}
extension CGSize : Equatable {}
@_transparent // @fragile
public func == (lhs: CGSize, rhs: CGSize) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
public extension CGVector {
static var zero: CGVector {
@_transparent // @fragile
get { return CGVector(dx: 0, dy: 0) }
}
@_transparent // @fragile
init(dx: Int, dy: Int) {
self.init(dx: CGFloat(dx), dy: CGFloat(dy))
}
@_transparent // @fragile
init(dx: Double, dy: Double) {
self.init(dx: CGFloat(dx), dy: CGFloat(dy))
}
}
extension CGVector : Equatable {}
@_transparent // @fragile
public func == (lhs: CGVector, rhs: CGVector) -> Bool {
return lhs.dx == rhs.dx && lhs.dy == rhs.dy
}
public extension CGRect {
static var zero: CGRect {
@_transparent // @fragile
get { return CGRect(x: 0, y: 0, width: 0, height: 0) }
}
@_transparent // @fragile
init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
@_transparent // @fragile
init(x: Double, y: Double, width: Double, height: Double) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
@_transparent // @fragile
init(x: Int, y: Int, width: Int, height: Int) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
init?(dictionaryRepresentation dict: CFDictionary) {
var rect = CGRect()
if CGRect.__setFromDictionaryRepresentation(dict, &rect) {
self = rect
} else {
return nil
}
}
@_transparent // @fragile
func divided(atDistance: CGFloat, from fromEdge: CGRectEdge)
-> (slice: CGRect, remainder: CGRect)
{
var slice = CGRect.zero
var remainder = CGRect.zero
self.__divided(slice: &slice, remainder: &remainder, atDistance: atDistance,
from: fromEdge)
return (slice, remainder)
}
}
extension CGRect : CustomReflectable, CustomPlaygroundQuickLookable {
public var customMirror: Mirror {
return Mirror(
self,
children: ["origin": origin, "size": size],
displayStyle: .`struct`)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .rectangle(
Double(origin.x), Double(origin.y),
Double(size.width), Double(size.height))
}
}
extension CGRect : CustomDebugStringConvertible {
public var debugDescription : String {
return "(\(origin.x), \(origin.y), \(size.width), \(size.height))"
}
}
extension CGRect : Equatable {}
@_transparent // @fragile
public func == (lhs: CGRect, rhs: CGRect) -> Bool {
return lhs.equalTo(rhs)
}
extension CGAffineTransform {
public static var identity: CGAffineTransform {
@_transparent // @fragile
get { return CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) }
}
}
//===----------------------------------------------------------------------===//
// CGImage
//===----------------------------------------------------------------------===//
extension CGImage {
public func copy(maskingColorComponents components: [CGFloat]) -> CGImage? {
return self.__copy(maskingColorComponents: UnsafePointer(components))
}
}
//===----------------------------------------------------------------------===//
// CGLayer
//===----------------------------------------------------------------------===//
// TODO: remove auxiliaryInfo parameter from CGLayer.init,
// or at least give it a default value (empty/nil)
// blocked on rdar://problem/27444567
extension CGContext {
public func draw(_ layer: CGLayer, in rect: CGRect) {
self.__draw(in: rect, layer: layer)
}
public func draw(_ layer: CGLayer, at point: CGPoint) {
self.__draw(at: point, layer: layer)
}
}
//===----------------------------------------------------------------------===//
// CGPath & CGMutablePath
//===----------------------------------------------------------------------===//
// TODO: Make this a nested type (CGPath.FillRule)
public enum CGPathFillRule: Int {
/// Nonzero winding number fill rule.
///
/// This rule plots a ray from the interior of the region to be evaluated
/// toward the bounds of the drawing, and sums the closed path elements
/// that the ray crosses: +1 for counterclockwise paths, -1 for clockwise.
/// If the sum is zero, the region is left empty; if the sum is nonzero,
/// the region is filled.
case winding
/// Even-Odd fill rule.
///
/// This rule plots a ray from the interior of the region to be evaluated
/// toward the bounds of the drawing, and sums the closed path elements
/// that the ray crosses.
/// If the sum is an even numner, the region is left empty; if the sum is
/// an odd number, the region is filled.
case evenOdd
}
extension CGPath {
public func copy(dashingWithPhase phase: CGFloat, lengths: [CGFloat],
transform: CGAffineTransform = .identity) -> CGPath {
return CGPath(__byDashing: self, transform: [transform],
phase: phase, lengths: lengths, count: lengths.count)!
// force unwrap / non-optional return ok: underlying func returns nil
// only on bad input that we've made impossible (self and transform)
}
public func copy(strokingWithWidth lineWidth: CGFloat, lineCap: CGLineCap,
lineJoin: CGLineJoin, miterLimit: CGFloat,
transform: CGAffineTransform = .identity) -> CGPath {
return CGPath(__byStroking: self, transform: [transform],
lineWidth: lineWidth, lineCap: lineCap, lineJoin: lineJoin,
miterLimit: miterLimit)!
// force unwrap / non-optional return ok: underlying func returns nil
// only on bad input that we've made impossible (self and transform)
}
public func contains(_ point: CGPoint, using rule: CGPathFillRule = .winding,
transform: CGAffineTransform = .identity) -> Bool {
return self.__containsPoint(transform: [transform],
point: point, eoFill: (rule == .evenOdd))
}
}
extension CGPath: Equatable {}
public func ==(lhs: CGPath, rhs: CGPath) -> Bool {
return lhs.__equalTo(rhs)
}
extension CGMutablePath {
public func addRoundedRect(in rect: CGRect, cornerWidth: CGFloat,
cornerHeight: CGFloat, transform: CGAffineTransform = .identity) {
self.__addRoundedRect(transform: [transform], rect: rect,
cornerWidth: cornerWidth, cornerHeight: cornerHeight)
}
public func move(to point: CGPoint,
transform: CGAffineTransform = .identity) {
self.__moveTo(transform: [transform], x: point.x, y: point.y)
}
public func addLine(to point: CGPoint,
transform: CGAffineTransform = .identity) {
self.__addLineTo(transform: [transform], x: point.x, y: point.y)
}
public func addQuadCurve(to end: CGPoint, control: CGPoint,
transform: CGAffineTransform = .identity) {
self.__addQuadCurve(transform: [transform], cpx: control.x, cpy: control.y,
endingAtX: end.x, y: end.y)
}
public func addCurve(to end: CGPoint, control1: CGPoint, control2: CGPoint,
transform: CGAffineTransform = .identity) {
self.__addCurve(transform: [transform], cp1x: control1.x, cp1y: control1.y,
cp2x: control2.x, cp2y: control2.y, endingAtX: end.x, y: end.y)
}
public func addRect(_ rect: CGRect,
transform: CGAffineTransform = .identity) {
self.__addRect(transform: [transform], rect: rect)
}
public func addRects(_ rects: [CGRect],
transform: CGAffineTransform = .identity) {
self.__addRects(transform: [transform], rects: rects, count: rects.count)
}
public func addLines(between points: [CGPoint],
transform: CGAffineTransform = .identity) {
self.__addLines(transform: [transform],
between: points, count: points.count)
}
public func addEllipse(in rect: CGRect,
transform: CGAffineTransform = .identity) {
self.__addEllipse(transform: [transform], rect: rect)
}
public func addRelativeArc(center: CGPoint, radius: CGFloat,
startAngle: CGFloat, delta: CGFloat,
transform: CGAffineTransform = .identity) {
self.__addRelativeArc(transform: [transform], x: center.x, y: center.y,
radius: radius, startAngle: startAngle, delta: delta)
}
public func addArc(center: CGPoint, radius: CGFloat,
startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool,
transform: CGAffineTransform = .identity) {
self.__addArc(transform: [transform], x: center.x, y: center.y,
radius: radius, startAngle: startAngle, endAngle: endAngle,
clockwise: clockwise)
}
public func addArc(tangent1End: CGPoint, tangent2End: CGPoint,
radius: CGFloat, transform: CGAffineTransform = .identity) {
self.__addArc(transform: [transform], x1: tangent1End.x, y1: tangent1End.y,
x2: tangent2End.x, y2: tangent2End.y, radius: radius)
}
public func addPath(_ path: CGPath,
transform: CGAffineTransform = .identity) {
self.__addPath(transform: [transform], path: path)
}
}
| 31.215054 | 84 | 0.613848 |
db38eadb0f6b2bd9ceb0dbf092b5ae1eb00a934f | 3,344 | import Auth0ObjC // Added by Auth0toSPM
// JWTAlgorithmSpec.swift
//
// Copyright (c) 2019 Auth0 (http://auth0.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 Foundation
import Quick
import Nimble
@testable import Auth0
@available(iOS 10.0, macOS 10.12, *)
class JWTAlgorithmSpec: QuickSpec {
override func spec() {
let jwk = generateRSAJWK()
describe("signature validation") {
context("RS256") {
let alg = "RS256"
it("should verify the signature") {
expect(JWTAlgorithm.rs256.shouldVerify).to(beTrue())
}
it("should return true with a correct RS256 signature") {
let jwt = generateJWT(alg: alg)
expect(JWTAlgorithm.rs256.verify(jwt, using: jwk)).to(beTrue())
}
it("should return false with an empty signature") {
let jwt = generateJWT(alg: alg, signature: "")
expect(JWTAlgorithm.rs256.verify(jwt, using: jwk)).to(beFalse())
}
it("should return false with an incorrect signature") {
let jwt = generateJWT(alg: alg, signature: "abc123")
expect(JWTAlgorithm.rs256.verify(jwt, using: jwk)).to(beFalse())
}
}
context("HS256") {
let alg = "HS256"
it("should not verify the signature") {
expect(JWTAlgorithm.hs256.shouldVerify).to(beFalse())
}
it("should return true with any signature") {
let jwt = generateJWT(alg: alg, signature: "abc123")
expect(JWTAlgorithm.hs256.verify(jwt, using: jwk)).to(beTrue())
}
it("should return false with an empty signature") {
let jwt = generateJWT(alg: alg, signature: "")
expect(JWTAlgorithm.hs256.verify(jwt, using: jwk)).to(beFalse())
}
}
}
}
}
| 38.883721 | 84 | 0.561603 |
567a720d791935b53cd5e22eced504a5c6a0e967 | 2,562 | //
// UIImageViewGif.swift
// Gif
//
// Created by Jack on 2019/6/17.
// Copyright © 2019 Howeix. All rights reserved.
//
import UIKit
extension UIImageView {
static func JHCreateGIF(imageView: UIImageView, imageName: String, imageExtName: String? = nil) -> UIImageView {
let dataPath = Bundle.main.path(forResource: imageName, ofType: imageExtName ?? ".gif")
if let source = CGImageSourceCreateWithURL(NSURL(fileURLWithPath: dataPath!) as CFURL, nil){
let count: size_t = CGImageSourceGetCount(source)
var allTime: CGFloat = 0
let imageArray = NSMutableArray()
let timeArray = NSMutableArray()
let widthArray = NSMutableArray()
let heightArray = NSMutableArray()
for i in 0..<count {
if let image = CGImageSourceCreateImageAtIndex(source, i, nil) {
imageArray.add(image)
if let info = CGImageSourceCopyPropertiesAtIndex(source, i, nil) {
let imageinfo = info as NSDictionary
let width = imageinfo.object(forKey: kCGImagePropertyPixelWidth) as! Double
let height = imageinfo.object(forKey: kCGImagePropertyPixelHeight) as! Double
widthArray.add(NSNumber(floatLiteral: width))
heightArray.add(NSNumber(floatLiteral: height))
let timeDic = imageinfo.object(forKey: kCGImagePropertyGIFDictionary) as! NSDictionary
let time = timeDic.object(forKey: kCGImagePropertyGIFDelayTime) as! CGFloat
allTime += time
timeArray.add(NSNumber(floatLiteral: Double(time)))
}
}
}
let animation = CAKeyframeAnimation(keyPath: "contents")
let times = NSMutableArray()
var currentTime: CGFloat = 0
for i in 0..<imageArray.count {
times.add(NSNumber(floatLiteral: Double(currentTime / allTime)))
currentTime += timeArray[i] as! CGFloat
}
animation.keyTimes = (times as! [NSNumber])
animation.values = (imageArray as! [Any])
animation.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)]
animation.repeatCount = MAXFLOAT
animation.duration = CFTimeInterval(allTime)
imageView.layer.add(animation, forKey: "gifAnimation")
}
return imageView
}
}
| 48.339623 | 116 | 0.596409 |
dee2b81e81fa2ab1eda8d309eda4275dc2165c32 | 1,251 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.0.1-9346c8cc45
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
Whether a reference needs to be version specific or version independent, or whether either can be used.
URL: http://hl7.org/fhir/reference-version-rules
ValueSet: http://hl7.org/fhir/ValueSet/reference-version-rules
*/
public enum ReferenceVersionRules: String, FHIRPrimitiveType {
/// The reference may be either version independent or version specific.
case either = "either"
/// The reference must be version independent.
case independent = "independent"
/// The reference must be version specific.
case specific = "specific"
}
| 32.076923 | 104 | 0.739408 |
b9ab52610867d1d8f2066f32b38cf77fca8a45dc | 773 | //
// MarvelHashGeneratorTests.swift
// MarvelAPIClient
//
// Created by Pedro Vicente on 14/11/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
import XCTest
import Nimble
@testable import MarvelAPIClient
class MarvelHashGeneratorTests: XCTestCase {
func testGeneratesTheMd5HashUsingATimestampPlusThePublicKeyPlusThePrivateKey() {
let timestamp = 1
let privateKey = "abcd"
let publicKey = "1234"
let result = MarvelHashGenerator.generateHash(timestamp: timestamp,
privateKey: privateKey,
publicKey: publicKey)
expect(result).to(equal("ffd275c5130566a2916217b101f26150"))
}
}
| 26.655172 | 84 | 0.6326 |
f8624d8cb9419187c4b49868d84e4adc302dd67f | 496 | //
// HomeProductsCollectionCell.swift
// FyndAssignment
//
// Created by Tania Jasam on 28/03/20.
// Copyright © 2020 CodeIt. All rights reserved.
//
import UIKit
class HomeProductsCollectionCell: UICollectionViewCell {
@IBOutlet weak var productName: UILabel!
@IBOutlet weak var productPrice: UILabel!
@IBOutlet weak var productImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
productImage.layer.cornerRadius = 8.0
}
}
| 22.545455 | 56 | 0.699597 |
ff82db8f08ef1504ba031942a51c37f15fab9d5a | 462 | // 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
struct d{enum S<l:A{}enum A{func a{struct S<T where g:a{class a
| 46.2 | 79 | 0.748918 |
6a8364de09beff63e3a22b953fb0c4d2f3d0008f | 2,184 | //
// AppDelegate.swift
// BottomCurverdView
//
// Created by Digit Bazar on 13/03/18.
// Copyright © 2018 Incredible_Dev. 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.468085 | 285 | 0.756868 |
ac6f4aad8ee4c0d7bd86347381912980356ccd6c | 768 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// These two should not have the same type.
// CHECK: !DIGlobalVariable(name: "a",{{.*}} line: [[@LINE+2]]
// CHECK-SAME: type: ![[INT64:[0-9]+]]
var a : Int64 = 2
// CHECK: ![[INT64]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int64"
// CHECK-SAME: size: 64, align: 64
// CHECK-NOT: offset: 0
// CHECK-NOT: DIFlagFwdDecl
// CHECK-SAME: identifier: "_T0s5Int64VD"
// CHECK: !DIGlobalVariable(name: "b",{{.*}} line: [[@LINE+2]]
// CHECK-SAME: type: ![[INT:[0-9]+]]
var b = 2
// CHECK: ![[INT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int"
// CHECK-SAME: identifier: "_T0SiD"
| 40.421053 | 81 | 0.549479 |
f8334f62b7a8efe21f214d5ff761b781528a6c72 | 2,489 | import UIKit
class FeedModel {
private weak var feedView: UITableView?
weak var storage: Storage?
init(_ feedView: UITableView, _ storage: Storage) {
self.feedView = feedView
self.storage = storage
}
private var internetAvailable: Bool = true
func updater(url: String? = nil) {
let indicator = UIActivityIndicatorView(style: .gray)
indicator.startAnimating()
feedView?.backgroundView = indicator
func feedReloader(bg view: UIView? = nil) {
DispatchQueue.main.async { [weak feedView] in
feedView?.backgroundView = view
feedView?.reloadData()
}
}
guard let url = url else {
feedReloader()
return
}
func worker(with data: Data) {
Handler.work(with: data, storage) { [weak storage] (result: Result<Feed?,Error>) in
switch result {
case .success(let feed):
guard let feed = feed else { fatalError("feed nil") }
storage?.feed.setup(with: feed)
feedReloader()
case .failure(let error):
print("DECODE_ERROR:", error.localizedDescription)
if let text = String(data: data, encoding: .utf8) {
// Here you can implement the functionality you need,
// for example, when you receive a message from the server about exceeding the request limit
print("🟡 WARNING:", text)
}
}
}
}
API.get(to: url, with: { [self] in
do {
guard let data = try $0.get() else { fatalError("data nil") }
storage?.dataStorage.append(data)
internetAvailable = true
worker(with: data)
} catch {
print("🛑 CONNECTION FAILED!!!", error.localizedDescription)
guard internetAvailable else { return }
// MARK: Retrieving stored data from UserDefaults
// Everything works perfectly!
guard let key = storage?.dataBackupKey,
let datas: [Data] = storage?.dataBackup[key] else { return }
datas.forEach({ worker(with: $0) })
internetAvailable = false
}
})
}
}
| 36.072464 | 116 | 0.507433 |
1847859d6f90defb609bd49291fc5a85d7559d08 | 679 | //
// UsersListInteractor.swift
// GitHubExp
//
// Created by Marek on 29/10/2018.
// Copyright © 2018 MTruszko. All rights reserved.
//
import Moviper
import RxSwift
class UsersListInteractor: BaseRxInteractor, UsersListContractInteractor {
let gitHubUserRepository: AnyRepository<GitHubUser> =
assembler
.get(name: DIConstants.GutHubUser.repository)
let gitHubUserSpecification: Specification =
assembler
.get(name: DIConstants.GutHubUser.specification)
func getGitHubUsers() -> Observable<[GitHubUser]> {
return gitHubUserRepository
.query(specification: gitHubUserSpecification)
}
}
| 26.115385 | 74 | 0.699558 |
d9103a5ae738c5d39d1e318fa96077941b1d8cfb | 2,374 | @objc(MWMRoutePreviewTaxiCell)
final class RoutePreviewTaxiCell: UICollectionViewCell {
@IBOutlet private weak var icon: UIImageView!
@IBOutlet private weak var title: UILabel!
@IBOutlet private weak var info: UILabel!
@objc func config(type: MWMRoutePreviewTaxiCellType, title: String, eta: String, price: String, currency: String) {
let iconImage = { () -> UIImage in
switch type {
case .taxi: return #imageLiteral(resourceName: "icTaxiTaxi")
case .uber: return #imageLiteral(resourceName: "icTaxiUber")
case .yandex: return #imageLiteral(resourceName: "ic_taxi_logo_yandex")
case .maxim: return #imageLiteral(resourceName: "ic_taxi_logo_maksim")
case .vezet: return #imageLiteral(resourceName: "ic_taxi_logo_vezet")
case .freenow: return #imageLiteral(resourceName: "ic_logo_freenow")
case .yango: return #imageLiteral(resourceName: "ic_taxi_logo_yango")
case .citymobil: return #imageLiteral(resourceName: "ic_taxi_logo_citymobil_light")
}
}
let titleString = { () -> String in
switch type {
case .taxi, .uber, .freenow, .citymobil: return title
case .yandex: return L("yandex_taxi_title")
case .maxim: return L("maxim_taxi_title")
case .vezet: return L("vezet_taxi")
case .yango: return L("yango_taxi_title")
}
}
let priceString = { () -> String in
switch type {
case .taxi, .uber, .freenow: return price
case .yandex, .maxim, .vezet, .yango, .citymobil:
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = currency
formatter.maximumFractionDigits = 0
if let number = UInt(price), let formattedPrice = formatter.string(from: NSNumber(value: number)) {
return formattedPrice
} else {
return "\(currency) \(price)"
}
}
}
let timeString = { () -> String in
var timeValue = DateComponentsFormatter.etaString(from: TimeInterval(eta)!)!
if type == .vezet {
timeValue = String(coreFormat: L("place_page_starting_from"), arguments: [timeValue]);
}
return String(coreFormat: L("taxi_wait"), arguments: [timeValue])
}
icon.image = iconImage()
self.title.text = titleString()
info.text = "~ \(priceString()) • \(timeString())"
}
}
| 37.68254 | 117 | 0.658804 |
8749d16bf684b6868c7b8d4902dfcb86f01e91e4 | 7,001 | //
// RichEditorOptionItem.swift
//
// Created by Caesar Wirth on 4/2/15.
// Copyright (c) 2015 Caesar Wirth. All rights reserved.
//
import UIKit
/// A RichEditorOption object is an object that can be displayed in a RichEditorToolbar.
/// This protocol is proviced to allow for custom actions not provided in the RichEditorOptions enum.
public protocol RichEditorOption {
/// The image to be displayed in the RichEditorToolbar.
var image: UIImage? { get }
/// The title of the item.
/// If `image` is nil, this will be used for display in the RichEditorToolbar.
var title: String { get }
/// The action to be evoked when the action is tapped
/// - parameter editor: The RichEditorToolbar that the RichEditorOption was being displayed in when tapped.
/// Contains a reference to the `editor` RichEditorView to perform actions on.
func action(_ editor: RichEditorToolbar)
}
/// RichEditorOptionItem is a concrete implementation of RichEditorOption.
/// It can be used as a configuration object for custom objects to be shown on a RichEditorToolbar.
public struct RichEditorOptionItem: RichEditorOption {
/// The image that should be shown when displayed in the RichEditorToolbar.
public var image: UIImage?
/// If an `itemImage` is not specified, this is used in display
public var title: String
/// The action to be performed when tapped
public var handler: ((RichEditorToolbar) -> Void)
public init(image: UIImage? = nil, title: String, action: @escaping ((RichEditorToolbar) -> Void)) {
self.image = image
self.title = title
self.handler = action
}
public init(title: String, action: @escaping ((RichEditorToolbar) -> Void)) {
self.init(image: nil, title: title, action: action)
}
// MARK: RichEditorOption
public func action(_ toolbar: RichEditorToolbar) {
handler(toolbar)
}
}
/// RichEditorOptions is an enum of standard editor actions
public enum RichEditorDefaultOption: RichEditorOption {
case clear
case undo
case redo
case bold
case italic
case `subscript`
case superscript
case strike
case underline
case textColor
case textBackgroundColor
case header(Int)
case indent
case outdent
case orderedList
case unorderedList
case alignLeft
case alignCenter
case alignRight
case image
case link
public static let all: [RichEditorDefaultOption] = [
//.clear,
.undo, .redo, .bold, .italic,
.subscript, .superscript, .strike, .underline,
.textColor, .textBackgroundColor,
.header(1), .header(2), .header(3), .header(4), .header(5), .header(6),
.indent, outdent, orderedList, unorderedList,
.alignLeft, .alignCenter, .alignRight, .image, .link
]
// MARK: RichEditorOption
public var image: UIImage? {
var name = ""
switch self {
case .clear: name = "clear"
case .undo: name = "undo"
case .redo: name = "redo"
case .bold: name = "bold"
case .italic: name = "italic"
case .subscript: name = "subscript"
case .superscript: name = "superscript"
case .strike: name = "strikethrough"
case .underline: name = "underline"
case .textColor: name = "text_color"
case .textBackgroundColor: name = "bg_color"
case .header(let h): name = "h\(h)"
case .indent: name = "indent"
case .outdent: name = "outdent"
case .orderedList: name = "ordered_list"
case .unorderedList: name = "unordered_list"
case .alignLeft: name = "justify_left"
case .alignCenter: name = "justify_center"
case .alignRight: name = "justify_right"
case .image: name = "insert_image"
case .link: name = "insert_link"
}
let bundle = Bundle(for: RichEditorToolbar.self)
return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
}
public var title: String {
switch self {
case .clear: return NSLocalizedString("Clear", comment: "")
case .undo: return NSLocalizedString("Undo", comment: "")
case .redo: return NSLocalizedString("Redo", comment: "")
case .bold: return NSLocalizedString("Bold", comment: "")
case .italic: return NSLocalizedString("Italic", comment: "")
case .subscript: return NSLocalizedString("Sub", comment: "")
case .superscript: return NSLocalizedString("Super", comment: "")
case .strike: return NSLocalizedString("Strike", comment: "")
case .underline: return NSLocalizedString("Underline", comment: "")
case .textColor: return NSLocalizedString("Color", comment: "")
case .textBackgroundColor: return NSLocalizedString("BG Color", comment: "")
case .header(let h): return NSLocalizedString("H\(h)", comment: "")
case .indent: return NSLocalizedString("Indent", comment: "")
case .outdent: return NSLocalizedString("Outdent", comment: "")
case .orderedList: return NSLocalizedString("Ordered List", comment: "")
case .unorderedList: return NSLocalizedString("Unordered List", comment: "")
case .alignLeft: return NSLocalizedString("Left", comment: "")
case .alignCenter: return NSLocalizedString("Center", comment: "")
case .alignRight: return NSLocalizedString("Right", comment: "")
case .image: return NSLocalizedString("Image", comment: "")
case .link: return NSLocalizedString("Link", comment: "")
}
}
public func action(_ toolbar: RichEditorToolbar) {
switch self {
case .clear: toolbar.editor?.removeFormat()
case .undo: toolbar.editor?.undo()
case .redo: toolbar.editor?.redo()
case .bold: toolbar.editor?.bold()
case .italic: toolbar.editor?.italic()
case .subscript: toolbar.editor?.subscriptText()
case .superscript: toolbar.editor?.superscript()
case .strike: toolbar.editor?.strikethrough()
case .underline: toolbar.editor?.underline()
case .textColor: toolbar.delegate?.richEditorToolbarChangeTextColor?(toolbar)
case .textBackgroundColor: toolbar.delegate?.richEditorToolbarChangeBackgroundColor?(toolbar)
case .header(let h): toolbar.editor?.header(h)
case .indent: toolbar.editor?.indent()
case .outdent: toolbar.editor?.outdent()
case .orderedList: toolbar.editor?.orderedList()
case .unorderedList: toolbar.editor?.unorderedList()
case .alignLeft: toolbar.editor?.alignLeft()
case .alignCenter: toolbar.editor?.alignCenter()
case .alignRight: toolbar.editor?.alignRight()
case .image: toolbar.delegate?.richEditorToolbarInsertImage?(toolbar)
case .link: toolbar.delegate?.richEditorToolbarInsertLink?(toolbar)
}
}
}
| 39.778409 | 111 | 0.653907 |
678a9531e6448d312c920ad3c009c9f2613a8b53 | 463 | //
// Types.swift
// Covid-19 Status
//
// Created by Marcin Gajda on 24/03/2020.
// Copyright © 2020 Marcin Gajda. All rights reserved.
//
struct RegionStats: Decodable {
let country: String;
let cases: Int;
let todayCases: Int?;
let deaths: Int;
let todayDeaths: Int?;
let recovered: Int;
let active: Int;
let critical: Int;
}
struct CoronaStats: Decodable {
let data: [RegionStats];
let worldStats: RegionStats;
}
| 19.291667 | 55 | 0.650108 |
728b63c3e8a2913f06db05ed35d0f0fecf0ccc47 | 171 | #if os(Linux)
import XCTest
@testable import AppTests
XCTMain([
// AppTests
testCase(NoteControllerTests.allTests),
testCase(RouteTests.allTests)
])
#endif
| 13.153846 | 43 | 0.725146 |
d629f7e569446d0beb91e7820f8ae12fd7671a50 | 4,756 | //
// MIDISendVC.swift
// MIDIUtility
//
// Created by Jeff Cooper on 9/13/17.
// Copyright © 2017 AudioKit. All rights reserved.
//
import Foundation
import AudioKit
import Cocoa
class MIDISenderVC: NSViewController {
let midiOut = AKMIDI()
@IBOutlet var noteNumField: NSTextField!
@IBOutlet var noteVelField: NSTextField!
@IBOutlet var noteChanField: NSTextField!
@IBOutlet var ccField: NSTextField!
@IBOutlet var ccValField: NSTextField!
@IBOutlet var ccChanField: NSTextField!
@IBOutlet var sysexField: NSTextView!
var noteToSend: Int? {
return Int(noteNumField.stringValue)
}
var velocityToSend: Int? {
return Int(noteVelField.stringValue)
}
var noteChanToSend: Int {
if Int(noteChanField.stringValue) == nil {
return 1
}
return Int(noteChanField.stringValue)! - 1
}
var ccToSend: Int? {
return Int(ccField.stringValue)
}
var ccValToSend: Int? {
return Int(ccValField.stringValue)
}
var ccChanToSend: Int {
if Int(ccChanField.stringValue) == nil {
return 1
}
return Int(ccChanField.stringValue)! - 1
}
var sysexToSend: [Int]? {
var data = [Int]()
let splitField = sysexField.string.components(separatedBy: " ")
for entry in splitField {
let intVal = Int(entry)
if intVal != nil && intVal! <= 247 && intVal! > -1 {
data.append(intVal!)
}
}
return data
}
override func viewDidLoad() {
midiOut.openOutput()
}
@IBAction func sendNotePressed(_ sender: NSButton) {
if noteToSend != nil && velocityToSend != nil {
Swift.print("sending note: \(noteToSend!) - \(velocityToSend!)")
let event = AKMIDIEvent(noteOn: MIDINoteNumber(noteToSend!), velocity: MIDIVelocity(velocityToSend!), channel: MIDIChannel(noteChanToSend))
midiOut.sendEvent(event)
} else {
print("error w note fields")
}
}
@IBAction func sendCCPressed(_ sender: NSButton) {
if ccToSend != nil && ccValToSend != nil {
Swift.print("sending cc: \(ccToSend!) - \(ccValToSend!)")
let event = AKMIDIEvent(controllerChange: MIDIByte(ccToSend!), value: MIDIByte(ccValToSend!), channel: MIDIChannel(ccChanToSend))
midiOut.sendEvent(event)
} else {
print("error w cc fields")
}
}
@IBAction func sendSysexPressed(_ sender: NSButton) {
if sysexToSend != nil {
var midiBytes = [MIDIByte]()
for byte in sysexToSend! {
midiBytes.append(MIDIByte(byte))
}
if midiBytes[0] != 240 || midiBytes.last != 247 || midiBytes.count < 2 {
Swift.print("bad sysex data - must start with 240 and end with 247")
Swift.print("parsed sysex: \(sysexToSend!)")
return
}
Swift.print("sending sysex \(sysexToSend!)")
let event = AKMIDIEvent(data: midiBytes)
midiOut.sendEvent(event)
} else {
print("error w sysex field")
}
}
}
class MIDIChannelFormatter: NumberFormatter {
override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
Swift.print("checking string")
let partialStr = partialStringPtr.pointee
let charset = CharacterSet(charactersIn: "0123456789").inverted
let result = partialStr.rangeOfCharacter(from: charset)
if result.length > 0 || partialStr.intValue > 16 || partialStr == "0" || partialStr.length > 2 {
return false
}
return true
}
}
class MIDINumberFormatter: NumberFormatter {
override func isPartialStringValid(_ partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString>, proposedSelectedRange proposedSelRangePtr: NSRangePointer?, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
Swift.print("checking string")
let partialStr = partialStringPtr.pointee
let charset = CharacterSet(charactersIn: "0123456789").inverted
let result = partialStr.rangeOfCharacter(from: charset)
if result.length > 0 || partialStr.intValue > 127 || partialStr == "0000" || partialStr.length > 3 {
return false
}
return true
}
}
| 38.048 | 324 | 0.634146 |
16543167ee9ac35995b096cc2b03981ec4a7dfbc | 966 | //
// AppDelegate.swift
// Scholarship
//
// Created by Laurin Brandner on 06/02/15.
// Copyright (c) 2015 Laurin Brandner. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private lazy var window: UIWindow = {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
window.backgroundColor = UIColor.whiteColor()
window.tintColor = UIColor.brandnerColor()
return window
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let controller = WelcomeViewController()
let navigationController = UINavigationController(rootViewController: controller)
navigationController.navigationBarHidden = true
window.rootViewController = navigationController
self.window.makeKeyAndVisible()
return true
}
}
| 26.833333 | 127 | 0.694617 |
1ca6dbcf9dde34fa688f1b3ce8223c437ae869ab | 4,678 | //
// SFUIViewExtentions.swift
// Pods-SFLibrary_Example
//
// Created by sattar.falahati on 27/03/18.
//
import Foundation
extension UIView
{
// MARK: - Border and corners
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat
{
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor
{
get {
return .clear
}
set {
layer.borderColor = newValue.cgColor
}
}
public func roundViewWith(borderColor: UIColor, borderWidth: CGFloat)
{
cornerRadiusWith(radius: self.layer.frame.size.width / 2, borderColor: borderColor, borderWidth: borderWidth)
}
public func cornerRadiusWith(radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat)
{
setBorderWith(borderColor: borderColor, borderWidth: borderWidth)
self.layer.cornerRadius = radius
}
public func setBorderWith(borderColor: UIColor, borderWidth: CGFloat)
{
self.layer.borderColor = borderColor.cgColor
self.layer.borderWidth = borderWidth
self.clipsToBounds = true
}
public func setBottomCornerRadiusWith(radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat)
{
if #available(iOS 11.0, *) {
self.clipsToBounds = true
self.layer.cornerRadius = radius
self.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
if borderWidth != 0 {
self.setBorderWith(borderColor: borderColor, borderWidth: borderWidth)
}
}
else{
self.roundCornersWith(corners: [.bottomLeft , .bottomRight], radius: radius, borderColor: borderColor, borderWidth: borderWidth)
}
}
public func setTopCornerRadiusWith(radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat)
{
if #available(iOS 11.0, *) {
self.clipsToBounds = true
self.layer.cornerRadius = radius
self.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
if borderWidth != 0 {
self.setBorderWith(borderColor: borderColor, borderWidth: borderWidth)
}
}
else{
self.roundCornersWith(corners: [.topRight , .topLeft], radius: radius, borderColor: borderColor, borderWidth: borderWidth)
}
}
public func roundCornersWith(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat)
{
// Setup bezier path
let bezPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
// Setup round corners
let rectShape = CAShapeLayer()
rectShape.frame = self.bounds
rectShape.path = bezPath
self.layer.mask = rectShape
// Setup border
let rectShapeForBorder = CAShapeLayer()
rectShapeForBorder.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
rectShapeForBorder.strokeColor = borderColor.cgColor
rectShapeForBorder.fillColor = UIColor.clear.cgColor
rectShapeForBorder.lineWidth = borderWidth
rectShapeForBorder.frame = .zero
self.layer.addSublayer(rectShapeForBorder)
}
// MARK: - Image creation
public func createImageFromView () -> UIImage?
{
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
defer {
UIGraphicsEndImageContext()
}
if let contex = UIGraphicsGetCurrentContext() {
self.layer.render(in: contex)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
return nil
}
// MARK: - Shadow
public func setShadowWith(shadowColor: UIColor,shadowOffset: CGSize,shadowOpacity: CGFloat, shadowRadius: CGFloat)
{
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOffset = shadowOffset
self.layer.shadowOpacity = Float(shadowOpacity)
self.layer.shadowRadius = shadowRadius
self.layer.masksToBounds = false
}
}
| 31.395973 | 159 | 0.61864 |
eb70d0289bf1fcb3cd11cba4793f6231082cb79b | 1,095 | //
// NewsTVC.swift
// BeeApp
//
// Created by iOSDev on 20/04/21.
//
import UIKit
import SafariServices
class NewsTVC: YZParentTVC {
@IBOutlet weak var imgMain: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblDate: UILabel!
weak var parentVC: HomeVC!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
var newsModel: NewsModel? {
didSet {
setData()
}
}
func setData() {
guard let model = newsModel else { return }
imgMain.setImageWith(model.imageURL, placeholder: UIImage(named: "iconUserPlaceholder"), completionBlock: nil)
lblTitle.text = model.title
lblDate.text = model.strDate
}
@IBAction func btnMorePressed(_ sender: UIButton) {
guard let model = newsModel else { return }
if let url = URL(string: model.urlNews) {
let safariVC = SFSafariViewController(url: url)
parentVC.present(safariVC, animated: true, completion: nil)
}
}
}
| 24.333333 | 118 | 0.611872 |
6abd614c9d381a576b4b271ab8fae5a4056613a1 | 292 | // 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 A{let a{{let:A{{A:{t v{class d{let a{{{a d{class c{func b{c{let:{{f=b
| 36.5 | 87 | 0.712329 |
08d1ee6451353a3f97239be507d26b5c490fdc14 | 612 | //
// PlanningGroupReference.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Planning Group */
public class PlanningGroupReference: Codable {
/** The globally unique identifier for the object. */
public var _id: String?
/** The URI for this object */
public var selfUri: String?
public init(_id: String?, selfUri: String?) {
self._id = _id
self.selfUri = selfUri
}
public enum CodingKeys: String, CodingKey {
case _id = "id"
case selfUri
}
}
| 17 | 57 | 0.607843 |
e81decb390fbf467406ba71034ed32692f6e57b0 | 5,330 | // The MIT License (MIT)
//
// Copyright (c) 2019 Inácio Ferrarini
//
// 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
///
/// Array-based UICollectionView data source having elements of type `Type` and using `ConfigurableCollectionViewCell`.
///
open class CollectionViewArrayDataSource<CellType: UICollectionViewCell, Type: Equatable>: ArrayDataSource<Type>, UICollectionViewDataSource
where CellType: Configurable {
// MARK: - Properties
///
/// TableView that owns this DataSource.
///
public let collectionView: UICollectionView
///
/// Returns the Reuse Identifier for a Cell at the given `IndexPath`.
///
let reuseIdentifier: ((IndexPath) -> (String))
///
/// This clojure is executed, for each cell, before the cell's `setup` method is executed.
/// Allows a custom preparation of the cell to take place before setup is properly executed.
///
public var prepareCellBlock: ((_ cell: CellType) -> Void)?
// MARK: - Initialization
///
/// Inits the DataSource providing an UICollectionView and its objects.
/// Assumes the ReuseIdentifier will have the same name as `CellType` type.
///
/// - parameter for: The target UICollectionView.
///
/// - parameter dataProvider: The array-based Data provider.
///
public convenience init(for collectionView: UICollectionView, with dataProvider: ArrayDataProvider<Type>) {
let reuseIdentifier = { (indexPath: IndexPath) -> String in
return CellType.simpleClassName()
}
self.init(for: collectionView,
reuseIdentifier: reuseIdentifier,
with: dataProvider)
}
///
/// Inits the DataSource providing an UICollectionView and its objects.
///
/// - parameter for: The target UICollectionView.
///
/// - parameter reuseIdentifier: Block used to define the Ruse Identifier based on the given IndexPath.
///
/// - parameter dataProvider: The array-based Data provider.
///
public required init(for collectionView: UICollectionView,
reuseIdentifier: @escaping ((IndexPath) -> (String)),
with dataProvider: ArrayDataProvider<Type>) {
self.collectionView = collectionView
self.reuseIdentifier = reuseIdentifier
super.init(with: dataProvider)
}
// MARK: - Public Methods
///
/// Propagates through `onRefresh` a refresh for interested objects and also
/// calls `reloadData` on `tableView`.
///
open override func refresh() {
super.refresh()
self.collectionView.reloadData()
}
// MARK: - Collection View Data Source
///
/// Returns the number of items in its only section. The number of items always matches the number of contained objects.
///
/// - parameter collectionView: The target UICollectionView.
///
/// - parameter section: The desired sections. Values different than `0` will result in `0` being returned.
///
/// - returns: number of objects.
///
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataProvider.numberOfItems(in: section)
}
///
/// Returns the number of items in its only section. The number of rows always matches the number of contained objects.
///
/// - parameter collectionView: The target UICollectionView.
///
/// - parameter cellForItemAt: The indexPath for the given object, or `nil` if not found.
///
/// - returns: number of objects.
///
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let reuseIdentifier = self.reuseIdentifier(indexPath)
guard var cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? CellType else {
fatalError("Cell with reuse identifier \"\(reuseIdentifier)\" not found.")
}
if let value = self.dataProvider[indexPath] as? CellType.ValueType {
self.prepareCellBlock?(cell)
cell.setup(with: value)
}
return cell
}
}
| 39.481481 | 140 | 0.674484 |
1e606f83c2019619e7319ff4a514aa35c1adcade | 2,372 | //
// Copyright (c) 2018 Related Code - http://relatedcode.com
//
// 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.
//-------------------------------------------------------------------------------------------------------------------------------------------------
class DBMessage: RLMObject {
@objc dynamic var objectId = ""
@objc dynamic var chatId = ""
@objc dynamic var members = ""
@objc dynamic var senderId = ""
@objc dynamic var senderName = ""
@objc dynamic var senderInitials = ""
@objc dynamic var senderPictureAt: Int64 = 0
@objc dynamic var recipientId = ""
@objc dynamic var recipientName = ""
@objc dynamic var recipientInitials = ""
@objc dynamic var recipientPictureAt: Int64 = 0
@objc dynamic var groupId = ""
@objc dynamic var groupName = ""
@objc dynamic var type = ""
@objc dynamic var text = ""
@objc dynamic var pictureWidth: Int = 0
@objc dynamic var pictureHeight: Int = 0
@objc dynamic var pictureMD5 = ""
@objc dynamic var videoDuration: Int = 0
@objc dynamic var videoMD5 = ""
@objc dynamic var audioDuration: Int = 0
@objc dynamic var audioMD5 = ""
@objc dynamic var latitude: CLLocationDegrees = 0
@objc dynamic var longitude: CLLocationDegrees = 0
@objc dynamic var status = ""
@objc dynamic var isDeleted = false
@objc dynamic var createdAt: Int64 = 0
@objc dynamic var updatedAt: Int64 = 0
//---------------------------------------------------------------------------------------------------------------------------------------------
class func lastUpdatedAt() -> Int64 {
let dbmessage = DBMessage.allObjects().sortedResults(usingKeyPath: "updatedAt", ascending: true).lastObject() as? DBMessage
return dbmessage?.updatedAt ?? 0
}
//---------------------------------------------------------------------------------------------------------------------------------------------
override static func primaryKey() -> String? {
return FMESSAGE_OBJECTID
}
}
| 34.882353 | 147 | 0.588954 |
e839a3f355cf38f008af2beafe121e776b00c412 | 4,252 | //
// SignUpTeamUrl.swift
// SecondTaut
//
// Created by Matrix Marketers on 21/08/19.
// Copyright © 2019 pawan. All rights reserved.
//
import UIKit
import MyBaby
import NVActivityIndicatorView
class SignUpTeamUrl: UIViewController,UITextFieldDelegate,ApiResponceDelegateMB,NVActivityIndicatorViewable {
@IBOutlet weak var btnNext: UIButton!
@IBOutlet weak var viewBtnNext: UIView!
@IBOutlet weak var txtTeamUrl: UITextField!
var TeamName : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
self.viewBtnNext.layer.cornerRadius = 6
self.txtTeamUrl.becomeFirstResponder()
if self.txtTeamUrl.text == ""{
txtTeamUrl.textAlignment = .left
}
else{
txtTeamUrl.textAlignment = .right
}
}
//MARK: - TextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.NextScreen()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string != ""{
if self.txtTeamUrl.text!.count > 19{
return false
}
}
self.txtTeamUrl.placeholder = ""
if string == "" && self.txtTeamUrl.text?.count == 1{
self.txtTeamUrl.placeholder = "your_team"
txtTeamUrl.textAlignment = .left
}
else{
txtTeamUrl.textAlignment = .right
}
let ACCEPTABLE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
let cs = NSCharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
let filtered = string.components(separatedBy: cs).joined(separator: "")
return (string == filtered)
}
@IBAction func btnBack(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func btnNext(_ sender: Any) {
self.NextScreen()
}
func NextScreen(){
if txtTeamUrl.text == ""{
MyBaby.Alert.AlertForTextFieldAppear(Message: "Please enter team url", TextField: self.txtTeamUrl)
}
else{
self.CheckTeamUrl()
}
}
//MARK: - ApiCall
func CheckTeamUrl(){
self.startAnimating(CGSize(width: 50, height:50), message: "", type: NVActivityIndicatorType.ballScaleRippleMultiple)
MyBaby.Loader.ButtonLoader(Button: self.btnNext, LoaderColour: UIColor.black, show: true)
MyBaby.ApiCall.ApiHitUsingPostMethod(APiUrl: ApiUrlCall.BaseUrl + ApiUrlCall.RegisterCheckTeamUrl as NSString, HeaderParameter: ["Content-Type":"application/x-www-form-urlencoded"], BodyParameter: ["teamurl":self.txtTeamUrl.text!], ApiName: "CheckTeamExistOrNot", Log: true, Controller: self)
}
func ApiResponceSuccess(Success: NSDictionary) {
print(Success)
self.stopAnimating()
MyBaby.Loader.ButtonLoader(Button: self.btnNext, LoaderColour: UIColor.black, show: false)
MyBaby.Alert.AlertAppear(Messaage: Success["message"] as! String, Title: "", View: self, Button: true, SingleButton: true, FirstButtonText: "OK", SecondButtonText: "")
}
func ApiResponceFailure(Failure: NSDictionary) {
MyBaby.Loader.ButtonLoader(Button: self.btnNext, LoaderColour: UIColor.black, show: false)
self.stopAnimating()
let Instace = self.storyboard?.instantiateViewController(withIdentifier: "SignUpFullName") as! SignUpFullName
Instace.TeamName = self.TeamName
Instace.TeamUrl = self.txtTeamUrl.text!
self.navigationController?.pushViewController(Instace, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 35.731092 | 300 | 0.65428 |
61ec49a4d768455dc5bed611de33b6bcdf18d1a4 | 218 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let end = [ {
protocol g {
enum S {
class
case ,
| 21.8 | 87 | 0.733945 |
3369400067389c1b7322499656417723ff433625 | 2,251 | /// Type used by `Range` and `Count` validators to indicate where a value fell within a range.
public enum RangeResult<T>: Equatable where T: Comparable{
/// The value was between `min` and `max`.
case between(min: T, max: T)
/// The value was greater than or equal to `min`.
case greaterThanOrEqualToMin(T)
/// The value was greater than `max`.
case greaterThanMax(T)
/// The value was less than or equal to `max`.
case lessThanOrEqualToMax(T)
/// The value was less than `min`.
case lessThanMin(T)
var isWithinRange: Bool {
switch self {
case .between, .greaterThanOrEqualToMin, .lessThanOrEqualToMax: return true
case .greaterThanMax, .lessThanMin: return false
}
}
var description: String {
switch self {
case let .between(min, max):
return "between \(min) and \(max)"
case let .greaterThanOrEqualToMin(min):
return "greater than or equal to minimum of \(min)"
case let .greaterThanMax(max):
return "greater than maximum of \(max)"
case let .lessThanMin(min):
return "less than minimum of \(min)"
case let .lessThanOrEqualToMax(max):
return "less than or equal to maximum of \(max)"
}
}
init(min: T?, max: T?, value: T) {
precondition(min != nil || max != nil, "Either `min` or `max` has to be non-nil")
switch (min, max) {
case let (.some(min), .some(max)) where value >= min && value <= max:
self = .between(min: min, max: max)
case let (.some(min), _) where value < min:
self = .lessThanMin(min)
case let (_, .some(max)) where value > max:
self = .greaterThanMax(max)
case let (.some(min), _):
self = .greaterThanOrEqualToMin(min)
case let (_, .some(max)):
self = .lessThanOrEqualToMax(max)
case (.none, .none):
// This cannot happen because all static methods on `Validator` that can make
// the count and range validators all result in at least a minimum or a maximum or both.
fatalError("No minimum or maximum was supplied to the Count validator")
}
}
}
| 37.516667 | 100 | 0.591737 |
5d62bc003704e5c56aa46c8aa0308867dd20e016 | 1,664 | //
// FoundationDeprecated.swift
// SwifterSwift
//
// Created by Guy Kogus on 04/10/2018.
// Copyright © 2018 SwifterSwift
//
#if canImport(Foundation)
import Foundation
extension Date {
/// SwifterSwift: Random date between two dates.
///
/// Date.random()
/// Date.random(from: Date())
/// Date.random(upTo: Date())
/// Date.random(from: Date(), upTo: Date())
///
/// - Parameters:
/// - fromDate: minimum date (default is Date.distantPast)
/// - toDate: maximum date (default is Date.distantFuture)
/// - Returns: random date between two dates.
@available(*, deprecated: 4.7.0, message: "Use random(in:) or random(in:using:) instead")
public static func random(from fromDate: Date = Date.distantPast, upTo toDate: Date = Date.distantFuture) -> Date {
guard fromDate != toDate else {
return fromDate
}
let diff = llabs(Int64(toDate.timeIntervalSinceReferenceDate - fromDate.timeIntervalSinceReferenceDate))
var randomValue: Int64 = Int64.random(in: Int64.min...Int64.max)
randomValue = llabs(randomValue%diff)
let startReferenceDate = toDate > fromDate ? fromDate : toDate
return startReferenceDate.addingTimeInterval(TimeInterval(randomValue))
}
/// SwifterSwift: Time zone used currently by system.
///
/// Date().timeZone -> Europe/Istanbul (current)
///
@available(*, deprecated: 4.7.0, message: "`Date` objects are timezone-agnostic. Please use Calendar.current.timeZone instead.")
public var timeZone: TimeZone {
return Calendar.current.timeZone
}
}
#endif
| 33.28 | 132 | 0.647837 |
1da0430d9a16a09d75fc73f8b41a45602a049f60 | 1,219 | //
// Copyright © 2019 Frollo. 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 CoreData
import Foundation
extension PayAnyoneContact {
/**
Fetch Request
- returns: Fetch request for `PayAnyoneContact` type
*/
@nonobjc public class func fetchRequest() -> NSFetchRequest<PayAnyoneContact> {
return NSFetchRequest<PayAnyoneContact>(entityName: "PayAnyoneContact")
}
/// Account name of the contact
@NSManaged public var accountHolder: String
/// BSB of the contact
@NSManaged public var bsb: String
/// Account number of the contact
@NSManaged public var accountNumber: String
}
| 29.731707 | 83 | 0.698113 |
28da49a8cdbc90f0b1554994a3e9a1ea0550d4fa | 277 | //
// ViewController.swift
// SpeakFruit
//
// Created by Brena Amorim on 22/06/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 15.388889 | 58 | 0.65343 |
9bb5aa7af626c95ca4319f2e33f795e243afc047 | 3,300 | // REQUIRES: VENDOR=apple
// RUN: %empty-directory(%t)
// RUN: %empty-directory(%t.mod1)
// RUN: %empty-directory(%t.mod2)
// RUN: %empty-directory(%t.sdk)
// RUN: %empty-directory(%t.module-cache)
// RUN: %empty-directory(%t.baseline/ABI)
// RUN: echo "public func foo() {}" > %t.mod1/Foo.swift
// RUN: echo "public func bar() {}" > %t.mod2/Foo.swift
// RUN: echo "Foo: Func foo() has been removed" > %t/incomplete-allowlist.txt
// RUN: echo "Foo: Func foo() has been removed" > %t/complete-allowlist.txt
// RUN: echo "Foo: Func bar() is a new API without @available attribute" >> %t/complete-allowlist.txt
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-module -o %t.mod1/Foo.swiftmodule %t.mod1/Foo.swift -parse-as-library -enable-library-evolution -emit-module-source-info -emit-module-source-info-path %t.mod1/Foo.swiftsourceinfo -emit-module-interface-path %t.mod1/Foo.swiftinterface -module-name Foo -swift-version 5
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-module -o %t.mod2/Foo.swiftmodule %t.mod2/Foo.swift -parse-as-library -enable-library-evolution -emit-module-source-info -emit-module-source-info-path %t.mod2/Foo.swiftsourceinfo -emit-module-interface-path %t.mod2/Foo.swiftinterface -module-name Foo -swift-version 5
// RUN: %api-digester -dump-sdk -module Foo -output-dir %t.baseline -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod1 -abi -use-interface-for-module Foo
// RUN: %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -breakage-allowlist-path %t/complete-allowlist.txt -o %t/expected-diags.txt
// RUN: not %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -compiler-style-diags
// RUN: not %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -compiler-style-diags -breakage-allowlist-path %t/incomplete-allowlist.txt
// RUN: %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -compiler-style-diags -breakage-allowlist-path %t/complete-allowlist.txt
// RUN: not %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -serialize-diagnostics-path %t/serialized-diag.dia
// RUN: ls %t/serialized-diag.dia
// RUN: not %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -serialize-diagnostics-path %t/serialized-diag.dia -breakage-allowlist-path %t/incomplete-allowlist.txt
// RUN: ls %t/serialized-diag.dia
// RUN: %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module Foo -I %t.mod2 -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -serialize-diagnostics-path %t/serialized-diag.dia -breakage-allowlist-path %t/complete-allowlist.txt
// RUN: ls %t/serialized-diag.dia
| 84.615385 | 351 | 0.745455 |
223bfe5f1c21be0522f702da2112787a30f968a6 | 6,564 | //
// CodableExtension.swift
// ZDPlayerDemo
//
// Created by season on 2019/2/22.
// Copyright © 2019 season. All rights reserved.
//
import Foundation
extension JSONEncoder {
/// 序列化到沙盒的错误
///
/// - createDirectoryError: 创建文件夹的错误
/// - encodeError: 序列化错误
/// - writeError: 写入错误
public enum EncodeToSandBoxError: Error {
case encodeError
case createDirectoryError
case writeError
}
/// 便利构造函数
public convenience init(outputFormatting: JSONEncoder.OutputFormatting = .prettyPrinted,
dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .deferredToDate,
dataEncodingStrategy: JSONEncoder.DataEncodingStrategy = .base64,
nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategy = .throw,
keyEncodingStrategy: JSONEncoder.KeyEncodingStrategy = .useDefaultKeys) {
self.init()
self.outputFormatting = outputFormatting
self.dateEncodingStrategy = dateEncodingStrategy
self.dataEncodingStrategy = dataEncodingStrategy
self.nonConformingFloatEncodingStrategy = nonConformingFloatEncodingStrategy
self.keyEncodingStrategy = keyEncodingStrategy
}
/// 类方法写入
///
/// - Parameters:
/// - model: 模型
/// - filePath: 文件路径
/// - Throws: 抛出的错误 EncodeToSandBoxError
public static func write<T: Codable>(model: T, filePath: String) throws {
try JSONEncoder().write(model: model, filePath: filePath)
}
/// 写入
///
/// - Parameters:
/// - model: 模型
/// - filePath: 文件路径
/// - Throws: 抛出的错误 EncodeToSandBoxError
public func write<T: Codable>(model: T, filePath: String) throws {
// 编码
let data: Data
do {
data = try encode(model)
} catch {
throw EncodeToSandBoxError.encodeError
}
// 文件夹相关
let folder = (filePath as NSString).deletingLastPathComponent
if !FileManager.default.fileExists(atPath: folder) {
do {
try FileManager.default.createDirectory(atPath: folder, withIntermediateDirectories: true, attributes: nil)
}catch {
throw EncodeToSandBoxError.createDirectoryError
}
}
let fileUrl = URL(fileURLWithPath: filePath)
// 写入到沙盒
do {
try data.write(to: fileUrl)
} catch {
throw EncodeToSandBoxError.writeError
}
}
/// 类方法模型转Data
///
/// - Parameter model: 模型
/// - Returns: Data
public static func transformModelToData<T: Codable>(_ model: T) -> Data? {
return try? JSONEncoder().encode(model)
}
/// 类方法模型转JSONString
///
/// - Parameter model: 模型
/// - Returns: String
public static func transformModelToJSONString<T: Codable>(_ model: T) -> String? {
guard let data = try? JSONEncoder().encode(model) else {
return nil
}
return String(data: data, encoding: .utf8)
}
/// 类方法模型转JSONObject 典型的是字典
///
/// - Parameter model: 模型
/// - Returns: Any
public static func transformModelToJSONObject<T: Codable>(_ model: T) -> Any? {
guard let data = try? JSONEncoder().encode(model) else {
return nil
}
return try? JSONSerialization.jsonObject(with: data, options: [])
}
/// 模型转Data
///
/// - Parameter model: 模型
/// - Returns: Data
public func transformModelToData<T: Codable>(_ model: T) -> Data? {
return try? encode(model)
}
/// 模型转JSONString
///
/// - Parameter model: 模型
/// - Returns: String
public func transformModelToJSONString<T: Codable>(_ model: T) -> String? {
guard let data = try? encode(model) else {
return nil
}
return String(data: data, encoding: .utf8)
}
/// 模型转JSONObject 典型的是字典
///
/// - Parameter model: 模型
/// - Returns: Any
public func transformModelToJSONObject<T: Codable>(_ model: T) -> Any? {
guard let data = try? encode(model) else {
return nil
}
return try? JSONSerialization.jsonObject(with: data, options: [])
}
}
extension JSONDecoder {
/// 反序列化的错误
///
/// - fileNotExists: 文件不存在的错误
/// - readError: 读取数据错误
/// - decodeError: 反序列化错误
public enum DecodeFromSandBoxError: Error {
case fileNotExists
case readError
case decodeError
}
/// 便利构造函数
public convenience init(dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate,
dataDecodingStrategy: JSONDecoder.DataDecodingStrategy = .base64,
nonConformingFloatDecodingStrategy: JSONDecoder.NonConformingFloatDecodingStrategy = .throw,
keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) {
self.init()
self.dateDecodingStrategy = dateDecodingStrategy
self.dataDecodingStrategy = dataDecodingStrategy
self.nonConformingFloatDecodingStrategy = nonConformingFloatDecodingStrategy
self.keyDecodingStrategy = keyDecodingStrategy
}
/// 类方法读取模型
///
/// - Parameters:
/// - type: 模型类型
/// - filePath: 文件路径
/// - Returns: 返回模型实例
/// - Throws: 抛出错误 DecodeFromSandBoxError
public static func read<T: Codable>(_ type: T.Type, frome filePath: String) throws -> T {
return try JSONDecoder.read(type, frome: filePath)
}
/// 读取模型
///
/// - Parameters:
/// - type: 模型类型
/// - filePath: 文件路径
/// - Returns: 返回模型实例
/// - Throws: 抛出错误 DecodeFromSandBoxError
public func read<T: Codable>(_ type: T.Type, frome filePath: String) throws -> T {
// 检查文件是否存在
if !FileManager.default.fileExists(atPath: filePath) {
throw DecodeFromSandBoxError.fileNotExists
}
let fileUrl = URL(fileURLWithPath: filePath)
// 读取数据
let data: Data
do {
data = try Data(contentsOf: fileUrl)
} catch {
throw DecodeFromSandBoxError.readError
}
// 反序列化为模型
do {
let model = try decode(type, from: data)
return model
} catch {
throw DecodeFromSandBoxError.decodeError
}
}
}
| 30.388889 | 123 | 0.588208 |
f5d9674990f8b312cdbde5d553d5f613371ea9a8 | 1,347 | //
// AppDelegate.swift
// tip
//
// Created by Education Center on 12/10/20.
//
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.405405 | 179 | 0.74536 |
0a4fcbe8b634d4b238babd8166f96615a84efa36 | 1,461 | //
// NSObject+LogProperties.swift
// JWPreview
//
// Created by Amitai Blickstein on 7/7/19.
// Copyright © 2019 JWPlayer. All rights reserved.
//
import Foundation
import ObjectiveC
extension NSObject {
func prettyProperties() -> String { return createPropertiesString() }
func createPropertiesString() -> String {
var ret = "----------------------------------------------- Properties for object \(NSStringFromClass(Self.self))\n[\n"
var numberOfProperties: UInt32 = 0
let propertyArrayPointer = class_copyPropertyList(Self.self, &numberOfProperties)
let propertyArray = Array(UnsafeBufferPointer(start: propertyArrayPointer, count: Int(numberOfProperties)))
for property in propertyArray {
if let name = String(cString: property_getName(property), encoding: .utf8),
let value = value(forKey: name)
{
ret += "\t\(name): \(value),\n"
}
}
free(propertyArrayPointer)
ret += "]\n-----------------------------------------------\n"
return ret
}
func logProperties() {
print(createPropertiesString())
}
// MARK: class function versions
// helpful for lldb
static func prettyProperties(of obj: NSObject) -> String {
return obj.prettyProperties()
}
static func logProperties(of obj: NSObject) {
print(obj.createPropertiesString())
}
}
| 29.816327 | 126 | 0.587953 |
ac4268568b8344c3c10dda6443e00e5c5670107e | 4,275 | //
// Copyright 2020 Swiftkube Project
//
// 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.
//
///
/// Generated by Swiftkube:ModelGen
/// Kubernetes v1.20.9
/// autoscaling.v2beta1.HorizontalPodAutoscalerStatus
///
import Foundation
public extension autoscaling.v2beta1 {
///
/// HorizontalPodAutoscalerStatus describes the current status of a horizontal pod autoscaler.
///
struct HorizontalPodAutoscalerStatus: KubernetesResource {
///
/// conditions is the set of conditions required for this autoscaler to scale its target, and indicates whether or not those conditions are met.
///
public var conditions: [autoscaling.v2beta1.HorizontalPodAutoscalerCondition]
///
/// currentMetrics is the last read state of the metrics used by this autoscaler.
///
public var currentMetrics: [autoscaling.v2beta1.MetricStatus]?
///
/// currentReplicas is current number of replicas of pods managed by this autoscaler, as last seen by the autoscaler.
///
public var currentReplicas: Int32
///
/// desiredReplicas is the desired number of replicas of pods managed by this autoscaler, as last calculated by the autoscaler.
///
public var desiredReplicas: Int32
///
/// lastScaleTime is the last time the HorizontalPodAutoscaler scaled the number of pods, used by the autoscaler to control how often the number of pods is changed.
///
public var lastScaleTime: Date?
///
/// observedGeneration is the most recent generation observed by this autoscaler.
///
public var observedGeneration: Int64?
///
/// Default memberwise initializer
///
public init(
conditions: [autoscaling.v2beta1.HorizontalPodAutoscalerCondition],
currentMetrics: [autoscaling.v2beta1.MetricStatus]? = nil,
currentReplicas: Int32,
desiredReplicas: Int32,
lastScaleTime: Date? = nil,
observedGeneration: Int64? = nil
) {
self.conditions = conditions
self.currentMetrics = currentMetrics
self.currentReplicas = currentReplicas
self.desiredReplicas = desiredReplicas
self.lastScaleTime = lastScaleTime
self.observedGeneration = observedGeneration
}
}
}
///
/// Codable conformance
///
public extension autoscaling.v2beta1.HorizontalPodAutoscalerStatus {
private enum CodingKeys: String, CodingKey {
case conditions = "conditions"
case currentMetrics = "currentMetrics"
case currentReplicas = "currentReplicas"
case desiredReplicas = "desiredReplicas"
case lastScaleTime = "lastScaleTime"
case observedGeneration = "observedGeneration"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.conditions = try container.decode([autoscaling.v2beta1.HorizontalPodAutoscalerCondition].self, forKey: .conditions)
self.currentMetrics = try container.decodeIfPresent([autoscaling.v2beta1.MetricStatus].self, forKey: .currentMetrics)
self.currentReplicas = try container.decode(Int32.self, forKey: .currentReplicas)
self.desiredReplicas = try container.decode(Int32.self, forKey: .desiredReplicas)
self.lastScaleTime = try container.decodeIfPresent(Date.self, forKey: .lastScaleTime)
self.observedGeneration = try container.decodeIfPresent(Int64.self, forKey: .observedGeneration)
}
func encode(to encoder: Encoder) throws {
var encodingContainer = encoder.container(keyedBy: CodingKeys.self)
try encodingContainer.encode(conditions, forKey: .conditions)
try encodingContainer.encode(currentMetrics, forKey: .currentMetrics)
try encodingContainer.encode(currentReplicas, forKey: .currentReplicas)
try encodingContainer.encode(desiredReplicas, forKey: .desiredReplicas)
try encodingContainer.encode(lastScaleTime, forKey: .lastScaleTime)
try encodingContainer.encode(observedGeneration, forKey: .observedGeneration)
}
}
| 38.169643 | 166 | 0.768655 |
87b0ca22d0947d76185a4073e8f03b5961838679 | 581 | //
// Webview.swift
// ios-app-bootstrap
//
// Created by xdf on 9/4/15.
// Copyright (c) 2015 open source. All rights reserved.
//
import UIKit
class Webview: UIWebView {
func loadURL(_ urlString: String) {
var url: URL
if (urlString == Const.TEST) {
url = URL(fileURLWithPath:Bundle.main.path(forResource: "test", ofType:"html" , inDirectory:"static")!)
} else {
url = URL(string: urlString)!
}
let request = URLRequest(url: url)
super.loadRequest(request)
}
}
| 21.518519 | 115 | 0.55938 |
5bfa4458fed4d2e8783f695bdfbac372a4be3e4e | 163 | //
// TestData.swift
// MsuCse_Example
//
// Created by Jasmin Suljic on 11/02/2020.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import Foundation
| 16.3 | 52 | 0.693252 |
337b61f0dfea77ec01b610869f3bf40d292730ea | 1,380 | //
// ViewController.swift
// DidScrollTest
//
// Created by Don Mag on 7/22/20.
// Copyright © 2020 DonMag. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var happyOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
self.happyOutlet.imageView?.tintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print("content offset x:", scrollView.contentOffset.x)
// if we've scrolled left more than 50 points
if scrollView.contentOffset.x > 50 {
print("greater than 50")
happyOutlet.imageView?.tintColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
}
else {
print("less than 51")
happyOutlet.imageView?.tintColor = #colorLiteral(red: 0.9294117647, green: 0.4705882353, blue: 0.07450980392, alpha: 1)
}
}
@IBAction func happy(_ sender: Any) {
// to change button image tintColor in response to touchUpInside,
// we have to set it after the built-in animation has finished
DispatchQueue.main.async {
self.happyOutlet.imageView?.tintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
}
}
}
| 28.75 | 127 | 0.721014 |
751b6ac354ffac38becd3da42c1f566ff25df5c4 | 884 | //
// UserDefaultsServices.swift
// RememberIt
//
// Created by Julianny Favinha on 06/10/19.
// Copyright © 2019 Julianny Favinha. All rights reserved.
//
import Foundation
final class UserDefaultsServices {
let defaults: UserDefaults
init(defaults: UserDefaults = UserDefaults.standard) {
self.defaults = defaults
}
func add(day: Int, month: Month) {
let days = getDays(for: month)
var newDays = days + [day]
newDays.sort()
defaults.set(newDays, forKey: month.rawValue)
}
func remove(day: Int, month: Month) {
let days = getDays(for: month)
var newDays = days.filter { $0 != day }
newDays.sort()
defaults.set(newDays, forKey: month.rawValue)
}
func getDays(for month: Month) -> [Int] {
return defaults.value(forKey: month.rawValue) as? [Int] ?? []
}
}
| 22.1 | 69 | 0.616516 |
db1b90ac5ca49d9b61aad412c83dcaccbcc71789 | 671 | //
// StorageContextObserver.swift
// Tools
//
// Created by Almaz Ibragimov on 10.05.2018.
// Copyright © 2018 Flatstack. All rights reserved.
//
import Foundation
public protocol StorageContextObserver: AnyObject {
// MARK: - Instance Methods
func storageContext(_ storageContext: StorageContext, didRemoveObjects objects: [StorageObject])
func storageContext(_ storageContext: StorageContext, didAppendObjects objects: [StorageObject])
func storageContext(_ storageContext: StorageContext, didUpdateObjects objects: [StorageObject])
func storageContext(_ storageContext: StorageContext, didChangeObjects objects: [StorageObject])
}
| 33.55 | 100 | 0.769001 |
5d8fbd848370e2ea090359b7d45ad75a82f33041 | 2,332 | import Foundation
import azureSwiftRuntime
public protocol JobCollectionsEnable {
var headerParameters: [String: String] { get set }
var subscriptionId : String { get set }
var resourceGroupName : String { get set }
var jobCollectionName : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void;
}
extension Commands.JobCollections {
// Enable enables all of the jobs in the job collection. This method may poll for completion. Polling can be canceled
// by passing the cancel channel argument. The channel will be used to cancel polling and any outstanding HTTP
// requests.
internal class EnableCommand : BaseCommand, JobCollectionsEnable {
public var subscriptionId : String
public var resourceGroupName : String
public var jobCollectionName : String
public var apiVersion = "2016-03-01"
public init(subscriptionId: String, resourceGroupName: String, jobCollectionName: String) {
self.subscriptionId = subscriptionId
self.resourceGroupName = resourceGroupName
self.jobCollectionName = jobCollectionName
super.init()
self.method = "Post"
self.isLongRunningOperation = true
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/enable"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{jobCollectionName}"] = String(describing: self.jobCollectionName)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void {
client.executeAsyncLRO(command: self) {
(error) in
completionHandler(error)
}
}
}
}
| 45.72549 | 165 | 0.663379 |
294461216013b2cadd6f1235f5cc529ded53f28f | 1,540 | import Foundation
let headers = ["content-type": "multipart/form-data; boundary=---011000010111000001101001"]
let parameters = [
[
"name": "foo",
"fileName": "test/fixtures/files/hello.txt",
"contentType": "text/plain"
]
]
let boundary = "---011000010111000001101001"
var body = ""
var error: NSError? = nil
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
if (error != nil) {
print(error)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
| 29.615385 | 116 | 0.638961 |
269dea19e6d6f361b68e5fd92bafacff26a5857d | 17,123 | //
// CKRoomSettingsParticipantViewController.swift
// Riot
//
// Created by Sinbad Flyce on 1/19/19.
// Copyright © 2019 matrix.org. All rights reserved.
//
import Foundation
final class CKRoomSettingsParticipantViewController: MXKViewController {
// MARK: - OUTLET
@IBOutlet weak var tableView: UITableView!
private enum Section: Int {
case search = 0
case participants = 1
case invited = 2
static func count() -> Int {
return 2
}
}
// MARK: - PROPERTY
/**
MX Room
*/
public var mxRoom: MXRoom!
private var mxRoomPowerLevels: MXRoomPowerLevels?
/**
Original data source
*/
private var originalDataSource: [MXRoomMember]! = nil
/**
filtered out participants
*/
private var filteredParticipants: [MXRoomMember]! = [MXRoomMember]() {
didSet {
listInvited = filteredParticipants.filter { $0.membership.identifier == __MXMembershipInvite }
listParticipant = filteredParticipants.filter { $0.membership.identifier == __MXMembershipJoin }
tableView.reloadData()
}
}
private var listParticipant: [MXRoomMember] = []
private var listInvited: [MXRoomMember] = []
// List admin in room
private var adminList = [String]()
/**
members Listener
*/
private var membersListener: Any!
// Observers
private var removedAccountObserver: Any?
private var accountUserInfoObserver: Any?
private var pushInfoUpdateObserver: Any?
private let kCkRoomAdminLevel = 100
private let disposeBag = DisposeBag()
// MARK: - OVERRIDE
override func destroy() {
if pushInfoUpdateObserver != nil {
NotificationCenter.default.removeObserver(pushInfoUpdateObserver!)
pushInfoUpdateObserver = nil
}
if accountUserInfoObserver != nil {
NotificationCenter.default.removeObserver(accountUserInfoObserver!)
accountUserInfoObserver = nil
}
if removedAccountObserver != nil {
NotificationCenter.default.removeObserver(removedAccountObserver!)
removedAccountObserver = nil
}
super.destroy()
}
override func viewDidLoad() {
super.viewDidLoad()
self.finalizeLoadView()
// Add observer to handle removed accounts
removedAccountObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.mxkAccountManagerDidRemoveAccount, object: nil, queue: OperationQueue.main, using: { notif in
// Refresh table to remove this account
self.reloadParticipantsInRoom()
})
// Add observer to handle accounts update
accountUserInfoObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.mxkAccountUserInfoDidChange, object: nil, queue: OperationQueue.main, using: { notif in
self.stopActivityIndicator()
self.reloadParticipantsInRoom()
})
// Add observer to push settings
pushInfoUpdateObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.mxkAccountPushKitActivityDidChange, object: nil, queue: OperationQueue.main, using: { notif in
self.stopActivityIndicator()
self.reloadParticipantsInRoom()
})
}
// MARK: - PRIVATE
private func finalizeLoadView() {
// title
self.navigationItem.title = CKLocalization.string(byKey: "room_setting_participant_title")
// register cells
self.tableView.register(
CKRoomSettingsParticipantCell.nib,
forCellReuseIdentifier: CKRoomSettingsParticipantCell.identifier)
self.tableView.register(
CKRoomSettingsParticipantSearchCell.nib,
forCellReuseIdentifier: CKRoomSettingsParticipantSearchCell.identifier)
// invoke timeline event
self.liveTimelineEvents()
// reload
self.reloadParticipantsInRoom()
bindingTheme()
addCustomBackButton()
}
func bindingTheme() {
// Binding navigation bar color
themeService.attrsStream.subscribe(onNext: { [weak self] (theme) in
self?.defaultBarTintColor = themeService.attrs.navBarBgColor
self?.barTitleColor = themeService.attrs.navBarTintColor
self?.tableView.reloadData()
}).disposed(by: disposeBag)
themeService.rx
.bind({ $0.primaryBgColor }, to: view.rx.backgroundColor, tableView.rx.backgroundColor)
.disposed(by: disposeBag)
}
private func liveTimelineEvents() {
// event of types
let eventsOfTypes = [MXEventType.roomMember,
MXEventType.roomThirdPartyInvite,
MXEventType.roomPowerLevels]
// list members
self.mxRoom.liveTimeline { (liveTimeline: MXEventTimeline?) in
// guard
guard let liveTimeline = liveTimeline else {
return
}
// timeline listen to events
self.membersListener = liveTimeline.listenToEvents(eventsOfTypes, { (event: MXEvent, direction: MXTimelineDirection, state: MXRoomState) in
// direction
if direction == MXTimelineDirection.forwards {
// case in room member
switch event.eventType {
case __MXEventTypeRoomMember:
// ignore current user who is as a member
if event.stateKey != self.mxRoom.mxSession.myUser.userId {
// ask to init mx member
if let mxMember = liveTimeline.state.members.member(withUserId: event.stateKey) {
// handle member
self.handle(roomMember: mxMember)
self.getAdmin(state: liveTimeline.state, member: mxMember)
}
// finalize room member state
self.finalizeReloadingParticipants(state)
}
case __MXEventTypeRoomPowerLevels:
self.reloadParticipantsInRoom()
default:
break
}
}
})
}
}
private func reloadParticipantsInRoom() {
// reset
self.filteredParticipants.removeAll()
// room state
self.mxRoom.state { (state: MXRoomState?) in
self.mxRoomPowerLevels = state?.powerLevels
// try to get members
if let members = state?.members.membersWithoutConferenceUser() {
// handl each member
for m in members {
self.handle(roomMember: m)
self.getAdmin(state: state, member: m)
}
// finalize room member state
self.finalizeReloadingParticipants(state!)
}
}
}
private func getAdmin(state: MXRoomState?, member: MXRoomMember) {
// power lever is admin
guard let state = state, let powerLevels = state.powerLevels else {
return
}
if powerLevels.powerLevelOfUser(withUserID: member.userId) >= self.kCkRoomAdminLevel {
adminList.append(member.userId)
}
}
private func finalizeReloadingParticipants(_ state: MXRoomState) {
DispatchQueue.main.async {
self.originalDataSource = self.filteredParticipants
}
}
private func handle(roomMember member: MXRoomMember) {
self.filteredParticipants = self.filteredParticipants.filter { $0.userId != member.userId }
self.filteredParticipants.append(member)
}
private func showPersonalAccountProfile() {
// initialize vc from xib
let vc = CKAccountProfileViewController(
nibName: CKAccountProfileViewController.nibName,
bundle: nil)
// import mx session and room id
vc.importSession(self.mxSessions)
vc.mxRoomPowerLevels = mxRoomPowerLevels
self.navigationController?.pushViewController(vc, animated: true)
}
private func showOthersAccountProfile(mxMember: MXRoomMember) {
// initialize vc from xib
let vc = CKOtherProfileViewController(
nibName: CKOtherProfileViewController.nibName,
bundle: nil)
// import mx session and room id
vc.importSession(self.mxSessions)
vc.mxMember = mxMember
vc.mxRoom = mxRoom
vc.mxRoomPowerLevels = mxRoomPowerLevels
self.navigationController?.pushViewController(vc, animated: true)
}
private func titleForHeader(atSection section: Int) -> String {
guard let s = Section(rawValue: section) else { return ""}
switch s {
case .search:
return ""
case .participants:
return self.listParticipant.isEmpty ? CKLocalization.string(byKey: "room_setting_participant_invite").uppercased() : CKLocalization.string(byKey: "room_setting_participant_title").uppercased()
case .invited:
return CKLocalization.string(byKey: "room_setting_participant_invite").uppercased()
}
}
// MARK: - ACTION
@objc private func clickedOnBackButton(_ sender: Any?) {
if let nvc = self.navigationController {
nvc.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - PUBLIC
}
// MARK: - UITableViewDelegate
extension CKRoomSettingsParticipantViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let s = Section(rawValue: indexPath.section) else { return 1}
switch s {
case .search:
return CKLayoutSize.Table.row70px
default:
return CKLayoutSize.Table.row80px
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let section = Section(rawValue: indexPath.section) else { return }
switch section {
case .search:
return
case .participants:
let mxMember = self.listParticipant.isEmpty ? listInvited[indexPath.row]: listParticipant[indexPath.row]
if mxMember.userId == mainSession.myUser.userId {
self.showPersonalAccountProfile()
} else {
self.showOthersAccountProfile(mxMember: mxMember)
}
case .invited:
let mxMember = listInvited[indexPath.row]
self.showOthersAccountProfile(mxMember: mxMember)
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let view = CKRoomHeaderInSectionView.instance() {
view.theme.backgroundColor = themeService.attrStream{ $0.tblHeaderBgColor }
view.descriptionLabel.theme.textColor = themeService.attrStream{ $0.primaryTextColor }
view.descriptionLabel?.text = self.titleForHeader(atSection: section)
return view
}
return nil
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = UILabel()
view.theme.backgroundColor = themeService.attrStream{ $0.secondBgColor }
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let s = Section(rawValue: section) else { return 1}
switch s {
case .search:
return CGFloat.leastNonzeroMagnitude
default:
return CKLayoutSize.Table.defaultHeader
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNonzeroMagnitude
}
}
// MARK: - UITableViewDataSource
extension CKRoomSettingsParticipantViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
var result: Int = 1
if !listParticipant.isEmpty {
result += 1
}
if !listInvited.isEmpty {
result += 1
}
return result
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let s = Section(rawValue: section) else { return 0}
switch s {
case .search:
return 1
case .participants:
return listParticipant.isEmpty ? listInvited.count : listParticipant.count
case .invited:
return listInvited.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let s = Section(rawValue: indexPath.section) else { return CKRoomSettingsBaseCell()}
switch s {
case .search:
return cellForParticipantSearch(atIndexPath: indexPath)
case .participants:
let flagInvited: Bool = listParticipant.isEmpty
return cellForParticipant(atIndexPath: indexPath, isInvited: flagInvited)
case .invited:
return cellForParticipant(atIndexPath: indexPath, isInvited: true)
}
}
private func cellForParticipant(atIndexPath indexPath: IndexPath, isInvited: Bool = false) -> CKRoomSettingsParticipantCell {
// de-cell
if let cell = self.tableView.dequeueReusableCell(
withIdentifier: CKRoomSettingsParticipantCell.identifier,
for: indexPath) as? CKRoomSettingsParticipantCell {
// pick index of member
let mxMember = isInvited ? self.listInvited[indexPath.row] : self.listParticipant[indexPath.row]
// fill fields to cell
cell.participantLabel.text = mxMember.displayname ?? mxMember.userId
cell.isAdmin = adminList.contains(mxMember.userId)
cell.participantLabel.backgroundColor = UIColor.clear
// avt
cell.setAvatarUri(
mxMember.avatarUrl,
identifyText: mxMember.userId,
session: self.mainSession)
// status
if let u = self.mainSession?.user(
withUserId: mxMember.userId ?? "") {
cell.status = u.presence == MXPresenceOnline ? 1 : 0
} else { cell.status = 0 }
cell.participantLabel.theme.textColor = themeService.attrStream{ $0.primaryTextColor }
cell.roomAdminLabel.theme.textColor = themeService.attrStream{ $0.primaryTextColor }
cell.theme.backgroundColor = themeService.attrStream{ $0.primaryBgColor }
return cell
}
return CKRoomSettingsParticipantCell()
}
private func cellForParticipantSearch(atIndexPath indexPath: IndexPath) -> CKRoomSettingsParticipantSearchCell{
// deque cell
let cell = self.tableView.dequeueReusableCell(
withIdentifier: CKRoomSettingsParticipantSearchCell.identifier,
for: indexPath) as! CKRoomSettingsParticipantSearchCell
// handle searching
cell.beginSearchingHandler = { text in
if text.count > 0 {
self.filteredParticipants = self.originalDataSource.filter({ (member: MXRoomMember) -> Bool in
if let displayname = member.displayname {
return displayname.lowercased().contains(text.lowercased())
} else {
return member.userId.lowercased().contains(text.lowercased())
}
})
} else {
self.filteredParticipants = self.originalDataSource
}
}
cell.contentView.theme.backgroundColor = themeService.attrStream{ $0.primaryBgColor }
cell.theme.backgroundColor = themeService.attrStream{ $0.primaryBgColor }
return cell
}
// MARK: - PUBLIC
}
| 34.802846 | 204 | 0.590726 |
1d3f870eea16ebdc536f0ac163ca579f7984d98b | 4,428 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -I %S/Inputs/objc_nonnull_lie_hack/ -enable-source-import -primary-file %s | %FileCheck -check-prefix=SILGEN %s
// RUN: %target-swiftemit-sil -O -sdk %S/Inputs -I %S/Inputs -I %S/Inputs/objc_nonnull_lie_hack/ -enable-source-import -primary-file %s | %FileCheck -check-prefix=OPT %s
// REQUIRES: objc_interop
// REQUIRES: rdar33495516
import Foundation
import NonNilTest
func checkThatAPINotesAreBeingUsed() {
let hopefullyNotOptional = NonNilTest.nonNilObject()
let _: NonNilTest = hopefullyNotOptional
}
// SILGEN-LABEL: sil hidden @$s21objc_nonnull_lie_hack10makeObjectSo8NSObjectCSgyF
// SILGEN: [[INIT:%.*]] = function_ref @$sSo8NSObjectCABycfC
// SILGEN: [[NONOPTIONAL:%.*]] = apply [[INIT]]
// SILGEN: [[OPTIONAL:%.*]] = unchecked_ref_cast [[NONOPTIONAL]]
// OPT-LABEL: sil hidden @$s21objc_nonnull_lie_hack10makeObjectSo8NSObjectCSgyF
// OPT: [[OPT:%.*]] = unchecked_ref_cast
// OPT: switch_enum [[OPT]] : $Optional<NSObject>, case #Optional.some!enumelt:
func makeObject() -> NSObject? {
let foo: NSObject? = NSObject()
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil hidden @$s21objc_nonnull_lie_hack15callClassMethodSo10NonNilTestCSgyF
// OPT: [[METATYPE:%[0-9]+]] = metatype $@thick NonNilTest.Type
// OPT: [[METHOD:%[0-9]+]] = objc_method [[METATYPE]] : $@thick NonNilTest.Type, #NonNilTest.nonNilObject!foreign : (NonNilTest.Type) -> () -> NonNilTest, $@convention(objc_method) (@objc_metatype NonNilTest.Type) -> @autoreleased NonNilTest
// OPT: [[OBJC_METATYPE:%[0-9]+]] = metatype $@objc_metatype NonNilTest.Type
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJC_METATYPE]]) : $@convention(objc_method) (@objc_metatype NonNilTest.Type) -> @autoreleased NonNilTest
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $NonNilTest to $Optional<NonNilTest>
// OPT: switch_enum [[OPTIONAL]] : $Optional<NonNilTest>
func callClassMethod() -> NonNilTest? {
let foo: NonNilTest? = NonNilTest.nonNilObject()
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil shared @$s21objc_nonnull_lie_hack18callInstanceMethodSo10NonNilTestCSgAD3obj_tFTf4g_n
// OPT: [[METHOD:%[0-9]+]] = objc_method [[OBJ:%[0-9]+]] : $NonNilTest, #NonNilTest.nonNilObject!foreign : (NonNilTest) -> () -> NonNilTest, $@convention(objc_method) (NonNilTest) -> @autoreleased NonNilTest
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[METHOD]]([[OBJ]]) : $@convention(objc_method) (NonNilTest) -> @autoreleased NonNilTest
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]]
// OPT: switch_enum [[OPTIONAL]] : $Optional<NonNilTest>
func callInstanceMethod(obj: NonNilTest) -> NonNilTest? {
let foo: NonNilTest? = obj.nonNilObject()
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil shared @$s21objc_nonnull_lie_hack12loadPropertySo10NonNilTestCSgAD3obj_tFTf4g_n
// OPT: [[GETTER:%[0-9]+]] = objc_method [[OBJ:%[0-9]+]] : $NonNilTest, #NonNilTest.nonNilObjectProperty!getter.foreign : (NonNilTest) -> () -> NonNilTest, $@convention(objc_method) (NonNilTest) -> @autoreleased NonNilTest
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (NonNilTest) -> @autoreleased NonNilTest
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $NonNilTest to $Optional<NonNilTest>
// OPT: switch_enum [[OPTIONAL]] : $Optional<NonNilTest>,
func loadProperty(obj: NonNilTest) -> NonNilTest? {
let foo: NonNilTest? = obj.nonNilObjectProperty
if foo == nil {
print("nil")
}
return foo
}
// OPT-LABEL: sil shared @$s21objc_nonnull_lie_hack19loadUnownedPropertySo10NonNilTestCSgAD3obj_tFTf4g_n
// OPT: [[GETTER:%[0-9]+]] = objc_method [[OBJ:%[0-9]+]] : $NonNilTest, #NonNilTest.unownedNonNilObjectProperty!getter.foreign : (NonNilTest) -> () -> NonNilTest, $@convention(objc_method) (NonNilTest) -> @autoreleased NonNilTest
// OPT: [[NONOPTIONAL:%[0-9]+]] = apply [[GETTER]]([[OBJ]]) : $@convention(objc_method) (NonNilTest) -> @autoreleased NonNilTest
// OPT: [[OPTIONAL:%[0-9]+]] = unchecked_ref_cast [[NONOPTIONAL]] : $NonNilTest to $Optional<NonNilTest>
// OPT: switch_enum [[OPTIONAL]] : $Optional<NonNilTest>
func loadUnownedProperty(obj: NonNilTest) -> NonNilTest? {
let foo: NonNilTest? = obj.unownedNonNilObjectProperty
if foo == nil {
print("nil")
}
return foo
}
| 52.094118 | 241 | 0.698509 |
915e31af09bc8633f5dcca9863066b7a8fed30bb | 2,717 | //
// SignupViewController.swift
// iCampus
//
// Created by Yuchen Cheng on 2018/4/24.
// Copyright © 2018年 Yuchen Cheng. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import CryptoSwift
import PKHUD
class SignupViewController: UIViewController {
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var userIdTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var backButton: UIButton!
private let bag = DisposeBag()
private let memberViewModel = MemberViewModel()
override func viewDidLoad() {
super.viewDidLoad()
signupButton.layer.cornerRadius = 5.0
signupButton.layer.masksToBounds = true
let phoneValidator = phoneTextField.rx.text
.orEmpty
.map { $0.count == 11 }
.share(replay: 1)
let userIdValidator = userIdTextField.rx.text
.orEmpty
.map { $0.count == 10 || $0.count == 12 }
.share(replay: 1)
let passwordValidator = passwordTextField.rx.text
.orEmpty
.map { $0.count >= 4 }
.share(replay: 1)
let validator = Observable
.combineLatest(phoneValidator, userIdValidator, passwordValidator) { $0 && $1 && $2 }
.share(replay: 1)
validator
.bind(to: signupButton.rx.isEnabled)
.disposed(by: bag)
validator
.subscribe(onNext: { [unowned self] valid in
self.signupButton.alpha = valid ? 1 : 0.5
})
.disposed(by: bag)
signupButton.rx.tap
.flatMapLatest {
return self.memberViewModel.signup(userId: self.userIdTextField.text!, password: self.passwordTextField.text!.md5(), phone: self.phoneTextField.text!)
}
.bind { [unowned self] _ in self.dismiss(animated: true, completion: nil) }
.disposed(by: bag)
backButton.rx.tap
.bind { [unowned self] _ in self.dismiss(animated: true, completion: nil) }
.disposed(by: bag)
}
fileprivate func signup() {
memberViewModel
.signup(userId: userIdTextField.text!, password: passwordTextField.text!.md5(), phone: phoneTextField.text!)
.subscribe()
.disposed(by: bag)
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 31.229885 | 166 | 0.588517 |
22816bc7b2cedc61e9a124b9cd92a797aa669032 | 330 | //
// AccountView.swift
// CovidMarketPlace
//
// Created by Moïse AGBENYA on 13/11/2020.
//
import UIKit
class AccountView: UIViewController {
static let storyboardID = "account-view"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 16.5 | 58 | 0.654545 |
670c5778d8628cd4153eaaf55e1ab405eadf3347 | 1,646 | //
// CodeSystems.swift
// HealthRecords
//
// Generated from FHIR 4.4.0-29ad3ab0
// Copyright 2020 Apple Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import FMCore
/**
Indicates the degree of adherence to a specified behavior or capability expected for a system to be deemed conformant
with a specification.
URL: http://terminology.hl7.org/CodeSystem/conformance-expectation
ValueSet: http://hl7.org/fhir/ValueSet/conformance-expectation
*/
public enum ConformanceExpectation: String, FHIRPrimitiveType {
/// Support for the specified capability is required to be considered conformant.
case SHALL = "SHALL"
/// Support for the specified capability is strongly encouraged, and failure to support it should only occur after
/// careful consideration.
case SHOULD = "SHOULD"
/// Support for the specified capability is not necessary to be considered conformant, and the requirement should be
/// considered strictly optional.
case MAY = "MAY"
/// Support for the specified capability is strongly discouraged and should occur only after careful consideration.
case SHOULDNOT = "SHOULD-NOT"
}
| 36.577778 | 118 | 0.755772 |
293abc4f205a6d87ade86b77ed6ae62326eed2f2 | 841 | //
// Node.swift
// HHModule
//
// Created by Howie on 26/6/20.
// Copyright © 2020 Beijing Bitstar Technology Co., Ltd. All rights reserved.
//
import UIKit
protocol Dependency {
func register(context: Context)
func prepare()
}
class Module {
let parentContext: Context
fileprivate let dependencies: [(Context)->Module]
internal lazy var context: Context = {
let context = Context(parentContext)
// 注入依赖
for dep in dependencies {
let depInstance = dep(context)
}
return context
}()
init(parentContext: Context, dependencies: [(Context)->Module] = []) {
self.parentContext = parentContext
self.dependencies = dependencies
registerTo(context: parentContext)
}
func registerTo(context: Context) {
}
}
| 22.131579 | 78 | 0.619501 |
bba128559cc0f93263880df84989b96ca6d0e758 | 319 | //
// ViewDidLoadState.swift
// TPGHorizontalMenu
//
// Created by David Livadaru on 15/03/2017.
// Copyright © 2017 3Pillar Global. All rights reserved.
//
import UIKit
class ViewDidLoadState: ViewControllerState {
override var validNextStates: [AnyClass] {
return [ViewWillAppearState.self]
}
}
| 19.9375 | 57 | 0.711599 |
287f26f9325ee8e5f1124cf063531902697d53de | 809 | //
// IntTests.swift
// HISwiftExtensions
//
// Created by Matthew on 26/12/2015.
// Copyright © 2015 CocoaPods. All rights reserved.
import Quick
import Nimble
import HISwiftExtensions
class IntSpec: QuickSpec {
override func spec() {
describe("int extensions") {
it("times") {
var count = 0
3.times { count += 1 }
expect(count).to(equal(3))
}
it("upto") {
var int = 0
int.upto(2) { _ in int += 1 }
expect(int).to(equal(3))
}
it("downto") {
var int = 2
int.downto(0) { _ in int += 1 }
expect(int).to(equal(4))
}
}
}
}
| 21.289474 | 52 | 0.420272 |
ef26dbc4a589bc8e51cf89ab7f9d47baedcb9715 | 2,346 | //
// WBLaunchViewController.swift
// WBLib
//
// Created by Bingo on 2019/6/18.
// Copyright © 2019 Bingo. All rights reserved.
//
import UIKit
class BNLaunchViewController: UIViewController {
let imageView = UIImageView()
var launchImage = UIImage()
let viewSize:CGSize = UIScreen.main.bounds.size
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
let dict = Bundle.main.infoDictionary
if let info = dict {
if info["UILaunchImages"] != nil{
let imagesArr:Array<Dictionary<String,Any>> = info["UILaunchImages"] as! Array
for items:Dictionary<String,Any> in imagesArr
{
self.launchImage = UIImage(named: items["UILaunchImageName"] as! String )!
}
}
}
if self.launchImage.size == CGSize(width: 0, height: 0){
let story:UIStoryboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let launchVC:UIViewController = story.instantiateInitialViewController() ?? UIViewController()
self.launchImage = self.getImageFromView(view: launchVC.view)
}else{
}
self.imageView.frame = CGRect(x: 0, y: 0, width: kDeviceWidth, height: kDeviceHeight)
self.imageView.isUserInteractionEnabled = true
self.imageView.image = self.launchImage
self.imageView.contentMode = .scaleAspectFill
self.view.addSubview(self.imageView)
// Do any additional setup after loading the view.
}
//MARK: - uiview转uiimage
func getImageFromView(view: UIView) -> UIImage {
// 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
UIGraphicsBeginImageContextWithOptions(view.frame.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
view.layer.render(in: context!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| 28.609756 | 106 | 0.571185 |
89a52ac984b38cebf2d72e0ae1a3f21ebac1a522 | 3,588 | //
// Base64.swift
// SwiftyBase64
//
// Created by Doug Richardson on 8/7/15.
//
//
/**
Base64 Alphabet to use during encoding.
- Standard: The standard Base64 encoding, defined in RFC 4648 section 4.
- URLAndFilenameSafe: The base64url encoding, defined in RFC 4648 section 5.
*/
public enum Alphabet {
/// The standard Base64 alphabet
case Standard
/// The URL and Filename Safe Base64 alphabet
case URLAndFilenameSafe
}
/**
Encode a [UInt8] byte array as a Base64 String.
- parameter bytes: Bytes to encode.
- parameter alphabet: The Base64 alphabet to encode with.
- returns: A String of the encoded bytes.
*/
public func EncodeString(_ bytes : [UInt8], alphabet : Alphabet = .Standard) -> String {
let encoded = Encode(bytes, alphabet : alphabet)
var result = String()
for b in encoded {
result.append(String(UnicodeScalar(b)))
}
return result
}
/// Get the encoding table for the alphabet.
private func tableForAlphabet(_ alphabet : Alphabet) -> [UInt8] {
switch alphabet {
case .Standard:
return StandardAlphabet
case .URLAndFilenameSafe:
return URLAndFilenameSafeAlphabet
}
}
/**
Use the Base64 algorithm as decribed by RFC 4648 section 4 to
encode the input bytes. The alphabet specifies the translation
table to use. RFC 4648 defines two such alphabets:
- Standard (section 4)
- URL and Filename Safe (section 5)
- parameter bytes: Bytes to encode.
- parameter alphabet: The Base64 alphabet to encode with.
- returns: Base64 encoded ASCII bytes.
*/
public func Encode(_ bytes : [UInt8], alphabet : Alphabet = .Standard) -> [UInt8] {
var encoded : [UInt8] = []
let table = tableForAlphabet(alphabet)
let padding = table[64]
var i = 0
let count = bytes.count
while i+3 <= count {
let one = bytes[i] >> 2
let two = ((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4)
let three = ((bytes[i+1] & 0b00001111) << 2) | ((bytes[i+2] & 0b11000000) >> 6)
let four = bytes[i+2] & 0b00111111
encoded.append(table[Int(one)])
encoded.append(table[Int(two)])
encoded.append(table[Int(three)])
encoded.append(table[Int(four)])
i += 3
}
if i+2 == count {
// (3) The final quantum of encoding input is exactly 16 bits; here, the
// final unit of encoded output will be three characters followed by
// one "=" padding character.
let one = bytes[i] >> 2
let two = ((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4)
let three = ((bytes[i+1] & 0b00001111) << 2)
encoded.append(table[Int(one)])
encoded.append(table[Int(two)])
encoded.append(table[Int(three)])
encoded.append(padding)
} else if i+1 == count {
// (2) The final quantum of encoding input is exactly 8 bits; here, the
// final unit of encoded output will be two characters followed by
// two "=" padding characters.
let one = bytes[i] >> 2
let two = ((bytes[i] & 0b11) << 4)
encoded.append(table[Int(one)])
encoded.append(table[Int(two)])
encoded.append(padding)
encoded.append(padding)
} else {
// (1) The final quantum of encoding input is an integral multiple of 24
// bits; here, the final unit of encoded output will be an integral
// multiple of 4 characters with no "=" padding.
assert(i == count)
}
return encoded
}
| 31.473684 | 88 | 0.613434 |