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
|
---|---|---|---|---|---|
919764971c765251de62263522dd34fc560f4e62 | 3,508 | //
// ProfileViewController.swift
// TwitterClient
//
// Created by Lilian Ngweta on 2/27/16.
// Copyright © 2016 Lilian Ngweta. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var numTweets: UILabel!
@IBOutlet weak var numFollowers: UILabel!
@IBOutlet weak var numFollowing: UILabel!
@IBOutlet weak var profileImageView: UIImageView!
//@IBOutlet weak var profileBackgroundImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var screennameLabel: UILabel!
var tweets: [Tweet]!
var user: User?
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
//tableView.estimatedRowHeight = 120
//tableView.rowHeight = UITableViewAutomaticDimension
TwitterClient.sharedInstance.userTimeLine({ (tweets:[Tweet]) -> () in
self.tweets = tweets
self.tableView.reloadData()
for tweet in tweets {
print(tweet.user?.profileImageURL)
}
}) { (error:NSError) -> () in
print(error.localizedDescription)
}
/*
//self.numTweets.text = String(self.user!.profileTweets!)
self.numFollowing.text = String(self.user?.profileFollowing)
self.numFollowers.text = String(self.user?.profileFollowers!)
self.screennameLabel.text = "@" + String(self.user?.screenname!)
self.usernameLabel.text = String(self.user?.name!)
//self.profileBackgroundImageView.setImageWithURL(NSURL(string: self.user!.profileImageURL!)!)
//self.profileImageView.setImageWithURL(NSURL(string: self.user!.profileImageBackgroundURL!)!)
self.tableView.reloadData()
// Do any additional setup after loading the view.
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLogoutButton(sender: AnyObject) {
TwitterClient.sharedInstance.logout()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
if let tweets = tweets{
return tweets.count
}else {
return 0;
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("TweetCell", forIndexPath: indexPath) as! TweetCell
cell.tweet = tweets![indexPath.row]
// print("row\(indexPath.row)")
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 27.622047 | 114 | 0.599487 |
2837562dfc614223458a3739a2e44d9d21fd2468 | 626 | //
// AmountViewCollectionVIew.swift
// AmountView
//
// Created by Marcelo Oscar José on 02/07/2018.
// Copyright © 2018 Marcelo Oscar José. All rights reserved.
//
import UIKit
class AmountViewCollectionVIew: UICollectionView {
convenience init(cellIdentifier: String) {
self.init(frame: .zero, collectionViewLayout: AmountViewCollectionLayout())
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.isScrollEnabled = false
self.backgroundColor = UIColor.clear
self.register(AmountViewCollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
}
}
| 28.454545 | 100 | 0.734824 |
fef2a5ce5482b4acb78712e164a8895382408115 | 2,807 | //
// TableViewController.swift
// GiphySwift-Example
//
// Created by Matias Seijas on 9/29/16.
// Copyright © 2016 Matias Seijas. All rights reserved.
//
import UIKit
enum Section: Int {
case gifs, stickers
var title: String {
switch self {
case .gifs: return "Gifs"
case .stickers: return "Stickers"
}
}
var rows: [Row] {
switch self {
case .gifs: return [Row.trending, Row.search, Row.translate, Row.byID, Row.random]
case .stickers: return [Row.trending, Row.search, Row.translate, Row.random]
}
}
static var count: Int { return 2 }
}
enum Row: Int {
case trending, search, translate, byID, random
var title: String {
switch self {
case .trending: return "Trending"
case .search: return "Search"
case .translate: return "Translate"
case .byID: return "By ID"
case .random: return "Random"
}
}
}
class TableViewController: UITableViewController {
var config: (section: Section, row: Row)?
override func numberOfSections(in tableView: UITableView) -> Int {
return Section.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = Section(rawValue: section) else { fatalError("Could not retrieve Section") }
return section.rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
guard let section = Section(rawValue: indexPath.section) else { fatalError("Could not retrieve Section") }
let row = section.rows[indexPath.row]
cell.textLabel?.text = row.title
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let section = Section(rawValue: section) else { fatalError("Could not retrieve Section") }
return section.title
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let section = Section(rawValue: indexPath.section) else { fatalError("Could not retrieve Section") }
let row = section.rows[indexPath.row]
config = (section: section, row: row)
performSegue(withIdentifier: "showImages", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let collectionViewController = segue.destination as? CollectionViewController else { return }
collectionViewController.config = self.config
}
}
| 31.539326 | 114 | 0.648023 |
6af06648ab19407b77d4a98fcca52056fc90fe9b | 2,623 | // The MIT License (MIT)
// Copyright © 2021 Ivan Vorobei ([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 SPPageCollectionViewCell: UICollectionViewCell {
// MARK: - Data
static var id: String { return "SPPageCollectionViewCell" }
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
insetsLayoutMarginsFromSafeArea = false
preservesSuperviewLayoutMargins = false
contentView.insetsLayoutMarginsFromSafeArea = false
contentView.preservesSuperviewLayoutMargins = false
contentView.layoutMargins = .zero
}
override func prepareForReuse() {
super.prepareForReuse()
contentView.subviews.forEach({ $0.removeFromSuperview() })
}
// MARK: - Actions
func setViewController(_ controller: UIViewController) {
guard let view = controller.view else { return }
let superView = contentView
superView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
view.topAnchor.constraint(equalTo: superView.topAnchor),
view.leftAnchor.constraint(equalTo: superView.leftAnchor),
view.rightAnchor.constraint(equalTo: superView.rightAnchor),
view.bottomAnchor.constraint(equalTo: superView.bottomAnchor)
])
}
}
| 36.430556 | 81 | 0.703393 |
cc61d49f961c18e8eac7981b0da56a9a1c108b08 | 4,942 | //
// ChangeLayoutSection.swift
// AnKitPlayground
//
// Created by Anvipo on 10.11.2021.
//
import AnKit
import UIKit
final class ChangeLayoutSection: CollectionViewSection {
var mode: Mode
init(
mode: Mode,
items: [CollectionViewItem]
) throws {
self.mode = mode
try super.init(
items: items
)
}
override func layoutConfiguration(
context: LayoutCreationContext
) -> NSCollectionLayoutSection {
switch mode {
case .cardsListLayout:
return cardsListLayout(context: context)
case .threeSmallUnderOneBigLayout:
return threeSmallUnderOneBigLayout(context: context)
case .gridLayout:
return gridLayout(context: context)
case .plainListLayout:
// swiftlint:disable:next force_try
return try! listLayout(context: context)
}
}
}
private extension ChangeLayoutSection {
func cardsListLayout(
context: LayoutCreationContext
) -> NSCollectionLayoutSection {
let layoutItem = NSCollectionLayoutItem(
layoutSize: .fullSize
)
layoutItem.contentInsets = .default
let verticalGroupLayout = NSCollectionLayoutGroup.vertical(
layoutSize: .fullWidth(heightDimension: .fractionalHeight(1 / 3)),
subitem: layoutItem,
count: 1
)
return NSCollectionLayoutSection(group: verticalGroupLayout)
}
func threeSmallUnderOneBigLayout(
context: LayoutCreationContext
) -> NSCollectionLayoutSection {
let smallItemCount = 3
let smallItemLayout = NSCollectionLayoutItem(
layoutSize: .fullHeight(
widthDimension: .fractionalWidth(1 / CGFloat(smallItemCount))
)
)
smallItemLayout.contentInsets = NSDirectionalEdgeInsets(
horizontalInset: 2
)
let smallItemsGroupLayoutFractionalHeight: CGFloat = 1 / 3
let bigItemLayoutFractionalHeight: CGFloat = 1 - smallItemsGroupLayoutFractionalHeight
let smallItemsGroupLayout = NSCollectionLayoutGroup.horizontal(
layoutSize: .fullWidth(
heightDimension: .fractionalHeight(smallItemsGroupLayoutFractionalHeight)
),
subitem: smallItemLayout,
count: smallItemCount
)
smallItemsGroupLayout.contentInsets = NSDirectionalEdgeInsets(
horizontalInset: 0,
verticalInset: 2
)
let bigItemLayout = NSCollectionLayoutItem(
layoutSize: .fullWidth(
heightDimension: .fractionalHeight(bigItemLayoutFractionalHeight)
)
)
bigItemLayout.contentInsets = NSDirectionalEdgeInsets(
horizontalInset: 2,
verticalInset: 2
)
let groupLayout = NSCollectionLayoutGroup.vertical(
// half screen height
layoutSize: .fullWidth(heightDimension: .fractionalHeight(1 / 2)),
subitems: [bigItemLayout, smallItemsGroupLayout]
)
return NSCollectionLayoutSection(group: groupLayout)
}
func gridLayout(
context: LayoutCreationContext
) -> NSCollectionLayoutSection {
let smallItemCount = 3
let itemLayout = NSCollectionLayoutItem(
layoutSize: .square(fractionalWidth: 1 / CGFloat(smallItemCount))
)
itemLayout.contentInsets = NSDirectionalEdgeInsets(
horizontalInset: 1,
verticalInset: 1
)
let groupLayout = NSCollectionLayoutGroup.horizontal(
layoutSize: .fullWidth(
heightDimension: itemLayout.layoutSize.heightDimension
),
subitem: itemLayout,
count: smallItemCount
)
return NSCollectionLayoutSection(group: groupLayout)
}
func listLayout(context: LayoutCreationContext) throws -> NSCollectionLayoutSection {
let effectiveContentWidth = effectiveContentWidth(layoutEnvironment: context.layoutEnvironment)
return sectionListLayout(
context: context,
effectiveContentWidth: effectiveContentWidth
)
}
func sectionListLayout(
context: LayoutCreationContext,
effectiveContentWidth: CGFloat
) -> NSCollectionLayoutSection {
if #available(iOS 14, *) {
var sectionConfiguration = UICollectionLayoutListConfiguration(
appearance: .plain
)
sectionConfiguration.showsSeparators = false
sectionConfiguration.backgroundColor = .clear
return .list(
using: sectionConfiguration,
layoutEnvironment: context.layoutEnvironment
)
}
// iOS < 14
let cellHeightCalculationContext = CollectionViewItem.CellHeightCalculationContext(
availableWidthForCell: effectiveContentWidth,
layoutEnvironment: AnyNSCollectionLayoutEnvironment(context.layoutEnvironment)
)
let layoutItems: [NSCollectionLayoutItem] = items.map { item in
do {
let cellHeight = try item.cellHeight(
context: cellHeightCalculationContext
)
return NSCollectionLayoutItem(
layoutSize: .fullWidth(heightDimension: .absolute(cellHeight))
)
} catch {
return NSCollectionLayoutItem(
layoutSize: .fullWidth(heightDimension: .estimated(44))
)
}
}
let contentHeight = layoutItems.map { $0.layoutSize.heightDimension.dimension }.sum
let verticalGroupLayout = NSCollectionLayoutGroup.vertical(
layoutSize: .fullWidth(heightDimension: .absolute(contentHeight)),
subitems: layoutItems
)
return NSCollectionLayoutSection(group: verticalGroupLayout)
}
}
| 25.606218 | 97 | 0.764265 |
8af6f84434df886dcef1481cc05b080290782495 | 195 | //
// XZTakePictureTools.swift
// XZWeChatDemo
//
// Created by admin on 2018/8/13.
// Copyright © 2018年 XZ. All rights reserved.
// 拍照/相册处理
import UIKit
class XZTakePictureTools {
}
| 13.928571 | 46 | 0.671795 |
23898f757b50ffd6bf7bf5e7b27f3540998ac6b9 | 4,933 | //
// MusicCalendarViewCell.swift
// SimpleNeteaseMusic
//
// Created by shenjie on 2021/6/4.
// Copyright © 2021 shenjie. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
class MusicCalendarViewCell: UICollectionViewCell {
/// 日历容器
lazy var container: UIView! = {
let view = UIView()
view.backgroundColor = UIColor.clear
return view
}()
/// cover image
lazy var coverImage: UIImageView! = {
let cover = UIImageView()
cover.backgroundColor = UIColor.clear
cover.contentMode = .scaleAspectFill
return cover
}()
/// titile
lazy var titleL: UILabel! = {
let descLabel = UILabel()
descLabel.backgroundColor = UIColor.clear
descLabel.tintColor = UIColor.darkModeTextColor
descLabel.font = UIFont.systemFont(ofSize: 14)
return descLabel
}()
/// 日期
lazy var dateL: UILabel! = {
let dateLabel = UILabel()
dateLabel.backgroundColor = UIColor.clear
dateLabel.tintColor = UIColor.lightGray
dateLabel.font = UIFont.systemFont(ofSize: 12)
return dateLabel
}()
/// 标签
lazy var tagL: UILabel! = {
let tagLabel = UILabel()
tagLabel.backgroundColor = UIColor.clear
tagLabel.tintColor = UIColor.darkModeTextColor
tagLabel.font = UIFont.systemFont(ofSize: 12)
return tagLabel
}()
/// 提醒闹钟按钮
lazy var clockBtn: UIButton! = {
let btn = UIButton(type: .custom)
btn.backgroundColor = UIColor.clear
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.container)
self.addSubview(self.coverImage)
self.container.addSubview(self.dateL)
self.container.addSubview(self.tagL)
self.container.addSubview(self.titleL)
self.container.addSubview(self.clockBtn)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let marginLeft: CGFloat = 10
let marginRight: CGFloat = 10
let marginTop: CGFloat = 5
let height: CGFloat = self.frame.size.height
let width: CGFloat = self.frame.size.width
let clockW: CGFloat = 25
let clockH: CGFloat = 25
/// 计算日期的尺寸
let rect = getStrBoundRect(str: "今天", font: UIFont.systemFont(ofSize: 12), constrainedSize: CGSize(width: 14, height: 40))
self.container.snp.makeConstraints { (make) in
make.width.equalTo(width - (height - marginTop * 2) - marginLeft - marginRight)
make.height.equalTo(height - marginTop * 2)
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(marginLeft)
}
self.coverImage.snp.makeConstraints { (make) in
make.width.equalTo(height - marginTop * 2)
make.height.equalTo(height - marginTop * 2)
make.centerY.equalToSuperview()
make.right.equalToSuperview().offset(-marginRight)
}
self.coverImage.layer.cornerRadius = 10
self.coverImage.layer.masksToBounds = true
self.dateL.snp.makeConstraints { (make) in
make.width.equalTo(rect.width + 20)
make.height.equalTo((height - marginTop * 2) / 2)
make.top.equalToSuperview().offset(-5)
make.left.equalToSuperview()
}
self.tagL.snp.makeConstraints { (make) in
make.width.equalTo(100)
make.height.equalTo((height - marginTop * 2) / 2)
make.top.equalToSuperview().offset(-5)
make.left.equalTo(self.dateL.snp.right).offset(5)
}
self.titleL.snp.makeConstraints { (make) in
make.width.equalTo(width - (height - marginTop * 2) - marginLeft - marginRight - clockW)
make.height.equalTo(height - marginTop * 2)
make.bottom.equalToSuperview().offset(5)
make.left.equalToSuperview()
}
self.clockBtn.snp.makeConstraints { (make) in
make.width.equalTo(clockW)
make.width.equalTo(clockH)
make.centerY.equalToSuperview()
make.right.equalToSuperview()
}
}
func updateUI(tag: String, title: String, coverUrl: String) -> Void {
if coverUrl != "" {
self.coverImage.kf.setImage(with: URL(string: coverUrl), placeholder: nil, options: nil, progressBlock: nil) { (reslt) in
}
}
if tag != "" {
self.dateL.text = "今天"
} else {
self.dateL.text = "明天"
}
self.tagL.text = tag
self.titleL.text = title
}
}
| 31.221519 | 133 | 0.584229 |
62e6dd68709145a403d0525a9838b02e293ab353 | 2,126 | // Telegrammer - Telegram Bot Swift SDK.
// This file is autogenerated by API/generate_wrappers.rb script.
/**
Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use input_message_content to send a message with the specified content instead of the audio.
SeeAlso Telegram Bot API Reference:
[InlineQueryResultCachedAudio](https://core.telegram.org/bots/api#inlinequeryresultcachedaudio)
*/
public final class InlineQueryResultCachedAudio: Codable {
/// Custom keys for coding/decoding `InlineQueryResultCachedAudio` struct
enum CodingKeys: String, CodingKey {
case type = "type"
case id = "id"
case audioFileId = "audio_file_id"
case caption = "caption"
case parseMode = "parse_mode"
case replyMarkup = "reply_markup"
case inputMessageContent = "input_message_content"
}
/// Type of the result, must be audio
public var type: String
/// Unique identifier for this result, 1-64 bytes
public var id: String
/// A valid file identifier for the audio file
public var audioFileId: String
/// Optional. Caption, 0-1024 characters after entities parsing
public var caption: String?
/// Optional. Mode for parsing entities in the audio caption. See formatting options for more details.
public var parseMode: String?
/// Optional. Inline keyboard attached to the message
public var replyMarkup: InlineKeyboardMarkup?
/// Optional. Content of the message to be sent instead of the audio
public var inputMessageContent: InputMessageContent?
public init (type: String, id: String, audioFileId: String, caption: String? = nil, parseMode: String? = nil, replyMarkup: InlineKeyboardMarkup? = nil, inputMessageContent: InputMessageContent? = nil) {
self.type = type
self.id = id
self.audioFileId = audioFileId
self.caption = caption
self.parseMode = parseMode
self.replyMarkup = replyMarkup
self.inputMessageContent = inputMessageContent
}
}
| 39.37037 | 241 | 0.714017 |
1a3906ea44de81a5e2434fc0fd453ed747ab003d | 2,737 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | FileCheck %s
@objc protocol P1 {
optional func method(x: Int)
optional var prop: Int { get }
optional subscript (i: Int) -> Int { get }
}
// CHECK-LABEL: sil hidden @{{.*}}optionalMethodGeneric{{.*}} : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalMethodGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
// CHECK-NEXT: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: store [[T]] to [[PT]] : $*T
// CHECK-NEXT: [[OPT_BOX:%[0-9]+]] = alloc_box $Optional<Int -> ()>
// CHECK-NEXT: project_box [[OPT_BOX]]
// CHECK-NEXT: [[T:%[0-9]+]] = load [[PT]] : $*T
// CHECK-NEXT: strong_retain [[T]] : $T
// CHECK-NEXT: alloc_stack $Optional<Int -> ()>
// CHECK-NEXT: dynamic_method_br [[T]] : $T, #P1.method!1.foreign
var methodRef = t.method
}
// CHECK-LABEL: sil hidden @_TF17protocol_optional23optionalPropertyGeneric{{.*}} : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalPropertyGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
// CHECK-NEXT: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: store [[T]] to [[PT]] : $*T
// CHECK-NEXT: [[OPT_BOX:%[0-9]+]] = alloc_box $Optional<Int>
// CHECK-NEXT: project_box [[OPT_BOX]]
// CHECK-NEXT: [[T:%[0-9]+]] = load [[PT]] : $*T
// CHECK-NEXT: strong_retain [[T]] : $T
// CHECK-NEXT: alloc_stack $Optional<Int>
// CHECK-NEXT: dynamic_method_br [[T]] : $T, #P1.prop!getter.1.foreign
var propertyRef = t.prop
}
// CHECK-LABEL: sil hidden @_TF17protocol_optional24optionalSubscriptGeneric{{.*}} : $@convention(thin) <T where T : P1> (@owned T) -> ()
func optionalSubscriptGeneric<T : P1>(t t : T) {
var t = t
// CHECK: bb0([[T:%[0-9]+]] : $T):
// CHECK: [[TBOX:%[0-9]+]] = alloc_box $T
// CHECK-NEXT: [[PT:%[0-9]+]] = project_box [[TBOX]]
// CHECK: store [[T]] to [[PT]] : $*T
// CHECK-NEXT: [[OPT_BOX:%[0-9]+]] = alloc_box $Optional<Int>
// CHECK-NEXT: project_box [[OPT_BOX]]
// CHECK-NEXT: [[T:%[0-9]+]] = load [[PT]] : $*T
// CHECK-NEXT: strong_retain [[T]] : $T
// CHECK: [[INTCONV:%[0-9]+]] = function_ref @_TFSiC
// CHECK-NEXT: [[INT64:%[0-9]+]] = metatype $@thin Int.Type
// CHECK-NEXT: [[FIVELIT:%[0-9]+]] = integer_literal $Builtin.Int2048, 5
// CHECK-NEXT: [[FIVE:%[0-9]+]] = apply [[INTCONV]]([[FIVELIT]], [[INT64]]) : $@convention(thin) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK-NEXT: alloc_stack $Optional<Int>
// CHECK-NEXT: dynamic_method_br [[T]] : $T, #P1.subscript!getter.1.foreign
var subscriptRef = t[5]
}
| 44.145161 | 139 | 0.583486 |
645dc5d5c54016a2901421d3f794e1b2fc8feb17 | 12,454 | // 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
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
open class FileHandle : NSObject, NSSecureCoding {
internal var _fd: Int32
internal var _closeOnDealloc: Bool
internal var _closed: Bool = false
open var availableData: Data {
return _readDataOfLength(Int.max, untilEOF: false)
}
open func readDataToEndOfFile() -> Data {
return readData(ofLength: Int.max)
}
open func readData(ofLength length: Int) -> Data {
return _readDataOfLength(length, untilEOF: true)
}
internal func _readDataOfLength(_ length: Int, untilEOF: Bool) -> Data {
var statbuf = stat()
var dynamicBuffer: UnsafeMutableRawPointer? = nil
var total = 0
if _closed || fstat(_fd, &statbuf) < 0 {
fatalError("Unable to read file")
}
if statbuf.st_mode & S_IFMT != S_IFREG {
/* We get here on sockets, character special files, FIFOs ... */
var currentAllocationSize: size_t = 1024 * 8
dynamicBuffer = malloc(currentAllocationSize)
var remaining = length
while remaining > 0 {
let amountToRead = min(1024 * 8, remaining)
// Make sure there is always at least amountToRead bytes available in the buffer.
if (currentAllocationSize - total) < amountToRead {
currentAllocationSize *= 2
dynamicBuffer = _CFReallocf(dynamicBuffer!, currentAllocationSize)
if dynamicBuffer == nil {
fatalError("unable to allocate backing buffer")
}
}
let amtRead = read(_fd, dynamicBuffer!.advanced(by: total), amountToRead)
if 0 > amtRead {
free(dynamicBuffer)
fatalError("read failure")
}
if 0 == amtRead {
break // EOF
}
total += amtRead
remaining -= amtRead
if total == length || !untilEOF {
break // We read everything the client asked for.
}
}
} else {
let offset = lseek(_fd, 0, SEEK_CUR)
if offset < 0 {
fatalError("Unable to fetch current file offset")
}
if off_t(statbuf.st_size) > offset {
var remaining = size_t(statbuf.st_size - offset)
remaining = min(remaining, size_t(length))
dynamicBuffer = malloc(remaining)
if dynamicBuffer == nil {
fatalError("Malloc failure")
}
while remaining > 0 {
let count = read(_fd, dynamicBuffer!.advanced(by: total), remaining)
if count < 0 {
free(dynamicBuffer)
fatalError("Unable to read from fd")
}
if count == 0 {
break
}
total += count
remaining -= count
}
}
}
if length == Int.max && total > 0 {
dynamicBuffer = _CFReallocf(dynamicBuffer!, total)
}
if (0 == total) {
free(dynamicBuffer)
}
if total > 0 {
let bytePtr = dynamicBuffer!.bindMemory(to: UInt8.self, capacity: total)
return Data(bytesNoCopy: bytePtr, count: total, deallocator: .none)
}
return Data()
}
open func write(_ data: Data) {
data.enumerateBytes() { (bytes, range, stop) in
do {
try NSData.write(toFileDescriptor: self._fd, path: nil, buf: UnsafeRawPointer(bytes.baseAddress!), length: bytes.count)
} catch {
fatalError("Write failure")
}
}
}
// TODO: Error handling.
open var offsetInFile: UInt64 {
return UInt64(lseek(_fd, 0, SEEK_CUR))
}
@discardableResult
open func seekToEndOfFile() -> UInt64 {
return UInt64(lseek(_fd, 0, SEEK_END))
}
open func seek(toFileOffset offset: UInt64) {
lseek(_fd, off_t(offset), SEEK_SET)
}
open func truncateFile(atOffset offset: UInt64) {
if lseek(_fd, off_t(offset), SEEK_SET) == 0 {
ftruncate(_fd, off_t(offset))
}
}
open func synchronizeFile() {
fsync(_fd)
}
open func closeFile() {
if !_closed {
close(_fd)
_closed = true
}
}
public init(fileDescriptor fd: Int32, closeOnDealloc closeopt: Bool) {
_fd = fd
_closeOnDealloc = closeopt
}
internal init?(path: String, flags: Int32, createMode: Int) {
_fd = _CFOpenFileWithMode(path, flags, mode_t(createMode))
_closeOnDealloc = true
super.init()
if _fd < 0 {
return nil
}
}
deinit {
if _fd >= 0 && _closeOnDealloc && !_closed {
close(_fd)
}
}
public required init?(coder: NSCoder) {
NSUnimplemented()
}
open func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
public static var supportsSecureCoding: Bool {
return true
}
}
extension FileHandle {
internal static var _stdinFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDIN_FILENO, closeOnDealloc: false)
}()
open class var standardInput: FileHandle {
return _stdinFileHandle
}
internal static var _stdoutFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDOUT_FILENO, closeOnDealloc: false)
}()
open class var standardOutput: FileHandle {
return _stdoutFileHandle
}
internal static var _stderrFileHandle: FileHandle = {
return FileHandle(fileDescriptor: STDERR_FILENO, closeOnDealloc: false)
}()
open class var standardError: FileHandle {
return _stderrFileHandle
}
internal static var _nulldeviceFileHandle: FileHandle = {
class NullDevice: FileHandle {
override var availableData: Data {
return Data()
}
override func readDataToEndOfFile() -> Data {
return Data()
}
override func readData(ofLength length: Int) -> Data {
return Data()
}
override func write(_ data: Data) {}
override var offsetInFile: UInt64 {
return 0
}
override func seekToEndOfFile() -> UInt64 {
return 0
}
override func seek(toFileOffset offset: UInt64) {}
override func truncateFile(atOffset offset: UInt64) {}
override func synchronizeFile() {}
override func closeFile() {}
deinit {}
}
return NullDevice(fileDescriptor: -1, closeOnDealloc: false)
}()
open class var nullDevice: FileHandle {
return _nulldeviceFileHandle
}
public convenience init?(forReadingAtPath path: String) {
self.init(path: path, flags: O_RDONLY, createMode: 0)
}
public convenience init?(forWritingAtPath path: String) {
self.init(path: path, flags: O_WRONLY, createMode: 0)
}
public convenience init?(forUpdatingAtPath path: String) {
self.init(path: path, flags: O_RDWR, createMode: 0)
}
internal static func _openFileDescriptorForURL(_ url : URL, flags: Int32, reading: Bool) throws -> Int32 {
let path = url.path
let fd = _CFOpenFile(path, flags)
if fd < 0 {
throw _NSErrorWithErrno(errno, reading: reading, url: url)
}
return fd
}
public convenience init(forReadingFrom url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDONLY, reading: true)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
public convenience init(forWritingTo url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_WRONLY, reading: false)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
public convenience init(forUpdating url: URL) throws {
let fd = try FileHandle._openFileDescriptorForURL(url, flags: O_RDWR, reading: false)
self.init(fileDescriptor: fd, closeOnDealloc: true)
}
}
extension NSExceptionName {
public static let fileHandleOperationException = NSExceptionName(rawValue: "NSFileHandleOperationException")
}
extension Notification.Name {
public static let NSFileHandleReadToEndOfFileCompletion = Notification.Name(rawValue: "NSFileHandleReadToEndOfFileCompletionNotification")
public static let NSFileHandleConnectionAccepted = Notification.Name(rawValue: "NSFileHandleConnectionAcceptedNotification")
public static let NSFileHandleDataAvailable = Notification.Name(rawValue: "NSFileHandleDataAvailableNotification")
}
extension FileHandle {
public static let readCompletionNotification = Notification.Name(rawValue: "NSFileHandleReadCompletionNotification")
}
public let NSFileHandleNotificationDataItem: String = "NSFileHandleNotificationDataItem"
public let NSFileHandleNotificationFileHandleItem: String = "NSFileHandleNotificationFileHandleItem"
extension FileHandle {
open func readInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func readInBackgroundAndNotify() {
NSUnimplemented()
}
open func readToEndOfFileInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func readToEndOfFileInBackgroundAndNotify() {
NSUnimplemented()
}
open func acceptConnectionInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func acceptConnectionInBackgroundAndNotify() {
NSUnimplemented()
}
open func waitForDataInBackgroundAndNotify(forModes modes: [RunLoopMode]?) {
NSUnimplemented()
}
open func waitForDataInBackgroundAndNotify() {
NSUnimplemented()
}
open var readabilityHandler: ((FileHandle) -> Void)? {
NSUnimplemented()
}
open var writeabilityHandler: ((FileHandle) -> Void)? {
NSUnimplemented()
}
}
extension FileHandle {
public convenience init(fileDescriptor fd: Int32) {
self.init(fileDescriptor: fd, closeOnDealloc: false)
}
open var fileDescriptor: Int32 {
return _fd
}
}
open class Pipe: NSObject {
private let readHandle: FileHandle
private let writeHandle: FileHandle
public override init() {
/// the `pipe` system call creates two `fd` in a malloc'ed area
var fds = UnsafeMutablePointer<Int32>.allocate(capacity: 2)
defer {
free(fds)
}
/// If the operating system prevents us from creating file handles, stop
guard pipe(fds) == 0 else { fatalError("Could not open pipe file handles") }
/// The handles below auto-close when the `NSFileHandle` is deallocated, so we
/// don't need to add a `deinit` to this class
/// Create the read handle from the first fd in `fds`
self.readHandle = FileHandle(fileDescriptor: fds.pointee, closeOnDealloc: true)
/// Advance `fds` by one to create the write handle from the second fd
self.writeHandle = FileHandle(fileDescriptor: fds.successor().pointee, closeOnDealloc: true)
super.init()
}
open var fileHandleForReading: FileHandle {
return self.readHandle
}
open var fileHandleForWriting: FileHandle {
return self.writeHandle
}
}
| 31.135 | 142 | 0.594026 |
0329699362b21303f6d4f495749ac5a45fedbb35 | 2,302 | import JSONAPI
/// A `ResourceStore` can hold JSONAPI `ResourceObjects` of
/// any type.
public final class ResourceStore {
internal var storage: [ObjectIdentifier: [AnyHashable: Any]]
public var count: Int {
return storage.values.reduce(0, { $0 + $1.values.count })
}
public init() {
storage = [:]
}
/// Update or insert (upsert) the given resource.
public func upsert<T: JSONAPI.IdentifiableResourceObjectType>(_ resource: T) {
upsert([resource])
}
/// Update or insert (upsert) the given resources.
public func upsert<T: JSONAPI.IdentifiableResourceObjectType>(_ resources: [T]) {
for resource in resources {
storage[ObjectIdentifier(T.Id.self), default: [:]][resource.id] = resource
}
}
public subscript<T: JSONAPI.IdentifiableResourceObjectType>(id: T.Id) -> StoredResource<T>? {
return storage[ObjectIdentifier(T.Id.self)].flatMap { resourceHash in
resourceHash[id]
.map { $0 as! T }
.map { StoredResource(store: self, primary: $0) }
}
}
}
extension EncodableJSONAPIDocument where BodyData.PrimaryResourceBody: SingleResourceBodyProtocol, BodyData.PrimaryResourceBody.PrimaryResource: JSONAPI.IdentifiableResourceObjectType, BodyData.IncludeType: StorableResource {
public func resourceStore() -> ResourceStore? {
guard let bodyData = body.data else {
return nil
}
let store = ResourceStore()
store.upsert(bodyData.primary.value)
for include in bodyData.includes.values {
include.store(in: store)
}
return store
}
}
extension EncodableJSONAPIDocument where BodyData.PrimaryResourceBody: ManyResourceBodyProtocol, BodyData.PrimaryResourceBody.PrimaryResource: JSONAPI.IdentifiableResourceObjectType, BodyData.IncludeType: StorableResource {
public func resourceStore() -> ResourceStore? {
guard let bodyData = body.data else {
return nil
}
let store = ResourceStore()
for resource in bodyData.primary.values {
store.upsert(resource)
}
for include in bodyData.includes.values {
include.store(in: store)
}
return store
}
}
| 31.108108 | 225 | 0.652042 |
21f7e311d27e811f989e19ee8e930ead9164fa5e | 276 | //
// Frame.swift
// RSocketSwift
//
// Created by Nathany, Sumit on 21/10/20.
// Copyright © 2020 Mint.com. All rights reserved.
//
import Foundation
private let FlagsMask: Int = 1023
private let FrameTypeShift: Int = 10
protocol Frame {
var streamId: Int { get }
}
| 15.333333 | 51 | 0.684783 |
76c660ddd73e1bdc7c6b96bd764b5950f4e1b31d | 148 | //
// LocationsVC.swift
// Kuppajo
//
// Created by Sagar Patel on 2019-10-12.
// Copyright © 2019 Sagar. All rights reserved.
//
import UIKit
| 14.8 | 48 | 0.662162 |
90eb9b69563339294cacc4ef0686150b045e4c1c | 1,630 | //
// BaseTableViewController.swift
// Hackers
//
// Created by Weiran Zhang on 21/04/2019.
// Copyright © 2019 Glass Umbrella. All rights reserved.
//
import UIKit
extension UITableViewController {
public func smoothlyDeselectRows() {
// Get the initially selected index paths, if any
let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? []
// Grab the transition coordinator responsible for the current transition
if let coordinator = transitionCoordinator {
// Animate alongside the master view controller's view
coordinator.animateAlongsideTransition(in: parent?.view, animation: { context in
// Deselect the cells, with animations enabled if this is an animated transition
selectedIndexPaths.forEach {
self.tableView.deselectRow(at: $0, animated: context.isAnimated)
}
}, completion: { context in
// If the transition was cancel, reselect the rows that were selected before,
// so they are still selected the next time the same animation is triggered
if context.isCancelled {
selectedIndexPaths.forEach {
self.tableView.selectRow(at: $0, animated: false, scrollPosition: .none)
}
}
})
} else { // If this isn't a transition coordinator, just deselect the rows without animating
selectedIndexPaths.forEach {
self.tableView.deselectRow(at: $0, animated: false)
}
}
}
}
| 40.75 | 100 | 0.61411 |
cc4095cb1393d6c7de74c2e4f2c4c6d940ff6b53 | 506 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "SwiftyBeaverVapor",
products: [
.library(name: "SwiftyBeaverVapor", targets: ["SwiftyBeaverVapor"])
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
.package(url: "https://github.com/SwiftyBeaver/SwiftyBeaver.git", from: "1.6.0")
],
targets: [
.target(name: "SwiftyBeaverVapor", dependencies: ["Vapor", "SwiftyBeaver"])
]
)
| 29.764706 | 88 | 0.628458 |
c17bbec180ac3bc880e404576496ef2bbad5eb75 | 345 | import Vapor
// configures your application
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
// print available routes in table
print(app.routes.all)
// register routes
try routes(app)
}
| 28.75 | 86 | 0.73913 |
335686509039688abd13481adae5963157e690e9 | 17,749 | //
// PageViewController.swift
// iOS-SDK
//
// Created by Balazs Vincze on 2018. 04. 20..
// Copyright © 2018. SchedJoules. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SchedJoulesApiClient
import SafariServices
import WebKit
class PageViewController<PageQuery: Query>: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating,
UISearchBarDelegate, SFSafariViewControllerDelegate, LoadErrorViewDelegate where PageQuery.Result == Page {
// - MARK: Public Properties
/// Reload the view if true.
public var shouldReload = false
// - MARK: Private Properties
/// The Page query used by this view controller.
private let pageQuery: PageQuery!
/// The returned Pages object from the query.
private var page: Page?
/// A temporary variable to hold the Pages object while searching.
private var tempPage: Page?
/// The Api client.
private let apiClient: Api
/// The table view for presenting the pages.
private var tableView: UITableView!
// Acitivity indicator
private lazy var activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
// Load error view
private lazy var loadErrorView = Bundle.resourceBundle.loadNibNamed("LoadErrorView", owner: self, options: nil)![0] as! LoadErrorView
// Search controller
private lazy var searchController = UISearchController(searchResultsController: nil)
// Refresh control
private var refreshControl = UIRefreshControl()
/// If this is true, the search controller is added to the view
private let isSearchEnabled: Bool
// - MARK: Initialization
/* This method is only called when initializing a `UIViewController` from a `Storyboard` or `XIB`. The `PageViewController`
must only be used programatically, but every subclass of `UIViewController` must implement `init?(coder aDecoder: NSCoder)`. */
required init?(coder aDecoder: NSCoder) {
fatalError("PageViewController must only be initialized programatically.")
}
/**
Initialize with a Page query and an Api.
- parameter apiClient: The API Key (access token) for the **SchedJoules API**.
- parameter pageQuery: A query with a `Result` of type `Page`.
- parameter searchEnabled: Set this parameter to true, if you would like to have a search controller present. Default is `false`.
*/
required init(apiClient: Api, pageQuery: PageQuery, searchEnabled: Bool = false) {
self.pageQuery = pageQuery
self.apiClient = apiClient
self.isSearchEnabled = searchEnabled
super.init(nibName: nil, bundle: nil)
}
// - MARK: ViewController Methods
override func viewDidLoad() {
super.viewDidLoad()
// Fetch the pages from the API
fetchPages()
// Create a table view
tableView = UITableView(frame: .zero)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
])
// Set up the activity indicator
setUpActivityIndicator()
// Remove empty table cell seperators
tableView.tableFooterView = UIView(frame: .zero)
// Register table cell for reuse
tableView.register(ItemCollectionViewCell.self, forCellReuseIdentifier: "Cell")
// Set up the refresh control
refreshControl.tintColor = navigationController?.navigationBar.tintColor
refreshControl.addTarget(self, action: #selector(fetchPages), for: UIControl.Event.valueChanged)
tableView.refreshControl = refreshControl
// Set up the search controller (if neccessary)
if isSearchEnabled && navigationItem.searchController == nil {
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
definesPresentationContext = true
searchController.searchBar.delegate = self
searchController.searchBar.tintColor = navigationController?.navigationBar.tintColor
navigationItem.searchController = searchController
navigationController?.view.setNeedsLayout()
navigationController?.view.layoutIfNeeded()
}
}
override func viewWillAppear(_ animated: Bool) {
// Refetch the pages if neccessary
if shouldReload { fetchPages() }
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
// - MARK: Helper Methods
/// Execute the Page query and handle the result.
@objc private func fetchPages() {
// Execute the query
apiClient.execute(query: pageQuery, completion: { result in
switch result {
case let .success(page):
// Set the Page variable to the just fecthed Page object
self.page = page as Page
AnalyticsTracker.shared().trackScreen(name: self.title,
page: self.page,
url: self.pageQuery.url)
self.navigationItem.title = page.name
case .failure:
// Remove the previous pages
self.page = nil
// Show the loading error view
self.showErrorView()
}
self.tableView.reloadData()
self.stopLoading()
})
}
///Safaridelegate
func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: URL, title: String?) -> [UIActivity] {
return []
}
func safariViewController(_ controller: SFSafariViewController, excludedActivityTypesFor URL: URL, title: String?) -> [UIActivity.ActivityType] {
return []
}
//WKWebView delegate
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
return nil
}
/// Subscribe to a calendar
@objc private func subscribe(sender: UIButton){
let cell = sender.superview as! UITableViewCell
guard let indexPath = tableView.indexPath(for: cell) else {
sjPrint("Could not get row")
return
}
let pageSection = page!.sections[indexPath.section]
let item = pageSection.items[indexPath.row]
guard let webcal = item.url.webcalURL() else {
open(item: item)
return
}
//First we check if the user has a valid subscription
if StoreManager.shared.isSubscriptionValid == true {
openCalendar(calendarId: item.itemID ?? 0, url: webcal)
} else {
let storeVC = StoreViewController(apiClient: self.apiClient)
self.present(storeVC, animated: true, completion: nil)
}
}
private func openCalendar(calendarId: Int, url: URL) {
let subscriber = SJDeviceCalendarSubscriber.shared
subscriber.subscribe(to: calendarId,
url: url,
screenName: self.title) { (error) in
if error == nil {
let freeCalendarAlertController = UIAlertController(title: "Error",
message: error?.localizedDescription,
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Ok",
style: .cancel)
freeCalendarAlertController.addAction(cancelAction)
self.present(freeCalendarAlertController, animated: true)
}
}
}
/// Set up the activity indicator in the view and start loading
private func setUpActivityIndicator() {
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.hidesWhenStopped = true
activityIndicator.color = navigationController?.navigationBar.tintColor
view.addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor)
])
startLoading()
}
/// Show network indicator and activity indicator
private func startLoading(){
// Remove the load error view, if present
if view.subviews.contains(loadErrorView) {
loadErrorView.removeFromSuperview()
}
UIApplication.shared.isNetworkActivityIndicatorVisible = true
activityIndicator.startAnimating()
}
/// Stop all loading indicators and remove error view
private func stopLoading(){
UIApplication.shared.isNetworkActivityIndicatorVisible = false
activityIndicator.stopAnimating()
tableView.refreshControl?.endRefreshing()
if tableView.numberOfSections > 0 {
// Remove the load error view, if present
if view.subviews.contains(loadErrorView) {
loadErrorView.removeFromSuperview()
}
// Add the refresh control
tableView.refreshControl = refreshControl
}
}
//Open calendar details
func open(item: PageItem) {
if item.url.contains("weather") {
let weatherViewController = WeatherMapViewController(apiClient: apiClient, url: item.url, calendarId: item.itemID ?? 0)
navigationController?.pushViewController(weatherViewController, animated: true)
} else {
let storyboard = UIStoryboard(name: "SDK", bundle: Bundle.resourceBundle)
let calendarVC = storyboard.instantiateViewController(withIdentifier: "CalendarItemViewController") as! CalendarItemViewController
calendarVC.icsURL = URL(string: item.url)
calendarVC.title = item.name
calendarVC.apiClient = apiClient
calendarVC.itemId = item.itemID ?? 0
navigationController?.pushViewController(calendarVC, animated: true)
}
}
/// Show the load error view and hide the refresh control
private func showErrorView() {
// Set up the load error view
self.loadErrorView.delegate = self
self.loadErrorView.refreshButton.setTitleColor(self.navigationController?.navigationBar.tintColor, for: .normal)
self.loadErrorView.refreshButton.layer.borderColor = self.navigationController?.navigationBar.tintColor.cgColor
self.loadErrorView.center = self.view.center
self.view.addSubview(self.loadErrorView)
// Remove the refresh control
self.tableView.refreshControl = nil
// Remove the search controller
self.navigationItem.searchController = nil
}
// - MARK: Table View Data source Methods
func numberOfSections(in tableView: UITableView) -> Int {
return page?.sections.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return page?.sections[section].items.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue a reusable cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ItemCollectionViewCell
cell.delegate = self
// Get the page section
let pageSection = page?.sections[indexPath.section]
// Get the page item from the given section
guard let pageItem = pageSection?.items[indexPath.row] else {
sjPrint("Could not get page item.")
return cell
}
cell.setup(pageItem: pageItem,
tintColor: navigationController?.navigationBar.tintColor)
return cell
}
// Set title for the headers
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return page?.sections[section].name
}
// - MARK: Table View Delegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Deselect the row
tableView.deselectRow(at: indexPath, animated: true)
// Get page section
let pageSection = page!.sections[indexPath.section]
// Show the seleced page in a PageViewController
if pageSection.items[indexPath.row].itemClass == .page {
let languageSetting = SettingsManager.get(type: .language)
let singlePageQuery = SinglePageQuery(pageID: String(pageSection.items[indexPath.row].itemID!),
locale: languageSetting.code)
let pageVC = PageViewController<SinglePageQuery>(apiClient: apiClient,
pageQuery: singlePageQuery,
searchEnabled: true)
navigationController?.pushViewController(pageVC, animated: true)
// Show the selected calendar
} else {
let item = pageSection.items[indexPath.row]
open(item: item)
}
}
// MARK: - Search Delegate Methods
// Store the current page before searching
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
tempPage = page
}
// Perfrom the search
func updateSearchResults(for searchController: UISearchController) {
// Get the search text from the search bar
guard let queryText = searchController.searchBar.text else {
return
}
// Only search if more than 2 charachters were entered
if queryText.count > 2 {
apiClient.execute(query: SearchQuery(query: queryText), completion: { result in
switch result {
case let .success(searchPage):
self.page = searchPage
self.tableView.reloadData()
case let .failure(error):
sjPrint("There was an error searching: \(error)")
}
})
}
}
// Cancel the search and show the page before searching
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
page = tempPage
tableView.reloadData()
}
// MARK: - Load Error View Delegate Methods
func refreshPressed() {
startLoading()
fetchPages()
}
}
extension PageViewController: ItemCollectionViewCellDelegate {
/// Subscribe to a calendar
func subscribe(to pageItem: PageItem) {
let sjCalendar = SJAnalyticsCalendar(calendarId: pageItem.itemID ?? 0,
calendarURL: URL(string: pageItem.url))
let sjEvent = SJAnalyticsObject(calendar: sjCalendar, screenName: self.title)
NotificationCenter.default.post(name: .SJPlustButtonClicked, object: sjEvent)
guard let webcal = pageItem.url.webcalURL() else {
open(item: pageItem)
return
}
if StoreManager.shared.isSubscriptionValid == true {
self.openCalendar(calendarId: pageItem.itemID ?? 0, url: webcal)
} else {
let storeVC = StoreViewController(apiClient: self.apiClient)
self.present(storeVC, animated: true, completion: nil)
return
}
}
}
| 40.522831 | 187 | 0.626401 |
56e86644ae3712f0b434fc49179fa53eebb25b6f | 836 | import UIKit
import ThemeKit
struct ThemeSettingsModule {
static func viewController() -> UIViewController {
let service = ThemeSettingsService(themeManager: ThemeManager.shared)
let viewModel = ThemeSettingsViewModel(service: service)
return ThemeSettingsViewController(viewModel: viewModel)
}
}
extension ThemeMode: CustomStringConvertible {
public var description: String {
switch self {
case .system: return "settings_theme.system".localized
case .dark: return "settings_theme.dark".localized
case .light: return "settings_theme.light".localized
}
}
public var iconName: String {
switch self {
case .system: return "settings_20"
case .dark: return "dark_20"
case .light: return "light_20"
}
}
}
| 23.885714 | 77 | 0.66866 |
eba3af7a98d8440ff40208d5c17859bf84b41025 | 1,405 | //
// Config.swift
// Translate
//
// Created by Stanislav Ivanov on 29.03.2020.
// Copyright © 2020 Stanislav Ivanov. All rights reserved.
//
import Foundation
protocol IConfig {
func baseUrl() -> String
}
enum ConfigError: Error {
case missingKey
case invalidValue
}
final class Config {
static let shared = Config()
// MARK: - Private
private enum ConfigKeys: String {
case baseUrl = "API_BASE_URL"
}
private let baseUrlValue: String
private init() {
do {
let baseUrl: String = try Config.value(for: ConfigKeys.baseUrl.rawValue)
self.baseUrlValue = "https://" + baseUrl
} catch {
#if DEBUG
fatalError("Exception \(#file) \(#function) \(#line) \(error)")
#else
debugPrint("Exception \(#file) \(#function) \(#line) \(error)")
self.baseUrlValue = ""
#endif
}
}
private static func value<T>(for key: String) throws -> T {
guard let object = Bundle.main.object(forInfoDictionaryKey: key) else {
throw ConfigError.missingKey
}
if let value = object as? T {
return value
} else {
throw ConfigError.invalidValue
}
}
}
extension Config: IConfig {
func baseUrl() -> String {
return self.baseUrlValue
}
}
| 21.953125 | 84 | 0.560142 |
71552fa235fd1930369919f05e79981d05064e57 | 315 | // 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 d {
struct d {
func compose( ) {
let f = {
deinit {
protocol A {
class
case ,
var {
{
{
{
{
{
{
{
[ [ {
{
{
{
{
{
{
{
{
{
{
{
{
{
{
{
P {
| 8.076923 | 87 | 0.593651 |
ef2f626711c409e1b97aae6244a3cb608146b424 | 504 | //
// AppDelegate.swift
// CBZed
//
// Created by Joseph Toronto on 5/5/16.
// Copyright © 2016 Janken Studios. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| 18.666667 | 71 | 0.714286 |
f55275df75d795e18073e7c74f7cf9173cb86bf2 | 298 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=i386_or_x86_64
@_silgen_name("atan2") func atan2test(_ a: Double, _ b: Double) -> Double
atan2test(0.0, 0.0)
// CHECK: call swiftcc double @atan2(double {{.*}}, double {{.*}})
| 29.8 | 100 | 0.684564 |
26cab8f6f07be979244b3f4d255a3178d7991f55 | 3,132 | //
// Copyright © FINN.no AS, Inc. All rights reserved.
//
import UIKit
public class ObjectPageTitleView: UIView {
// MARK: - Public properties
public var isTitleTextCopyable: Bool {
get { titleLabel.isTextCopyable }
set { titleLabel.setTextCopyable(newValue) }
}
public var isSubtitleTextCopyable: Bool {
get { subtitleLabel.isTextCopyable }
set { subtitleLabel.setTextCopyable(newValue) }
}
// MARK: - Private properties
private let titleStyle: Label.Style
private let subtitleStyle: Label.Style
private let captionStyle: Label.Style
private lazy var ribbonView = RibbonView(withAutoLayout: true)
private lazy var stackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [ribbonView, titleLabel, subtitleLabel, captionLabel])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.alignment = .leading
stackView.setCustomSpacing(.spacingS, after: ribbonView)
return stackView
}()
private lazy var titleLabel: Label = {
let label = Label(style: titleStyle, withAutoLayout: true)
label.numberOfLines = 0
return label
}()
private lazy var subtitleLabel: Label = {
let label = Label(style: subtitleStyle, withAutoLayout: true)
label.numberOfLines = 0
return label
}()
private lazy var captionLabel: Label = {
let label = Label(style: captionStyle, withAutoLayout: true)
label.numberOfLines = 0
return label
}()
// MARK: - Init
public init(titleStyle: Label.Style = .title2, subtitleStyle: Label.Style = .body, captionStyle: Label.Style = .caption, withAutoLayout: Bool = false) {
self.titleStyle = titleStyle
self.subtitleStyle = subtitleStyle
self.captionStyle = captionStyle
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = !withAutoLayout
setup()
}
required init?(coder: NSCoder) { fatalError() }
// MARK: - Setup
private func setup() {
addSubview(stackView)
stackView.fillInSuperview()
}
// MARK: - Public methods
public func configure(
withTitle title: String? = nil,
subtitle: String? = nil,
caption: String? = nil,
ribbonViewModel: RibbonViewModel? = nil,
spacingAfterTitle: CGFloat = .spacingXS,
spacingAfterSubtitle: CGFloat = .spacingXS
) {
titleLabel.text = title
titleLabel.isHidden = title?.isEmpty ?? true
subtitleLabel.text = subtitle
subtitleLabel.isHidden = subtitle?.isEmpty ?? true
captionLabel.text = caption
captionLabel.isHidden = caption?.isEmpty ?? true
if let ribbonViewModel = ribbonViewModel {
ribbonView.configure(with: ribbonViewModel)
}
ribbonView.isHidden = ribbonViewModel == nil
stackView.setCustomSpacing(spacingAfterTitle, after: titleLabel)
stackView.setCustomSpacing(spacingAfterSubtitle, after: subtitleLabel)
}
}
| 30.115385 | 156 | 0.659323 |
18e702b1514945cfd0e4e5723fee5c93d9f28f6d | 919 | //
// ANCommonKitTests.swift
// ANCommonKitTests
//
// Created by Paul Chavarria Podoliako on 6/9/15.
// Copyright (c) 2015 AnyTap. All rights reserved.
//
import UIKit
import XCTest
class ANCommonKitTests: 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.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 24.837838 | 111 | 0.621328 |
338fd2f631fcdecc2b4bc7aafec92a30132a294c | 2,508 | //
// ExtensionDelegate.swift
// SwiftWatchOS Extension
//
// Created by Aditi Agrawal on 11/07/18.
// Copyright © 2018 Aditi Agrawal. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// 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 applicationWillResignActive() {
// 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, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
| 49.176471 | 285 | 0.698565 |
8fe6090f89d6fdda49f6077f171df3a96db68f79 | 763 | import XCTest
import JVNoParameterInitializable
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.
}
}
}
| 26.310345 | 111 | 0.609436 |
0e2674bba1f22f371fa323ae7f022acf40f4cee4 | 14,974 | //
// MealplanViewModel.swift
// YourKitchen
//
// Created by Markus Moltke on 31/05/2020.
// Copyright © 2020 Markus Moltke. All rights reserved.
//
import Foundation
public class MealplanViewModel {
public func updateMadeThis(recipe: Recipe) {
print("Made this")
YKNetworkManager.Refrigerators.get { refrigerator in
var newIngredients = [Ingredient]()
if let refrigerator = refrigerator {
for ingredient in refrigerator.ingredients {
for recipeIngredient in recipe.ingredients {
if ingredient == recipeIngredient {
let tmpIngredient = ingredient
if let unit = Unit(symbol: ingredient.unit) as? UnitMass, let toUnit = Unit(symbol: recipeIngredient.unit) as? UnitMass {
let measurement1 = Measurement(value: ingredient.amount, unit: unit)
let measurement2 = Measurement(value: recipeIngredient.amount, unit: toUnit)
let finalMeasurement = measurement1 - measurement2
if finalMeasurement.value < 0 { // $ < 0
tmpIngredient.amount = 0
} else if finalMeasurement.value == 0 { // $ == 0
tmpIngredient.amount = 0
} else { // $ > 0
tmpIngredient.amount = finalMeasurement.value
tmpIngredient.unit = AppConstants.Measure.getUnitSymbol(unit: finalMeasurement.unit)
}
} else if let unit = Unit(symbol: ingredient.unit) as? UnitVolume, let toUnit = Unit(symbol: recipeIngredient.unit) as? UnitVolume {
let measurement1 = Measurement(value: ingredient.amount, unit: unit)
let measurement2 = Measurement(value: recipeIngredient.amount, unit: toUnit)
let finalMeasurement = measurement1 - measurement2
if finalMeasurement.value < 0 { // $ < 0
tmpIngredient.amount = 0
} else if finalMeasurement.value == 0 { // $ == 0
tmpIngredient.amount = 0
} else { // $ > 0
tmpIngredient.amount = finalMeasurement.value
tmpIngredient.unit = AppConstants.Measure.getUnitSymbol(unit: finalMeasurement.unit)
}
} else { // No unit
if ingredient.amount - recipeIngredient.amount < 0 { // $ < 0
tmpIngredient.amount = 0
} else if ingredient.amount - recipeIngredient.amount == 0 { // $ == 0
tmpIngredient.amount = 0
} else { // $ > 0
tmpIngredient.amount = ingredient.amount - recipeIngredient.amount
}
}
newIngredients.append(tmpIngredient)
}
}
}
let tmpRefrigerator = refrigerator
tmpRefrigerator.ingredients = YKNetworkManager.Ingredients.match(ingredients: newIngredients, storedIngredients: refrigerator.ingredients)
YKNetworkManager.Refrigerators.update(refrigerator: refrigerator)
}
}
}
// - TODO: Better generation when using premium
/**
Generate a random mealplan for the recipes that are empty
*/
func generateRandomMealplan(_ mealplan: Mealplan, completion: @escaping (Mealplan) -> Void) {
var selectedDishes = [String]()
for meal in mealplan.meals where !(meal.recipe == Recipe.none) && !selectedDishes.contains(meal.recipe.id) {
// Generate new dish
selectedDishes.append(meal.recipe.id)
}
let tmpMealplan = mealplan
YKNetworkManager.Recipes.getAll { recipes in
var maxTries = 20
if premium { // Prefer recommended recipes
SelectRecipeViewModel().getInterests(amount: 4) { recommendedRecipes in //Half of the mealplan is recommended dishes
let recipes = recipes.filter { $0.recipeType == .main }
for meal in mealplan.meals where meal.recipe == Recipe.none {
maxTries -= 1
if maxTries < 0 {
break
}
// Generate new dish
let result = self.getRandomRecipeWithRecommended(recommended: recommendedRecipes, recipes: recipes, reserved: selectedDishes)
tmpMealplan[meal.date] = result.0
selectedDishes = result.1
}
completion(tmpMealplan)
}
} else {
let recipes = recipes.filter { $0.recipeType == .main }
for meal in mealplan.meals where meal.recipe == Recipe.none {
maxTries -= 1
if maxTries < 0 {
break
}
// Generate new dish
let result = self.getRandomRecipe(recipes: recipes, reserved: selectedDishes)
tmpMealplan[meal.date] = result.0
selectedDishes = result.1
}
completion(tmpMealplan)
}
}
}
/**
Get random recipe, but prefer recommended
*/
private func getRandomRecipeWithRecommended(recommended: [Recipe], recipes: [Recipe], reserved: [String]) -> (Recipe, [String]) {
let tmpRecipes = recipes.filter { (recipe) -> Bool in
!reserved.contains(where: { $0 == recipe.id })
}
let tmpRecommended = recommended.filter { (recipe) -> Bool in
!reserved.contains(where: { $0 == recipe.id })
}
if tmpRecommended.count > 0 && Int.random(in: 0..<1) == 0 { //To randomize recipes, so the recommended won't be chosen every time
if let recipe = tmpRecommended.randomElement() {
var tmpReserved = reserved
tmpReserved.append(recipe.id)
return (recipe, tmpReserved)
}
}
if let recipe = tmpRecipes.randomElement() {
var tmpReserved = reserved
tmpReserved.append(recipe.id)
return (recipe, tmpReserved)
}
return (Recipe.none, reserved)
}
/**
Generate a random recipe
*/
private func getRandomRecipe(recipes: [Recipe], reserved: [String]) -> (Recipe, [String]) {
let tmpRecipes = recipes.filter { (recipe) -> Bool in
!reserved.contains(where: { $0 == recipe.id })
}
if let recipe = tmpRecipes.randomElement() {
var tmpReserved = reserved
tmpReserved.append(recipe.id)
return (recipe, tmpReserved)
}
return (Recipe.none, reserved)
}
/**
Used to add/remove the appropiate recipes from the mealplan to keep 8 items in it at all times (Removes old recipes)
*/
func maintainMealplan(mealplan: Mealplan, _ completion: @escaping (Mealplan) -> Void) {
var updateCount = 0
let tmpMealplan = mealplan
var removedRecipes = [Recipe]()
for meal in tmpMealplan.meals {
if meal.date.isInThePast {
updateCount += 1
removedRecipes.append(meal.recipe)
tmpMealplan.meals.removeAll(where: { $0.date == meal.date })
tmpMealplan[meal.date.addDays(value: 8).start] = Recipe.none
}
}
//Move items 8 days forward
if updateCount >= 8 { //Reset mealplan if
tmpMealplan.meals = Mealplan.emptyMealplan
} else {
var index = 0
var maxTries = 20
while tmpMealplan.meals.count < 8 && maxTries > 0 {
maxTries -= 1
if tmpMealplan.meals.first(where: { $0.date == Date.start.addDays(value: index) }) == nil {
tmpMealplan[Date.start.addDays(value: index)] = Recipe.none
}
index += 1
}
}
generateRandomMealplan(tmpMealplan) { mealplan in
let before = tmpMealplan.meals.filter { $0.recipe == Recipe.none }.map(\.recipe)
let after = mealplan.meals.filter {
$0.recipe.id != Recipe.none.id
}.filter {
!before.contains($0.recipe)
}.map(\.recipe)
self.fixShoppingList(removed: removedRecipes, new: after)
YKNetworkManager.Mealplans.update(mealplan) { mealplan in
completion(mealplan)
}
}
}
/**
Used to keep the shopping list updated, sometimes this might fail minimally and remove a ingredient that was user added...
- Parameters:
- removed: The removed recipes
- recipes: The new recipes
*/
private func fixShoppingList(removed: [Recipe], new recipes: [Recipe]) {
YKNetworkManager.Refrigerators.get { refrigerator in
if let refrigerator = refrigerator {
YKNetworkManager.ShoppingLists.get(refrigerator.ownerId) { shoppingList in
if var shoppingList = shoppingList {
guard let user = YKNetworkManager.shared.currentUser else { return }
var ingredients = [Ingredient]()
_ = recipes.map { ingredients.append(contentsOf: $0.getIngredientsForPersons(person: user.defaultPersons)) } // All ingredients in the new recipes
var removedIngredients = [Ingredient]() // All ingredients removed because the recipe changed without being made.
//We assume they were also added with default persons.
_ = removed.map { removedIngredients.append(contentsOf: $0.getIngredientsForPersons(person: user.defaultPersons)) }
// Combine ingredients amount
for item in ingredients {
let similar = ingredients.filter { $0 == item }
if similar.count > 1 { // If there is more than one of this item
let first = similar.first!
first.amount = 0.0
for sim in similar {
first.amount += sim.amount
}
ingredients.removeAll(where: { $0 == first }) // Remove all similar ingredients
ingredients.append(first) // Add ingredient with new amounts
}
}
// Add ingredients that aren't already on the list
for ingredient in ingredients { // The ingredients to add..
let shoppingListItem = shoppingList.ingredients.filter { $0 == ingredient }.first // If the ingredient we are about to add already is in the shoppinglist
if let shoppingListItem = shoppingListItem {
shoppingList.ingredients.removeAll(where: { $0 == shoppingListItem })
if shoppingListItem.amount - ingredient.amount > 0 {
// Shopping list amount is less than zero without the ingredient amount
shoppingListItem.amount += shoppingListItem.amount - ingredient.amount
} else {
// ShoppingList minus ingredient is under 0, set the amount to the new amount
shoppingListItem.amount = ingredient.amount
}
shoppingList.ingredients.append(shoppingListItem) // Re-add with new amount
} else {
// If the ingredient isn't already there add it
shoppingList.ingredients.append(ingredient)
}
}
// Remove what we already have in our refrigerator
for ingredient in shoppingList.ingredients {
let refIng = refrigerator.ingredients.filter { $0 == ingredient }.first // Get the refrigerator ingredient from mealplan
let removedIngredient = removedIngredients.filter { $0 == ingredient }.first // Get the removedIngredient from mealplan
if let refIng = refIng { // If it exists
let tmpIngredient = ingredient // Convert to let
tmpIngredient.amount -= refIng.amount // Subtract the refrigerator ingredients amount
shoppingList.ingredients.removeAll(where: { $0 == tmpIngredient }) // Remove it from the shoppingList
if tmpIngredient.amount > 0.0 { // If the ingredient amount is over 0
shoppingList.ingredients.append(tmpIngredient) // Add it again
}
}
if let removedIngredient = removedIngredient { // If it exists
let tmpIngredient = ingredient // Convert to var
tmpIngredient.amount -= removedIngredient.amount // Subtract the removed ingredients amount
shoppingList.ingredients.removeAll(where: { $0 == tmpIngredient }) // Remove it from the shoppingList
if tmpIngredient.amount > 0.0 { // If the ingredient amount is over 0
shoppingList.ingredients.append(tmpIngredient) // Add it again
}
}
}
YKNetworkManager.ShoppingLists.update(shoppingList: shoppingList) // Update the shoppinglist
} else {
YKNetworkManager.ShoppingLists.update(shoppingList: ShoppingList(ownerId: refrigerator.ownerId, ingredients: [])) {
self.fixShoppingList(removed: removed, new: recipes)
}
}
}
}
}
}
}
| 53.288256 | 181 | 0.513423 |
dec09f065f7b6b161504b1f3dcb3f6b9600f1a14 | 746 | import XCTest
import RulerView
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.724138 | 111 | 0.600536 |
fbfc7b2fba2910c822040837f4039156ac2b634c | 415 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "FINNBottomSheet",
defaultLocalization: "en",
platforms: [
.iOS(.v11)
],
products: [
.library(name: "FINNBottomSheet", targets: ["FINNBottomSheet"])
],
targets: [
.target(name: "FINNBottomSheet", path: "Sources", exclude: ["Info.plist"])
],
swiftLanguageVersions: [.v5]
)
| 23.055556 | 82 | 0.609639 |
edfead81a58321c67e8ccd729abf7414ff65df48 | 112 | import XCTest
import ugridTests
var tests = [XCTestCaseEntry]()
tests += ugridTests.allTests()
XCTMain(tests)
| 14 | 31 | 0.767857 |
dd91fee4c27459202d90a6741bbc89d00700ca3c | 4,087 | //
// AutomaticProperties.swift
// Mixpanel
//
// Created by Yarden Eitan on 7/8/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#else
import WatchKit
#endif
class AutomaticProperties {
static let automaticPropertiesLock = ReadWriteLock(label: "automaticPropertiesLock")
static var properties: InternalProperties = {
var p = InternalProperties()
#if os(iOS) || os(tvOS)
let screenSize = UIScreen.main.bounds.size
p["$screen_height"] = Int(screenSize.height)
p["$screen_width"] = Int(screenSize.width)
p["$os"] = UIDevice.current.systemName
p["$os_version"] = UIDevice.current.systemVersion
#elseif os(macOS)
if let screenSize = NSScreen.main?.frame.size {
p["$screen_height"] = Int(screenSize.height)
p["$screen_width"] = Int(screenSize.width)
}
p["$os"] = "macOS"
p["$os_version"] = ProcessInfo.processInfo.operatingSystemVersionString
#elseif os(watchOS)
let watchDevice = WKInterfaceDevice.current()
p["$os"] = watchDevice.systemName
p["$os_version"] = watchDevice.systemVersion
p["$watch_model"] = AutomaticProperties.watchModel()
let screenSize = watchDevice.screenBounds.size
p["$screen_width"] = Int(screenSize.width)
p["$screen_height"] = Int(screenSize.height)
#endif
let infoDict = Bundle.main.infoDictionary
if let infoDict = infoDict {
p["$app_build_number"] = infoDict["CFBundleVersion"]
p["$app_version_string"] = infoDict["CFBundleShortVersionString"]
}
p["mp_lib"] = "swift"
p["$lib_version"] = AutomaticProperties.libVersion()
p["$manufacturer"] = "Apple"
p["$model"] = AutomaticProperties.deviceModel()
return p
}()
static var peopleProperties: InternalProperties = {
var p = InternalProperties()
let infoDict = Bundle.main.infoDictionary
if let infoDict = infoDict {
p["$ios_app_version"] = infoDict["CFBundleVersion"]
p["$ios_app_release"] = infoDict["CFBundleShortVersionString"]
}
p["$ios_device_model"] = AutomaticProperties.deviceModel()
#if !os(OSX) && !os(watchOS)
p["$ios_version"] = UIDevice.current.systemVersion
#else
p["$ios_version"] = ProcessInfo.processInfo.operatingSystemVersionString
#endif
p["$ios_lib_version"] = AutomaticProperties.libVersion()
p["$swift_lib_version"] = AutomaticProperties.libVersion()
return p
}()
class func deviceModel() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let size = MemoryLayout<CChar>.size
let modelCode = withUnsafePointer(to: &systemInfo.machine) {
$0.withMemoryRebound(to: CChar.self, capacity: size) {
String(cString: UnsafePointer<CChar>($0))
}
}
if let model = String(validatingUTF8: modelCode) {
return model
}
return ""
}
#if os(watchOS)
class func watchModel() -> String {
let watchSize38mm = Int(136)
let watchSize40mm = Int(162)
let watchSize42mm = Int(156)
let watchSize44mm = Int(184)
let screenWidth = Int(WKInterfaceDevice.current().screenBounds.size.width)
switch screenWidth {
case watchSize38mm:
return "Apple Watch 38mm"
case watchSize40mm:
return "Apple Watch 40mm"
case watchSize42mm:
return "Apple Watch 42mm"
case watchSize44mm:
return "Apple Watch 44mm"
default:
return "Apple Watch"
}
}
#endif
class func libVersion() -> String {
return "2.9.3"
}
}
| 32.696 | 88 | 0.584047 |
4b9c90e60f601fe71fc602420a304d2e940340d3 | 931 | //
// TableElements.swift
// Ping Home
//
// Created by 西山 零士 on 2019/08/02.
// Copyright © 2019 西山 零士. All rights reserved.
//
import UIKit
struct CellElement {
let content: String
let detail: String?
let accessoryType: UITableViewCell.AccessoryType
let needSwitch: Bool
let switchIsOn: Bool
init(content: String, detail: String? = nil, accessoryType: UITableViewCell.AccessoryType = UITableViewCell.AccessoryType.none, needSwitch: Bool = false, switchIsOn: Bool = false) {
self.content = content
self.detail = detail
self.accessoryType = accessoryType
self.needSwitch = needSwitch
self.switchIsOn = switchIsOn
}
}
struct SectionElement {
let headerTitle: String?
let footerTitle: String?
var cells: [CellElement]?
init(headerTitle: String? = nil, footerTitle: String? = nil, cells: [CellElement]? = nil) {
self.headerTitle = headerTitle
self.footerTitle = footerTitle
self.cells = cells
}
}
| 24.5 | 182 | 0.73362 |
46c58d97076c7b25dce526095e2f11bda609fdb3 | 1,436 | //
// OrderView.swift
// DribbleSample
//
// Created by Sungwook Baek on 2021/04/20.
//
import UIKit
import Combine
@IBDesignable
class OrderView: UIView {
@IBOutlet weak var countButton: UIButton!
let select = PassthroughSubject<Void, Never>()
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
private func setupView() {
guard let nib = loadNib() else {
return
}
nib.translatesAutoresizingMaskIntoConstraints = false
addSubview(nib)
nib.backgroundColor = .clear
NSLayoutConstraint.activate([
nib.leadingAnchor.constraint(equalTo: self.leadingAnchor),
nib.trailingAnchor.constraint(equalTo: self.trailingAnchor),
nib.topAnchor.constraint(equalTo: self.topAnchor),
nib.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
backgroundColor = .clear
}
private func loadNib() -> UIView? {
let bundle = Bundle(for: Self.self)
return bundle.loadNibNamed(String(describing: Self.self), owner: self, options: nil)?.first as? UIView
}
@IBAction func countButtonTapped(_ sender: Any) {
select.send()
}
}
| 26.109091 | 110 | 0.630919 |
01bcf468bf4da8e0f8284a26006071dfb8bb316a | 1,211 | //
// FlickrPhotoCell.swift
// ios13test
//
// Created by Vladimir Amiorkov on 25.07.19.
// Copyright © 2019 Vladimir Amiorkov. All rights reserved.
//
import UIKit
class FlickPhotoCell: UICollectionViewCell {
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label1: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.blue
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.initBackgroundColor()
}
func initBackgroundColor() {
self.backgroundColor = UIColor.blue
}
func getCellSize(_ targetSize: CGSize) -> CGSize {
return CGSize(width: 50, height: 200)
}
// Only this is called on iOS 12 and lower
override func systemLayoutSizeFitting(_ targetSize: CGSize) -> CGSize {
return self.getCellSize(targetSize)
}
// Only this is called on iOS 13 beta
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
return self.getCellSize(targetSize)
}
}
| 27.522727 | 193 | 0.673823 |
f410d4c12db50d7a17f24147258496d43e1b8935 | 3,297 | //
// Copyright (c) 2021 Adyen N.V.
//
// This file is open source and available under the MIT license. See the LICENSE file for more info.
//
#if canImport(AdyenActions)
import AdyenActions
#endif
import Adyen
import Foundation
/// Defines the methods a delegate of the drop in component should implement.
public protocol DropInComponentDelegate: AnyObject {
/// Invoked when a payment method is selected and the initial details have been filled.
///
/// - Parameters:
/// - data: The data supplied by the drop in component, containing the filled payment method details.
/// - paymentMethod: The paymen method of selected paymen component.
/// - component: The drop in component in which the payment method was selected and filled.
func didSubmit(_ data: PaymentComponentData, for paymentMethod: PaymentMethod, from component: DropInComponent)
/// Invoked when additional details have been provided for a payment method.
///
/// - Parameters:
/// - data: The additional data supplied by the drop in component.
/// - component: The drop in component from which the additional details were provided.
func didProvide(_ data: ActionComponentData, from component: DropInComponent)
/// Invoked when the action component finishes,
/// without any further steps needed by the application, for example in case of voucher payment methods.
/// The application just needs to dismiss the `DropInComponent`.
///
/// - Parameters:
/// - component: The component that handled the action.
func didComplete(from component: DropInComponent)
/// Invoked when the drop in component failed with an error.
///
/// - Parameters:
/// - error: The error that occurred.
/// - component: The drop in component that failed.
func didFail(with error: Error, from component: DropInComponent)
/// Invoked when user closes a payment component.
///
/// - Parameters:
/// - component: The component that the user closed.
/// - dropInComponent: The drop in component that owns the `component`.
func didCancel(component: PaymentComponent, from dropInComponent: DropInComponent)
/// Invoked when payment component redirected to external app.
///
/// - Parameters:
/// - component: The component that the user closed.
/// - dropInComponent: The drop in component that owns the `component`.
func didOpenExternalApplication(_ component: DropInComponent)
}
public protocol StoredPaymentMethodsDelegate: AnyObject {
/// Invoked when shopper wants to delete a stored payment method.
///
/// - Parameters:
/// - storedPaymentMethod: The stored payment method that the user wants to disable.
/// - completion: The delegate need to call back this closure when the disabling is done,
/// with a boolean parameter that indicates success or failure.
func disable(storedPaymentMethod: StoredPaymentMethod, completion: @escaping Completion<Bool>)
}
/// :nodoc:
public extension DropInComponentDelegate {
/// :nodoc:
func didCancel(component: PaymentComponent, from dropInComponent: DropInComponent) {}
/// :nodoc:
func didOpenExternalApplication(_ component: DropInComponent) {}
}
| 40.703704 | 115 | 0.70276 |
acb12164d2ef4de7b13e09c753c3c8c4a3550243 | 1,366 | // Copyright (c) 2018-2020 XMLCoder contributors
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
//
// Created by Vincent Esche on 12/18/18.
//
import Foundation
public struct XMLHeader {
/// The XML standard that the produced document conforms to.
public let version: Double?
/// The encoding standard used to represent the characters in the produced document.
public let encoding: String?
/// Indicates whether a document relies on information from an external source.
public let standalone: String?
public init(version: Double? = nil, encoding: String? = nil, standalone: String? = nil) {
self.version = version
self.encoding = encoding
self.standalone = standalone
}
func isEmpty() -> Bool {
return version == nil && encoding == nil && standalone == nil
}
func toXML() -> String? {
guard !isEmpty() else {
return nil
}
var string = "<?xml"
if let version = version {
string += " version=\"\(version)\""
}
if let encoding = encoding {
string += " encoding=\"\(encoding)\""
}
if let standalone = standalone {
string += " standalone=\"\(standalone)\""
}
string += "?>\n"
return string
}
}
| 24.836364 | 93 | 0.589312 |
5635ed0a7e3347874dd279aa9944193b9f1d7234 | 2,599 | //
// functions.swift
// swift_combination
//
// Created by Keita Okamoto on 2014/12/15.
// Copyright (c) 2014年 Keita Okamoto. All rights reserved.
//
@discardableResult
public func combination<T>(_ arr:[T], length:Int) -> [[T]] {
if length > arr.count || length < 0 { return [] }
if arr.isEmpty { return [] }
if length == 0 { return [[]] }
var ret = [[T]]()
_combination(arr, length: length){ ret.append($0) }
return ret
}
@discardableResult
public func combination<T>(_ arr:[T], length:Int, process:([T]) -> ()) -> [T] {
if length > arr.count || length < 0 { return [] }
if arr.isEmpty { return [] }
if length == 0 { process([]); return arr }
return _combination(arr, length: length, process: process)
}
@discardableResult
public func repeatedCombination<T>(_ arr:[T], length:Int) -> [[T]] {
if length < 0 { return [] }
if arr.isEmpty { return [] }
if length == 0 { return [[]] }
var ret = [[T]]()
_repeatedCombination(arr, length: length){ ret.append($0) }
return ret
}
@discardableResult
public func repeatedCombination<T>(_ arr:[T], length:Int, process:([T]) -> ()) -> [T] {
if length < 0 { return [] }
if arr.isEmpty { return [] }
if length == 0 { process([]); return arr }
return _repeatedCombination(arr, length: length, process: process)
}
@discardableResult
public func repeatedPermutation<T>(_ arr:[T], length:Int) -> [[T]] {
if length < 0 { return [] }
if arr.isEmpty { return [] }
if length == 0 { return [[]] }
var ret = [[T]]()
_repeatedPermutation(arr, length: length){ ret.append($0) }
return ret
}
@discardableResult
public func repeatedPermutation<T>(_ arr:[T], length:Int, process:([T]) -> ()) -> [T] {
if length < 0 { return [] }
if arr.isEmpty { return [] }
if length == 0 { process([]); return arr }
return _repeatedPermutation(arr, length: length, process: process)
}
@discardableResult
public func permutation<T>(_ arr:[T], length:Int? = nil) -> [[T]] {
let _len = length ?? arr.count
if _len > arr.count || _len < 0 { return [] }
if arr.isEmpty { return [] }
if _len == 0 { return [[]] }
var ret = [[T]]()
_permutation(arr, length: _len){ ret.append($0) }
return ret
}
@discardableResult
public func permutation<T>(_ arr:[T], length:Int? = nil, process:([T]) -> ()) -> [T] {
let _len = length ?? arr.count
if _len > arr.count || _len < 0 { return [] }
if arr.isEmpty { return [] }
if _len == 0 { process([]); return arr }
return _permutation(arr, length: _len, process: process)
}
| 27.648936 | 87 | 0.594844 |
0182a20f25fad435a4549de03139e930ab19a49a | 1,813 | import Foundation
class Human {
var weight: Int
var age: Int
// designated initializer
init(weight: Int, age: Int) {
self.weight = weight
self.age = age
}
// convenience initializer
convenience init(age: Int) {
self.init(weight: 0, age: age)
}
convenience init(weight: Int) {
self.init(weight: weight, age: 0)
}
convenience init() {
self.init(weight: 0)
}
func test(){}
deinit {
print("Human deinitialized")
}
}
enum Color: Int {
case Black
case White
init?(_ value: Int) {
switch value {
case 0: self = Black
case 1: self = White
default: return nil
}
}
}
let color1 = Color(1)
let color2 = Color(rawValue: 0)
print(color1?.rawValue)
print(color2?.rawValue)
struct Size {
var width: Int
var height: Int
init?(width: Int, heigth: Int) {
if width < 0 && heigth < 0 { return nil }
self.width = width
self.height = heigth
}
}
class Friend: Human {
var name: String
let skin: Color = { return Color(Int(arc4random_uniform(2)))! }()
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
super.init(weight: 0, age: 0)
}
// must override in subclass
required init() {
self.name = "Hi"
super.init(weight: 0, age: 0)
}
deinit {
print("Friend deinitialized")
}
}
let f = Friend(name: "abc")
if let n = f?.name { print(n) }
class BestFriend: Friend {
override init(name: String) {
if name.isEmpty { super.init() }
else { super.init(name: name)! }
}
required init() {
super.init()
}
deinit {
print("BestFriend deinitialized")
}
}
f?.skin
// deinit test
var friends = [BestFriend]()
for _ in 0..<100 {
//let a = BestFriend()
//friends.append(a)
}
print(BestFriend())
| 14.054264 | 67 | 0.591837 |
201a59a59fc97d2235535f8221b7de0380bff685 | 716 | //
// ProductCollectionViewCell.swift
// DemoPodProject
//
// Created by GIZMEON on 09/06/21.
//
import Foundation
import Foundation
import UIKit
class ProductCollectionViewCell: UICollectionViewCell {
@IBOutlet var productImage: CustomImageView!
@IBOutlet var headerLabel: UILabel!
@IBOutlet var productNameLAbel: UILabel!
@IBOutlet var productPriceLAbel: UILabel!
@IBOutlet var productImageHeight: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
self.layoutIfNeeded()
if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
}
else{
productImageHeight.constant = 80
}
}
}
| 25.571429 | 76 | 0.688547 |
d963b54685f59a159d73dfb64bd58ba778ba829c | 2,013 | //
// ViewController.swift
// AWARE-CustomESM
//
// Created by Yuuki Nishiyama on 2019/04/02.
// Copyright © 2019 tetujin. All rights reserved.
//
import UIKit
import AWAREFramework
class ViewController: UIViewController {
var esmAppeared = false
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(willEnterForegroundNotification(notification:)),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
override func viewDidAppear(_ animated: Bool) {
checkESMSchedules()
}
@objc func willEnterForegroundNotification(notification: NSNotification) {
esmAppeared = false
UIApplication.shared.applicationIconBadgeNumber = 0
checkESMSchedules()
}
func checkESMSchedules(){
let schedules = ESMScheduleManager.shared().getValidSchedules()
if(schedules.count > 0){
let esmViewController = ESMScrollViewController()
/// Generate Original ESM
esmViewController.setOriginalESMViewGenerationHandler { (esm, positionY, viewController) -> BaseESMView? in
if esm.esm_type?.intValue == 99 {
let height = 100.0
let width = Double(viewController.view.frame.size.width)
let frame = CGRect(x:0.0, y:positionY, width:width, height:height)
return CustomESM(frame: frame, esm: esm, viewController: viewController)
}
return nil
}
/// Handle the survey completion
esmViewController.setAllESMCompletionHandler {
self.esmAppeared = true
}
if !esmAppeared {
self.present(esmViewController, animated: true){}
}
}
}
}
| 33 | 119 | 0.578738 |
48918c5525e9cf446727c8bb00dfeb412d7e467d | 2,886 | /**
* Copyright (c) 2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
// Type: response category, i.e. A (article), D (disambiguation), C (category), N (name), E (exclusive), or nothing.
enum ResultType: String, Codable {
case article = "A"
case disambiguation = "D"
case category = "C"
case name = "N"
case exclusive = "E"
}
struct Definition: Codable {
let title: String
let description: String
let resultType: ResultType
let imageURL: URL?
enum CodingKeys: String, CodingKey {
case title = "Heading"
case description = "AbstractText"
case resultType = "Type"
case imageURL = "Image"
}
}
extension Definition {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let title = try container.decode(String.self, forKey: .title)
let description = try container.decode(String.self, forKey: .description)
let resultType = try container.decode(ResultType.self, forKey: .resultType)
let imageURL = try container.decode(URL.self, forKey: .imageURL)
self.init(title: title, description: description, resultType: resultType, imageURL: imageURL)
}
}
final class DuckDuckGo {
func performSearch(for term: String, completion: @escaping (Definition?) -> Void) {
}
}
| 38.48 | 116 | 0.73562 |
e2efb7ac0ec8b581b311c36aa58e4aba7ac0998b | 38,836 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import NIO
class NonBlockingFileIOTest: XCTestCase {
private var group: EventLoopGroup!
private var eventLoop: EventLoop!
private var allocator: ByteBufferAllocator!
private var fileIO: NonBlockingFileIO!
private var threadPool: NIOThreadPool!
override func setUp() {
super.setUp()
self.allocator = ByteBufferAllocator()
self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.threadPool = NIOThreadPool(numberOfThreads: 6)
self.threadPool.start()
self.fileIO = NonBlockingFileIO(threadPool: threadPool)
self.eventLoop = self.group.next()
}
override func tearDown() {
XCTAssertNoThrow(try self.group?.syncShutdownGracefully())
XCTAssertNoThrow(try self.threadPool?.syncShutdownGracefully())
self.group = nil
self.eventLoop = nil
self.allocator = nil
self.threadPool = nil
self.fileIO = nil
super.tearDown()
}
func testBasicFileIOWorks() throws {
let content = "hello"
try withTemporaryFile(content: content) { (fileHandle, _) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
var buf = try self.fileIO.read(fileRegion: fr,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(content.utf8.count, buf.readableBytes)
XCTAssertEqual(content, buf.readString(length: buf.readableBytes))
}
}
func testOffsetWorks() throws {
let content = "hello"
try withTemporaryFile(content: content) { (fileHandle, _) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 3, endIndex: 5)
var buf = try self.fileIO.read(fileRegion: fr,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(2, buf.readableBytes)
XCTAssertEqual("lo", buf.readString(length: buf.readableBytes))
}
}
func testOffsetBeyondEOF() throws {
let content = "hello"
try withTemporaryFile(content: content) { (fileHandle, _) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 3000, endIndex: 3001)
var buf = try self.fileIO.read(fileRegion: fr,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(0, buf.readableBytes)
XCTAssertEqual("", buf.readString(length: buf.readableBytes))
}
}
func testEmptyReadWorks() throws {
try withTemporaryFile { (fileHandle, _) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 0)
let buf = try self.fileIO.read(fileRegion: fr,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(0, buf.readableBytes)
}
}
func testReadingShortWorks() throws {
let content = "hello"
try withTemporaryFile(content: "hello") { (fileHandle, _) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 10)
var buf = try self.fileIO.read(fileRegion: fr,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(content.utf8.count, buf.readableBytes)
XCTAssertEqual(content, buf.readString(length: buf.readableBytes))
}
}
func testDoesNotBlockTheThreadOrEventLoop() throws {
var innerError: Error? = nil
try withPipe { readFH, writeFH in
let bufferFuture = self.fileIO.read(fileHandle: readFH,
byteCount: 10,
allocator: self.allocator,
eventLoop: self.eventLoop)
do {
try self.eventLoop.submit {
try writeFH.withUnsafeFileDescriptor { writeFD in
_ = try Posix.write(descriptor: writeFD, pointer: "X", size: 1)
}
try writeFH.close()
}.wait()
var buf = try bufferFuture.wait()
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual("X", buf.readString(length: buf.readableBytes))
} catch {
innerError = error
}
return [readFH]
}
XCTAssertNil(innerError)
}
func testGettingErrorWhenEventLoopGroupIsShutdown() throws {
self.threadPool.shutdownGracefully(queue: .global()) { err in
XCTAssertNil(err)
}
try withPipe { readFH, writeFH in
do {
_ = try self.fileIO.read(fileHandle: readFH,
byteCount: 1,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTFail("should've thrown")
} catch let e as ChannelError {
XCTAssertEqual(ChannelError.ioOnClosedChannel, e)
} catch {
XCTFail("unexpected error \(error)")
}
return [readFH, writeFH]
}
}
func testChunkReadingWorks() throws {
let content = "hello"
let contentBytes = Array(content.utf8)
var numCalls = 0
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count, numCalls)
}
func testChunkReadingCanBeAborted() throws {
enum DummyError: Error { case dummy }
let content = "hello"
let contentBytes = Array(content.utf8)
var numCalls = 0
withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
do {
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(contentBytes[numCalls], buf.readBytes(length: 1)?.first!)
numCalls += 1
return self.eventLoop.makeFailedFuture(DummyError.dummy)
}.wait()
XCTFail("call successful but should've failed")
} catch let e as DummyError where e == .dummy {
// ok
} catch {
XCTFail("wrong error \(error) caught")
}
}
XCTAssertEqual(1, numCalls)
}
func testFailedIO() throws {
enum DummyError: Error { case dummy }
let unconnectedSockFH = NIOFileHandle(descriptor: socket(AF_UNIX, Posix.SOCK_STREAM, 0))
defer {
XCTAssertNoThrow(try unconnectedSockFH.close())
}
do {
try self.fileIO.readChunked(fileHandle: unconnectedSockFH,
byteCount: 5,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
XCTFail("shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
}.wait()
XCTFail("call successful but should've failed")
} catch let e as IOError {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
XCTAssertEqual(ENOTCONN, e.errnoCode)
#else
XCTAssertEqual(EINVAL, e.errnoCode)
#endif
} catch {
XCTFail("wrong error \(error) caught")
}
}
func testChunkReadingWorksForIncrediblyLongChain() throws {
let content = String(repeatElement("X", count: 20*1024))
var numCalls = 0
let expectedByte = content.utf8.first!
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: content.utf8.count)
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 1,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual(expectedByte, buf.readBytes(length: 1)!.first!)
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count, numCalls)
}
func testReadingDifferentChunkSize() throws {
let content = "0123456789"
var numCalls = 0
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: content.utf8.count)
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 2,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(2, buf.readableBytes)
XCTAssertEqual(Array("\(numCalls*2)\(numCalls*2 + 1)".utf8), buf.readBytes(length: 2)!)
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(content.utf8.count/2, numCalls)
}
func testReadDoesNotReadShort() throws {
var innerError: Error? = nil
try withPipe { readFH, writeFH in
let bufferFuture = self.fileIO.read(fileHandle: readFH,
byteCount: 10,
allocator: self.allocator,
eventLoop: self.eventLoop)
do {
for i in 0..<10 {
// this construction will cause 'read' to repeatedly return with 1 byte read
try self.eventLoop.scheduleTask(in: .milliseconds(50)) {
try writeFH.withUnsafeFileDescriptor { writeFD in
_ = try Posix.write(descriptor: writeFD, pointer: "\(i)", size: 1)
}
}.futureResult.wait()
}
try writeFH.close()
var buf = try bufferFuture.wait()
XCTAssertEqual(10, buf.readableBytes)
XCTAssertEqual("0123456789", buf.readString(length: buf.readableBytes))
} catch {
innerError = error
}
return [readFH]
}
XCTAssertNil(innerError)
}
func testChunkReadingWhereByteCountIsNotAChunkSizeMultiplier() throws {
let content = "prefix-12345-suffix"
var allBytesActual = ""
let allBytesExpected = String(content.dropFirst(7).dropLast(7))
var numCalls = 0
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 7, endIndex: 12)
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 3,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
allBytesActual += buf.readString(length: buf.readableBytes) ?? "WRONG"
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(allBytesExpected, allBytesActual)
XCTAssertEqual(2, numCalls)
}
func testChunkedReadDoesNotReadShort() throws {
var innerError: Error? = nil
try withPipe { readFH, writeFH in
var allBytes = ""
let f = self.fileIO.readChunked(fileHandle: readFH,
byteCount: 10,
chunkSize: 3,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
if allBytes.utf8.count == 9 {
XCTAssertEqual(1, buf.readableBytes)
} else {
XCTAssertEqual(3, buf.readableBytes)
}
allBytes.append(buf.readString(length: buf.readableBytes) ?? "THIS IS WRONG")
return self.eventLoop.makeSucceededFuture(())
}
do {
for i in 0..<10 {
// this construction will cause 'read' to repeatedly return with 1 byte read
try self.eventLoop.scheduleTask(in: .milliseconds(50)) {
try writeFH.withUnsafeFileDescriptor { writeFD in
_ = try Posix.write(descriptor: writeFD, pointer: "\(i)", size: 1)
}
}.futureResult.wait()
}
try writeFH.close()
try f.wait()
XCTAssertEqual("0123456789", allBytes)
} catch {
innerError = error
}
return [readFH]
}
XCTAssertNil(innerError)
}
func testChunkSizeMoreThanTotal() throws {
let content = "0123456789"
var numCalls = 0
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let fr = FileRegion(fileHandle: fileHandle, readerIndex: 0, endIndex: 5)
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
XCTAssertTrue(self.eventLoop.inEventLoop)
XCTAssertEqual(5, buf.readableBytes)
XCTAssertEqual("01234", buf.readString(length: buf.readableBytes) ?? "bad")
numCalls += 1
return self.eventLoop.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(1, numCalls)
}
func testFileRegionReadFromPipeFails() throws {
try withPipe { readFH, writeFH in
try! writeFH.withUnsafeFileDescriptor { writeFD in
_ = try! Posix.write(descriptor: writeFD, pointer: "ABC", size: 3)
}
let fr = FileRegion(fileHandle: readFH, readerIndex: 1, endIndex: 2)
do {
try self.fileIO.readChunked(fileRegion: fr,
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
XCTFail("this shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
}.wait()
XCTFail("succeeded and shouldn't have")
} catch let e as IOError where e.errnoCode == ESPIPE {
// OK
} catch {
XCTFail("wrong error \(error) caught")
}
return [readFH, writeFH]
}
}
func testReadFromNonBlockingPipeFails() throws {
try withPipe { readFH, writeFH in
do {
try readFH.withUnsafeFileDescriptor { readFD in
let flags = try Posix.fcntl(descriptor: readFD, command: F_GETFL, value: 0)
let ret = try Posix.fcntl(descriptor: readFD, command: F_SETFL, value: flags | O_NONBLOCK)
assert(ret == 0, "unexpectedly, fcntl(\(readFD), F_SETFL, O_NONBLOCK) returned \(ret)")
}
try self.fileIO.readChunked(fileHandle: readFH,
byteCount: 10,
chunkSize: 10,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
XCTFail("this shouldn't have been called")
return self.eventLoop.makeSucceededFuture(())
}.wait()
XCTFail("succeeded and shouldn't have")
} catch let e as NonBlockingFileIO.Error where e == NonBlockingFileIO.Error.descriptorSetToNonBlocking {
// OK
} catch {
XCTFail("wrong error \(error) caught")
}
return [readFH, writeFH]
}
}
func testSeekPointerIsSetToFront() throws {
let content = "0123456789"
var numCalls = 0
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
try self.fileIO.readChunked(fileHandle: fileHandle,
byteCount: content.utf8.count,
chunkSize: 9,
allocator: self.allocator,
eventLoop: self.eventLoop) { buf in
var buf = buf
numCalls += 1
XCTAssertTrue(self.eventLoop.inEventLoop)
if numCalls == 1 {
XCTAssertEqual(9, buf.readableBytes)
XCTAssertEqual("012345678", buf.readString(length: buf.readableBytes) ?? "bad")
} else {
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual("9", buf.readString(length: buf.readableBytes) ?? "bad")
}
return self.eventLoop.makeSucceededFuture(())
}.wait()
}
XCTAssertEqual(2, numCalls)
}
func testWriting() throws {
var buffer = allocator.buffer(capacity: 3)
buffer.writeStaticString("123")
try withTemporaryFile(content: "") { (fileHandle, path) in
try self.fileIO.write(fileHandle: fileHandle,
buffer: buffer,
eventLoop: self.eventLoop).wait()
let offset = try fileHandle.withUnsafeFileDescriptor {
try Posix.lseek(descriptor: $0, offset: 0, whence: SEEK_SET)
}
XCTAssertEqual(offset, 0)
let readBuffer = try self.fileIO.read(fileHandle: fileHandle,
byteCount: 3,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(readBuffer.getString(at: 0, length: 3), "123")
}
}
func testWriteMultipleTimes() throws {
var buffer = allocator.buffer(capacity: 3)
buffer.writeStaticString("xxx")
try withTemporaryFile(content: "AAA") { (fileHandle, path) in
for i in 0 ..< 3 {
buffer.writeString("\(i)")
try self.fileIO.write(fileHandle: fileHandle,
buffer: buffer,
eventLoop: self.eventLoop).wait()
}
let offset = try fileHandle.withUnsafeFileDescriptor {
try Posix.lseek(descriptor: $0, offset: 0, whence: SEEK_SET)
}
XCTAssertEqual(offset, 0)
let expectedOutput = "xxx0xxx01xxx012"
let readBuffer = try self.fileIO.read(fileHandle: fileHandle,
byteCount: expectedOutput.utf8.count,
allocator: self.allocator,
eventLoop: self.eventLoop).wait()
XCTAssertEqual(expectedOutput, String(decoding: readBuffer.readableBytesView, as: Unicode.UTF8.self))
}
}
func testFileOpenWorks() throws {
let content = "123"
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let (fh, fr) = try self.fileIO.openFile(path: path, eventLoop: self.eventLoop).wait()
try fh.withUnsafeFileDescriptor { fd in
XCTAssertGreaterThanOrEqual(fd, 0)
}
XCTAssertTrue(fh.isOpen)
XCTAssertEqual(0, fr.readerIndex)
XCTAssertEqual(3, fr.endIndex)
try fh.close()
}
}
func testFileOpenWorksWithEmptyFile() throws {
let content = ""
try withTemporaryFile(content: content) { (fileHandle, path) -> Void in
let (fh, fr) = try self.fileIO.openFile(path: path, eventLoop: self.eventLoop).wait()
try fh.withUnsafeFileDescriptor { fd in
XCTAssertGreaterThanOrEqual(fd, 0)
}
XCTAssertTrue(fh.isOpen)
XCTAssertEqual(0, fr.readerIndex)
XCTAssertEqual(0, fr.endIndex)
try fh.close()
}
}
func testFileOpenFails() throws {
do {
_ = try self.fileIO.openFile(path: "/dev/null/this/does/not/exist", eventLoop: self.eventLoop).wait()
XCTFail("should've thrown")
} catch let e as IOError where e.errnoCode == ENOTDIR {
// OK
} catch {
XCTFail("wrong error: \(error)")
}
}
func testOpeningFilesForWriting() {
XCTAssertNoThrow(try withTemporaryDirectory { dir in
try self.fileIO!.openFile(path: "\(dir)/file",
mode: .write,
flags: .allowFileCreation(),
eventLoop: self.eventLoop).wait().close()
})
}
func testOpeningFilesForWritingFailsIfWeDontAllowItExplicitly() {
XCTAssertThrowsError(try withTemporaryDirectory { dir in
try self.fileIO!.openFile(path: "\(dir)/file",
mode: .write,
flags: .default,
eventLoop: self.eventLoop).wait().close()
}) { error in
XCTAssertEqual(ENOENT, (error as? IOError)?.errnoCode)
}
}
func testOpeningFilesForWritingDoesNotAllowReading() {
XCTAssertNoThrow(try withTemporaryDirectory { dir in
let fileHandle = try self.fileIO!.openFile(path: "\(dir)/file",
mode: .write,
flags: .allowFileCreation(),
eventLoop: self.eventLoop).wait()
defer {
try! fileHandle.close()
}
XCTAssertEqual(-1 /* read must fail */,
try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in
var data: UInt8 = 0
return withUnsafeMutableBytes(of: &data) { ptr in
read(fd, ptr.baseAddress, ptr.count)
}
})
})
}
func testOpeningFilesForWritingAndReading() {
XCTAssertNoThrow(try withTemporaryDirectory { dir in
let fileHandle = try self.fileIO!.openFile(path: "\(dir)/file",
mode: [.write, .read],
flags: .allowFileCreation(),
eventLoop: self.eventLoop).wait()
defer {
try! fileHandle.close()
}
XCTAssertEqual(0 /* read should read EOF */,
try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in
var data: UInt8 = 0
return withUnsafeMutableBytes(of: &data) { ptr in
read(fd, ptr.baseAddress, ptr.count)
}
})
})
}
func testOpeningFilesForWritingDoesNotImplyTruncation() {
XCTAssertNoThrow(try withTemporaryDirectory { dir in
// open 1 + write
try {
let fileHandle = try self.fileIO!.openFile(path: "\(dir)/file",
mode: [.write, .read],
flags: .allowFileCreation(),
eventLoop: self.eventLoop).wait()
defer {
try! fileHandle.close()
}
try fileHandle.withUnsafeFileDescriptor { fd in
var data = UInt8(ascii: "X")
XCTAssertEqual(IOResult<Int>.processed(1),
try withUnsafeBytes(of: &data) { ptr in
try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count)
})
}
}()
// open 2 + write again + read
try {
let fileHandle = try self.fileIO!.openFile(path: "\(dir)/file",
mode: [.write, .read],
flags: .default,
eventLoop: self.eventLoop).wait()
defer {
try! fileHandle.close()
}
try fileHandle.withUnsafeFileDescriptor { fd in
try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_END)
var data = UInt8(ascii: "Y")
XCTAssertEqual(IOResult<Int>.processed(1),
try withUnsafeBytes(of: &data) { ptr in
try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count)
})
}
XCTAssertEqual(2 /* both bytes */,
try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in
var data: UInt16 = 0
try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_SET)
let readReturn = withUnsafeMutableBytes(of: &data) { ptr in
read(fd, ptr.baseAddress, ptr.count)
}
XCTAssertEqual(UInt16(bigEndian: (UInt16(UInt8(ascii: "X")) << 8) | UInt16(UInt8(ascii: "Y"))),
data)
return readReturn
})
}()
})
}
func testOpeningFilesForWritingCanUseTruncation() {
XCTAssertNoThrow(try withTemporaryDirectory { dir in
// open 1 + write
try {
let fileHandle = try self.fileIO!.openFile(path: "\(dir)/file",
mode: [.write, .read],
flags: .allowFileCreation(),
eventLoop: self.eventLoop).wait()
defer {
try! fileHandle.close()
}
try fileHandle.withUnsafeFileDescriptor { fd in
var data = UInt8(ascii: "X")
XCTAssertEqual(IOResult<Int>.processed(1),
try withUnsafeBytes(of: &data) { ptr in
try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count)
})
}
}()
// open 2 (with truncation) + write again + read
try {
let fileHandle = try self.fileIO!.openFile(path: "\(dir)/file",
mode: [.write, .read],
flags: .posix(flags: O_TRUNC, mode: 0),
eventLoop: self.eventLoop).wait()
defer {
try! fileHandle.close()
}
try fileHandle.withUnsafeFileDescriptor { fd in
try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_END)
var data = UInt8(ascii: "Y")
XCTAssertEqual(IOResult<Int>.processed(1),
try withUnsafeBytes(of: &data) { ptr in
try Posix.write(descriptor: fd, pointer: ptr.baseAddress!, size: ptr.count)
})
}
XCTAssertEqual(1 /* read should read just one byte because we truncated the file */,
try fileHandle.withUnsafeFileDescriptor { fd -> ssize_t in
var data: UInt16 = 0
try Posix.lseek(descriptor: fd, offset: 0, whence: SEEK_SET)
let readReturn = withUnsafeMutableBytes(of: &data) { ptr in
read(fd, ptr.baseAddress, ptr.count)
}
XCTAssertEqual(UInt16(bigEndian: UInt16(UInt8(ascii: "Y")) << 8), data)
return readReturn
})
}()
})
}
func testReadFromOffset() {
XCTAssertNoThrow(try withTemporaryFile(content: "hello world") { (fileHandle, path) in
let buffer = self.fileIO.read(fileHandle: fileHandle,
fromOffset: 6,
byteCount: 5,
allocator: ByteBufferAllocator(),
eventLoop: self.eventLoop)
XCTAssertNoThrow(try XCTAssertEqual("world",
String(decoding: buffer.wait().readableBytesView,
as: Unicode.UTF8.self)))
})
}
func testReadChunkedFromOffset() {
XCTAssertNoThrow(try withTemporaryFile(content: "hello world") { (fileHandle, path) in
var numberOfCalls = 0
try self.fileIO.readChunked(fileHandle: fileHandle,
fromOffset: 6,
byteCount: 5,
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop) { buffer in
numberOfCalls += 1
switch numberOfCalls {
case 1:
XCTAssertEqual("wo", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
case 2:
XCTAssertEqual("rl", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
case 3:
XCTAssertEqual("d", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
default:
XCTFail()
}
return self.eventLoop.makeSucceededFuture(())
}.wait()
})
}
func testReadChunkedFromNegativeOffsetFails() {
XCTAssertThrowsError(try withTemporaryFile(content: "hello world") { (fileHandle, path) in
try self.fileIO.readChunked(fileHandle: fileHandle,
fromOffset: -1,
byteCount: 5,
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop) { _ in
XCTFail("shouldn't be called")
return self.eventLoop.makeSucceededFuture(())
}.wait()
}) { error in
XCTAssertEqual(EINVAL, (error as? IOError)?.errnoCode)
}
}
func testReadChunkedFromOffsetAfterEOFDeliversExactlyOneChunk() {
var numberOfCalls = 0
XCTAssertNoThrow(try withTemporaryFile(content: "hello world") { (fileHandle, path) in
try self.fileIO.readChunked(fileHandle: fileHandle,
fromOffset: 100,
byteCount: 5,
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop) { buffer in
numberOfCalls += 1
XCTAssertEqual(1, numberOfCalls)
XCTAssertEqual(0, buffer.readableBytes)
return self.eventLoop.makeSucceededFuture(())
}.wait()
})
}
func testReadChunkedFromEOFDeliversExactlyOneChunk() {
var numberOfCalls = 0
XCTAssertNoThrow(try withTemporaryFile(content: "") { (fileHandle, path) in
try self.fileIO.readChunked(fileHandle: fileHandle,
byteCount: 5,
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop) { buffer in
numberOfCalls += 1
XCTAssertEqual(1, numberOfCalls)
XCTAssertEqual(0, buffer.readableBytes)
return self.eventLoop.makeSucceededFuture(())
}.wait()
})
}
func testReadFromOffsetAfterEOFDeliversExactlyOneChunk() {
XCTAssertNoThrow(try withTemporaryFile(content: "hello world") { (fileHandle, path) in
XCTAssertEqual(0,
try self.fileIO.read(fileHandle: fileHandle,
fromOffset: 100,
byteCount: 5,
allocator: .init(),
eventLoop: self.eventLoop).wait().readableBytes)
})
}
func testReadFromEOFDeliversExactlyOneChunk() {
XCTAssertNoThrow(try withTemporaryFile(content: "") { (fileHandle, path) in
XCTAssertEqual(0,
try self.fileIO.read(fileHandle: fileHandle,
byteCount: 5,
allocator: .init(),
eventLoop: self.eventLoop).wait().readableBytes)
})
}
func testReadChunkedFromOffsetFileRegion() {
XCTAssertNoThrow(try withTemporaryFile(content: "hello world") { (fileHandle, path) in
var numberOfCalls = 0
let fileRegion = FileRegion(fileHandle: fileHandle, readerIndex: 6, endIndex: 11)
try self.fileIO.readChunked(fileRegion: fileRegion,
chunkSize: 2,
allocator: .init(),
eventLoop: self.eventLoop) { buffer in
numberOfCalls += 1
switch numberOfCalls {
case 1:
XCTAssertEqual("wo", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
case 2:
XCTAssertEqual("rl", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
case 3:
XCTAssertEqual("d", String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self))
default:
XCTFail()
}
return self.eventLoop.makeSucceededFuture(())
}.wait()
})
}
}
| 46.677885 | 131 | 0.476182 |
f7a084bedaa2af49f3f0f7fa5e4dc0f0912a1607 | 754 | import XCTest
import MSRichLinkPreview
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.
}
}
}
| 26 | 111 | 0.604775 |
76d3f94442ffb645b9db17228be422eb7acef145 | 1,225 | //
// Validator+Strings.swift
// Quiver
//
// Created by Heitor Costa on 20/10/17.
// Copyright © 2017 Heitor Costa. All rights reserved.
//
import Foundation
// Strings
public extension Validator {
// Strings
static func length(min: Int = 0, max: Int = Int.max, message: String? = nil) -> Validator {
return LengthValidator(min: min, max: max).with(message: message)
}
static func regex(pattern: String, message: String? = nil) -> Validator {
return RegexValidator(pattern: pattern).with(message: message)
}
static func email(message: String? = nil) -> Validator {
return RegexValidator(pattern: "^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$").with(message: message)
}
static func alphabetic(message: String? = nil) -> Validator {
return RegexValidator(pattern: "^[A-Za-z]+$").with(message: message)
}
static func numeric(message: String? = nil) -> Validator {
return RegexValidator(pattern: "^[0-9]+$").with(message: message)
}
static func alphaNumeric(message: String? = nil) -> Validator {
return RegexValidator(pattern: "^[a-zA-Z0-9]+$").with(message: message)
}
}
| 32.236842 | 133 | 0.614694 |
d9d71b4d132e9e24f26fd4f9e2cc7b52ed9e19f9 | 1,264 | //
// ViewDecider.swift
// tander
//
// Created by Jirayut Patthaveesrisutha on 13/2/2563 BE.
// Copyright © 2563 Jirayut Patthaveesrisutha. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@EnvironmentObject var store: ProfileStore
var body: some View {
VStack{
getview().alert(isPresented: $store.showAlert) {
Alert(title: Text(store.errMsg!), dismissButton: Alert.Button.default(Text("Retry"),action: {self.store.profileSignInStatus = .Loading}))
}
} .alert(isPresented: self.$store.showWelcome) {
Alert(title: Text("Successful Registered"), message: Text(self.store.welMsg!), dismissButton: Alert.Button.default(Text("OK")))
}
}
private func getview() -> AnyView {
switch self.store.profileSignInStatus {
case .Loading:
return AnyView(Text("Loading"))
case .SignedIn:
return AnyView(RootView().environmentObject(self.store))
case .NotSignedIn:
return AnyView(SignInSignUpView().environmentObject(self.store))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 28.727273 | 153 | 0.623418 |
cc33421da9f528b68c88092e773995ce1b8ad58f | 2,833 | import Foundation
/// https://wamp-proto.org/_static/gen/wamp_latest.html#ids
public class RandomNumericID {
public enum OverflowStrategy {
case stop
case resetList
}
private var list: [Int]
private let range: ClosedRange<Int>
private let overflowStrategy: OverflowStrategy
private let lock = NSRecursiveLock()
public init(range: ClosedRange<Int>, overflowStrategy: OverflowStrategy = .resetList) {
self.range = range
self.overflowStrategy = overflowStrategy
self.list = []
}
}
extension RandomNumericID: IteratorProtocol {
public typealias Element = WampID
public func next() -> WampID? {
lock.lock()
defer { lock.unlock() }
if list.count >= (range.upperBound - range.lowerBound) {
switch overflowStrategy {
case .stop:
return nil
case .resetList:
list = []
}
}
while true {
let value = Int.random(in: range)
// TODO: Hipothetically slow after billions of IDs generated, it could be improved
// When odds to raffle an available number are tiny, this can be really slow
// Better algorithms are possibly available
if list.contains(value) { continue }
list.append(value)
return .init(integerLiteral: value)
}
}
}
/// https://wamp-proto.org/_static/gen/wamp_latest.html#ids
public class AutoIncrementID {
public enum OverflowStrategy {
case stop
case resetToZero
case resetToMin
case resetToSmallestNegative
}
private var current: Int
private let min: Int
private let max: Int
private let overflowStrategy: OverflowStrategy
private let lock = NSRecursiveLock()
public init(range: ClosedRange<Int>, overflowStrategy: OverflowStrategy = .resetToMin) {
self.min = range.lowerBound
self.max = range.upperBound
self.current = min
self.overflowStrategy = overflowStrategy
}
}
extension AutoIncrementID: IteratorProtocol {
public typealias Element = WampID
public func next() -> WampID? {
lock.lock()
defer { lock.unlock() }
current += 1
guard current <= max else {
switch overflowStrategy {
case .stop:
return nil
case .resetToMin:
current = min
return .init(integerLiteral: current)
case .resetToZero:
current = 0
return .init(integerLiteral: current)
case .resetToSmallestNegative:
current = Int.min
return .init(integerLiteral: current)
}
}
return .init(integerLiteral: current)
}
}
| 28.049505 | 94 | 0.596188 |
ed0636f7d7e0293bfe0d85ef342d791f0b777e16 | 576 | //
// EsoftAppState.swift
// RxExtensions
//
// Copyright © 2020 E-SOFT, OOO. All rights reserved.
//
import Foundation
import UIKit
public struct EsoftAppState {
public static var currentAppVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
}
extension EsoftAppState {
internal static func clearSharedObservables() {
objc_setAssociatedObject(UIApplication.shared,
&sharedRxAppStateKey,
nil,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
| 25.043478 | 121 | 0.663194 |
d91d169d2a2df407b1f42bb4538c53b67fae7097 | 7,061 | //
import Cocoa
import SWXMLHash
class DropView: NSView {
let pasteboardType = NSPasteboard.PasteboardType(rawValue: "public.utf8-plain-text")
let dragMutex = Mutex.init()
let folderMutex = Mutex.init()
var folder: URL?
@IBOutlet weak var lastActionText: NSTextField!
@IBOutlet weak var copyProgressIndicator: NSProgressIndicator!
@IBOutlet weak var dragHereLabel: NSTextField!
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
registerForDraggedTypes([pasteboardType])
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
if !dragMutex.tryLock() {
return NSDragOperation()
}
defer { dragMutex.unlock() }
return .copy
}
override func draggingEnded(_ sender: NSDraggingInfo) {
}
override func draggingExited(_ sender: NSDraggingInfo?) {
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
// Make sure we aren't already processing dragged data
if !dragMutex.tryLock() {
return false
}
guard let data = sender.draggingPasteboard().data(forType: pasteboardType) else {
return false
}
askUserForCopyLocation()
// Process the XML while the user is selecting a location
DispatchQueue.global().async {
var srcPaths: [URL] = []
var err: ParsingError? = nil
let parser = SWXMLHash.config { config in
config.detectParsingErrors = true
}.parse(data)
switch parser {
case .parsingError(let error):
err = error
default:
err = nil
}
if let error = err {
DispatchQueue.main.async {
buildAlert(
"""
A parsing error ocurred at line \(error.line) column \(error.column);
no files will be copied
"""
).runModal()
}
}
for elem in parser["fcpxml"]["resources"]["asset"].all {
srcPaths.append(URL.init(string: elem.element!.attribute(by: "src")!.text)!)
}
// Now that we have what we needed from the XML, lock `folder` and do copying
// if `folder` has been set to something
self.folderMutex.lock()
defer {
self.folderMutex.unlock()
self.dragMutex.unlock()
}
if let folder = self.folder {
DispatchQueue.main.async {
self.dragHereLabel.isHidden = true
self.copyProgressIndicator.isHidden = false
}
let (copied, errors) = self.copyFilesToFolder(srcPaths, folder: folder, progressCallback: { percent in
DispatchQueue.main.async {
self.copyProgressIndicator.doubleValue = percent
}
})
DispatchQueue.main.async {
self.copyProgressIndicator.isHidden = true
self.copyProgressIndicator.doubleValue = 0
self.dragHereLabel.isHidden = false
if !errors.isEmpty {
DispatchQueue.main.async {
buildAlert("\(errors.map({ $0.localizedDescription }))").runModal()
}
}
}
let attempted = srcPaths.count
let folderString = folder.absoluteString.removingPercentEncoding!
DispatchQueue.main.async {
self.lastActionText.stringValue = "Copied \(copied)/\(attempted) files to \(folderString)"
}
self.folder = nil
}
}
return true
}
/// Determines where the user wants to copy the assets; does not block.
///
/// The first thing this method does is lock `folderMutex`. It then creates and displays an
/// `NSOpenPanel`, setting `folder` to the chosen folder if OK was clicked and unlocking the
/// mutex regardless.
func askUserForCopyLocation() {
folderMutex.lock()
let openPanel = NSOpenPanel.init()
openPanel.canCreateDirectories = true
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = true
openPanel.canChooseFiles = false
openPanel.begin(completionHandler: { response in
if response == NSApplication.ModalResponse.OK {
self.folder = openPanel.url!
}
self.folderMutex.unlock()
})
}
/// Copies `files` to `folder`, calling `progressCallback` after each file copied.
///
/// File names are not changed in the copying process. If the names of any files to be copied
/// conflict with the names of files already in `folder`, those files will fail to copy.
///
/// Any errors will be accumulated and returned after an attempt has been made to copy all
/// files. The successfully copied files count is also returned.
func copyFilesToFolder(_ files: [URL], folder: URL, progressCallback: (Double) -> Void) -> (Int, [Error]) {
var errors: [Error] = []
var copied = files.count;
var currentPercent = Double(0)
let percentPerFile = Double(100) / Double(files.count)
for url in files {
do {
try FileManager.default.copyItem(
at: url,
to: folder.appendingPathComponent(url.lastPathComponent)
)
} catch let error {
copied -= 1
errors.append(error)
}
currentPercent += percentPerFile
// This is, unfortunately, the finest granularity that we can provide the callback.
// The `FileManager` API does not provide any hooks for progress updates and
// dropping down to a lower-level API would introduce unnecessary complication to
// this little utility.
progressCallback(currentPercent)
}
return (copied, errors)
}
}
/// A simple helper that configures an `NSAlert` instance with a single "OK" button and the
/// provided text.
func buildAlert(_ text: String) -> NSAlert {
let alert = NSAlert()
alert.messageText = text
alert.alertStyle = .warning
alert.addButton(withTitle: "OK")
return alert
}
| 34.783251 | 118 | 0.541425 |
f8e3b0675c64d70236a176b83d90fae7c4581c07 | 1,220 | //
// LoginView.swift
// zap-challenge-viper
//
// Created by Renato Medina on 05/04/19.
// Copyright © 2019 Renato Medina. All rights reserved.
//
import UIKit
class LoginView: UIView, KeyboardControllable {
@IBOutlet private weak var enterButton: UIButton!
@IBOutlet private weak var emailTextField: UITextField!
@IBOutlet private weak var passwordTextField: UITextField!
var validate: ((String?, String?)->Void)?
@IBAction func tapButtonEnter() {
self.validate?(emailTextField.text, passwordTextField.text)
}
func handleKeyboardWillShow(_ notification: Notification) {
let keyboardSize = notification.keyboardSize
let keyboardHeight = keyboardSize?.height ?? 250
if self.frame.origin.y == 0 {
self.frame.origin.y -= keyboardHeight
}
}
func handleKeyboardWillHide(_ notification: Notification) {
if self.frame.origin.y != 0 {
self.frame.origin.y = 0
}
}
}
extension LoginView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| 25.957447 | 67 | 0.643443 |
4ab9b7609ec9d6ef94fd9ebe95aa3c78065e93dc | 895 | //
// tipCalcTests.swift
// tipCalcTests
//
// Created by Axel Siliezar on 11/30/20.
//
import XCTest
@testable import tipCalc
class tipCalcTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.323529 | 111 | 0.66257 |
5d5ca3eba82d7b60e801fe0e3ee670f159530c4d | 609 | import UIKit
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addBottomSheetView()
}
func addBottomSheetView() {
let bottomSheetVC = BottomSheetViewController()
self.addChild(bottomSheetVC)
self.view.addSubview(bottomSheetVC.view)
bottomSheetVC.didMove(toParent: self)
let height = view.frame.height
let width = view.frame.width
bottomSheetVC.view.frame = CGRect(x: 0, y: view.frame.maxY, width: width, height: height)
}
}
| 25.375 | 97 | 0.648604 |
e2c25e0ce03204e98973ecaebbbd5a5b0ffd1e3d | 1,580 | //
// CGPDFDocument.swift
// Pods
//
// Created by Chris Anderson on 3/5/16.
//
//
import Foundation
public enum CGPDFDocumentError: Error {
case fileDoesNotExist
case passwordRequired
case couldNotUnlock
case unableToOpen
}
extension CGPDFDocument {
public static func create(url: URL, password: String?) throws -> CGPDFDocument {
guard let docRef = CGPDFDocument((url as CFURL)) else {
throw CGPDFDocumentError.fileDoesNotExist
}
if docRef.isEncrypted {
try CGPDFDocument.unlock(docRef: docRef, password: password)
}
return docRef
}
public static func create(data: NSData, password: String?) throws -> CGPDFDocument {
guard let dataProvider = CGDataProvider(data: data),
let docRef = CGPDFDocument(dataProvider) else {
throw CGPDFDocumentError.fileDoesNotExist
}
if docRef.isEncrypted {
try CGPDFDocument.unlock(docRef: docRef, password: password)
}
return docRef
}
public static func unlock(docRef: CGPDFDocument, password: String?) throws {
if docRef.unlockWithPassword("") == false {
guard let password = password else {
throw CGPDFDocumentError.passwordRequired
}
docRef.unlockWithPassword((password as NSString).utf8String!)
}
if docRef.isUnlocked == false {
throw CGPDFDocumentError.couldNotUnlock
}
}
}
| 26.333333 | 88 | 0.603165 |
0e605f69c504b20808d940fafb1dc613d2d74c53 | 1,346 | // Copyright 2016 Cisco Systems Inc
//
// 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
/// Service request results.
public enum Result<T> {
/// Result for Success, with the expected object.
case success(T)
/// Result for Failure, with the error message.
case failure(Error)
}
| 42.0625 | 80 | 0.748886 |
915f7e144cf1179f420c015b5b01b2f51da1a7ff | 1,148 | //
// UILabel+Default.swift
// MSToolKit
//
// Created by Manthan Shah on 2019-06-26.
// Copyright © 2019 Manthan Shah. All rights reserved.
//
import Foundation
/// This extension makes it easy to initialize an `UILabel`.
public extension UILabel {
/// This function initializes an `UILabel` with multiple common properties.
///
/// - Parameter text: the primary text for the label.
/// - Parameter textAlignment: the alignment of the label, which by default is `NSTextAlignment.left`.
/// - Parameter textColor: the desired `UIColor` property for the label text, which by default is `UIColor.black`.
/// - Parameter font: the font property for the text, which is system font of size 17 by default.
public convenience init(text: String,
textAlignment: NSTextAlignment = .left,
textColor: UIColor = .black,
font: UIFont = UIFont.systemFont(ofSize: 17)) {
self.init()
self.text = text
self.textAlignment = textAlignment
self.textColor = textColor
self.font = font
}
}
| 34.787879 | 118 | 0.626307 |
76c5bd4932fa9ccb6edf173215aa4bcc9ba58629 | 4,160 | //
// ACMessage.swift
// ACActionCable
//
// Created by Julian Tigler on 9/12/20.
//
import Foundation
public typealias ACMessageHandler = (ACMessage) -> Void
public struct ACMessage: Decodable {
// MARK: Properties
public static var decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}()
public var type: ACMessageType?
public var body: ACMessageBody?
public var identifier: ACChannelIdentifier?
public var disconnectReason: ACDisconnectReason?
public var reconnect: Bool?
enum CodingKeys: String, CodingKey {
case type
case identifier
case body = "message"
case disconnectReason = "reason"
case reconnect
}
// MARK: Initialization
init?(string: String) {
guard let data = string.data(using: .utf8), let message = try? Self.decoder.decode(ACMessage.self, from: data) else { return nil }
self = message
}
}
// MARK: ACMessageType
public enum ACMessageType: String, Decodable {
case confirmSubscription = "confirm_subscription"
case rejectSubscription = "reject_subscription"
case welcome
case disconnect
case ping
case message
}
// MARK: ACMessageBody
public enum ACMessageBody: Decodable {
case ping(Int)
case custom(ACMessageBodyObject)
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(Int.self) {
self = .ping(value)
} else if let value = try? container.decode(ACMessageBodyObject.self) {
self = .custom(value)
} else {
throw DecodingError.typeMismatch(ACMessageBody.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "Unable to parse message body"))
}
}
}
// MARK: ACMessageBodyObject
public struct ACMessageBodyObject: Decodable {
public let object: Any?
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DynamicKey.self)
guard container.allKeys.count == 1, let firstKey = container.allKeys.first else {
throw DecodingError.typeMismatch(ACMessageBodyObject.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "Expected message container to only have one top-level key"))
}
let key = firstKey.stringValue
guard let decoder = Self.decoders[key] else {
throw DecodingError.typeMismatch(ACMessageBodyObject.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "No message decoder registered for key: \(key)"))
}
object = try? decoder(container)
}
private typealias BodyDecoder = (KeyedDecodingContainer<DynamicKey>) throws -> Any
private static var decoders: [String: BodyDecoder] = [:]
public static func register<A: Decodable>(_ type: A.Type) {
let pascalCaseTypeName = String(describing: type)
let camelCaseTypeName = pascalCaseTypeName.prefix(1).lowercased() + pascalCaseTypeName.dropFirst()
decoders[camelCaseTypeName] = { container in
try container.decode(A.self, forKey: DynamicKey(stringValue: camelCaseTypeName)!)
}
}
public static func register<A: Decodable>(_ type: A.Type, forKey key: String) {
decoders[key] = { container in
try container.decode(A.self, forKey: DynamicKey(stringValue: key)!)
}
}
}
// MARK: DynamicKey
struct DynamicKey: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) {
self.intValue = intValue
self.stringValue = intValue.description
}
init?(stringValue: String) {
self.stringValue = stringValue
}
}
// MARK: ACDisconnectReason
public enum ACDisconnectReason: String, Decodable {
case unauthorized
case invalidRequest = "invalid_request"
case serverRestart = "server_restart"
}
| 31.044776 | 206 | 0.673317 |
defe0e0ccedce64387827398be5515232b4ce14e | 7,767 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Distributed Actors open source project
//
// Copyright (c) 2018-2020 Apple Inc. and the Swift Distributed Actors project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of Swift Distributed Actors project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import struct Foundation.Data
import NIO
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Actor Message
/// An Actor message is simply a Codable type.
///
/// Any Codable it able to be sent as an actor message.
///
/// You can customize which coder/decoder should be used by registering specialized manifests for the message type,
/// or having the type conform to one of the special `...Representable` (e.g. `_ProtobufRepresentable`) protocols.
public typealias ActorMessage = Codable // FIXME: MAKE THIS SENDABLE: & Sendable
/// A `Never` can never be sent as message, even more so over the wire.
extension Never: NonTransportableActorMessage {}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Common utility messages
// FIXME: we should not add Codable conformance onto a stdlib type, but rather fix this in stdlib
extension Result: ActorMessage where Success: ActorMessage, Failure: ActorMessage {
public enum DiscriminatorKeys: String, Codable {
case success
case failure
}
public enum CodingKeys: CodingKey {
case _case
case success_value
case failure_value
}
public init(from decoder: Swift.Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
switch try container.decode(DiscriminatorKeys.self, forKey: ._case) {
case .success:
self = .success(try container.decode(Success.self, forKey: .success_value))
case .failure:
self = .failure(try container.decode(Failure.self, forKey: .failure_value))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .success(let success):
try container.encode(DiscriminatorKeys.success, forKey: ._case)
try container.encode(success, forKey: .success_value)
case .failure(let failure):
try container.encode(DiscriminatorKeys.failure, forKey: ._case)
try container.encode(failure, forKey: .failure_value)
}
}
}
/// Generic transportable Error type, can be used to wrap error types and represent them as best as possible for transporting.
public struct ErrorEnvelope: Error, ActorMessage {
public typealias CodableError = Error & Codable
private let codableError: CodableError
public var error: Error {
self.codableError
}
enum CodingKeys: CodingKey {
case manifest
case error
}
public init(_ error: Error) {
if let alreadyAnEnvelope = error as? Self {
self = alreadyAnEnvelope
} else if let codableError = error as? CodableError {
self.codableError = codableError
} else {
// we can at least carry the error type (not the whole string repr, since it may have information we'd rather not share though)
self.codableError = BestEffortStringError(representation: String(reflecting: type(of: error as Any)))
}
}
// this is a cop out if we want to send back a message or just type name etc
public init(description: String) {
self.codableError = BestEffortStringError(representation: description)
}
public init(from decoder: Decoder) throws {
guard let context = decoder.actorSerializationContext else {
throw SerializationError.missingSerializationContext(decoder, ErrorEnvelope.self)
}
let container = try decoder.container(keyedBy: CodingKeys.self)
let manifest = try container.decode(Serialization.Manifest.self, forKey: .manifest)
let errorType = try context.summonType(from: manifest)
guard let codableErrorType = errorType as? CodableError.Type else {
throw SerializationError.unableToDeserialize(hint: "Error type \(errorType) is not Codable")
}
let errorDecoder = try container.superDecoder(forKey: .error)
self.codableError = try codableErrorType.init(from: errorDecoder)
}
public func encode(to encoder: Encoder) throws {
guard let context: Serialization.Context = encoder.actorSerializationContext else {
throw SerializationError.missingSerializationContext(encoder, ErrorEnvelope.self)
}
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(context.serialization.outboundManifest(type(of: self.codableError as Any)), forKey: .manifest)
let errorEncoder = container.superEncoder(forKey: .error)
try self.codableError.encode(to: errorEncoder)
}
}
public struct BestEffortStringError: Error, Codable, Equatable, CustomStringConvertible {
let representation: String
public var description: String {
"BestEffortStringError(\(representation))"
}
}
/// Useful error wrapper which performs an best effort Error serialization as configured by the actor system.
public struct NonTransportableAnyError: Error, NonTransportableActorMessage {
public let failure: Error
public init<Failure: Error>(_ failure: Failure) {
self.failure = failure
}
}
// ==== ----------------------------------------------------------------------------------------------------------------
// MARK: Not Transportable Actor Message (i.e. "local only")
/// Marks a type as `ActorMessage` however
/// Attempting to send such message to a remote actor WILL FAIL and log an error.
///
/// Use this with great caution and only for messages which are specifically designed to utilize the local assumption.
///
/// DO NOT default to using this kind of messages in your system, as it makes the "move" from local to distributed harder,
/// as eventually you realize you have to move messages to Codable or Protobuf backends. To avoid this surprise, always
/// default to actually serializable messages, and only use this type as an "opt out" for specific messages which require it.
///
/// No serializer is expected to be registered for such types.
///
/// - Warning: Attempting to send such message over the network will fail at runtime (and log an error or warning).
public protocol NonTransportableActorMessage: ActorMessage {}
public extension NonTransportableActorMessage {
init(from decoder: Swift.Decoder) throws {
fatalError("Attempted to decode NonTransportableActorMessage message: \(Self.self)! This should never happen.")
}
func encode(to encoder: Swift.Encoder) throws {
fatalError("Attempted to encode NonTransportableActorMessage message: \(Self.self)! This should never happen.")
}
init(context: Serialization.Context, from buffer: inout ByteBuffer, using manifest: Serialization.Manifest) throws {
fatalError("Attempted to deserialize NonTransportableActorMessage message: \(Self.self)! This should never happen.")
}
func serialize(context: Serialization.Context, to bytes: inout ByteBuffer) throws {
fatalError("Attempted to serialize NonTransportableActorMessage message: \(Self.self)! This should never happen.")
}
}
| 42.211957 | 139 | 0.664864 |
8a3f9bfa8fb4b54944f4933146ec08c3837e73f2 | 412 | //
// CustomCorner.swift
// Kids
//
// Created by Balaji on 28/09/20.
//
import SwiftUI
struct CustomCorner : Shape {
var corner : UIRectCorner
var size : CGFloat
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corner, cornerRadii: CGSize(width: size, height: size))
return Path(path.cgPath)
}
}
| 18.727273 | 125 | 0.61165 |
1acf02bcc8cca0fea86199729e2024f986036299 | 2,107 | //
// ColorHexing.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
//
import CoreGraphics
public protocol ColorHexing: class {
init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
init(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat)
#if os(iOS)
@discardableResult
func getRed(_ red: UnsafeMutablePointer<CGFloat>?, green: UnsafeMutablePointer<CGFloat>?, blue: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?) -> Bool
@discardableResult
func getHue(_ hue: UnsafeMutablePointer<CGFloat>?, saturation: UnsafeMutablePointer<CGFloat>?, brightness: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?) -> Bool
#elseif os(macOS)
func getRed(_ red: UnsafeMutablePointer<CGFloat>?, green: UnsafeMutablePointer<CGFloat>?, blue: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?)
func getHue(_ hue: UnsafeMutablePointer<CGFloat>?, saturation: UnsafeMutablePointer<CGFloat>?, brightness: UnsafeMutablePointer<CGFloat>?, alpha: UnsafeMutablePointer<CGFloat>?)
#endif
}
public extension ColorHexing {
var hexUInt: UInt {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return UInt(r * 255) << 16 | UInt(g * 255) << 8 | UInt(b * 255) << 0
}
init(hexUInt value: UInt, alpha: CGFloat = 1) {
let r = CGFloat((value & 0xFF0000) >> 16) / 255
let g = CGFloat((value & 0x00FF00) >> 8) / 255
let b = CGFloat((value & 0x0000FF) >> 0) / 255
self.init(red: r, green: g, blue: b, alpha: alpha)
}
}
public extension ColorHexing {
var hexString: String {
return String(format: "#%06X", hexUInt)
}
init?(hexString value: String) {
guard let hex = value.hexUInt else { return nil }
self.init(hexUInt: hex, alpha: 1)
}
}
#if os(iOS)
import UIKit
extension UIColor: ColorHexing {}
#elseif os(macOS)
import AppKit
extension NSColor: ColorHexing {}
#endif
| 31.447761 | 189 | 0.669673 |
dd65b4f794cffde6b97075a5073aaf0ea2083809 | 9,223 | // Copyright © 2021 Erica Sadun. All rights reserved.
import Foundation
import GeneralUtility
import MacUtility
struct Boilerplate {
static func year() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "Y"
return formatter.string(from: Date())
}
static func username() throws -> String {
try Utility.execute("/usr/bin/git config user.name")
}
static func dumpREADME(name: String, style: ProjectStyle, sap: Bool, gen: Bool, mac: Bool) throws {
var boilerplate = "# \(name)\n\n"
boilerplate += (style == .exe) ? "An executable project.\n" : "A library project.\n"
boilerplate += """
## Overview
An overview of this project.
## Known Issues
None.
"""
if (sap || gen || mac) {
boilerplate += "## Dependencies\n\n"
if sap {
boilerplate += "* [Swift Argument Parser](https://github.com/apple/swift-argument-parser)\n"
}
if gen || mac {
boilerplate += "* [Swift General Utility](https://github.com/erica/Swift-General-Utility)\n"
}
if mac {
boilerplate += "* [Swift Mac Utility](https://github.com/erica/Swift-Mac-Utility)\n"
}
boilerplate += "\n"
}
if style == .exe {
boilerplate += """
## Installation
* Install [homebrew](https://brew.sh).
* Install [mint](https://github.com/yonaskolb/Mint) with homebrew (`brew install mint`).
* From command line: `mint install erica/\(name)`
Note: This project uses a `master` branch to support `mint` installation.
"""
}
boilerplate += """
## Thanks and Acknowledgements
Thanks to everyone who pitched in and helped with this.
"""
let url = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
.appendingPathComponent("README.md")
try boilerplate.write(to: url, atomically: true, encoding: .utf8)
}
static func dumpCHANGELOG() throws {
let boilerplate = """
# CHANGELOG
## 0.0.1
Initial Commit
"""
let url = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
.appendingPathComponent("CHANGELOG.md")
try boilerplate.write(to: url, atomically: true, encoding: .utf8)
}
static func dumpLICENSE() throws {
let uname = try username()
let boilerplate = """
MIT License
Copyright (c) \(year()) \(uname)
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.
"""
let url = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
.appendingPathComponent("LICENSE.txt")
try boilerplate.write(to: url, atomically: true, encoding: .utf8)
}
static func buildMain(name: String, url: URL, sap: Bool) throws {
let uname = try username()
var boilerplate = """
/// Copyright (c) \(year()) \(uname). All Rights Reserved.
import Foundation\n
"""
switch sap {
case false:
boilerplate += #"\#nprint("Hello world!")\#n\#n"#
case true:
boilerplate += """
import ArgumentParser
struct \(name.capitalized): ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Execute the \(name) command",
shouldDisplay: true)
@Argument(help: "A name") var name = "World"
func run() throws {
print("Hello, \\(name)!")
}
}
\(name.capitalized).main()
"""
}
try boilerplate.write(to: url, atomically: true, encoding: .utf8)
}
static func buildPackage(name: String, url: URL, exe: Bool, sap: Bool, gen: Bool, mac: Bool) throws {
var boilerplate = """
// swift-tools-version:5.3
"""
// Add SAP note to the Project.swift file only when appropriate
if exe && sap {
boilerplate += """
// Version 5.3 required for Swift Argument Parser. Supports Catalina+
"""
}
boilerplate += """
import PackageDescription
let package = Package(
// This package name is normally synonymous with a hosted git repo and typically
// uses lower or upper kebab casing.
name: "\(name)",
// The oldest platform capable of supporting this code.
platforms: [.macOS(.v10_12)],
// The executables and/or libraries produced by this project
products: [
"""
if exe {
boilerplate += """
// The name of the executable produced by this project.
.executable(name: "\(name)",
// These are modules listed in the targets section.
targets: ["\(name)"]),
],
"""
} else {
boilerplate += """
// The linkable name of the library that is produced.
.library(name: "\(name)",
// A library includes one or more module targets, which are the modules
// you import into your Swift code when using this library.
// The module names are listed in the targets section.
targets: ["\(name)"]),
],
"""
}
boilerplate += """
dependencies: [
"""
if exe && sap {
// This is exact because of the changes in SAP
boilerplate += """
.package(url: "https://github.com/apple/swift-argument-parser", .exact("0.4.3")),
"""
}
if exe && (mac || gen) {
// General and Mac are fairly stable. It is safe to use "from"
boilerplate += """
.package(url: "https://github.com/erica/Swift-General-Utility", from: "0.0.6"),
"""
}
if exe && mac {
boilerplate += """
.package(url: "https://github.com/erica/Swift-Mac-Utility", from:"0.0.2"),
"""
}
boilerplate += """
],
// Create module targets
targets: [
.target(
// This is the module name. It is used by the product section targets
// and by test target dependencies. SPM now requires both module and package names.
name: "\(name)",
dependencies: [
"""
if exe && sap {
boilerplate += #" .product(name: "ArgumentParser", package: "swift-argument-parser"), \#n"#
}
if exe && (gen || mac) {
boilerplate += #" .product(name: "GeneralUtility", package: "Swift-General-Utility"), \#n"#
}
if exe && mac {
boilerplate += #" .product(name: "MacUtility", package: "Swift-Mac-Utility"), \#n"#
}
boilerplate += """
],
path: "Sources/" // Omit or override if needed. Overrides help .xcodeproj integration.
),
// Test target omitted here. FIXME!
//.testTarget(name: "\(name)Tests", dependencies: ["\(name)"]),
],
swiftLanguageVersions: [ .v5 ]
)
"""
try boilerplate.write(to: url, atomically: true, encoding: .utf8)
}
}
| 32.590106 | 118 | 0.51068 |
08da462f8f8b8d11eba8a368c678308e46ee9344 | 2,097 | //
// PlaySoundsViewController.swift
// PitchPerfect
//
// Created by Jess Le on 11/30/19.
// Copyright © 2019 lovelejess. All rights reserved.
//
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var recordedAudioURL: URL!
var audioFile:AVAudioFile!
var audioEngine:AVAudioEngine!
var audioPlayerNode: AVAudioPlayerNode!
var stopTimer: Timer!
@IBOutlet weak var slowButton: UIButton!
@IBOutlet weak var fastButton: UIButton!
@IBOutlet weak var lowPitchButton: UIButton!
@IBOutlet weak var highPitchButton: UIButton!
@IBOutlet weak var echoButton: UIButton!
@IBOutlet weak var reverbButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
enum ButtonType: Int {
case slow = 0, fast, chipmunk, vader, echo, reverb
}
override func viewDidLoad() {
super.viewDidLoad()
setupAudio()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
configureUI(.notPlaying)
}
// MARK: Actions
@IBAction func playSoundForButton(_ sender: UIButton) {
switch(ButtonType(rawValue: sender.tag)!) {
case .slow:
playSound(rate: 0.5)
case .fast:
playSound(rate: 1.5)
case .chipmunk:
playSound(pitch: 1000)
case .vader:
playSound(pitch: -1000)
case .echo:
playSound(echo: true)
case .reverb:
playSound(reverb: true)
}
configureUI(.playing)
}
@IBAction func stopButtonPressed(_ sender: AnyObject) {
stopAudio()
}
/*
// 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.
}
*/
}
| 26.544304 | 106 | 0.619933 |
1161fdc2cbf5a671fe6577298090980ae12cfbda | 2,052 | //
// Extensions.swift
// RandomNumberGenerator
//
// Created by Serega on 10.12.2021.
//
import Foundation
extension UserDefaults {
func isKeyPresentInUserDefaults(key: String) -> Bool {
return self.object(forKey: key) != nil
}
}
extension NumberFormatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = " "
return formatter
}()
}
extension Double {
var formattedWithSeparator: String {
let components = String(self).components(separatedBy: ".")
let integers = NumberFormatter.withSeparator.string(for: Int(components[0])!)
let floats = components[1]
return "\(integers!)\(floats == "0" ? "" : ",\(floats)")"
}
}
extension Double {
public func clamped(min: Double, max: Double) -> Double {
if self < min {
return min
} else if self > max {
return max
}
return self
}
public var decimalPlaces: Int {
let strDouble = String(self)
let decimals = strDouble.contains(".") ? strDouble.split(separator: ".")[1] : "0"
return decimals == "0" ? 0 : decimals.count
}
public func rounded(toPlaces places:Int) -> Double {
let str = String(format: "%.\(places)f", self)
return Double(str)!
}
public var stringWithoutZeroFraction: String {
let str = truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
return str == "-0" ? "0" : str
}
}
extension String {
public func count(of needle: Character) -> Int {
return reduce(0) {
$1 == needle ? $0 + 1 : $0
}
}
public func lastIndexOf(_ symbol: Character) -> Int
{
var lastIndex = -1
let arr = Array(self)
for i in 0..<arr.count {
if(arr[i] as Character? == symbol)
{
lastIndex = i
}
}
return lastIndex
}
}
| 28.901408 | 103 | 0.568226 |
4aaa157830262a76408180c67bd724c5f5448216 | 5,184 | //
// OptionsView.swift
// SlideController_Example
//
// Created by Evgeny Dedovets on 9/6/17.
// Copyright © 2017 Touchlane LLC. All rights reserved.
//
import UIKit
protocol OptionsViewProtocol: class {
var horizontalDemoButton: Actionable { get }
var verticalDemoButton: Actionable { get }
var carouselDemoButton: Actionable { get }
}
class OptionsView: UIView {
private let optionButtonWidth: CGFloat = 220
private let optionButtonHeigh: CGFloat = 32
private let horizontalDemoButtonCenterYOffset: CGFloat = -32
private let verticalDemoButtonCenterYOffset: CGFloat = 0
private let carouselDemoButtonCenterYOffset: CGFloat = 32
private let internalHorizontalDemoButton = FilledButton()
private let internalVerticalDemoButton = FilledButton()
private let internalCarouselDemoButton = FilledButton()
private let logoImageView = UIImageView()
private let label = UILabel()
init() {
super.init(frame: CGRect.zero)
backgroundColor = UIColor.white
internalHorizontalDemoButton.setTitle(NSLocalizedString("HorizontalSampleButtonTitle", comment: ""), for: .normal)
internalHorizontalDemoButton.clipsToBounds = true
internalHorizontalDemoButton.layer.cornerRadius = optionButtonHeigh / 2
internalHorizontalDemoButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(internalHorizontalDemoButton)
activateOptionButtonConstraints(view: internalHorizontalDemoButton, centerYOffset: horizontalDemoButtonCenterYOffset)
internalVerticalDemoButton.setTitle(NSLocalizedString("VerticalSampleButtonTitle", comment: ""), for: .normal)
internalVerticalDemoButton.clipsToBounds = true
internalVerticalDemoButton.layer.cornerRadius = optionButtonHeigh / 2
internalVerticalDemoButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(internalVerticalDemoButton)
activateOptionButtonConstraints(view: internalVerticalDemoButton, centerYOffset: verticalDemoButtonCenterYOffset)
internalCarouselDemoButton.setTitle(NSLocalizedString("CarouselSampleButtonTitle", comment: ""), for: .normal)
internalCarouselDemoButton.clipsToBounds = true
internalCarouselDemoButton.layer.cornerRadius = optionButtonHeigh / 2
internalCarouselDemoButton.translatesAutoresizingMaskIntoConstraints = false
addSubview(internalCarouselDemoButton)
activateOptionButtonConstraints(view: internalCarouselDemoButton, centerYOffset: carouselDemoButtonCenterYOffset)
logoImageView.image = UIImage(named: "main_logo")
logoImageView.translatesAutoresizingMaskIntoConstraints = false
addSubview(logoImageView)
activateLogoImageConstraints(view: logoImageView, anchorView: internalCarouselDemoButton)
label.text = "SlideController"
label.font = UIFont.boldSystemFont(ofSize: 24)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor(red: 61 / 255, green: 86 / 255, blue: 166 / 255, alpha: 1)
addSubview(label)
activateLabelConstraints(view: label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private typealias PrivateOptionsView = OptionsView
private extension PrivateOptionsView {
func activateOptionButtonConstraints (view: UIView, centerYOffset: CGFloat) {
guard let superview = view.superview else {
return
}
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: superview.centerXAnchor),
view.centerYAnchor.constraint(equalTo: superview.centerYAnchor, constant: centerYOffset * 2),
view.heightAnchor.constraint(equalToConstant: optionButtonHeigh),
view.widthAnchor.constraint(equalToConstant: optionButtonWidth)
])
}
func activateLogoImageConstraints(view: UIView, anchorView: UIView) {
guard let superview = view.superview else {
return
}
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: superview.centerXAnchor),
view.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -20),
view.heightAnchor.constraint(equalToConstant: 60)
])
}
func activateLabelConstraints(view: UIView) {
guard let superview = view.superview else {
return
}
NSLayoutConstraint.activate([
view.centerXAnchor.constraint(equalTo: superview.centerXAnchor),
view.topAnchor.constraint(equalTo: superview.topAnchor, constant: 20)
])
}
}
private typealias OptionsViewProtocolImplementation = OptionsView
extension OptionsViewProtocolImplementation: OptionsViewProtocol {
var horizontalDemoButton: Actionable {
return internalHorizontalDemoButton
}
var verticalDemoButton: Actionable {
return internalVerticalDemoButton
}
var carouselDemoButton: Actionable {
return internalCarouselDemoButton
}
}
| 42.491803 | 125 | 0.727238 |
e63b4d55aad2a8f502a7a95ac3d9b54332324166 | 1,205 | import AppKit
class Control: NSView {
private weak var target: AnyObject!
private let action: Selector
override var mouseDownCanMoveWindow: Bool { false }
required init?(coder: NSCoder) { nil }
init(_ target: AnyObject, _ action: Selector) {
self.target = target
self.action = action
super.init(frame: .zero)
translatesAutoresizingMaskIntoConstraints = false
setAccessibilityElement(true)
setAccessibilityRole(.button)
addTrackingArea(.init(rect: .zero, options: [.mouseEnteredAndExited, .activeInActiveApp, .inVisibleRect], owner: self))
}
override func resetCursorRects() {
addCursorRect(bounds, cursor: .pointingHand)
}
override func mouseDown(with: NSEvent) {
alphaValue = 0.3
}
override func mouseExited(with: NSEvent) {
alphaValue = 1
}
override func mouseUp(with: NSEvent) {
window!.makeFirstResponder(self)
if bounds.contains(convert(with.locationInWindow, from: nil)) {
_ = target.perform(action, with: self)
} else {
super.mouseUp(with: with)
}
alphaValue = 1
}
}
| 28.690476 | 127 | 0.626556 |
f81e25b36158443f28ea35a04debf716e29001fe | 8,468 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import BitByteData
import Foundation
/// Provides unarchive function for XZ archives.
public class XZArchive: Archive {
/**
Unarchives XZ archive. Archives with multiple streams are supported,
but uncompressed data from each stream will be combined into single `Data` object.
If an error happens during LZMA2 decompression, then `LZMAError` or `LZMA2Error` will be thrown.
- Parameter archive: Data archived using XZ format.
- Throws: `LZMAError`, `LZMA2Error` or `XZError` depending on the type of the problem.
Particularly, if filters other than LZMA2 are used in archive, then `XZError.wrongFilterID` will be thrown,
but it may also indicate that either the archive is damaged or
it might not be compressed with XZ or LZMA(2) at all.
- Returns: Unarchived data.
*/
public static func unarchive(archive data: Data) throws -> Data {
/// Object with input data which supports convenient work with bytes.
let byteReader = LittleEndianByteReader(data: data)
// Note: We don't check footer's magic bytes at the beginning,
// because it is impossible to determine the end of each stream in multi-stream archives
// without fully processing them, and checking last stream's footer doesn't
// guarantee correctness of other streams.
var result = Data()
while !byteReader.isFinished {
// Valid XZ archive must contain at least 32 bytes of data.
guard byteReader.bytesLeft >= 32
else { throw XZError.wrongMagic }
let streamResult = try processStream(byteReader)
result.append(streamResult.data)
guard !streamResult.checkError
else { throw XZError.wrongCheck([result]) }
try processPadding(byteReader)
}
return result
}
/**
Unarchives XZ archive. Archives with multiple streams are supported,
and uncompressed data from each stream will be stored in a separate element in the array
If data passed is not actually XZ archive, `XZError` will be thrown.
Particularly, if filters other than LZMA2 are used in archive, then `XZError.wrongFilterID` will be thrown.
If an error happens during LZMA2 decompression, then `LZMAError` or `LZMA2Error` will be thrown.
- Parameter archive: Data archived using XZ format.
- Throws: `LZMAError`, `LZMA2Error` or `XZError` depending on the type of the problem.
It may indicate that either the archive is damaged or it might not be compressed with XZ or LZMA(2) at all.
- Returns: Array of unarchived data from every stream in archive.
*/
public static func splitUnarchive(archive data: Data) throws -> [Data] {
// Same code as in `unarchive(archive:)` but with different type of `result`.
let byteReader = LittleEndianByteReader(data: data)
var result = [Data]()
while !byteReader.isFinished {
// Valid XZ archive must contain at least 32 bytes of data.
guard byteReader.bytesLeft >= 32
else { throw XZError.wrongMagic }
let streamResult = try processStream(byteReader)
result.append(streamResult.data)
guard !streamResult.checkError
else { throw XZError.wrongCheck(result) }
try processPadding(byteReader)
}
return result
}
private static func processStream(_ byteReader: LittleEndianByteReader) throws -> (data: Data, checkError: Bool) {
var out = Data()
let streamHeader = try XZStreamHeader(byteReader)
// BLOCKS AND INDEX
var blockInfos: [(unpaddedSize: Int, uncompSize: Int)] = []
var indexSize = -1
while true {
let blockHeaderSize = byteReader.byte()
if blockHeaderSize == 0 { // Zero value of blockHeaderSize means that we've encountered the index.
indexSize = try processIndex(blockInfos, byteReader)
break
} else {
let block = try XZBlock(blockHeaderSize, byteReader, streamHeader.checkType.size)
out.append(block.data)
switch streamHeader.checkType {
case .none:
break
case .crc32:
let check = byteReader.uint32()
guard CheckSums.crc32(block.data) == check
else { return (out, true) }
case .crc64:
let check = byteReader.uint64()
guard CheckSums.crc64(block.data) == check
else { return (out, true) }
case .sha256:
let check = byteReader.bytes(count: 32)
guard Sha256.hash(data: block.data) == check
else { return (out, true) }
}
blockInfos.append((block.unpaddedSize, block.uncompressedSize))
}
}
// STREAM FOOTER
try processFooter(streamHeader, indexSize, byteReader)
return (out, false)
}
private static func processIndex(_ blockInfos: [(unpaddedSize: Int, uncompSize: Int)],
_ byteReader: LittleEndianByteReader) throws -> Int
{
let indexStartIndex = byteReader.offset - 1
let recordsCount = try byteReader.multiByteDecode()
guard recordsCount == blockInfos.count
else { throw XZError.wrongField }
for blockInfo in blockInfos {
let unpaddedSize = try byteReader.multiByteDecode()
guard unpaddedSize == blockInfo.unpaddedSize
else { throw XZError.wrongField }
let uncompSize = try byteReader.multiByteDecode()
guard uncompSize == blockInfo.uncompSize
else { throw XZError.wrongDataSize }
}
var indexSize = byteReader.offset - indexStartIndex
if indexSize % 4 != 0 {
let paddingSize = 4 - indexSize % 4
for _ in 0 ..< paddingSize {
let byte = byteReader.byte()
guard byte == 0x00
else { throw XZError.wrongPadding }
indexSize += 1
}
}
let indexCRC = byteReader.uint32()
byteReader.offset = indexStartIndex
guard CheckSums.crc32(byteReader.bytes(count: indexSize)) == indexCRC
else { throw XZError.wrongInfoCRC }
byteReader.offset += 4
return indexSize + 4
}
private static func processFooter(_ streamHeader: XZStreamHeader, _ indexSize: Int,
_ byteReader: LittleEndianByteReader) throws
{
let footerCRC = byteReader.uint32()
/// Indicates the size of Index field. Should match its real size.
let backwardSize = (byteReader.int(fromBytes: 4) + 1) * 4
let streamFooterFlags = byteReader.int(fromBytes: 2)
byteReader.offset -= 6
guard CheckSums.crc32(byteReader.bytes(count: 6)) == footerCRC
else { throw XZError.wrongInfoCRC }
guard backwardSize == indexSize
else { throw XZError.wrongField }
// Flags in the footer should be the same as in the header.
guard streamFooterFlags & 0xFF == 0,
(streamFooterFlags & 0xF00) >> 8 == streamHeader.checkType.rawValue,
streamFooterFlags & 0xF000 == 0
else { throw XZError.wrongField }
// Check footer's magic number
guard byteReader.bytes(count: 2) == [0x59, 0x5A]
else { throw XZError.wrongMagic }
}
private static func processPadding(_ byteReader: LittleEndianByteReader) throws {
guard !byteReader.isFinished
else { return }
var paddingBytes = 0
while true {
let byte = byteReader.byte()
if byte != 0 {
if paddingBytes % 4 != 0 {
throw XZError.wrongPadding
} else {
break
}
}
if byteReader.isFinished {
if byte != 0 || paddingBytes % 4 != 3 {
throw XZError.wrongPadding
} else {
return
}
}
paddingBytes += 1
}
byteReader.offset -= 1
}
}
| 38.316742 | 118 | 0.601677 |
90cfae2693116dbb3a892bb6f68aa6c2586da139 | 854 | //: [Previous](@previous)
/* There are overall 2 types of Types
called 1) Named Types- They Have Names when they're defined
^Structures
^Classes
^Enumerations
^Protocols
2) Compound Types- They are Unnamed! defined by the types they contain, given by compound signature
like tuples ("Hello", true), thier compound signature is- (string, Bool
And Functions are also compound types)
Types on how the data is stored and how the data is copied
1-Value types
var name1="Chris"
var name2=name1
name2="sam"
name1==name2 (thi gives false changing value in one has no inference on other )
Structures and tuples
2-Reference types
Classes and Functions
2 or more instance refer to same data, changing one will change other also hence referenced*/
//: [Functions](@next)
| 34.16 | 107 | 0.688525 |
bba36ddba83b929159f7c04043d2e62d6e97891b | 11,941 | //
// xcclean.swift
// xcclean
//
// Created by Sascha M Holesch on 2016/04/21.
// Copyright © 2016年 NTSC. All rights reserved.
//
import Foundation
// MARK: Main
struct XCClean {
func main() {
guard Process.arguments.count > 2 else {
printUsage()
return
}
evaluateArguments(Process.arguments)
}
/**
Argument evaluation.
- parameter arguments: The array of arguments.
*/
func evaluateArguments(arguments: [String]) {
guard let dataType = DataType(rawValue: arguments[1]), action = Action(rawValue: arguments[2]) else {
printUsage()
return
}
switch action {
case .Show:
showDataForType(dataType)
case .Delete:
deleteDataForType(dataType, itemName: arguments[3])
case .DeleteAll:
deleteAllDataForType(dataType)
}
}
/**
Displays the usage explanation.
*/
func printUsage() {
print("XCode Cleaner v1.0.1")
print("")
print("Usage: xcclean data_type action item")
print("")
print("data_type:")
print("- \(DataType.DerivedData.rawValue) action")
print("- \(DataType.DeviceSupport.rawValue) action")
print("- \(DataType.Archives.rawValue) action")
print("- \(DataType.Simulators.rawValue) action")
print("- \(DataType.Documentation.rawValue) action")
print("")
print("action:")
print("- \(Action.Show.rawValue)")
print("- \(Action.Delete.rawValue)")
print("- \(Action.DeleteAll.rawValue)")
print(" Deletes all items available as displayed by the 'show' action")
print("")
print("item:")
print(" The item name as displayed by the 'show' action in the second column")
}
}
// MARK: Definitions
extension XCClean {
enum DataPath: String {
case DerivedData = "~/Library/Developer/Xcode/DerivedData/"
case DeviceSupport = "~/Library/Developer/Xcode/iOS DeviceSupport/"
case Archives = "~/Library/Developer/Xcode/Archives/"
case Simulators = "~/Library/Developer/CoreSimulator/Devices/"
case Documentation = "~/Library/Developer/Shared/Documentation/DocSets/"
}
enum DataType: String {
case DerivedData = "derived_data"
case DeviceSupport = "device_support"
case Archives = "archives"
case Simulators = "simulators"
case Documentation = "documentation"
func associatedPath() -> DataPath {
switch self {
case .DerivedData:
return DataPath.DerivedData
case .DeviceSupport:
return DataPath.DeviceSupport
case .Archives:
return DataPath.Archives
case .Simulators:
return DataPath.Simulators
case .Documentation:
return DataPath.Documentation
}
}
}
enum Action: String {
case Show = "show"
case Delete = "delete"
case DeleteAll = "delete_all"
}
}
// MARK: Helpers
extension XCClean {
/**
Creates a human readable string of the directory disk usage.
- parameter url: The NSURL for the directory.
- returns: A String containing a human readable disk usage.
*/
func sizeOfDirectoryAtURL(url: NSURL) -> String {
// Prepare the enumerator for deep iteration on directories
let errorHandler: (NSURL, NSError) -> Bool = {
(url, error) -> Bool in
print("Error: \(error.localizedDescription)")
return true
}
var bool = ObjCBool(true)
guard let path = url.path where NSFileManager().fileExistsAtPath(path, isDirectory: &bool),
let filesEnumerator = NSFileManager.defaultManager().enumeratorAtURL(url, includingPropertiesForKeys: nil, options: [], errorHandler: errorHandler)else {
return ""
}
// Iterate over the files to collect their sizes
var folderFileSizeInBytes = 0
while let fileURL = filesEnumerator.nextObject() {
guard let fileURL = fileURL as? NSURL, path = fileURL.path else {
return ""
}
do {
let attributes = try NSFileManager.defaultManager().attributesOfItemAtPath(path)
if let fileSize = attributes[NSFileSize] as? Int {
folderFileSizeInBytes += fileSize.hashValue
}
} catch let error as NSError {
print("Error retrieving file size: \(error.localizedDescription)")
}
}
// Format the file size string
let byteCountFormatter = NSByteCountFormatter()
byteCountFormatter.allowedUnits = .UseDefault
byteCountFormatter.countStyle = .File
return byteCountFormatter.stringFromByteCount(Int64(folderFileSizeInBytes))
}
/**
Creates a human readable string of the file disk usage.
- parameter files: The NSURL for the file.
- returns: A String containing a human readable disk usage.
*/
func sizeOfFiles(files: [NSURL]) -> [String] {
var longestSizeString = 0
var sizeStrings: [String] = Array()
// Create the array of filesize strings
for file in files {
let sizeString = "[\(sizeOfDirectoryAtURL(file))]"
let length = sizeString.characters.count
// Remember the longest string
if length > longestSizeString {
longestSizeString = length
}
sizeStrings.append(sizeString)
}
// Add prefix spaces for right hand side alignment
var paddedStrings: [String] = Array()
for sizeString in sizeStrings {
let lengthDelta = longestSizeString - sizeString.characters.count
var tempString = sizeString
for _ in 0..<lengthDelta {
tempString = " " + tempString
}
paddedStrings.append(tempString)
}
return paddedStrings
}
/**
Retrieve a files within a directory.
- parameter url: The NSURL to scan for files.
- parameter propertyKeys: Optional property keys.
- returns: An array of files.
*/
func filesAtURL(url: NSURL, propertyKeys: [String]?) -> [NSURL] {
do {
return try NSFileManager.defaultManager().contentsOfDirectoryAtURL(url, includingPropertiesForKeys: propertyKeys, options: .SkipsHiddenFiles)
} catch {
return []
}
}
}
// MARK: Show Action
extension XCClean {
/**
Retrieves the name of the archive contained in the directory.
- parameter url: The NSURL to the archive directory.
- returns: Returns a String containing detail information about the archive directory.
*/
func archiveDetailsForURL(url: NSURL) -> String {
var detailString = "("
let files = filesAtURL(url, propertyKeys: [NSURLIsDirectoryKey])
for file in files {
if let filename = file.lastPathComponent {
if detailString.characters.count == 1 {
detailString += filename
} else {
detailString += "; " + filename
}
}
}
return detailString + ")"
}
/**
Retrieves iOS version and device type for the simulator directory.
- parameter url: The NSURL to the simulator directory.
- returns: Returns a String containing detail information about the simulator.
*/
func simulatorDetailsForURL(url: NSURL) -> String {
var detailString = "("
let files = filesAtURL(url, propertyKeys: [NSURLIsDirectoryKey])
for file in files {
if let filename = file.lastPathComponent where filename == "device.plist",
let dict = NSDictionary(contentsOfURL: file),
os = dict["runtime"]?.componentsSeparatedByString(".").last,
deviceType = dict["deviceType"]?.componentsSeparatedByString(".").last?.stringByReplacingOccurrencesOfString("-", withString: " ") {
detailString += deviceType + ", " + os
}
}
return detailString + ")"
}
/**
Prints directory information to the screen.
- parameter dataType: The type of data for with to display information.
*/
func showDataForType(dataType: DataType) {
let path = dataType.associatedPath()
let url = NSURL(fileURLWithPath: (path.rawValue as NSString).stringByExpandingTildeInPath, isDirectory: true)
let files = filesAtURL(url, propertyKeys: nil)
// Iterate over the directory to gather all file sizes and format them with right alignment
let itemSizeStrings = sizeOfFiles(files)
for (index, file) in files.enumerate() {
if let filename = file.lastPathComponent {
switch path {
case .Archives:
let detailString = archiveDetailsForURL(file)
print(itemSizeStrings[index] + " " + filename + " " + detailString)
case .Simulators:
let detailString = simulatorDetailsForURL(file)
print(itemSizeStrings[index] + " " + filename + " " + detailString)
default:
print(itemSizeStrings[index] + " " + filename)
}
}
}
}
}
// MARK: Delete Action
extension XCClean {
/**
Deletes a specific file.
- parameter url: The NSURL to the file to delete.
*/
func deleteDataAtUrl(url: NSURL) {
guard let filename = url.lastPathComponent else {
return
}
do {
try NSFileManager.defaultManager().removeItemAtURL(url)
print("Deleted directory \"\(filename)\"")
} catch {
print("Failed to delete directory \"\(filename)\"")
}
}
/**
Deletes all files for a specific data type.
- parameter dataType: The DataType to delete all files for.
*/
func deleteAllDataForType(dataType: DataType) {
let directoryURL = NSURL(fileURLWithPath: (dataType.associatedPath().rawValue as NSString).stringByExpandingTildeInPath, isDirectory: true)
let files = filesAtURL(directoryURL, propertyKeys: [NSURLIsDirectoryKey])
for file in files {
var bool = ObjCBool(true)
if let filePath = file.path where NSFileManager().fileExistsAtPath(filePath, isDirectory: &bool) {
//print("Delete \(filePath)")
deleteDataAtUrl(file)
}
}
}
/**
Deletes a specific file for the specified data type.
- parameter dataType: The DataType to delete files for.
- parameter itemName: The name of the file to delete.
*/
func deleteDataForType(dataType: DataType, itemName: String) {
let directoryURL = NSURL(fileURLWithPath: (dataType.associatedPath().rawValue as NSString).stringByExpandingTildeInPath, isDirectory: true)
let deletionItemUrl = directoryURL.URLByAppendingPathComponent(itemName, isDirectory: true)
var bool = ObjCBool(true)
guard let deletionPath = deletionItemUrl.path where NSFileManager().fileExistsAtPath(deletionPath, isDirectory: &bool) else {
print("The directory \"\(itemName)\" does not exist.")
return
}
deleteDataAtUrl(deletionItemUrl)
}
}
// MARK: Entry point
XCClean().main()
| 32.804945 | 165 | 0.584457 |
dd30ff77435b27ee89fb5f7162a31a2e59ce2e14 | 4,317 | import XCTest
import Nimble
import Foundation
class PostNotificationTest: XCTestCase, XCTestCaseProvider {
var allTests: [(String, () throws -> Void)] {
return [
("testPassesWhenNoNotificationsArePosted", testPassesWhenNoNotificationsArePosted),
("testPassesWhenExpectedNotificationIsPosted", testPassesWhenExpectedNotificationIsPosted),
("testPassesWhenAllExpectedNotificationsArePosted", testPassesWhenAllExpectedNotificationsArePosted),
("testFailsWhenNoNotificationsArePosted", testFailsWhenNoNotificationsArePosted),
("testFailsWhenNotificationWithWrongNameIsPosted", testFailsWhenNotificationWithWrongNameIsPosted),
("testFailsWhenNotificationWithWrongObjectIsPosted", testFailsWhenNotificationWithWrongObjectIsPosted),
("testPassesWhenExpectedNotificationEventuallyIsPosted", testPassesWhenExpectedNotificationEventuallyIsPosted),
]
}
var notificationCenter: NSNotificationCenter!
#if _runtime(_ObjC)
override func setUp() {
_setUp()
super.setUp()
}
#else
func setUp() {
_setUp()
}
#endif
func _setUp() {
notificationCenter = NSNotificationCenter()
}
func testPassesWhenNoNotificationsArePosted() {
expect {
// no notifications here!
return nil
}.to(postNotifications(beEmpty(), fromNotificationCenter: notificationCenter))
}
func testPassesWhenExpectedNotificationIsPosted() {
let testNotification = NSNotification(name: "Foo", object: nil)
expect {
self.notificationCenter.postNotification(testNotification)
}.to(postNotifications(equal([testNotification]), fromNotificationCenter: notificationCenter))
}
func testPassesWhenAllExpectedNotificationsArePosted() {
let foo = NSNumber(int: 1)
let bar = NSNumber(int: 2)
let n1 = NSNotification(name: "Foo", object: foo)
let n2 = NSNotification(name: "Bar", object: bar)
expect {
self.notificationCenter.postNotification(n1)
self.notificationCenter.postNotification(n2)
return nil
}.to(postNotifications(equal([n1, n2]), fromNotificationCenter: notificationCenter))
}
func testFailsWhenNoNotificationsArePosted() {
let testNotification = NSNotification(name: "Foo", object: nil)
failsWithErrorMessage("expected to equal <[\(testNotification)]>, got no notifications") {
expect {
// no notifications here!
return nil
}.to(postNotifications(equal([testNotification]), fromNotificationCenter: self.notificationCenter))
}
}
func testFailsWhenNotificationWithWrongNameIsPosted() {
let n1 = NSNotification(name: "Foo", object: nil)
let n2 = NSNotification(name: n1.name + "a", object: nil)
failsWithErrorMessage("expected to equal <[\(n1)]>, got <[\(n2)]>") {
expect {
self.notificationCenter.postNotification(n2)
return nil
}.to(postNotifications(equal([n1]), fromNotificationCenter: self.notificationCenter))
}
}
func testFailsWhenNotificationWithWrongObjectIsPosted() {
let n1 = NSNotification(name: "Foo", object: nil)
let n2 = NSNotification(name: n1.name, object: NSObject())
failsWithErrorMessage("expected to equal <[\(n1)]>, got <[\(n2)]>") {
expect {
self.notificationCenter.postNotification(n2)
return nil
}.to(postNotifications(equal([n1]), fromNotificationCenter: self.notificationCenter))
}
}
func testPassesWhenExpectedNotificationEventuallyIsPosted() {
#if _runtime(_ObjC)
let testNotification = NSNotification(name: "Foo", object: nil)
expect {
deferToMainQueue {
self.notificationCenter.postNotification(testNotification)
}
return nil
}.toEventually(postNotifications(equal([testNotification]), fromNotificationCenter: notificationCenter))
#else
print("\(__FUNCTION__) is missing because toEventually is not implement on this platform")
#endif
}
} | 40.345794 | 123 | 0.659949 |
616517451f5e936378f6d5a1b57e18d292fc4fa9 | 15,616 | //
// SKProductDetailInfoView.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/21.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKProductDetailInfoView: UIScrollView, UIScrollViewDelegate {
var lineIndicatorView: UIScrollView?
var model: SKProductDetailModel? {
didSet{
// 产品相册
if (model?.produceinfo?.pimglist?.count)! > 0 {
pivView = UIView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 174))
pivView?.backgroundColor = UIColor(red: 231/255.0, green: 235/255.0, blue: 240/255.0, alpha: 1)
addSubview(pivView!)
contentHeight = 174
let count = (model?.produceinfo?.pimglist?.count)!
let picScrollView = UIScrollView(frame: CGRect(x: 0, y: 11, width: SKScreenWidth, height: 135))
picScrollView.delegate = self
picScrollView.showsHorizontalScrollIndicator = false
picScrollView.showsVerticalScrollIndicator = false
var picScrollViewContntSizeW: CGFloat = 16
for i in 0..<count {
let pimgModel = model?.produceinfo?.pimglist?[i] as! SKProductDetailPimgModel
let widthpxstr = pimgModel.width
let heightpxstr = pimgModel.height
let index = widthpxstr?.index((widthpxstr?.endIndex)!, offsetBy: -2)
let floatWidth = ((widthpxstr?.substring(to: index!))! as NSString).floatValue
let floatHeight = ((heightpxstr?.substring(to: index!))! as NSString).floatValue
let relWidth = floatWidth*135.0/floatHeight
let pimImage = UIImageView(frame: CGRect(x: picScrollViewContntSizeW, y: 0, width: CGFloat(relWidth), height: 135))
pimImage.isUserInteractionEnabled = true
pimImage.tag = 1000+i
pimImage.contentMode = .scaleAspectFit
if pimgModel.showPro_img == nil {
pimImage.image = UIImage(named: "pic_touxiang_little")
} else {
pimImage.sd_setImage(with: URL(string: pimgModel.showPro_img!), placeholderImage: UIImage(named: "pic_touxiang_little"))
}
let tap = UITapGestureRecognizer(target: self, action: #selector(tapPhotoImage))
tap.numberOfTouchesRequired = 1
pimImage.addGestureRecognizer(tap)
picScrollView.addSubview(pimImage)
picScrollViewContntSizeW += (16+CGFloat(relWidth))
}
picScrollView.contentSize = CGSize(width: picScrollViewContntSizeW, height: 0)
pivView?.addSubview(picScrollView)
let bgLineView = UIImageView(frame: CGRect(x: 16, y: 157, width: SKScreenWidth-32, height: 6))
bgLineView.image = UIImage(named: "pic_xiangqingbg")
pivView?.addSubview(bgLineView)
lineIndicatorView = UIScrollView(frame: CGRect(x: 0, y: 0, width: SKScreenWidth-32, height: 6))
lineIndicatorView?.contentSize = CGSize(width: SKScreenWidth-132, height: 0)
lineIndicatorView?.contentOffset = CGPoint(x: 0, y: 0)
lineIndicatorView?.showsVerticalScrollIndicator = false
lineIndicatorView?.showsHorizontalScrollIndicator = false
bgLineView.addSubview(lineIndicatorView!)
let indicatorImage = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 6))
indicatorImage.image = UIImage(named: "pic_xiangqing@")
lineIndicatorView?.addSubview(indicatorImage)
}
// 产品简介
productInfo = UIView()
productInfo?.backgroundColor = UIColor.white
addSubview(productInfo!)
productInfo?.addSubview(titleView(withString: "产品简介"))
let prdiuctInfoText = UILabel()
let labelSize = SKLabelSizeWith(labelText: (model?.produceinfo?.info)!, font: UIFont.systemFont(ofSize: 15), width: SKScreenWidth-32)
prdiuctInfoText.frame = CGRect(origin: CGPoint(x: 16, y: 60), size: labelSize)
prdiuctInfoText.text = model?.produceinfo?.info
prdiuctInfoText.textColor = UIColor(white: 152/255.0, alpha: 1)
prdiuctInfoText.numberOfLines = 0
prdiuctInfoText.font = UIFont.systemFont(ofSize: 15)
productInfo?.addSubview(prdiuctInfoText)
productInfo?.frame = CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: 80+labelSize.height)
contentHeight += (80+labelSize.height)
// 产品优势
if (model?.produceinfo?.advantage) != ""{
productSuperiority = UIView()
productSuperiority?.backgroundColor = UIColor.white
addSubview(productSuperiority!)
productSuperiority?.addSubview(linewView())
productSuperiority?.addSubview(titleView(withString: "产品优势"))
let prdiuctSuperiorityText = UILabel()
let labelSize = SKLabelSizeWith(labelText: (model?.produceinfo?.advantage)!, font: UIFont.systemFont(ofSize: 15), width: SKScreenWidth-32)
prdiuctSuperiorityText.frame = CGRect(origin: CGPoint(x: 16, y: 60), size: labelSize)
prdiuctSuperiorityText.text = model?.produceinfo?.advantage
prdiuctSuperiorityText.textColor = UIColor(white: 152/255.0, alpha: 1)
prdiuctSuperiorityText.numberOfLines = 0
prdiuctSuperiorityText.font = UIFont.systemFont(ofSize: 15)
productSuperiority?.addSubview(prdiuctSuperiorityText)
productSuperiority?.frame = CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: 80+labelSize.height)
contentHeight += (80+labelSize.height)
}
// 团队介绍
if (model?.team?.count)! > 0 {
let count = (model?.team?.count)!
teamView = UIView(frame: CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: CGFloat(count*120)+80))
teamView?.backgroundColor = UIColor.white
addSubview(teamView!)
teamView?.addSubview(linewView())
teamView?.addSubview(titleView(withString: "团队介绍"))
for i in 0..<count {
let teamModel = model?.team![i] as! SKProductDetailTeamModel
let subTeamView = UIView(frame: CGRect(x: 0, y: CGFloat(60+i*120), width: SKScreenWidth, height: 120))
let headImage = UIImageView(frame: CGRect(x: 32, y: 16, width: 35, height: 35))
headImage.layer.cornerRadius = 17.5
headImage.layer.masksToBounds = true
if teamModel.showThumbnail == nil {
headImage.image = UIImage(named: "pic_touxiang_little")
} else {
headImage.sd_setImage(with: URL(string: teamModel.showThumbnail!), placeholderImage: UIImage(named: "pic_touxiang_little"))
}
subTeamView.addSubview(headImage)
let nameLabel = UILabel(frame: CGRect(x: 83, y: 0, width: SKScreenWidth-96, height: 20))
nameLabel.text = teamModel.name
nameLabel.textColor = UIColor.black
nameLabel.font = UIFont.systemFont(ofSize: 19)
subTeamView.addSubview(nameLabel)
let jobLabel = UILabel(frame: CGRect(x: 83, y: 35, width: SKScreenWidth-96, height: 17))
jobLabel.text = teamModel.job
jobLabel.textColor = UIColor.black
jobLabel.font = UIFont.systemFont(ofSize: 16)
subTeamView.addSubview(jobLabel)
let introduceLabel = UILabel(frame: CGRect(x: 83, y: 62, width: SKScreenWidth-96, height: 40))
introduceLabel.text = teamModel.info
introduceLabel.textColor = UIColor(white: 152/255.0, alpha: 1)
introduceLabel.font = UIFont.systemFont(ofSize: 15)
introduceLabel.numberOfLines = 0
subTeamView.addSubview(introduceLabel)
teamView?.addSubview(subTeamView)
}
contentHeight += (CGFloat(count*120)+80)
}
// 大事记
if (model?.big_event?.count)! > 0 {
let count = (model?.big_event?.count)!
bigeventView = UIView(frame: CGRect(x: 0, y: contentHeight, width: SKScreenWidth, height: CGFloat(count*50+60)))
bigeventView?.backgroundColor = UIColor.white
addSubview(bigeventView!)
bigeventView?.addSubview(linewView())
bigeventView?.addSubview(titleView(withString: "大事记"))
for i in 0..<count {
let bagEventModel = model?.big_event?[i] as! SKProductDetailbig_eventModel
let everySubView = UIView(frame: CGRect(x: 0, y: CGFloat(60+i*50), width: SKScreenWidth, height: 50))
let dataLabel = UILabel(frame: CGRect(x: 16, y: 0, width: 70, height: 13))
let dataStr = bagEventModel.time?.description
let strIndex = dataStr?.index((dataStr?.startIndex)!, offsetBy: 10)
let showStr = dataStr?.substring(to: strIndex!)
dataLabel.text = showStr
dataLabel.textColor = UIColor(white: 152/255.0, alpha: 1)
dataLabel.font = UIFont.systemFont(ofSize: 11)
everySubView.addSubview(dataLabel)
let bigPointView = UIView(frame: CGRect(x: 90, y: 2, width: 10, height: 10))
bigPointView.layer.cornerRadius = 5
bigPointView.layer.masksToBounds = true
bigPointView.backgroundColor = UIColor(white: 152/255.0, alpha: 1)
everySubView.addSubview(bigPointView)
let smallPointView = UIView(frame: CGRect(x: 3, y: 3, width: 4, height: 4))
smallPointView.layer.cornerRadius = 2
smallPointView.layer.masksToBounds = true
smallPointView.backgroundColor = UIColor.white
bigPointView.addSubview(smallPointView)
let eventLabel = UILabel(frame: CGRect(x: 126, y: 0, width: SKScreenWidth-142, height: 16))
eventLabel.text = bagEventModel.events
eventLabel.textColor = UIColor(white: 152/255.0, alpha: 1)
eventLabel.font = UIFont.systemFont(ofSize: 15)
everySubView.addSubview(eventLabel)
let lineView = UIView(frame: CGRect(x: 95, y: 12, width: 1, height: 38))
lineView.backgroundColor = UIColor(white: 245/255.0, alpha: 1)
everySubView.addSubview(lineView)
bigeventView?.addSubview(everySubView)
}
contentHeight += (CGFloat(count*50)+60)
}
contentSize = CGSize(width: 0, height: contentHeight)
}
}
var pivView: UIView?
var productInfo: UIView?
var productSuperiority: UIView?
var teamView: UIView?
var bigeventView: UIView?
var contentHeight: CGFloat = 0
override init(frame: CGRect) {
super.init(frame: frame)
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func linewView() -> UIView {
let view = UIView()
view.frame = CGRect(x: 16, y: 0, width: SKScreenWidth-32, height: 0.5)
view.backgroundColor = UIColor(white: 245/255.0, alpha: 1)
return view
}
func titleView(withString: String) -> UIView {
let titleView = UILabel(frame: CGRect(x: 16, y: 20, width: SKScreenWidth-32, height: 20))
titleView.text = withString
titleView.textColor = UIColor.black
titleView.font = UIFont.systemFont(ofSize: 19)
return titleView
}
@objc private func tapPhotoImage(tap: UITapGestureRecognizer){
let photoAlbum = photoAlbumView(with: model?.produceinfo?.pimglist as! [SKProductDetailPimgModel])
photoAlbum.tag = (tap.view?.tag)!-1000
window?.addSubview(photoAlbum)
}
// 相册滑动的代理
func scrollViewDidScroll(_ scrollView: UIScrollView) {
lineIndicatorView?.setContentOffset(CGPoint(x: -scrollView.contentOffset.x*(SKScreenWidth-132)/(scrollView.contentSize.width-SKScreenWidth), y: 0), animated: false)
}
}
class photoAlbumView: UIScrollView {
override var tag: Int{
didSet{
setContentOffset(CGPoint(x: CGFloat(tag)*SKScreenWidth, y: 0), animated: false)
}
}
convenience init(with imageArray: [SKProductDetailPimgModel]){
self.init()
frame = CGRect(x: 0, y: 0, width: SKScreenWidth, height: SKScreenHeight)
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
isPagingEnabled = true
bounces = false
backgroundColor = UIColor.black
contentSize = CGSize(width: SKScreenWidth*CGFloat(imageArray.count), height: 0)
for i in 0..<imageArray.count {
let pimModel = imageArray[i] as SKProductDetailPimgModel
let image = UIImageView()
image.frame = CGRect(x: CGFloat(i)*SKScreenWidth, y: 75, width: SKScreenWidth, height: SKScreenHeight-150)
image.isUserInteractionEnabled = true
image.contentMode = .scaleAspectFit
image.clipsToBounds = true
if pimModel.showPro_img == nil {
image.image = UIImage(named: "pic_touxiang_little")
} else {
image.sd_setImage(with: URL(string: pimModel.showPro_img!), placeholderImage: UIImage(named: "pic_touxiang_little"))
}
addSubview(image)
}
let tap = UITapGestureRecognizer(target: self, action: #selector(touchScrollView))
tap.numberOfTouchesRequired = 1
addGestureRecognizer(tap)
}
@objc private func touchScrollView(){
removeFromSuperview()
}
}
| 46.064897 | 172 | 0.553599 |
08043f0cd62d19766bcb675bc82db843198f30fc | 2,403 | // Copyright (c) 2019 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses 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
/// A connectable adapter which imposes asynchronous dispatch blocks around calls in both directions.
///
/// * Consumers passed to `connect` will be executed on the provided `consumerQueue`
/// * The underlying connectable’s connections’ `acceptClosure` and `disposeClosure` will be executed on the provided
/// `acceptQueue`
final class AsyncDispatchQueueConnectable<InputType, OutputType>: Connectable {
private let underlyingConnectable: AnyConnectable<InputType, OutputType>
private let acceptQueue: DispatchQueue
init(
_ underlyingConnectable: AnyConnectable<InputType, OutputType>,
acceptQueue: DispatchQueue
) {
self.underlyingConnectable = underlyingConnectable
self.acceptQueue = acceptQueue
}
convenience init<C: Connectable>(
_ underlyingConnectable: C,
acceptQueue: DispatchQueue
) where C.InputType == InputType, C.OutputType == OutputType {
self.init(AnyConnectable(underlyingConnectable), acceptQueue: acceptQueue)
}
func connect(_ consumer: @escaping (OutputType) -> Void) -> Connection<InputType> {
let connection = underlyingConnectable.connect(consumer)
return Connection(
acceptClosure: { [acceptQueue] input in
acceptQueue.async {
connection.accept(input)
}
},
disposeClosure: { [acceptQueue] in
acceptQueue.async {
connection.dispose()
}
}
)
}
}
| 38.142857 | 117 | 0.689971 |
2fa5b5d6b932c3e9b26307032352b6f6c89628ec | 987 | // Copyright 2020 Itty Bitty Apps Pty Ltd
import ArgumentParser
import AppStoreConnect_Swift_SDK
import Combine
import Foundation
import struct Model.Device
struct RegisterDeviceCommand: CommonParsableCommand {
static var configuration = CommandConfiguration(
commandName: "register",
abstract: "Register a new device for app development."
)
@OptionGroup()
var common: CommonOptions
@Argument(help: "The UDID of the device to register.")
var udid: String
@Argument(help: "The name of the device to register.")
var name: String
@Argument(help: "The platform of the device to register \(Platform.allCases).")
var platform: Platform
func run() throws {
let service = try makeService()
let device = try service.request(APIEndpoint.registerNewDevice(name: name, platform: platform, udid: udid))
.map(Device.init)
.await()
device.render(options: common.outputOptions)
}
}
| 26.675676 | 115 | 0.693009 |
f4293024a74235a9dcaa776f38a4a13787602659 | 281 | //
// NoteLabel.swift
// Yomu
//
// Created by Sendy Halim on 9/2/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import Cocoa
class NoteLabel: NSTextField {
override func viewWillDraw() {
super.viewWillDraw()
textColor = Config.style.noteColor
}
}
| 15.611111 | 54 | 0.672598 |
28b022bd97424e27b14b0327fc445efae5f00bda | 3,880 | //
// StyledTextKitRenderCache.swift
// StyledTextKit
//
// Created by Ryan Nystrom on 12/13/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
public protocol LRUCachable {
var cachedSize: Int { get }
}
public final class LRUCache<Key: Hashable & Equatable, Value: LRUCachable> {
internal class Node {
// for reverse lookup in map
let key: Key
// mutable b/c you can change the value for an existing key
var value: Value
// 2-way linked list
weak var previous: Node? = nil
var next: Node? = nil
init(key: Key, value: Value) {
self.key = key
self.value = value
}
var tail: Node? {
var t: Node? = self
while let next = t?.next {
t = next
}
return t
}
}
public enum Compaction {
case `default`
case percent(Double)
}
// thread safety
private var lock = os_unfair_lock_s()
// mutable collection state
internal var map = [Key: Node]()
internal var size: Int = 0
internal var head: Node?
public let maxSize: Int
public let compaction: Compaction
public init(maxSize: Int, compaction: Compaction = .default, clearOnWarning: Bool = false) {
self.maxSize = maxSize
switch compaction {
case .default: self.compaction = compaction
case .percent(let percent):
if percent <= 0 || percent > 1 {
self.compaction = .default
} else {
self.compaction = compaction
}
}
if clearOnWarning {
NotificationCenter.default.addObserver(
self,
selector: #selector(clear),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil
)
}
}
public func get(_ key: Key) -> Value? {
os_unfair_lock_lock(&lock)
defer { os_unfair_lock_unlock(&lock) }
let node = map[key]
newHead(node: node)
return node?.value
}
public func set(_ key: Key, value: Value?) {
guard let value = value else { return }
os_unfair_lock_lock(&lock)
defer { os_unfair_lock_unlock(&lock) }
let node: Node
if let existingNode = map[key] {
size -= existingNode.value.cachedSize
existingNode.value = value
node = existingNode
} else {
node = Node(key: key, value: value)
map[key] = node
}
size += value.cachedSize
newHead(node: node)
compact()
}
public subscript(key: Key) -> Value? {
get {
return get(key)
}
set(newValue) {
set(key, value: newValue)
}
}
@objc public func clear() {
os_unfair_lock_lock(&lock)
defer { os_unfair_lock_unlock(&lock) }
head = nil
map.removeAll()
size = 0
}
// unsafe to call w/out nested in lock
private func newHead(node: Node?) {
// fill in the gap and break cycles
node?.previous?.next = node?.next
head?.previous = node
node?.next = head
node?.previous = nil
head = node
}
// unsafe to call w/out nested in lock
private func compact() {
guard size > maxSize else { return }
var tail = head?.tail
let compactSize: Int
switch compaction {
case .default: compactSize = maxSize
case .percent(let percent): compactSize = Int(Double(maxSize) * percent)
}
while size > compactSize, let next = tail {
size -= next.value.cachedSize
map.removeValue(forKey: next.key)
tail = next.previous
}
}
}
| 24.099379 | 96 | 0.54201 |
23768572758fa7a4c461e39904c3a160ed67deed | 4,702 | //
// Stack.swift
// SwiftDataStructures
//
// Created by bryn austin bellomy on 2014 Dec 17.
// Copyright (c) 2014 bryn austin bellomy. All rights reserved.
//
//
// MARK: - struct Stack<T> -
//
public struct Stack<T>
{
public typealias Element = T
internal typealias UnderlyingCollection = LinkedList<T>
private var elements = UnderlyingCollection()
public var top : Element? { return elements.last?.item }
public var bottom : Element? { return elements.first?.item }
public var count : Index.Distance { return elements.count }
public var isEmpty : Bool { return count == 0 }
public init() {
}
/**
Element order is [bottom, ..., top], as if one were to iterate through the sequence in forward order, calling `stack.push(element)` on each element.
*/
public init<S : SequenceType where S.Generator.Element == T>(_ elements:S) {
extend(elements)
}
/**
Adds an element to the top of the stack.
:param: elem The element to add.
*/
public mutating func push(elem: Element) {
let newElement = UnderlyingCollection.NodeType(elem)
elements.append(newElement)
}
/**
Removes the top element from the stack and returns it.
:returns: The removed element or `nil` if the stack is empty.
*/
public mutating func pop() -> Element? {
return (count > 0) ? removeTop() : nil
}
public func find(predicate: (Element) -> Bool) -> Index? {
return elements.find { predicate($0.item) }
}
/**
Removes the element `n` positions from the top of the stack and returns it. `index` must be a valid index or a precondition assertion will fail.
:param: index The index of the element to remove.
:returns: The removed element.
*/
public mutating func removeAtIndex(index:Index) -> Element {
precondition(index >= startIndex && index <= endIndex.predecessor(), "index (\(index)) is out of range [startIndex = \(startIndex), endIndex = \(endIndex), count = \(count)].")
return elements.removeAtIndex(endIndex.predecessor() - index).item
}
/**
This function is equivalent to `pop()`, except that it will fail if the stack is empty.
:returns: The removed element.
*/
public mutating func removeTop() -> Element {
precondition(count > 0, "Cannot removeTop() from an empty Stack.")
return elements.removeLast().item
}
}
//
// MARK: - Stack : SequenceType
//
extension Stack : SequenceType
{
public typealias Generator = GeneratorOf<T>
public func generate() -> Generator
{
var generator = elements.generate()
return GeneratorOf {
return generator.next()?.item
}
}
}
//
// MARK: - Stack : MutableCollectionType
//
extension Stack : MutableCollectionType
{
public typealias Index = UnderlyingCollection.Index
public var startIndex : Index { return elements.startIndex }
public var endIndex : Index { return elements.endIndex }
/**
Subscript `n` corresponds to the element that is `n` positions from the top of the stack. Subscript 0 always corresponds to the top element.
*/
public subscript(position:Index) -> Generator.Element
{
get {
return reverse(elements)[position].item
}
set {
let newNode = UnderlyingCollection.NodeType(newValue)
elements[position] = newNode
}
}
}
//
// MARK: - Stack : ExtensibleCollectionType
//
extension Stack : ExtensibleCollectionType
{
public mutating func reserveCapacity(n: Index.Distance) {
elements.reserveCapacity(n)
}
/**
This method is simply an alias for `push()`, included for `ExtensibleCollectionType` conformance.
*/
public mutating func append(newElement:Element) {
push(newElement)
}
/**
Element order is [bottom, ..., top], as if one were to iterate through the sequence in forward order, calling `stack.push(element)` on each element.
*/
public mutating func extend<S : SequenceType where S.Generator.Element == Element>(sequence: S) {
let wrapped = map(sequence) { UnderlyingCollection.NodeType($0) }
elements.extend(wrapped)
}
}
//
// MARK: - Stack : ArrayLiteralConvertible
//
extension Stack : ArrayLiteralConvertible
{
/**
Element order is [bottom, ..., top], as if one were to iterate through the sequence in forward order, calling `stack.push(element)` on each element.
*/
public init(arrayLiteral elements: Element...) {
extend(elements)
}
}
| 27.179191 | 184 | 0.635049 |
169178efad662b26a83174a3ee385a690c15337b | 1,038 | //
// grokHTMLAndDownloadsTests.swift
// grokHTMLAndDownloadsTests
//
// Created by Christina Moulton on 2015-10-12.
// Copyright © 2015 Teak Mobile Inc. All rights reserved.
//
import XCTest
@testable import grokHTMLAndDownloads
class grokHTMLAndDownloadsTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 28.054054 | 111 | 0.655106 |
20e2e192dc197442f70d037eba9dd0feeda57a23 | 449 | // 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
var f{if{enum A{protocol a}}class A{struct B<f:f.c
| 44.9 | 79 | 0.750557 |
4ab75cbcf999bfc887cfdeda3aebd7078c4acea9 | 1,543 | //
// InMemoryAppState.swift
// LibreDirect
//
import Combine
import Foundation
// MARK: - InMemoryAppState
struct MemoryAppState: AppState {
var alarmHigh = 160
var alarmLow = 80
var alarmSnoozeUntil: Date?
var bellmanAlarm = false
var bellmanConnectionState: BellmanConnectionState = .disconnected
var calendarExport = false
var chartShowLines = false
var chartZoomLevel = 1
var connectionAlarmSound: NotificationSound = .alarm
var connectionError: String?
var connectionErrorIsCritical = false
var connectionErrorTimestamp: Date? = Date()
var connectionInfos: [SensorConnectionInfo] = []
var connectionState: SensorConnectionState = .disconnected
var customCalibration: [CustomCalibration] = []
var expiringAlarmSound: NotificationSound = .expiring
var glucoseBadge = true
var glucoseUnit: GlucoseUnit = .mgdL
var glucoseValues: [Glucose] = []
var highGlucoseAlarmSound: NotificationSound = .alarm
var internalHttpServer = false
var isPaired = false
var ignoreMute = false
var lowGlucoseAlarmSound: NotificationSound = .alarm
var missedReadings = 0
var nightscoutApiSecret = ""
var nightscoutUpload = false
var nightscoutUrl = ""
var readGlucose = false
var selectedCalendarTarget: String?
var selectedConnection: SensorBLEConnection?
var selectedConnectionId: String?
var selectedView = 1
var sensor: Sensor?
var sensorInterval = 1
var targetValue = 100
var transmitter: Transmitter?
}
| 30.86 | 70 | 0.727155 |
aba4079a4f5ee1069c417a6578d57f31f92fdc78 | 915 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
import Foundation
import azureSwiftRuntime
internal struct OutputDataSourceData : OutputDataSourceProtocol {
public init() {
}
public init(from decoder: Decoder) throws {
if var pageDecoder = decoder as? PageDecoder {
if pageDecoder.isPagedData,
let nextLinkName = pageDecoder.nextLinkName {
pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName)
}
}
}
public func encode(to encoder: Encoder) throws {
}
}
extension DataFactory {
public static func createOutputDataSourceProtocol() -> OutputDataSourceProtocol {
return OutputDataSourceData()
}
}
| 29.516129 | 119 | 0.71694 |
6aac736623b12a1ae67604b953fc9e37a62339b4 | 7,073 | //
// DiaryEditViewController.swift
// MindWeather-iOS
//
// Created by 이승주 on 2021/06/29.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
class DiaryEditViewController : UIViewController, UITextViewDelegate{
var diaryId = K.newDiaryValue
let diaryDetailViewModel = DiaryDetailViewModel()
let disposeBag = DisposeBag()
var willShowToken: NSObjectProtocol?
var willHideToken: NSObjectProtocol?
deinit {
if let token = willShowToken {
NotificationCenter.default.removeObserver(token)
}
if let token = willHideToken {
NotificationCenter.default.removeObserver(token)
}
}
@IBOutlet weak var dateText: UILabel!
@IBOutlet weak var content: UITextView!
@IBOutlet weak var yearText: UILabel!
@IBOutlet weak var explainText: UILabel!
@IBOutlet weak var loadingUI: UIActivityIndicatorView!
@IBOutlet weak var loadingText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
content.delegate = self
setTextView()
bindViewModel()
if diaryId != K.newDiaryValue {
dateText.isHidden = true
content.isHidden = true
yearText.isHidden = true
explainText.isHidden = true
loadingUI.isHidden = false
loadingUI.startAnimating()
loadingText.isHidden = true
diaryDetailViewModel.loadDiary(diaryId: diaryId)
} else {
diaryDetailViewModel.newStateDiary()
loadingUI.isHidden = true
loadingUI.stopAnimating()
loadingText.isHidden = true
}
}
private func bindViewModel() {
diaryDetailViewModel.content
.asDriver()
.drive(content.rx.text)
.disposed(by: disposeBag)
diaryDetailViewModel.date
.asDriver()
.drive(dateText.rx.text)
.disposed(by: disposeBag)
diaryDetailViewModel.year
.asDriver()
.drive(yearText.rx.text)
.disposed(by: disposeBag)
diaryDetailViewModel.receiver
.observe(on: MainScheduler.instance)
.subscribe(
onNext: { value in
if value == "addOrUpdateDiary" {
//일기 작성 or 수정 후 dismiss
self.dateText.isHidden = false
self.content.isHidden = false
self.yearText.isHidden = false
self.explainText.isHidden = false
self.loadingUI.isHidden = true
self.loadingUI.stopAnimating()
self.loadingText.isHidden = true
NotificationCenter.default.post(name: Notification.Name(rawValue: K.isUpdateDiarysNotificationName), object: nil)
NotificationCenter.default.post(name: Notification.Name(rawValue: K.isUpdateEmotionsNotificationName), object: nil)
self.dismiss(animated: true, completion: nil)
} else if value == "loadDiary" {
//로딩 ui 끄기
self.dateText.isHidden = false
self.content.isHidden = false
self.yearText.isHidden = false
self.explainText.isHidden = false
self.setUI()
self.loadingUI.isHidden = true
self.loadingUI.stopAnimating()
self.loadingText.isHidden = true
} else if value == "newStateDiary" {
self.content.text = " "
self.setUI()
self.content.text = ""
}
})
.disposed(by: disposeBag)
}
@IBAction func closeButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func addButtonPressed(_ sender: Any) {
guard let content = content.text else {
return
}
//로딩 ui 켜기
loadingUI.isHidden = false
loadingUI.startAnimating()
loadingText.isHidden = false
let sendContent = Content(content: content)
diaryDetailViewModel.addOrUpdateDiary(content: sendContent, diaryId: diaryId)
}
// 사용자가 바로 입력할 수 있도록 세팅
override func viewWillAppear(_ animated: Bool) {
self.content.becomeFirstResponder()
}
// 키보드 밖을 클릭하면 키보드가 내려가도록 세팅
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.content.resignFirstResponder()
}
// 키보드가 올라올 때 텍스트뷰를 가리지 않도록 세팅
private func setTextView() {
willShowToken = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: OperationQueue.main, using: { [weak self] (noti) in
guard let strongSelf = self else { return }
if let frame = noti.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let height = frame.cgRectValue.height
var inset = strongSelf.content.contentInset
inset.bottom = height - 80
strongSelf.content.contentInset = inset
inset = strongSelf.content.horizontalScrollIndicatorInsets
inset.bottom = height - 80
strongSelf.content.scrollIndicatorInsets = inset
}
})
willHideToken = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: OperationQueue.main, using: { [weak self] (noti) in
guard let strongSelf = self else { return }
var inset = strongSelf.content.contentInset
inset.bottom = 0
strongSelf.content.contentInset = inset
inset = strongSelf.content.horizontalScrollIndicatorInsets
inset.bottom = 0
strongSelf.content.scrollIndicatorInsets = inset
})
}
private func setUI() {
let attrString = NSMutableAttributedString(string: content.text ?? "")
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 6
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attrString.length))
content.attributedText = attrString
content.font = UIFont.AppleSDGothic(type: .NanumMyeongjo, size: 15)
content.textColor = UIColor(rgb: K.brownColor)
content.textAlignment = .center
}
}
| 36.086735 | 185 | 0.560158 |
e8be9aefcd28eade56be0a225bc0db6184910425 | 808 | //
// ContentView.swift
// Shared
//
// Created by Christopher Jennewein on 10/3/21.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink("Completion Example", destination: CompletionExampleView())
NavigationLink("Combine Example", destination: CombineExampleView())
NavigationLink("Async/Await Example", destination: AsyncAwaitExampleView())
NavigationLink("Paginated Results Example", destination: PaginatedResultsView())
}
#if os(iOS) || os(macOS)
.listStyle(.sidebar)
#endif
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 24.484848 | 96 | 0.60396 |
0861b7fb6d6a8b0872401a0836100644cb30cd17 | 2,880 | //
// AppLauncher.swift
// Launcher
//
// Created by ellipse42 on 15/12/12.
// Copyright © 2015年 ellipse42. All rights reserved.
//
import Foundation
import Appz
public func launchApp(_ type: String, action: String, extra: String, app: ApplicationCaller) {
switch type {
case "phone":
if action == "dial" {
let number = extra
app.open(Applications.Phone(), action: .open(number: number))
}
case "message":
if action == "send" {
let phone = extra
app.open(Applications.Messages(), action: .sms(phone: phone))
}
case "gallery":
if action == "open" {
app.open(Applications.Gallery(), action: .open)
}
case "safari":
if action == "open" {
app.open(Applications.Prefs(), action: .keyboard)
}
case "setting":
if action == "open" {
app.open(Applications.AppSettings(), action: .open)
}
case "weixin":
if action == "open" {
app.open(Applications.Weixin(), action: .open)
} else if action == "official_accounts" {
app.open(Applications.Weixin(), action: .officialAccounts)
} else if action == "scan" {
app.open(Applications.Weixin(), action: .scan)
} else if action == "profile" {
app.open(Applications.Weixin(), action: .profile)
} else if action == "moments" {
app.open(Applications.Weixin(), action: .moments)
}
case "orpheus":
if action == "open" {
app.open(Applications.Orpheus(), action: .open)
}
case "alipay":
if action == "open" {
app.open(Applications.Alipay(), action: .open)
}
case "zhihu":
if action == "open" {
app.open(Applications.Zhihu(), action: .open)
}
case "bilibili":
if action == "open" {
app.open(Applications.Bilibili(), action: .open)
}
case "uber":
if action == "open" {
app.open(Applications.Uber(), action: .open)
}
case "diditaxi":
if action == "open" {
app.open(Applications.DidiTaxi(), action: .open)
}
case "duokan-reader":
if action == "open" {
app.open(Applications.DuokanReader(), action: .open)
}
case "baidumap":
if action == "open" {
app.open(Applications.BaiduMap(), action: .open)
}
case "weibo":
if action == "open" {
app.open(Applications.Weibo(), action: .open)
}
case "note":
if action == "open" {
app.open(Applications.Notes(), action: .open)
}
case "setting":
if action == "open" {
app.open(Applications.AppSettings(), action: .open)
}
default:
print("item")
}
}
| 28.514851 | 94 | 0.522917 |
7944ea2390aeef85704415c4b7bf678e095caa51 | 259 | //
// Network.swift
// ARKKit
//
// Copyright © 2017 sleepdefic1t. All rights reserved.
//
import Foundation
public struct Network: Networkable {
public var
ip: String!,
hash: String!,
url: String!,
peers: [String]!
}
| 15.235294 | 55 | 0.590734 |
11308515149743af355f5f686a4ebfd51b427ca8 | 1,019 | //
// GameController.swift
// App
//
// Created by Alexander Skorulis on 26/6/18.
//
public class GameController {
public static let instance = GameController()
public let action:ActionController;
public let player:PlayerCharacterController;
public let city:CityController;
public let npc:NPCController
public let reference:ReferenceController
public let majorState:MajorStateController
public init() {
reference = ReferenceController.instance
action = ActionController(ref:reference)
city = CityController()
player = PlayerCharacterController(actions: action,city:city)
npc = NPCController(actions: action,city:city,ref:reference)
majorState = MajorStateController(player:player)
action.dayFinishObservers.add(object:self) {[unowned self] (controller) in
self.city.dayFinished()
self.player.dayFinished()
self.npc.dayFinished()
}
}
}
| 26.815789 | 82 | 0.662414 |
649a8edcd0edc4a69bb65d2c8e99b0047839f679 | 3,786 | //
// CustomTabBar.swift
// TestSwift
//
// Created by open-roc on 2018/9/10.
// Copyright © 2018年 open-roc. All rights reserved.
//
import UIKit
class UNCustomTabBar: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = WHITECOLOR;
self.setUpAllChildViewController();
// Do any additional setup after loading the view.
}
func setUpAllChildViewController(){
var homeImage = ""
var unHomeImage = ""
var personalImage = ""
var unPersonalImage = ""
var centerImage = ""
var unCenterImage = ""
var courseImage = ""
var unCourseImage = ""
var gongnegImage = ""
var unGongnegImage = ""
homeImage += "hover";
unHomeImage += "unhover";
courseImage += "icon_book_p";
unCourseImage += "icon_book_n";
centerImage += "icon_continue";
unCenterImage += "icon_continue";
gongnegImage += "icon_function_p";
unGongnegImage += "icon_function_n";
personalImage += "uesrhover";
unPersonalImage += "unuesrhover";
// self.tabBar.backgroundImage = imageWithColor(color: WHITECOLOR)
let home = UNHomeViewController.init()
self.setUpOneChildViewController(viewController: home, selectedImage:(UIImage.init(named: homeImage)?.withRenderingMode(.alwaysOriginal))!, unSelectedImage: (UIImage.init(named: unHomeImage)?.withRenderingMode(.alwaysOriginal))!, title: "首页", itemTag: 0)
let classification = UNCenterViewController.init()
self.setUpOneChildViewController(viewController: classification, selectedImage:(UIImage.init(named: courseImage)?.withRenderingMode(.alwaysOriginal))!, unSelectedImage: (UIImage.init(named: unCourseImage)?.withRenderingMode(.alwaysOriginal))!, title: "课程分类", itemTag: 0)
let MeVc = UNMineViewController.init()
self.setUpOneChildViewController(viewController: MeVc, selectedImage:(UIImage.init(named: personalImage)?.withRenderingMode(.alwaysOriginal))!, unSelectedImage: (UIImage.init(named: unPersonalImage)?.withRenderingMode(.alwaysOriginal))!, title: "我的", itemTag: 0)
}
func setUpOneChildViewController(viewController:UIViewController,selectedImage:UIImage,unSelectedImage:UIImage,title:NSString,itemTag:NSInteger){
let nav = CustomNavigationViewController.init(rootViewController: viewController)
nav.tabBarItem = UITabBarItem.init(title: title as String, image: unSelectedImage, selectedImage: selectedImage)
nav.tabBarItem.tag = itemTag;
nav.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -6)
nav.tabBarItem.setTitleTextAttributes([kCTForegroundColorAttributeName as NSAttributedString.Key:UIColor.orange], for: UIControl.State.normal)
nav.tabBarItem.setTitleTextAttributes([kCTForegroundColorAttributeName as NSAttributedString.Key:UIColor.blue], for: UIControl.State.selected)
self.addChild(nav)
}
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.
}
*/
}
| 36.057143 | 278 | 0.659535 |
e6ad5306bc6dcf4d10b45ad7e694874d682c0672 | 16,743 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2017 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import ObjectiveC
@_implementationOnly import _FoundationOverlayShims
// This exists to allow for dynamic dispatch on KVO methods added to NSObject.
// Extending NSObject with these methods would disallow overrides.
public protocol _KeyValueCodingAndObserving {}
extension NSObject : _KeyValueCodingAndObserving {}
public struct NSKeyValueObservedChange<Value> {
public typealias Kind = NSKeyValueChange
public let kind: Kind
///newValue and oldValue will only be non-nil if .new/.old is passed to `observe()`. In general, get the most up to date value by accessing it directly on the observed object instead.
public let newValue: Value?
public let oldValue: Value?
///indexes will be nil unless the observed KeyPath refers to an ordered to-many property
public let indexes: IndexSet?
///'isPrior' will be true if this change observation is being sent before the change happens, due to .prior being passed to `observe()`
public let isPrior:Bool
}
///Conforming to NSKeyValueObservingCustomization is not required to use Key-Value Observing. Provide an implementation of these functions if you need to disable auto-notifying for a key, or add dependent keys
public protocol NSKeyValueObservingCustomization : NSObjectProtocol {
static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath>
static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool
}
private extension NSObject {
@objc class func __old_unswizzled_automaticallyNotifiesObservers(forKey key: String?) -> Bool {
fatalError("Should never be reached")
}
@objc class func __old_unswizzled_keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> {
fatalError("Should never be reached")
}
}
// NOTE: older overlays called this _KVOKeyPathBridgeMachinery. The two
// must coexist, so it was renamed. The old name must not be used in the
// new runtime.
@objc private class __KVOKeyPathBridgeMachinery : NSObject {
@nonobjc static let swizzler: () = {
/*
Move all our methods into place. We want the following:
__KVOKeyPathBridgeMachinery's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replaces NSObject's versions of them
NSObject's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replace NSObject's __old_unswizzled_* methods
NSObject's _old_unswizzled_* methods replace __KVOKeyPathBridgeMachinery's methods, and are never invoked
*/
threeWaySwizzle(#selector(NSObject.keyPathsForValuesAffectingValue(forKey:)), with: #selector(NSObject.__old_unswizzled_keyPathsForValuesAffectingValue(forKey:)))
threeWaySwizzle(#selector(NSObject.automaticallyNotifiesObservers(forKey:)), with: #selector(NSObject.__old_unswizzled_automaticallyNotifiesObservers(forKey:)))
}()
/// Performs a 3-way swizzle between `NSObject` and `__KVOKeyPathBridgeMachinery`.
///
/// The end result of this swizzle is the following:
/// * `NSObject.selector` contains the IMP from `__KVOKeyPathBridgeMachinery.selector`
/// * `NSObject.unswizzledSelector` contains the IMP from the original `NSObject.selector`.
/// * __KVOKeyPathBridgeMachinery.selector` contains the (useless) IMP from `NSObject.unswizzledSelector`.
///
/// This swizzle is done in a manner that modifies `NSObject.selector` last, in order to ensure thread safety
/// (by the time `NSObject.selector` is swizzled, `NSObject.unswizzledSelector` will contain the original IMP)
@nonobjc private static func threeWaySwizzle(_ selector: Selector, with unswizzledSelector: Selector) {
let rootClass: AnyClass = NSObject.self
let bridgeClass: AnyClass = __KVOKeyPathBridgeMachinery.self
// Swap bridge.selector <-> NSObject.unswizzledSelector
let unswizzledMethod = class_getClassMethod(rootClass, unswizzledSelector)!
let bridgeMethod = class_getClassMethod(bridgeClass, selector)!
method_exchangeImplementations(unswizzledMethod, bridgeMethod)
// Swap NSObject.selector <-> NSObject.unswizzledSelector
// NSObject.unswizzledSelector at this point contains the bridge IMP
let rootMethod = class_getClassMethod(rootClass, selector)!
method_exchangeImplementations(rootMethod, unswizzledMethod)
}
private class BridgeKey : NSObject, NSCopying {
let value: String
init(_ value: String) {
self.value = value
}
func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func isEqual(_ object: Any?) -> Bool {
return value == (object as? BridgeKey)?.value
}
override var hash: Int {
var hasher = Hasher()
hasher.combine(ObjectIdentifier(BridgeKey.self))
hasher.combine(value)
return hasher.finalize()
}
}
/// Temporarily maps a `String` to an `AnyKeyPath` that can be retrieved with `_bridgeKeyPath(_:)`.
///
/// This uses a per-thread storage so key paths on other threads don't interfere.
@nonobjc static func _withBridgeableKeyPath(from keyPathString: String, to keyPath: AnyKeyPath, block: () -> Void) {
_ = __KVOKeyPathBridgeMachinery.swizzler
let key = BridgeKey(keyPathString)
let oldValue = Thread.current.threadDictionary[key]
Thread.current.threadDictionary[key] = keyPath
defer { Thread.current.threadDictionary[key] = oldValue }
block()
}
@nonobjc static func _bridgeKeyPath(_ keyPath:String?) -> AnyKeyPath? {
guard let keyPath = keyPath else { return nil }
return Thread.current.threadDictionary[BridgeKey(keyPath)] as? AnyKeyPath
}
@objc override class func automaticallyNotifiesObservers(forKey key: String) -> Bool {
//This is swizzled so that it's -[NSObject automaticallyNotifiesObserversForKey:]
if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = __KVOKeyPathBridgeMachinery._bridgeKeyPath(key) {
return customizingSelf.automaticallyNotifiesObservers(for: path)
} else {
return self.__old_unswizzled_automaticallyNotifiesObservers(forKey: key) //swizzled to be NSObject's original implementation
}
}
@objc override class func keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> {
//This is swizzled so that it's -[NSObject keyPathsForValuesAffectingValueForKey:]
if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = __KVOKeyPathBridgeMachinery._bridgeKeyPath(key!) {
let resultSet = customizingSelf.keyPathsAffectingValue(for: path)
return Set(resultSet.lazy.map {
guard let str = $0._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \($0)") }
return str
})
} else {
return self.__old_unswizzled_keyPathsForValuesAffectingValue(forKey: key) //swizzled to be NSObject's original implementation
}
}
}
func _bridgeKeyPathToString(_ keyPath:AnyKeyPath) -> String {
guard let keyPathString = keyPath._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \(keyPath)") }
return keyPathString
}
// NOTE: older overlays called this NSKeyValueObservation. We now use
// that name in the source code, but add an underscore to the runtime
// name to avoid conflicts when both are loaded into the same process.
@objc(_NSKeyValueObservation)
public class NSKeyValueObservation : NSObject {
// We use a private helper class as the actual observer. This lets us attach the helper as an associated object
// to the object we're observing, thus ensuring the helper will still be alive whenever a KVO change notification
// is broadcast, even on a background thread.
//
// For the associated object, we use the Helper instance itself as its own key. This guarantees key uniqueness.
private class Helper : NSObject {
@nonobjc weak var object : NSObject?
@nonobjc let path: String
@nonobjc let callback : (NSObject, NSKeyValueObservedChange<Any>) -> Void
// workaround for <rdar://problem/31640524> Erroneous (?) error when using bridging in the Foundation overlay
// specifically, overriding observeValue(forKeyPath:of:change:context:) complains that it's not Obj-C-compatible
@nonobjc static let swizzler: () = {
let cls = NSClassFromString("_NSKVOCompatibility") as? _NSKVOCompatibilityShim.Type
cls?._noteProcessHasUsedKVOSwiftOverlay()
let bridgeClass: AnyClass = Helper.self
let observeSel = #selector(NSObject.observeValue(forKeyPath:of:change:context:))
let swapSel = #selector(Helper._swizzle_me_observeValue(forKeyPath:of:change:context:))
let swapObserveMethod = class_getInstanceMethod(bridgeClass, swapSel)!
class_addMethod(bridgeClass, observeSel, method_getImplementation(swapObserveMethod), method_getTypeEncoding(swapObserveMethod))
}()
@nonobjc init(object: NSObject, keyPath: AnyKeyPath, options: NSKeyValueObservingOptions, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) {
_ = Helper.swizzler
let path = _bridgeKeyPathToString(keyPath)
self.object = object
self.path = path
self.callback = callback
super.init()
objc_setAssociatedObject(object, associationKey(), self, .OBJC_ASSOCIATION_RETAIN)
__KVOKeyPathBridgeMachinery._withBridgeableKeyPath(from: path, to: keyPath) {
object.addObserver(self, forKeyPath: path, options: options, context: nil)
}
}
@nonobjc func invalidate() {
guard let object = self.object else { return }
object.removeObserver(self, forKeyPath: path, context: nil)
objc_setAssociatedObject(object, associationKey(), nil, .OBJC_ASSOCIATION_ASSIGN)
self.object = nil
}
@nonobjc private func associationKey() -> UnsafeRawPointer {
return UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
}
@objc private func _swizzle_me_observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSString : Any]?, context: UnsafeMutableRawPointer?) {
guard let object = object as? NSObject, object === self.object, let change = change else { return }
let rawKind:UInt = change[NSKeyValueChangeKey.kindKey.rawValue as NSString] as! UInt
let kind = NSKeyValueChange(rawValue: rawKind)!
let notification = NSKeyValueObservedChange(kind: kind,
newValue: change[NSKeyValueChangeKey.newKey.rawValue as NSString],
oldValue: change[NSKeyValueChangeKey.oldKey.rawValue as NSString],
indexes: change[NSKeyValueChangeKey.indexesKey.rawValue as NSString] as! IndexSet?,
isPrior: change[NSKeyValueChangeKey.notificationIsPriorKey.rawValue as NSString] as? Bool ?? false)
callback(object, notification)
}
}
@nonobjc private let helper: Helper
fileprivate init(object: NSObject, keyPath: AnyKeyPath, options: NSKeyValueObservingOptions, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) {
helper = Helper(object: object, keyPath: keyPath, options: options, callback: callback)
}
///invalidate() will be called automatically when an NSKeyValueObservation is deinited
@objc public func invalidate() {
helper.invalidate()
}
deinit {
invalidate()
}
}
// Used for type-erase Optional type
private protocol _OptionalForKVO {
static func _castForKVO(_ value: Any) -> Any?
}
extension Optional: _OptionalForKVO {
static func _castForKVO(_ value: Any) -> Any? {
return value as? Wrapped
}
}
extension _KeyValueCodingAndObserving {
///when the returned NSKeyValueObservation is deinited or invalidated, it will stop observing
public func observe<Value>(
_ keyPath: KeyPath<Self, Value>,
options: NSKeyValueObservingOptions = [],
changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void)
-> NSKeyValueObservation {
return NSKeyValueObservation(object: self as! NSObject, keyPath: keyPath, options: options) { (obj, change) in
let converter = { (changeValue: Any?) -> Value? in
if let optionalType = Value.self as? _OptionalForKVO.Type {
// Special logic for keyPath having a optional target value. When the keyPath referencing a nil value, the newValue/oldValue should be in the form .some(nil) instead of .none
// Solve https://bugs.swift.org/browse/SR-6066
// NSNull is used by KVO to signal that the keyPath value is nil.
// If Value == Optional<T>.self, We will get nil instead of .some(nil) when casting Optional(<null>) directly.
// To fix this behavior, we will eliminate NSNull first, then cast the transformed value.
if let unwrapped = changeValue {
// We use _castForKVO to cast first.
// If Value != Optional<NSNull>.self, the NSNull value will be eliminated.
let nullEliminatedValue = optionalType._castForKVO(unwrapped) as Any
let transformedOptional: Any? = nullEliminatedValue
return transformedOptional as? Value
}
}
return changeValue as? Value
}
let notification = NSKeyValueObservedChange(kind: change.kind,
newValue: converter(change.newValue),
oldValue: converter(change.oldValue),
indexes: change.indexes,
isPrior: change.isPrior)
changeHandler(obj as! Self, notification)
}
}
public func willChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath))
}
public func willChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).willChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
}
public func willChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
(self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
}
public func didChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath))
}
public func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: __owned KeyPath<Self, Value>) {
(self as! NSObject).didChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath))
}
public func didChangeValue<Value>(for keyPath: __owned KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void {
(self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set)
}
}
| 53.321656 | 209 | 0.67037 |
0a6ea49c074cafd51ee0af63bc313e72e71f2d41 | 286 | // 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
enum A : A {
private class A : AnyObject) {
}
}
enum S<T where T.e : S
| 23.833333 | 87 | 0.713287 |
1c169f506c80a44b260d5f05bc1860c649c7d2bf | 1,801 | //
// 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 SwiftUI
@available(iOS 14.0, *)
struct TemplateUserProfileHeader: View {
// MARK: - Properties
// MARK: Private
@Environment(\.theme) private var theme: ThemeSwiftUI
// MARK: Public
let avatar: AvatarInputProtocol?
let displayName: String?
let presence: TemplateUserProfilePresence
var body: some View {
VStack {
if let avatar = avatar {
AvatarImage(avatarData: avatar, size: .xxLarge)
.padding(.vertical)
}
VStack(spacing: 8){
Text(displayName ?? "")
.font(theme.fonts.title3)
.accessibility(identifier: "displayNameText")
.padding(.horizontal)
.lineLimit(1)
TemplateUserProfilePresenceView(presence: presence)
}
}
}
}
// MARK: - Previews
@available(iOS 14.0, *)
struct TemplateUserProfileHeader_Previews: PreviewProvider {
static var previews: some View {
TemplateUserProfileHeader(avatar: MockAvatarInput.example, displayName: "Alice", presence: .online)
.addDependency(MockAvatarService.example)
}
}
| 30.525424 | 107 | 0.636868 |
79ae72ffd76896f9d9a5e0d674f79a896780f915 | 436 | //
// ObstructableView.swift
// MemoryChainKit
//
// Created by Marc Steven on 2020/4/21.
// Copyright © 2020 Marc Steven All rights reserved.
//
import Foundation
/// A protocol to indicate that conforming view is obstructing the screen
/// (e.g., interstitial view).
///
/// Such information is useful when certain actions can't be triggered,
/// for example, in-app deep-linking routing.
public protocol ObstructableView { }
| 22.947368 | 73 | 0.722477 |
4b5157fd6e56473aed0de4d1fb32042bc9874e47 | 23,310 | //
// StringExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension String {
/// SwifterSwift: String decoded from base64 (if applicable).
public var base64Decoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
guard let decodedData = Data(base64Encoded: self) else {
return nil
}
return String(data: decodedData, encoding: .utf8)
}
/// SwifterSwift: String encoded in base64 (if applicable).
public var base64Encoded: String? {
// https://github.com/Reza-Rg/Base64-Swift-Extension/blob/master/Base64.swift
let plainData = data(using: .utf8)
return plainData?.base64EncodedString()
}
/// SwifterSwift: Array of characters of a string.
public var charactersArray: [Character] {
return Array(characters)
}
/// SwifterSwift: CamelCase of string.
public var camelCased: String {
let source = lowercased()
if source.characters.contains(" ") {
let first = source.substring(to: source.index(after: source.startIndex))
let camel = source.capitalized.replacing(" ", with: "").replacing("\n", with: "")
let rest = String(camel.characters.dropFirst())
return first + rest
}
let first = source.lowercased().substring(to: source.index(after: source.startIndex))
let rest = String(source.characters.dropFirst())
return first + rest
}
/// SwifterSwift: Check if string contains one or more emojis.
public var containEmoji: Bool {
// http://stackoverflow.com/questions/30757193/find-out-if-character-in-string-is-emoji
for scalar in unicodeScalars {
switch scalar.value {
case 0x3030, 0x00AE, 0x00A9, // Special Characters
0x1D000...0x1F77F, // Emoticons
0x2100...0x27BF, // Misc symbols and Dingbats
0xFE00...0xFE0F, // Variation Selectors
0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs
return true
default:
continue
}
}
return false
}
/// SwifterSwift: First character of string (if applicable).
public var firstCharacter: String? {
guard let first = characters.first else {
return nil
}
return String(first)
}
/// SwifterSwift: Check if string contains one or more letters.
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
}
/// SwifterSwift: Check if string contains one or more numbers.
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal, range: nil) != nil
}
/// SwifterSwift: Check if string contains only letters.
public var isAlphabetic: Bool {
return hasLetters && !hasNumbers
}
/// SwifterSwift: Check if string contains at least one letter and one number.
public var isAlphaNumeric: Bool {
return components(separatedBy: CharacterSet.alphanumerics).joined(separator: "").characters.count == 0 && hasLetters && hasNumbers
}
/// SwifterSwift: Check if string is valid email format.
public var isEmail: Bool {
// http://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
return matches(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
}
/// SwifterSwift: Check if string is a valid URL.
public var isValidUrl: Bool {
return URL(string: self) != nil
}
/// SwifterSwift: Check if string is a valid schemed URL.
public var isValidSchemedUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme != nil
}
/// SwifterSwift: Check if string is a valid https URL.
public var isValidHttpsUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme == "https"
}
/// SwifterSwift: Check if string is a valid http URL.
public var isValidHttpUrl: Bool {
guard let url = URL(string: self) else {
return false
}
return url.scheme == "http"
}
/// SwifterSwift: Check if string contains only numbers.
public var isNumeric: Bool {
return !hasLetters && hasNumbers
}
/// SwifterSwift: Last character of string (if applicable).
public var lastCharacter: String? {
guard let last = characters.last else {
return nil
}
return String(last)
}
/// SwifterSwift: Latinized string.
public var latinized: String {
return folding(options: .diacriticInsensitive, locale: Locale.current)
}
/// SwifterSwift: Number of characters in string.
public var length: Int {
return characters.count
}
/// SwifterSwift: Array of strings separated by new lines.
public var lines: [String] {
var result = [String]()
enumerateLines { line, _ in
result.append(line)
}
return result
}
/// SwifterSwift: The most common character in string.
public var mostCommonCharacter: String {
let mostCommon = withoutSpacesAndNewLines.characters.reduce([Character: Int]()) {
var counts = $0
counts[$1] = ($0[$1] ?? 0) + 1
return counts
}.max { $0.1 < $1.1 }?.0
return mostCommon?.string ?? ""
}
/// SwifterSwift: Reversed string.
public var reversed: String {
return String(characters.reversed())
}
/// SwifterSwift: Bool value from string (if applicable).
public var bool: Bool? {
let selfLowercased = trimmed.lowercased()
if selfLowercased == "true" || selfLowercased == "1" {
return true
} else if selfLowercased == "false" || selfLowercased == "0" {
return false
}
return nil
}
/// SwifterSwift: Date object from "yyyy-MM-dd" formatted string
public var date: Date? {
let selfLowercased = trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
return formatter.date(from: selfLowercased)
}
/// SwifterSwift: Date object from "yyyy-MM-dd HH:mm:ss" formatted string.
public var dateTime: Date? {
let selfLowercased = trimmed.lowercased()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.date(from: selfLowercased)
}
/// SwifterSwift: Double value from string (if applicable).
public var double: Double? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Double
}
/// SwifterSwift: Float value from string (if applicable).
public var float: Float? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float
}
/// SwifterSwift: Float32 value from string (if applicable).
public var float32: Float32? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float32
}
/// SwifterSwift: Float64 value from string (if applicable).
public var float64: Float64? {
let formatter = NumberFormatter()
return formatter.number(from: self) as? Float64
}
/// SwifterSwift: Integer value from string (if applicable).
public var int: Int? {
return Int(self)
}
/// SwifterSwift: Int16 value from string (if applicable).
public var int16: Int16? {
return Int16(self)
}
/// SwifterSwift: Int32 value from string (if applicable).
public var int32: Int32? {
return Int32(self)
}
/// SwifterSwift: Int64 value from string (if applicable).
public var int64: Int64? {
return Int64(self)
}
/// SwifterSwift: Int8 value from string (if applicable).
public var int8: Int8? {
return Int8(self)
}
/// SwifterSwift: URL from string (if applicable).
public var url: URL? {
return URL(string: self)
}
/// SwifterSwift: String with no spaces or new lines in beginning and end.
public var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
/// SwifterSwift: Array with unicodes for all characters in a string.
public var unicodeArray: [Int] {
return unicodeScalars.map({$0.hashValue})
}
/// SwifterSwift: Readable string from a URL string.
public var urlDecoded: String {
return removingPercentEncoding ?? self
}
/// SwifterSwift: URL escaped string.
public var urlEncoded: String {
return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
/// SwifterSwift: String without spaces and new lines.
public var withoutSpacesAndNewLines: String {
return replacing(" ", with: "").replacing("\n", with: "")
}
}
// MARK: - Methods
public extension String {
/// SwifterSwift: Safely subscript string with index.
///
/// - Parameter i: index.
public subscript(i: Int) -> String? {
guard i >= 0 && i < characters.count else {
return nil
}
return String(self[index(startIndex, offsetBy: i)])
}
/// SwifterSwift: Safely subscript string within a half-open range.
///
/// - Parameter range: Half-open range.
public subscript(range: CountableRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) else {
return nil
}
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) else {
return nil
}
return self[lowerIndex..<upperIndex]
}
/// SwifterSwift: Safely subscript string within a closed range.
///
/// - Parameter range: Closed range.
public subscript(range: ClosedRange<Int>) -> String? {
guard let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) else {
return nil
}
guard let upperIndex = index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) else {
return nil
}
return self[lowerIndex..<upperIndex]
}
#if os(iOS) || os(macOS)
/// SwifterSwift: Copy string to global pasteboard.
public func copyToPasteboard() {
#if os(iOS)
UIPasteboard.general.string = self
#elseif os(macOS)
NSPasteboard.general().clearContents()
NSPasteboard.general().setString(self, forType: NSPasteboardTypeString)
#endif
}
#endif
/// SwifterSwift: Converts string format to CamelCase.
public mutating func camelize() {
self = camelCased
}
/// SwifterSwift: Check if string contains one or more instance of substring.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string contains one or more instance of substring.
public func contains(_ string: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return range(of: string, options: .caseInsensitive) != nil
}
return range(of: string) != nil
}
/// SwifterSwift: Count of substring in string.
///
/// - Parameters:
/// - string: substring to search for.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: count of appearance of substring in string.
public func count(of string: String, caseSensitive: Bool = true) -> Int {
if !caseSensitive {
return lowercased().components(separatedBy: string.lowercased()).count - 1
}
return components(separatedBy: string).count - 1
}
/// SwifterSwift: Check if string ends with substring.
///
/// - Parameters:
/// - suffix: substring to search if string ends with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string ends with substring.
public func ends(with suffix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasSuffix(suffix.lowercased())
}
return hasSuffix(suffix)
}
/// SwifterSwift: First index of substring in string.
///
/// - Parameter string: substring to search for.
/// - Returns: first index of substring in string (if applicable).
public func firstIndex(of string: String) -> Int? {
return Array(characters).map({String($0)}).index(of: string)
}
/// SwifterSwift: Latinize string.
public mutating func latinize() {
self = latinized
}
/// SwifterSwift: Random string of given length.
///
/// - Parameter length: number of characters in string.
/// - Returns: random string of given length.
public static func random(ofLength length: Int) -> String {
guard length > 0 else { return "" }
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return (0..<length).reduce("") {
let randomIndex = arc4random_uniform(UInt32(base.characters.count))
let randomCharacter = "\(base[base.index(base.startIndex, offsetBy: IndexDistance(randomIndex))])"
return $0.0 + randomCharacter
}
}
/// SwifterSwift: String by replacing part of string with another string.
///
/// - Parameters:
/// - substring: old substring to find and replace.
/// - newString: new string to insert in old string place.
/// - Returns: string after replacing substring with newString.
public func replacing(_ substring: String, with newString: String) -> String {
return replacingOccurrences(of: substring, with: newString)
}
/// SwifterSwift: Reverse string.
public mutating func reverse() {
self = String(characters.reversed())
}
/// SwifterSwift: Sliced string from a start index with length.
///
/// - Parameters:
/// - i: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
/// - Returns: sliced substring of length number of characters (if applicable) (example: "Hello World".slicing(from: 6, length: 5) -> "World")
public func slicing(from i: Int, length: Int) -> String? {
guard length >= 0, i >= 0, i < characters.count else {
return nil
}
guard i.advanced(by: length) <= characters.count else {
return slicing(at: i)
}
guard length > 0 else {
return ""
}
return self[i..<i.advanced(by: length)]
}
/// SwifterSwift: Slice given string from a start index with length (if applicable).
///
/// - Parameters:
/// - i: string index the slicing should start from.
/// - length: amount of characters to be sliced after given index.
public mutating func slice(from i: Int, length: Int) {
if let str = slicing(from: i, length: length) {
self = str
}
}
/// SwifterSwift: Sliced string from a start index to an end index.
///
/// - Parameters:
/// - start: string index the slicing should start from.
/// - end: string index the slicing should end at.
/// - Returns: sliced substring starting from start index, and ends at end index (if applicable) (example: "Hello World".slicing(from: 6, to: 11) -> "World")
public func slicing(from start: Int, to end: Int) -> String? {
guard end >= start else {
return nil
}
return self[start..<end]
}
/// SwifterSwift: Slice given string from a start index to an end index (if applicable).
///
/// - Parameters:
/// - start: string index the slicing should start from.
/// - end: string index the slicing should end at.
public mutating func slice(from start: Int, to end: Int) {
if let str = slicing(from: start, to: end) {
self = str
}
}
/// SwifterSwift: Sliced string from a start index.
///
/// - Parameter i: string index the slicing should start from.
/// - Returns: sliced substring starting from start index (if applicable) (example: "Hello world".slicing(at: 6) -> "world")
public func slicing(at i: Int) -> String? {
guard i < characters.count else {
return nil
}
return self[i..<characters.count]
}
/// SwifterSwift: Slice given string from a start index (if applicable).
///
/// - Parameter i: string index the slicing should start from.
public mutating func slice(at i: Int) {
if let str = slicing(at: i) {
self = str
}
}
/// SwifterSwift: Array of strings separated by given string.
///
/// - Parameter separator: separator to split string by.
/// - Returns: array of strings separated by given string.
public func splitted(by separator: Character) -> [String] {
return characters.split{$0 == separator}.map(String.init)
}
/// SwifterSwift: Check if string starts with substring.
///
/// - Parameters:
/// - suffix: substring to search if string starts with.
/// - caseSensitive: set true for case sensitive search (default is true).
/// - Returns: true if string starts with substring.
public func starts(with prefix: String, caseSensitive: Bool = true) -> Bool {
if !caseSensitive {
return lowercased().hasPrefix(prefix.lowercased())
}
return hasPrefix(prefix)
}
/// SwifterSwift: Date object from string of date format.
///
/// - Parameter format: date format.
/// - Returns: Date object from string (if applicable).
public func date(withFormat format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.date(from: self)
}
/// SwifterSwift: Removes spaces and new lines in beginning and end of string.
public mutating func trim() {
self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// SwifterSwift: Truncate string (cut it to a given number of characters).
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string (default is "...").
public mutating func truncate(toLength: Int, trailing: String? = "...") {
guard toLength > 0 else {
return
}
if characters.count > toLength {
self = substring(to: index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
}
/// SwifterSwift: Truncated string (limited to a given number of characters).
///
/// - Parameters:
/// - toLength: maximum number of characters before cutting.
/// - trailing: string to add at the end of truncated string.
/// - Returns: truncated string (this is an extr...).
public func truncated(toLength: Int, trailing: String? = "...") -> String {
guard 1..<characters.count ~= toLength else { return self }
return substring(to: index(startIndex, offsetBy: toLength)) + (trailing ?? "")
}
/// SwifterSwift: Convert URL string to readable string.
public mutating func urlDecode() {
if let decoded = removingPercentEncoding {
self = decoded
}
}
/// SwifterSwift: Escape string.
public mutating func urlEncode() {
if let encoded = addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
self = encoded
}
}
/// SwifterSwift: Verify if string matches the regex pattern.
/// - Parameter pattern: Pattern to verify.
/// - Returns: true if string matches the pattern.
func matches(pattern: String) -> Bool {
return range(of: pattern,
options: String.CompareOptions.regularExpression,
range: nil, locale: nil) != nil
}
}
// MARK: - Operators
public extension String {
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: string to repeat.
/// - rhs: number of times to repeat character.
/// - Returns: new string with given string repeated n times.
static public func * (lhs: String, rhs: Int) -> String {
guard rhs > 0 else {
return ""
}
return String(repeating: lhs, count: rhs)
}
/// SwifterSwift: Repeat string multiple times.
///
/// - Parameters:
/// - lhs: number of times to repeat character.
/// - rhs: string to repeat.
/// - Returns: new string with given string repeated n times.
static public func * (lhs: Int, rhs: String) -> String {
guard lhs > 0 else {
return ""
}
return String(repeating: rhs, count: lhs)
}
}
// MARK: - Initializers
public extension String {
/// SwifterSwift: Create a new string from a base64 string (if applicable).
///
/// - Parameter base64: base64 string.
public init?(base64: String) {
guard let str = base64.base64Decoded else {
return nil
}
self.init(str)
}
/// SwifterSwift: Create a new random string of given length.
///
/// - Parameter length: number of characters in string.
public init(randomOfLength length: Int) {
self = String.random(ofLength: length)
}
}
// MARK: - NSAttributedString extensions
public extension String {
#if !os(tvOS) && !os(watchOS)
/// SwifterSwift: Bold string.
public var bold: NSAttributedString {
#if os(macOS)
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: NSFont.boldSystemFont(ofSize: NSFont.systemFontSize())])
#else
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
#endif
}
#endif
/// SwifterSwift: Underlined string
public var underline: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
}
/// SwifterSwift: Strikethrough string.
public var strikethrough: NSAttributedString {
return NSAttributedString(string: self, attributes: [NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)])
}
#if os(iOS)
/// SwifterSwift: Italic string.
public var italic: NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
#if os(macOS)
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: NSColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
}
#else
/// SwifterSwift: Add color to string.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString versions of string colored with given color.
public func colored(with color: UIColor) -> NSAttributedString {
return NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
}
#endif
}
//MARK: - NSString extensions
public extension String {
/// SwifterSwift: NSString from a string.
public var nsString: NSString {
return NSString(string: self)
}
/// SwifterSwift: NSString lastPathComponent.
public var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
/// SwifterSwift: NSString pathExtension.
public var pathExtension: String {
return (self as NSString).pathExtension
}
/// SwifterSwift: NSString deletingLastPathComponent.
public var deletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
/// SwifterSwift: NSString deletingPathExtension.
public var deletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
/// SwifterSwift: NSString pathComponents.
public var pathComponents: [String] {
return (self as NSString).pathComponents
}
/// SwifterSwift: NSString appendingPathComponent(str: String)
///
/// - Parameter str: the path component to append to the receiver.
/// - Returns: a new string made by appending aString to the receiver, preceded if necessary by a path separator.
public func appendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
/// SwifterSwift: NSString appendingPathExtension(str: String)
///
/// - Parameter str: The extension to append to the receiver.
/// - Returns: a new string made by appending to the receiver an extension separator followed by ext (if applicable).
public func appendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
}
| 31.038615 | 158 | 0.7 |
b99b88851117db55379b98d1b8283796fc622e99 | 6,222 | //
// Dijkstra.swift
// Swift6006
//
// Created by Barış Deniz Sağlam on 17.08.2020.
// Copyright © 2020 BDS. All rights reserved.
//
import Foundation
extension WeightedGraph {
func exploreDijkstra(from source: Vertex)
-> WeightedGraphSearch<Vertex, Weight>
{
var distanceMap: [Vertex: Weight] = [:]
var parentshipMap: [Vertex: Vertex] = [:]
for vertex in vertices() {
distanceMap[vertex] = Weight.max
}
distanceMap[source] = 0
var pq = vertices()
while !pq.isEmpty {
let u = pq.min { (x, y) -> Bool in
distanceMap[x]! < distanceMap[y]!
}!
pq.remove(u)
let du = distanceMap[u]!
guard du != Weight.max else { continue }
// relax edges
for v in neighbors(of: u) {
let w = weightOfEdge(u: u, v: v)
let duv = du + w
if duv < distanceMap[v]! {
distanceMap[v] = duv
parentshipMap[v] = u
}
}
}
return WeightedGraphSearch(
source: source,
parentshipMap: parentshipMap,
distanceMap: distanceMap
)
}
}
extension WeightedGraph {
func shortestPathDijkstra(from source: Vertex, to target: Vertex)
-> [Vertex]?
{
var distanceMap: [Vertex: Weight] = [:]
var parentshipMap: [Vertex: Vertex] = [:]
let vs = vertices()
for vertex in vs {
distanceMap[vertex] = Weight.max
}
distanceMap[source] = 0
var pq = vs
while !pq.isEmpty {
let u = pq.min { (x, y) -> Bool in
distanceMap[x]! < distanceMap[y]!
}!
if u == target { break } // already found target, can stop early
pq.remove(u)
let du = distanceMap[u]!
guard du != Weight.max else { continue }
// relax edges
for v in neighbors(of: u) {
let w = weightOfEdge(u: u, v: v)
let duv = du + w
if duv < distanceMap[v]! {
distanceMap[v] = duv
parentshipMap[v] = u
}
}
}
let gs = WeightedGraphSearch(
source: source,
parentshipMap: parentshipMap,
distanceMap: distanceMap
)
return gs.path(to: target)
}
func shortestPathBiDijkstra(from source: Vertex, to target: Vertex)
-> [Vertex]?
{
var distanceMapForward: [Vertex: Weight] = [:]
var parentshipMapForward: [Vertex: Vertex] = [:]
var distanceMapBackward: [Vertex: Weight] = [:]
var parentshipMapBackward: [Vertex: Vertex] = [:]
let vs = vertices()
for vertex in vs {
distanceMapForward[vertex] = Weight.max
distanceMapBackward[vertex] = Weight.max
}
distanceMapForward[source] = 0
distanceMapBackward[target] = 0
var pqForward = vs
var pqBackward = vs
let transposedWG = transposed()
var forward = true
var lastVertex: Vertex? = nil
outerLoop: while !pqForward.isEmpty && !pqBackward.isEmpty {
if forward {
let u = pqForward.min { (x, y) -> Bool in
distanceMapForward[x]! < distanceMapForward[y]!
}!
if u == target { break outerLoop }
pqForward.remove(u)
let du = distanceMapForward[u]!
guard du != Weight.max else { continue }
if u == lastVertex { break outerLoop}
lastVertex = u
// relax edges
for v in self.neighbors(of: u) {
let w = self.weightOfEdge(u: u, v: v)
let duv = du + w
if duv < distanceMapForward[v]! {
distanceMapForward[v] = duv
parentshipMapForward[v] = u
}
}
} else {
let u = pqBackward.min { (x, y) -> Bool in
distanceMapBackward[x]! < distanceMapBackward[y]!
}!
if u == source { break outerLoop }
pqBackward.remove(u)
let du = distanceMapBackward[u]!
guard du != Weight.max else { continue }
if u == lastVertex { break outerLoop}
lastVertex = u
// relax edges
for v in transposedWG.neighbors(of: u) {
let w = transposedWG.weightOfEdge(u: u, v: v)
let duv = du + w
if duv < distanceMapBackward[v]! {
distanceMapBackward[v] = duv
parentshipMapBackward[v] = u
}
}
}
forward = !forward
}
let intersection = distanceMapForward
.map { (u, df) -> (Vertex, Weight) in
guard let db = distanceMapBackward[u], df < Weight.max && db < Weight.max
else { return (u, Weight.max) }
return (u, df + db)
}
.min { $0.1 < $1.1 }
guard let intersectionVertex = intersection?.0 else { return nil }
let gsForward = WeightedGraphSearch(source: source, parentshipMap: parentshipMapForward, distanceMap: distanceMapForward)
let gsBackward = WeightedGraphSearch(source: target, parentshipMap: parentshipMapBackward, distanceMap: distanceMapBackward)
var pathForward = gsForward.path(to: intersectionVertex)!
let pathBackward = gsBackward.path(to: intersectionVertex)!
pathForward.append(contentsOf: pathBackward.dropLast().reversed())
return pathForward
}
}
| 32.575916 | 132 | 0.474446 |
d95703ff551a1ed41a15112c2c80af1c042920d6 | 293 | //
// Validatable.swift
// MassiveValidator
//
// Created by Julio Collado on 3/29/20.
// Copyright © 2020 Altimetrik. All rights reserved.
//
import Foundation
public protocol Validatable {
func isValid(_ value: String, completion: ((_ errorDescription: String?) -> ())?) -> Bool
}
| 20.928571 | 93 | 0.686007 |
29de9f1f63ad1653279dce428c9b05556879fd7a | 1,299 | //
// SocketResponse.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/22/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import Starscream
public struct SocketResponse {
var socket: WebSocket?
var result: JSON
// JSON Data
var id: String?
var msg: ResponseMessage?
var collection: String?
var event: String?
// MARK: Initializer
init?(_ result: JSON, socket: WebSocket?) {
self.result = result
self.socket = socket
self.id = result["id"].string
self.collection = result["collection"].string
if let eventName = result["fields"]["eventName"].string {
self.event = eventName
}
if let msg = result["msg"].string {
self.msg = ResponseMessage(rawValue: msg) ?? ResponseMessage.unknown
// Sometimes response is an error, but the "msg" isn't.
if self.msg == ResponseMessage.unknown {
if self.isError() {
self.msg = ResponseMessage.error
}
}
}
}
// MARK: Checks
func isError() -> Bool {
if msg == .error || result["error"] != JSON.null {
return true
}
return false
}
}
| 22.789474 | 80 | 0.562741 |
690e2839c7530bd8ae125fb55958bf5f24089157 | 4,540 | //
// UIButton+DSL.swift
// Swiftesla
//
// Created by xudongzhang on 2018/9/13.
//
import Foundation
public extension UIButton {
@discardableResult
func title(_ text: String, _ state: UIControl.State = .normal) -> Self {
setTitle(text, for: state)
return self
}
@discardableResult
func color(_ color: UIColor, _ state: UIControl.State = .normal) -> Self {
setTitleColor(color, for: state)
return self
}
@discardableResult
func font(_ font: UIFont) -> Self {
titleLabel?.font = font
return self
}
@discardableResult
func font(_ fontSize: Float) -> Self {
titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
return self
}
@discardableResult
func font(_ fontSize: Int) -> Self {
titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
return self
}
@discardableResult
func boldFont(_ fontSize: Float) -> Self {
titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
return self
}
@discardableResult
func boldFont(_ fontSize: Int) -> Self {
titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(fontSize))
return self
}
@discardableResult
func image(_ image: UIImage?, _ state: UIControl.State = .normal) -> Self {
setImage(image, for: state)
return self
}
@discardableResult
func image(in bundle: Bundle? = nil, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: bundle, compatibleWith: nil)
setImage(image, for: state)
return self
}
@discardableResult
func image(in bundle: Bundle, name imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: bundle, compatibleWith: nil)
setImage(image, for: state)
return self
}
@discardableResult
func image(for aClass: AnyClass, name imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: Bundle(for: aClass), compatibleWith: nil)
setImage(image, for: state)
return self
}
@discardableResult
func image(forParent aClass: AnyClass, bundleName: String, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
guard let path = Bundle(for: aClass).path(forResource: bundleName, ofType: "bundle") else {
return self
}
let image = UIImage(named: imageName, in: Bundle(path: path), compatibleWith: nil)
setImage(image, for: state)
return self
}
@discardableResult
func image(_ color: UIColor, _ state: UIControl.State = .normal) -> Self {
let image = UIImage.imageWithColor(color)
setImage(image, for: state)
return self
}
@discardableResult
func bgImage(_ image: UIImage?, _ state: UIControl.State = .normal) -> Self {
setBackgroundImage(image, for: state)
return self
}
@discardableResult
func bgImage(forParent aClass: AnyClass, bundleName: String, _ imageName: String, _: UIControl.State = .normal) -> Self {
guard let path = Bundle(for: aClass).path(forResource: bundleName, ofType: "bundle") else {
return self
}
let image = UIImage(named: imageName, in: Bundle(path: path), compatibleWith: nil)
setBackgroundImage(image, for: state)
return self
}
@discardableResult
func bgImage(in bundle: Bundle? = nil, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: bundle, compatibleWith: nil)
setBackgroundImage(image, for: state)
return self
}
@discardableResult
func bgImage(for aClass: AnyClass, _ imageName: String, _ state: UIControl.State = .normal) -> Self {
let image = UIImage(named: imageName, in: Bundle(for: aClass), compatibleWith: nil)
setBackgroundImage(image, for: state)
return self
}
@discardableResult
func bgImage(_ color: UIColor, _ state: UIControl.State = .normal) -> Self {
let image = UIImage.imageWithColor(color)
setBackgroundImage(image, for: state)
return self
}
@discardableResult
func textColor(_ color: UIColor?, state: UIControl.State = .normal) -> Self {
setTitleColor(color, for: state)
return self
}
}
| 32.198582 | 129 | 0.631938 |
8f37348455a3b9cf4e28ea91e3a1ef02f91a3a4e | 2,161 | //
// HHDicomDecoderUtils.swift
// HHDicom
//
// Created by iOS on 2017/4/20.
// Copyright © 2017年 HH. All rights reserved.
//
import UIKit
struct DecoderUtils
{
static let Bit_8: Int = 8
static let Bit_16: Int = 16
static let Max_Bit16: Int = 65535
}
struct CreateImage
{
static func create(config:ImageConfig) ->UIImage?
{
guard let aPixels = config.pixels else { return nil }
let width = config.width
let height = config.height
let capacity = aPixels.count
let data = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity)
data.initialize(from: aPixels, count: capacity)
let bytesPerRow = config.space * width
let context = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: config.colorSpace, bitmapInfo: config.bitmapInfo.rawValue)
guard let cgImage = context?.makeImage() else { return nil }
data.deallocate(capacity: aPixels.count)
return UIImage(cgImage: cgImage)
}
}
struct ImageConfig
{
var width = 0
var height = 0
var pixels: [UInt8]?
var space = 1
var colorSpace = CGColorSpaceCreateDeviceGray()
var bitmapInfo = CGBitmapInfo(rawValue:CGImageAlphaInfo.none.rawValue)
}
struct ImageBuilder
{
var width = 0
var height = 0
var pixels: [UInt8]?
init(w:Int,h:Int,pData:[UInt8]?)
{
width = w
height = h
pixels = pData
}
func builde(gray:Bool) ->ImageConfig
{
var config = ImageConfig()
config.height = height
config.width = width
config.pixels = pixels
if !gray
{
config.colorSpace = CGColorSpaceCreateDeviceRGB()
config.bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue )
config.space = 4
}
return config
}
}
| 19.294643 | 186 | 0.561777 |
ded76fe2fd97449754b9eb539a0950e935dd2764 | 781 | //
// Endpoint.swift
// Shortcuts
//
// Created by Ryan Leake on 05/02/2022.
//
import Foundation
struct Endpoint<Response: Decodable> {
var path: String
var query: String?
}
extension Endpoint {
func makeRequest() -> URLRequest? {
var components = URLComponents()
components.scheme = "https"
components.host = "swifted.io"
components.path = "/" + path
if let query = query {
components.path += "/" + query
}
guard let url = components.url else {
return nil
}
let request = URLRequest(url: url)
return request
}
}
extension Endpoint where Response == [Shortcut] {
static var shortcuts: Self {
Endpoint(path: "json/shortcuts.json")
}
}
| 20.025641 | 49 | 0.580026 |
e97247201b4a5ab9192479fe65fb8e7635e3434f | 3,479 |
import UIKit
class FoodInfoView: UIView {
var foodInfo:Food?{
willSet{
DispatchQueue.main.async {
self.img.image = UIImage(named: self.foodInfo?.img ?? "")
self.name.text = self.foodInfo?.name
self.price.text = self.foodInfo?.price
self.descriptions.text = self.foodInfo?.descriptions
}
}
}
var img:UIImageView={
let img = UIImageView()
img.translatesAutoresizingMaskIntoConstraints = false
img.backgroundColor = .clear
img.layer.cornerRadius = .cornerRadius
img.contentMode = .scaleAspectFill
img.layer.masksToBounds = true
return img
}()
var name:UILabel={
let label = UILabel()
label.Label(textColor: .Dark, textAlignment: .left, fontSize: 20, font: .AppleSDGothicNeo_SemiBold)
return label
}()
var price:UILabel={
let label = UILabel()
label.Label(textColor: .systemOrange, textAlignment: .left, fontSize: 25, font: .AppleSDGothicNeo_Bold)
return label
}()
var descriptions:UILabel={
let label = UILabel()
label.Label(textColor: .Light, textAlignment: .center, fontSize: 15, font: .AppleSDGothicNeo_Light)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addsubviews(){
self.layer.cornerRadius = .cornerRadius
self.layer.masksToBounds = true
self.backgroundColor = .systemGray6
self.addSubview(img)
NSLayoutConstraint.activate([
img.topAnchor.constraint(equalTo: self.topAnchor, constant: .topConstant),
img.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: .leftConstant*2),
img.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: .rightConstant),
img.heightAnchor.constraint(equalToConstant: 140)
])
self.addSubview(name)
NSLayoutConstraint.activate([
name.topAnchor.constraint(equalTo: img.bottomAnchor, constant: .topConstant),
name.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: .leftConstant*2),
name.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: .rightConstant),
name.heightAnchor.constraint(equalToConstant: 40)
])
self.addSubview(price)
NSLayoutConstraint.activate([
price.topAnchor.constraint(equalTo: name.bottomAnchor, constant: .topConstant),
price.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: .leftConstant*2),
price.widthAnchor.constraint(equalToConstant: 100),
price.heightAnchor.constraint(equalToConstant: 40)
])
self.addSubview(descriptions)
NSLayoutConstraint.activate([
descriptions.topAnchor.constraint(equalTo: name.bottomAnchor, constant: .topConstant),
descriptions.leadingAnchor.constraint(equalTo: price.trailingAnchor, constant: .leftConstant),
descriptions.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: .rightConstant),
descriptions.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: .bottomConstant),
])
}
}
| 37.010638 | 111 | 0.640126 |
8f11e3a2407d29720d92a8b27c79c985db54fc63 | 2,652 | //
// CSVDocument.swift
// App
//
// Created by Martin Prot on 22/03/2018.
//
import Foundation
struct CSVParser {
struct Defaults {
static let separator = ";"
static let quote = "\""
}
enum ParsingError: Error {
case quoteInNotQuotedWord
case letterOutsideQuotedWord
case eofInQuotedWord
}
enum State {
case wordStart
case inWord
case firstQuote
case secondQuote
}
let csvData: String
let separator: Character
let quote: Character
init(csvData: String, separator: String = Defaults.separator) {
guard let sep = separator.first, let quote = Defaults.quote.first else {
fatalError("wrong separator given to csv parser")
}
self.csvData = csvData
self.separator = sep
self.quote = quote
}
func parse() throws -> [[String]] {
var state = State.wordStart
var word: [Character] = []
var columns: [String] = []
var lines: [[String]] = []
try self.csvData.forEach { char in
// first, check if new line
guard String(char).rangeOfCharacter(from: CharacterSet.newlines) == nil else {
switch state {
case .wordStart:
columns.append("")
lines.append(columns)
columns.removeAll()
case .inWord:
columns.append(String(word))
word.removeAll()
lines.append(columns)
columns.removeAll()
state = .wordStart
case .firstQuote:
word.append(char)
case .secondQuote:
columns.append(String(word))
word.removeAll()
lines.append(columns)
columns.removeAll()
state = .wordStart
}
return
}
switch state {
case .wordStart:
switch char {
case separator:
columns.append("")
case quote:
state = .firstQuote
default:
word.append(char)
state = .inWord
}
case .inWord:
switch char {
case separator:
columns.append(String(word))
word.removeAll()
state = .wordStart
case quote:
throw ParsingError.quoteInNotQuotedWord
default:
word.append(char)
}
case .firstQuote:
switch char {
case separator:
word.append(char)
case quote:
state = .secondQuote
default:
word.append(char)
}
case .secondQuote:
switch char {
case separator:
columns.append(String(word))
word.removeAll()
state = .wordStart
case quote:
word.append(char)
state = .firstQuote
default:
throw ParsingError.letterOutsideQuotedWord
}
}
}
switch state {
case .wordStart, .inWord, .secondQuote:
columns.append(String(word))
lines.append(columns)
case .firstQuote:
throw ParsingError.eofInQuotedWord
}
return lines
}
}
| 19.5 | 81 | 0.638386 |
ddb7de8af5ce6b597ffc4941d3075b822577640a | 1,149 | //
// ViewModelCell.swift
// CoreCollection
//
// Created by Пользователь on 24/04/2019.
// Copyright © 2019 com.skibinalexander.ru. All rights reserved.
//
import UIKit
public protocol ViewModelCellProtocol: ViewModelProtocol {
var indexPath: IndexPath! { get set }
func willSelect()
func didSelect()
func willDeselect()
func didDeselect()
func willDisplay()
func didHighlight()
func didUnhighlight()
func shouldHighlight() -> Bool
func editingStyle() -> UITableViewCell.EditingStyle
func shouldIndentWhileEditing() -> Bool
}
open class ViewModelCell<V: ViewCellProtocol, M: ModelCellProtocol>:
ViewModel<V, M>, ViewModelCellProtocol {
public var indexPath: IndexPath!
open func willDisplay() { }
open func willSelect() {}
open func didSelect() {}
open func willDeselect() {}
open func didDeselect() {}
open func didHighlight() {}
open func didUnhighlight() {}
open func shouldHighlight() -> Bool { true }
open func editingStyle() -> UITableViewCell.EditingStyle { .none }
open func shouldIndentWhileEditing() -> Bool { false }
}
| 27.357143 | 70 | 0.680592 |
8a006a967b37d71922612c09bbdaa635c6f80408 | 2,955 | //
// AppDelegate.swift
// CoreDataMigration-Example
//
// Created by William Boles on 11/09/2017.
// Copyright © 2017 William Boles. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// MARK: - AppLifecycle
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
guard ProcessInfo.processInfo.environment["runningTests"] == nil else {
FileManager.clearApplicationSupportDirectoryContents()
return true
}
CoreDataManager.shared.setup {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { // just for example purposes
self.presentMainUI()
}
}
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:.
// Saves changes in the application's managed object context before the application terminates.
try? CoreDataManager.shared.mainContext.save()
}
// MARK: - Main
func presentMainUI() {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
window?.rootViewController = mainStoryboard.instantiateInitialViewController()
}
}
| 44.104478 | 285 | 0.718443 |
ed1541ec75bd9786cce03ce0d366d80e0314f978 | 831 | //
// ValueBoxTransformersTests.swift
// Data
//
// Created by Ryne Cheow on 25/5/17.
// Copyright © 2017 Pointwelve. All rights reserved.
//
@testable import Data
import Domain
import RxSwift
import XCTest
class ValueBoxTransformersTests: XCTestCase {
let disposeBag = DisposeBag()
func testValueBoxTransformerTransform() {
let intToStringTransformer = ValueTransformerBox<Int, String> {
number in
Observable.just("\(number)")
}
let expect = expectation(description: "Transform int to string int")
intToStringTransformer
.transform(123)
.subscribe(onNext: {
XCTAssertEqual("123", $0)
expect.fulfill()
}).disposed(by: disposeBag)
waitForExpectations(timeout: 1) { error in
XCTAssertNil(error)
}
}
}
| 23.083333 | 74 | 0.648616 |
098a75265ca916d3bb3ee153488c6228f6a0cabe | 721 | //
// WKWebView+Scripts.swift
// AviasalesSDKTemplate
//
// Created by Dim on 28.03.2018.
// Copyright © 2018 Go Travel Un Limited. All rights reserved.
//
import WebKit
extension WKWebView {
convenience init(scripts: [String]) {
let userContentController = WKUserContentController()
scripts.forEach { (script) in
let userScript = WKUserScript.init(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
userContentController.addUserScript(userScript)
}
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
self.init(frame: .zero, configuration: configuration)
}
}
| 30.041667 | 118 | 0.700416 |