repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TheInfiniteKind/duckduckgo-iOS | Core/AppUrls.swift | 1 | 2608 | //
// AppUrls.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 24/01/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import Foundation
public struct AppUrls {
private struct Url {
static let base = "duckduckgo.com"
static let home = "https://www.duckduckgo.com/?ko=-1&kl=wt-wt"
static let autocomplete = "https://duckduckgo.com/ac/"
static let favicon = "https://duckduckgo.com/favicon.ico"
}
private struct Param {
static let search = "q"
static let safeSearch = "kp"
static let regionFilter = "kl"
static let dateFilter = "df"
}
private struct ParamValue {
static let safeSearchOff = "-1"
}
public static var base: URL {
return URL(string: Url.base)!
}
public static var favicon: URL {
return URL(string: Url.favicon)!
}
public static var home: URL {
return URL(string: Url.home)!
}
public static func isDuckDuckGo(url: URL) -> Bool {
return url.absoluteString.contains(Url.base)
}
public static func searchQuery(fromUrl url: URL) -> String? {
if !isDuckDuckGo(url: url) {
return nil
}
return url.getParam(name: Param.search)
}
public static func url(forQuery query: String, filters: SearchFilterStore) -> URL? {
if let url = URL.webUrl(fromText: query) {
return url
}
if let searchUrl = searchUrl(text: query, filters: filters) {
return searchUrl
}
return nil
}
public static func searchUrl(text: String, filters: SearchFilterStore) -> URL? {
let url = addfilters(filters, toUrl: home)
return url.addParam(name: Param.search, value: text)
}
private static func addfilters(_ filters: SearchFilterStore, toUrl url: URL) -> URL {
var filteredUrl = url
if !filters.safeSearchEnabled {
filteredUrl = filteredUrl.addParam(name: Param.safeSearch, value: ParamValue.safeSearchOff)
}
if let regionFilter = filters.regionFilter {
filteredUrl = filteredUrl.addParam(name: Param.regionFilter, value: regionFilter)
}
if let dateFilter = filters.dateFilter {
filteredUrl = filteredUrl.addParam(name: Param.dateFilter, value: dateFilter)
}
return filteredUrl
}
public static func autocompleteUrl(forText text: String) -> URL? {
return URL(string: Url.autocomplete)?.addParam(name: Param.search, value: text)
}
}
| apache-2.0 | 7733bdaf5f0f82fd7d8a8bb0335f4e1d | 29.313953 | 103 | 0.608362 | 4.131537 | false | false | false | false |
darrarski/SharedShopping-iOS | SharedShoppingAppTests/UI/Table/ViewModels/TableRowViewModelStub.swift | 1 | 1523 | import UIKit
@testable import SharedShoppingApp
class TableRowViewModelStub: TableRowViewModel {
init(shopping: Shopping) {
self.shopping = shopping
}
let shopping: Shopping
var estimatedHeightStub = CGFloat(66)
var heightStub = CGFloat(55)
var cellStub = UITableViewCell(style: .default, reuseIdentifier: "")
var actionsStub: [UITableViewRowAction]?
var registerInTableViewCalled: (UITableView)?
var estimatedHeightCalled = false
var heightCalled = false
var cellAtIndexPathInTableViewCalled: (IndexPath, UITableView)?
var actionsCalled = false
var didSelectCalled = false
// MARK: TableRowViewModel
func register(in tableView: UITableView) {
registerInTableViewCalled = (tableView)
}
var estimatedHeight: CGFloat {
estimatedHeightCalled = true
return estimatedHeightStub
}
var height: CGFloat {
heightCalled = true
return heightStub
}
func cell(at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell {
cellAtIndexPathInTableViewCalled = (indexPath, tableView)
return cellStub
}
var actions: [UITableViewRowAction]? {
actionsCalled = true
return actionsStub
}
func isEqual(to other: TableRowViewModel) -> Bool {
guard let other = other as? TableRowViewModelStub else { return false }
return shopping.isEqual(to: other.shopping)
}
func didSelect() {
didSelectCalled = true
}
}
| mit | 3f569e956b42633dcc0b78540b38393b | 24.813559 | 86 | 0.682206 | 5.043046 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TableViewDataSources/NotificationsDataSource.swift | 1 | 8442 | //
// NotificationsDataSource.swift
// Habitica
//
// Created by Phillip Thelen on 23.04.19.
// Copyright © 2019 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
import PinLayout
class NotificationsDataSource: BaseReactiveTableViewDataSource<NotificationProtocol> {
weak var viewController: UIViewController?
private let userRepository = UserRepository()
private let inventoryRepository = InventoryRepository()
private let socialRepository = SocialRepository()
override init() {
super.init()
sections.append(ItemSection<NotificationProtocol>())
fetchNotifications()
}
private func fetchNotifications() {
disposable.add(userRepository.getNotifications().on(value: {[weak self] (entries, changes) in
self?.sections[0].items = entries
self?.notify(changes: changes)
}).start())
}
func headerView(forSection section: Int, frame: CGRect) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 54))
view.backgroundColor = ThemeService.shared.theme.contentBackgroundColor
if sections[0].items.isEmpty {
return view
}
let label = UILabel()
label.font = CustomFontMetrics.scaledSystemFont(ofSize: 14)
label.textColor = ThemeService.shared.theme.secondaryTextColor
label.text = L10n.Titles.notifications.uppercased()
view.addSubview(label)
label.pin.start(16).sizeToFit().vCenter()
let pillLabel = UILabel()
pillLabel.font = CustomFontMetrics.scaledSystemFont(ofSize: 12)
pillLabel.textColor = ThemeService.shared.theme.secondaryTextColor
pillLabel.backgroundColor = ThemeService.shared.theme.offsetBackgroundColor
pillLabel.textAlignment = .center
pillLabel.text = "\(sections[0].items.count)"
view.addSubview(pillLabel)
pillLabel.pin.after(of: label).marginStart(8).sizeToFit().wrapContent(padding: 8)
pillLabel.pin.width(pillLabel.frame.size.width + 12).height(pillLabel.frame.size.height + 4).vCenter()
pillLabel.cornerRadius = pillLabel.frame.size.height/2
let button = UIButton()
button.setTitle(L10n.Notifications.dismissAll, for: .normal)
button.backgroundColor = .clear
button.setTitleColor(ThemeService.shared.theme.tintColor, for: .normal)
view.addSubview(button)
button.pin.top().bottom().sizeToFit(.height).end(16)
button.addTarget(self, action: #selector(dismissAll), for: .touchUpInside)
let separator = UIView()
separator.backgroundColor = ThemeService.shared.theme.tableviewSeparatorColor
view.addSubview(separator)
separator.pin.start().end().bottom().height(1)
return view
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let notification = item(at: indexPath) else {
return UITableViewCell()
}
let cell = tableView.dequeueReusableCell(withIdentifier: notification.type.rawValue, for: indexPath)
cell.backgroundColor = ThemeService.shared.theme.contentBackgroundColor
if !notification.isValid { return cell }
switch notification.type {
case .unallocatedStatsPoints:
if let cell = cell as? UnallocatedPointsNotificationCell, let notif = notification as? NotificationUnallocatedStatsProtocol {
cell.configureFor(notification: notif)
cell.closeAction = { [weak self] in self?.dismiss(notification: notification) }
}
case .newStuff:
if let cell = cell as? NewsNotificationCell, let notif = notification as? NotificationNewsProtocol {
cell.configureFor(notification: notif)
cell.closeAction = { [weak self] in self?.dismiss(notification: notification) }
}
case .newChatMessage:
if let cell = cell as? UnreadGroupNotificationCell, let notif = notification as? NotificationNewChatProtocol {
cell.configureFor(notification: notif)
cell.closeAction = { [weak self] in self?.dismiss(notification: notification) }
}
case .newMysteryItem:
if let cell = cell as? NewMysteryItemNotificationCell, let notif = notification as? NotificationNewMysteryItemProtocol {
cell.configureFor(notification: notif)
cell.closeAction = { [weak self] in self?.dismiss(notification: notification) }
}
case .questInvite:
if let cell = cell as? QuestInviteNotificationCell, let notif = notification as? NotificationQuestInviteProtocol {
if let quest = try? inventoryRepository.getQuest(key: notif.questKey ?? "").first()?.get() {
cell.configureFor(quest: quest)
}
cell.configureFor(notification: notif)
cell.declineAction = { [weak self] in self?.socialRepository.rejectQuestInvitation(groupID: "party").observeCompleted {
self?.dismiss(notification: notification)
}
}
cell.acceptAction = { [weak self] in self?.socialRepository.acceptQuestInvitation(groupID: "party").observeCompleted {
self?.dismiss(notification: notification)
}
}
}
case .groupInvite:
if let cell = cell as? GroupInviteNotificationCell, let notif = notification as? NotificationGroupInviteProtocol {
cell.configureFor(notification: notif)
cell.declineAction = { [weak self] in self?.socialRepository.rejectGroupInvitation(groupID: notif.groupID ?? "").observeCompleted {
self?.dismiss(notification: notification)
}
}
cell.acceptAction = { [weak self] in self?.socialRepository.joinGroup(groupID: notif.groupID ?? "").observeCompleted {
self?.dismiss(notification: notification)
}
}
}
default:
cell.textLabel?.text = notification.id
}
return cell
}
func didSelectedNotificationAt(indexPath: IndexPath) {
if let notification = item(at: indexPath) {
openNotification(notification: notification)
}
}
private func dismiss(notification: NotificationProtocol) {
disposable.add(userRepository.readNotification(notification: notification).observeCompleted { })
}
@objc
private func dismissAll() {
let dismissableNotifications = sections[0].items.filter { (notification) -> Bool in
return notification.isDismissable
}
disposable.add(userRepository.readNotifications(notifications: dismissableNotifications).observeCompleted {})
}
private func openNotification(notification: NotificationProtocol) {
// This could be handled better
var url: String?
switch notification.type {
case .groupInvite:
if let notif = notification as? NotificationGroupInviteProtocol {
if notif.isParty {
url = "/party"
} else {
if !notif.isPublicGuild {
return
}
url = "/groups/guild/\(notif.groupID ?? "")"
}
}
case .newChatMessage:
if let notif = notification as? NotificationNewChatProtocol {
if notif.isParty {
url = "/party"
} else {
url = "/groups/guild/\(notif.groupID ?? "")"
}
}
case .questInvite:
url = "/party"
case .unallocatedStatsPoints:
url = "/user/stats"
case .newMysteryItem:
url = "/inventory/items"
case .newStuff:
url = "/static/new-stuff"
default:
break
}
if let url = url {
viewController?.dismiss(animated: true) {
RouterHandler.shared.handle(urlString: url)
}
}
}
}
| gpl-3.0 | e2d280926aa3b2192c319a2928afdeb0 | 42.066327 | 147 | 0.612368 | 5.150092 | false | false | false | false |
mitchellporter/PullToBounce | PullToBounce/Source/WaveView.swift | 23 | 3164 | //
// PullToWaveView.swift
// BezierPathAnimation
//
// Created by Takuya Okamoto on 2015/08/11.
// Copyright (c) 2015年 Uniface. All rights reserved.
//
import UIKit
class WaveView: UIView, UIGestureRecognizerDelegate {
var didEndPull: (()->())?
var bounceDuration:CFTimeInterval!
var waveLayer:CAShapeLayer!
init(frame:CGRect, bounceDuration:CFTimeInterval = 0.4, color:UIColor = UIColor.whiteColor()) {
self.bounceDuration = bounceDuration
super.init(frame:frame)
waveLayer = CAShapeLayer(layer: self.layer)
waveLayer.lineWidth = 0
waveLayer.path = wavePath(amountX: 0.0, amountY: 0.0)
waveLayer.strokeColor = color.CGColor
waveLayer.fillColor = color.CGColor
self.layer.addSublayer(waveLayer)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func wave(y:CGFloat) {
self.waveLayer.path = self.wavePath(amountX: 0, amountY: y)
}
func didRelease(#amountX: CGFloat,amountY: CGFloat) {
self.boundAnimation(positionX: amountX, positionY: amountY)
didEndPull?()
}
func boundAnimation(#positionX: CGFloat,positionY: CGFloat) {
self.waveLayer.path = self.wavePath(amountX: 0, amountY: 0)
var bounce = CAKeyframeAnimation(keyPath: "path")
bounce.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
var values = [
self.wavePath(amountX: positionX, amountY: positionY),
self.wavePath(amountX: -(positionX * 0.7), amountY: -(positionY * 0.7)),
self.wavePath(amountX: positionX * 0.4, amountY: positionY * 0.4),
self.wavePath(amountX: -(positionX * 0.3), amountY: -(positionY * 0.3)),
self.wavePath(amountX: positionX * 0.15, amountY: positionY * 0.15),
self.wavePath(amountX: 0.0, amountY: 0.0)
]
bounce.values = values
bounce.duration = bounceDuration
bounce.removedOnCompletion = true
bounce.fillMode = kCAFillModeForwards
bounce.delegate = self
self.waveLayer.addAnimation(bounce, forKey: "return")
}
func wavePath(#amountX:CGFloat, amountY:CGFloat) -> CGPathRef {
let w = self.frame.width
let h = self.frame.height
let centerY:CGFloat = 0
let bottomY = h
var topLeftPoint = CGPointMake(0, centerY)
var topMidPoint = CGPointMake(w / 2 + amountX, centerY + amountY)
var topRightPoint = CGPointMake(w, centerY)
let bottomLeftPoint = CGPointMake(0, bottomY)
let bottomRightPoint = CGPointMake(w, bottomY)
var bezierPath = UIBezierPath()
bezierPath.moveToPoint(bottomLeftPoint)
bezierPath.addLineToPoint(topLeftPoint)
bezierPath.addQuadCurveToPoint(topRightPoint, controlPoint: topMidPoint)
bezierPath.addLineToPoint(bottomRightPoint)
return bezierPath.CGPath
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
waveLayer.path = wavePath(amountX: 0.0, amountY: 0.0)
}
} | mit | a4af8fb7403dd8c4c45532a331ab3d21 | 36.211765 | 99 | 0.651486 | 4.530086 | false | false | false | false |
hrscy/TodayNews | News/News/Classes/Mine/View/UserDetailHeaderView.swift | 1 | 24065 | //
// UserDetailHeaderView.swift
// News
//
// Created by 杨蒙 on 2017/11/30.
// Copyright © 2017年 hrscy. All rights reserved.
//
// ****************不再使用************************
//
import UIKit
import IBAnimatable
import Kingfisher
import SVProgressHUD
class UserDetailHeaderView: UIView, NibLoadable {
/// 点击了 用户名
var didSelectHeaderUserID: ((_ uid: Int)->())?
/// 点击了 话题
var didSelectHeaderTopicID: ((_ cid: Int)->())?
/// 刷新的指示器
var maxCursor = 0
var wendaCursor = ""
/// 当前选中的 topTab 的索引,点击了第几个
var currentSelectedIndex = 0
/// 当前的 topTab 类型
var currentTopTabType: TopTabType = .dongtai {
didSet {
let tableView = bottomScrollView.subviews[currentSelectedIndex] as! UITableView
switch currentTopTabType {
// 如果已经显示过了,就不再刷新数据了
case .dongtai: // 动态
// 设置 footer
setupFooter(tableView, completionHandler: { (dongtais) in
self.dongtais += dongtais
tableView.reloadData()
})
if !isDongtaisShown {
isDongtaisShown = true
tableView.reloadData()
}
// 获取用户详情的问答列表数据
NetworkTool.loadUserDetailWendaList(userId: userDetail!.user_id, cursor: wendaCursor, completionHandler: { (cursor, wendas) in
self.wendas = wendas
self.wendaCursor = cursor
})
case .article: // 文章
// 设置 footer
setupFooter(tableView, completionHandler: { (dongtais) in
self.articles += dongtais
tableView.reloadData()
})
if !isArticlesShown {
isArticlesShown = true
tableView.mj_footer.beginRefreshing()
}
case .video: // 视频
// 设置 footer
setupFooter(tableView, completionHandler: { (dongtais) in
self.videos += dongtais
tableView.reloadData()
})
if !isVideosShown {
isVideosShown = true
tableView.mj_footer.beginRefreshing()
}
case .wenda: // 问答
tableView.mj_footer = RefreshAutoGifFooter(refreshingBlock: { [weak self] in
// 获取用户详情的问答列表更多数据
NetworkTool.loadUserDetailLoadMoreWendaList(userId: self!.userDetail!.user_id, cursor: self!.wendaCursor, completionHandler: { (cursor, wendas) in
self!.wendaCursor = cursor
if tableView.mj_footer.isRefreshing { tableView.mj_footer.endRefreshing() }
tableView.mj_footer.pullingPercent = 0.0
if wendas.count == 0 {
tableView.mj_footer.endRefreshingWithNoMoreData()
SVProgressHUD.showInfo(withStatus: "没有更多数据啦!")
return
}
self!.wendas += wendas
tableView.reloadData()
})
})
if !isWendasShown {
isWendasShown = true
tableView.reloadData()
}
case .iesVideo: // 小视频
// 设置 footer
setupFooter(tableView, completionHandler: { (dongtais) in
self.iesVideos += dongtais
tableView.reloadData()
})
if !isIesVideosShown {
isIesVideosShown = true
tableView.mj_footer.beginRefreshing()
}
}
}
}
/// 设置 footer
private func setupFooter(_ tableView: UITableView, completionHandler:@escaping ((_ datas: [UserDetailDongtai])->())) {
tableView.mj_footer = RefreshAutoGifFooter(refreshingBlock: { [weak self] in
NetworkTool.loadUserDetailDongtaiList(userId: self!.userDetail!.user_id, maxCursor: self!.maxCursor, completionHandler: { (cursor, dongtais) in
if tableView.mj_footer.isRefreshing { tableView.mj_footer.endRefreshing() }
tableView.mj_footer.pullingPercent = 0.0
if dongtais.count == 0 {
tableView.mj_footer.endRefreshingWithNoMoreData()
SVProgressHUD.showInfo(withStatus: "没有更多数据啦!")
return
}
self!.maxCursor = cursor
completionHandler(dongtais)
})
})
}
/// 动态数据 数组
var dongtais = [UserDetailDongtai]()
var articles = [UserDetailDongtai]()
var videos = [UserDetailDongtai]()
var wendas = [UserDetailWenda]()
var iesVideos = [UserDetailDongtai]()
/// 记录当前的数据是否刷新过
var isDongtaisShown = false
var isArticlesShown = false
var isVideosShown = false
var isWendasShown = false
var isIesVideosShown = false
var userDetail: UserDetail? {
didSet {
backgroundImageView.kf.setImage(with: URL(string: userDetail!.bg_img_url)!)
avatarImageView.kf.setImage(with: URL(string: userDetail!.avatar_url)!)
vImageView.isHidden = !userDetail!.user_verified
nameLabel.text = userDetail!.screen_name
if userDetail!.verified_agency == "" {
verifiedAgencyLabelHeight.constant = 0
verifiedAgencyLabelTop.constant = 0
} else {
verifiedAgencyLabel.text = userDetail!.verified_agency + ":"
verifiedContentLabel.text = userDetail!.verified_content
}
concernButton.isSelected = userDetail!.is_following
concernButton.theme_backgroundColor = userDetail!.is_following ? "colors.userDetailFollowingConcernBtnBgColor" : "colors.globalRedColor"
concernButton.borderColor = userDetail!.is_following ? .grayColor232() : .globalRedColor()
concernButton.borderWidth = userDetail!.is_following ? 1 : 0
if userDetail!.area == "" {
areaButton.isHidden = true
areaButtonHeight.constant = 0
areaButtonTop.constant = 0
} else {
areaButton.setTitle(userDetail!.area, for: .normal)
}
descriptionLabel.text = userDetail!.description as String
if userDetail!.descriptionHeight > 21 {
unfoldButton.isHidden = false
unfoldButtonWidth.constant = 40.0
}
// 推荐按钮的约束
recommendButtonWidth.constant = 0
recommendButtonTrailing.constant = 10.0
followersCountLabel.text = userDetail!.followersCount
followingsCountLabel.text = userDetail!.followingsCount
if userDetail!.top_tab.count > 0 {
// 添加按钮和 tableView
for (index, topTab) in userDetail!.top_tab.enumerated() {
// 添加按钮
let button = UIButton(frame: CGRect(x: CGFloat(index) * topTabButtonWidth, y: 0, width: topTabButtonWidth, height: scrollView.height))
button.setTitle(topTab.show_name, for: .normal)
button.tag = index
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.theme_setTitleColor("colors.black", forState: .normal)
button.theme_setTitleColor("colors.globalRedColor", forState: .selected)
button.addTarget(self, action: #selector(topTabButtonClicked), for: .touchUpInside)
scrollView.addSubview(button)
if index == 0 {
button.isSelected = true
privorButton = button
}
// 添加 tableView
let tableView = UITableView(frame: CGRect(x: CGFloat(index) * screenWidth, y: 0, width: screenWidth, height: bottomScrollView.height))
if topTab.type == .wenda {
tableView.ym_registerCell(cell: UserDetailWendaCell.self)
} else {
tableView.ym_registerCell(cell: UserDetailDongTaiCell.self)
}
if userDetail!.bottom_tab.count == 0 { tableView.contentInset = UIEdgeInsetsMake(0, 0, 34, 0) }
tableView.delegate = self
tableView.dataSource = self
tableView.isScrollEnabled = false
tableView.showsVerticalScrollIndicator = false
tableView.separatorStyle = .none
tableView.tableFooterView = UIView()
bottomScrollView.addSubview(tableView)
if index == userDetail!.top_tab.count - 1 {
scrollView.contentSize = CGSize(width: button.frame.maxX, height: scrollView.height)
bottomScrollView.contentSize = CGSize(width: tableView.frame.maxX, height: bottomScrollView.height)
}
}
scrollView.addSubview(indicatorView)
} else {
topTabHeight.constant = 0
topTabView.isHidden = true
}
layoutIfNeeded()
}
}
/// topTab 指示条
private lazy var indicatorView: UIView = {
let indicatorView = UIView(frame: CGRect(x: (topTabButtonWidth - topTabindicatorWidth) * 0.5 , y: topTabView.height - 3, width: topTabindicatorWidth, height: topTabindicatorHeight))
indicatorView.theme_backgroundColor = "colors.globalRedColor"
return indicatorView
}()
weak var privorButton = UIButton()
/// 点击了头像
var didSelectAvatarImageView: (()->())?
/// 点击了 cell
var didSelectCellWithDongtai: ((_ dongtai: UserDetailDongtai)->())?
/// 背景图片
@IBOutlet weak var backgroundImageView: UIImageView!
/// 背景图片顶部约束
@IBOutlet weak var bgImageViewTop: NSLayoutConstraint!
/// 用户头像
@IBOutlet weak var avatarImageView: UIImageView!
/// V 图标
@IBOutlet weak var vImageView: UIImageView!
/// 用户名
@IBOutlet weak var nameLabel: UILabel!
/// 头条号图标
@IBOutlet weak var toutiaohaoImageView: UIImageView!
/// 发私信按钮
@IBOutlet weak var sendMailButton: UIButton!
/// 关注按钮
@IBOutlet weak var concernButton: AnimatableButton!
/// 推荐按钮
@IBOutlet weak var recommendButton: AnimatableButton!
@IBOutlet weak var recommendButtonWidth: NSLayoutConstraint!
@IBOutlet weak var recommendButtonTrailing: NSLayoutConstraint!
/// 推荐 view
@IBOutlet weak var recommendView: UIView!
@IBOutlet weak var recommendViewHeight: NSLayoutConstraint!
/// 头条认证
@IBOutlet weak var verifiedAgencyLabel: UILabel!
@IBOutlet weak var verifiedAgencyLabelHeight: NSLayoutConstraint!
@IBOutlet weak var verifiedAgencyLabelTop: NSLayoutConstraint!
/// 认证内容
@IBOutlet weak var verifiedContentLabel: UILabel!
/// 地区
@IBOutlet weak var areaButton: UIButton!
@IBOutlet weak var areaButtonHeight: NSLayoutConstraint!
@IBOutlet weak var areaButtonTop: NSLayoutConstraint!
/// 描述内容
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var descriptionLabelHeight: NSLayoutConstraint!
/// 展开按钮
@IBOutlet weak var unfoldButton: UIButton!
@IBOutlet weak var unfoldButtonTrailing: NSLayoutConstraint!
@IBOutlet weak var unfoldButtonWidth: NSLayoutConstraint!
/// 关注数量
@IBOutlet weak var followingsCountLabel: UILabel!
/// 粉丝数量
@IBOutlet weak var followersCountLabel: UILabel!
// 文章 视频 问答
@IBOutlet weak var topTabView: UIView!
@IBOutlet weak var topTabHeight: NSLayoutConstraint!
@IBOutlet weak var separatorView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
/// 底层 view
@IBOutlet weak var baseView: UIView!
/// 底部的 ScrollView
@IBOutlet weak var bottomScrollView: UIScrollView!
/// 自定义的推荐 view
fileprivate lazy var relationRecommendView: RelationRecommendView = {
let relationRecommendView = RelationRecommendView.loadViewFromNib()
return relationRecommendView
}()
override func awakeFromNib() {
super.awakeFromNib()
concernButton.setTitle("关注", for: .normal)
concernButton.setTitle("已关注", for: .selected)
// 设置主题颜色
theme_backgroundColor = "colors.cellBackgroundColor"
baseView.theme_backgroundColor = "colors.cellBackgroundColor"
avatarImageView.layer.theme_borderColor = "colors.cellBackgroundColor"
topTabView.theme_backgroundColor = "colors.cellBackgroundColor"
separatorView.theme_backgroundColor = "colors.separatorViewColor"
nameLabel.theme_textColor = "colors.black"
sendMailButton.theme_setTitleColor("colors.userDetailSendMailTextColor", forState: .normal)
unfoldButton.theme_setTitleColor("colors.userDetailSendMailTextColor", forState: .normal)
followersCountLabel.theme_textColor = "colors.userDetailSendMailTextColor"
followingsCountLabel.theme_textColor = "colors.userDetailSendMailTextColor"
concernButton.theme_setTitleColor("colors.userDetailConcernButtonTextColor", forState: .normal)
concernButton.theme_setTitleColor("colors.userDetailConcernButtonSelectedTextColor", forState: .selected)
verifiedAgencyLabel.theme_textColor = "colors.verifiedAgencyTextColor"
verifiedContentLabel.theme_textColor = "colors.black"
descriptionLabel.theme_textColor = "colors.black"
descriptionLabel.theme_textColor = "colors.black"
toutiaohaoImageView.theme_image = "images.toutiaohao"
areaButton.theme_setTitleColor("colors.black", forState: .normal)
NotificationCenter.default.addObserver(self, selector: #selector(receivedConcernButtonClicked), name: NSNotification.Name(rawValue: NavigationBarConcernButtonClicked), object: nil)
SVProgressHUD.configuration()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension UserDetailHeaderView: UITableViewDelegate, UITableViewDataSource {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0 {
for subview in bottomScrollView.subviews {
let tableView = subview as! UITableView
tableView.isScrollEnabled = false
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch currentTopTabType {
case .dongtai: // 动态
return dongtais.count
case .article: // 文章
return articles.count
case .video: // 视频
return videos.count
case .wenda: // 问答
return wendas.count
case .iesVideo: // 小视频
return iesVideos.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch currentTopTabType {
case .dongtai: // 动态
return cellFor(tableView, at: indexPath, with: dongtais)
case .article: // 文章
return cellFor(tableView, at: indexPath, with: articles)
case .video: // 视频
return cellFor(tableView, at: indexPath, with: videos)
case .wenda: // 问答
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as UserDetailWendaCell
cell.wenda = wendas[indexPath.row]
return cell
case .iesVideo: // 小视频
return cellFor(tableView, at: indexPath, with: iesVideos)
}
}
/// 设置 cell
private func cellFor(_ tableView: UITableView, at indexPath: IndexPath, with datas: [UserDetailDongtai]) -> UserDetailDongTaiCell {
let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as UserDetailDongTaiCell
cell.dongtai = datas[indexPath.row]
cell.didSelectDongtaiUserName = { [weak self] (uid) in
self!.didSelectHeaderUserID?(uid)
}
cell.didSelectDongtaiTopic = { [weak self] (cid) in
self!.didSelectHeaderTopicID?(cid)
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch currentTopTabType {
case .dongtai: // 动态
return cellHeight(with: dongtais[indexPath.row])
case .article: // 文章
return cellHeight(with: articles[indexPath.row])
case .video: // 视频
return cellHeight(with: videos[indexPath.row])
case .wenda: // 问答
let wenda = wendas[indexPath.row]
return wenda.cellHeight
case .iesVideo: // 小视频
return cellHeight(with: iesVideos[indexPath.row])
}
}
/// 设置 cell 的高度
private func cellHeight(with dongtai: UserDetailDongtai) -> CGFloat {
return dongtai.cellHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch currentTopTabType {
case .dongtai: // 动态
didSelectCellWithDongtai?(dongtais[indexPath.row])
case .article: // 文章
didSelectCellWithDongtai?(articles[indexPath.row])
case .video: // 视频
didSelectCellWithDongtai?(videos[indexPath.row])
case .wenda: // 问答
print("")
// didSelectCellWithDongtai?([indexPath.row])
case .iesVideo: // 小视频
didSelectCellWithDongtai?(iesVideos[indexPath.row])
}
}
}
// MARK: - 按钮点击事件
extension UserDetailHeaderView {
/// 头像按钮点击
@IBAction func avatarButtonClicked(_ sender: UIButton) {
didSelectAvatarImageView?()
}
/// topTab 按钮点击事件
@objc func topTabButtonClicked(button: UIButton) {
privorButton?.isSelected = false
button.isSelected = !button.isSelected
UIView.animate(withDuration: 0.25, animations: {
self.indicatorView.centerX = button.centerX
self.bottomScrollView.contentOffset = CGPoint(x: CGFloat(button.tag) * screenWidth, y: 0)
}) { (_) in
self.privorButton = button
}
// 获取索引
currentSelectedIndex = button.tag
// 取出 当前点击的 topTab, 赋值给 currentTopTabType
let topTab = userDetail!.top_tab[button.tag]
currentTopTabType = topTab.type
}
/// 接收到了关注按钮的点击
@objc private func receivedConcernButtonClicked(notification: Notification) {
let userInfo = notification.userInfo as! [String: Any]
let isSelected = userInfo["isSelected"] as! Bool
concernButton.isSelected = isSelected
concernButton.theme_backgroundColor = isSelected ? "colors.userDetailFollowingConcernBtnBgColor" : "colors.globalRedColor"
concernButton.borderColor = isSelected ? .grayColor232() : .globalRedColor()
concernButton.borderWidth = isSelected ? 1 : 0
}
/// 发私信按钮点击
@IBAction func sendMailButtonClicked() {
let storyboard = UIStoryboard(name: String(describing: MoreLoginViewController.self), bundle: nil)
let moreLoginVC = storyboard.instantiateViewController(withIdentifier: String(describing: MoreLoginViewController.self)) as! MoreLoginViewController
moreLoginVC.modalSize = (width: .full, height: .custom(size: Float(screenHeight - (isIPhoneX ? 44 : 20))))
UIApplication.shared.keyWindow?.rootViewController?.present(moreLoginVC, animated: true, completion: nil)
}
/// 关注按钮点击
@IBAction func concernButtonClicked(_ sender: AnimatableButton) {
if sender.isSelected { // 已经关注,点击则取消关注
// 已关注用户,取消关注
NetworkTool.loadRelationUnfollow(userId: userDetail!.user_id, completionHandler: { (_) in
sender.isSelected = !sender.isSelected
sender.theme_backgroundColor = "colors.globalRedColor"
self.recommendButton.isHidden = true
self.recommendButton.isSelected = false
self.recommendButtonWidth.constant = 0
self.recommendButtonTrailing.constant = 0
self.recommendViewHeight.constant = 0
UIView.animate(withDuration: 0.25, animations: {
self.recommendButton.imageView?.transform = .identity
self.layoutIfNeeded()
})
NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserDetailHeaderViewButtonClicked), object: self, userInfo: ["isSelected": sender.isSelected])
})
} else { // 未关注,点击则关注这个用户
// 点击关注按钮,关注用户
NetworkTool.loadRelationFollow(userId: userDetail!.user_id, completionHandler: { (_) in
sender.isSelected = !sender.isSelected
sender.theme_backgroundColor = "colors.userDetailFollowingConcernBtnBgColor"
sender.borderColor = .grayColor232()
sender.borderWidth = 1
self.recommendButton.isHidden = false
self.recommendButton.isSelected = false
self.recommendButtonWidth.constant = 28.0
self.recommendButtonTrailing.constant = 15.0
self.recommendViewHeight.constant = 233
UIView.animate(withDuration: 0.25, animations: {
self.layoutIfNeeded()
}, completion: { (_) in
// 点击了关注按钮,就会出现相关推荐数据
NetworkTool.loadRelationUserRecommend(userId: self.userDetail!.user_id, completionHandler: { (userCards) in
self.recommendView.addSubview(self.relationRecommendView)
self.relationRecommendView.userCards = userCards
})
})
NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserDetailHeaderViewButtonClicked), object: self, userInfo: ["isSelected": sender.isSelected])
})
}
}
/// 推荐关注按钮点击
@IBAction func recommendButtonClicked(_ sender: AnimatableButton) {
sender.isSelected = !sender.isSelected
recommendViewHeight.constant = sender.isSelected ? 0 : 233.0
UIView.animate(withDuration: 0.25, animations: {
sender.imageView?.transform = CGAffineTransform(rotationAngle: CGFloat(sender.isSelected ? Double.pi : 0))
self.layoutIfNeeded()
})
}
/// 展开按钮点击
@IBAction func unfoldButtonClicked() {
unfoldButton.isHidden = true
unfoldButtonWidth.constant = 0
relationRecommendView.labelHeight.constant = 0
relationRecommendView.layoutIfNeeded()
descriptionLabelHeight.constant = userDetail!.descriptionHeight
UIView.animate(withDuration: 0.25, animations: {
self.layoutIfNeeded()
})
}
}
| mit | 36ea84d7de4734883a8cb24fc49676f5 | 43.367816 | 189 | 0.607124 | 5 | false | false | false | false |
TrustWallet/trust-wallet-ios | Trust/Lock/ViewControllers/LockPasscodeViewController.swift | 1 | 4972 | // Copyright DApps Platform Inc. All rights reserved.
import UIKit
class LockPasscodeViewController: UIViewController {
var willFinishWithResult: ((_ success: Bool) -> Void)?
let model: LockViewModel
var lockView: LockView!
let lock: Lock
private var invisiblePasscodeField = UITextField()
private var shouldIgnoreTextFieldDelegateCalls = false
init(model: LockViewModel, lock: Lock = Lock()) {
self.model = model
self.lock = lock
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
self.navigationItem.hidesBackButton = true
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
self.view.backgroundColor = UIColor.white
self.configureInvisiblePasscodeField()
self.configureLockView()
if !invisiblePasscodeField.isFirstResponder && !lock.incorrectMaxAttemptTimeIsSet() {
invisiblePasscodeField.becomeFirstResponder()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if invisiblePasscodeField.isFirstResponder {
invisiblePasscodeField.resignFirstResponder()
}
}
public func configureInvisiblePasscodeField() {
invisiblePasscodeField = UITextField()
invisiblePasscodeField.keyboardType = .numberPad
invisiblePasscodeField.isSecureTextEntry = true
invisiblePasscodeField.delegate = self
invisiblePasscodeField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
view.addSubview(invisiblePasscodeField)
}
public func configureLockView() {
lockView = LockView(model)
lockView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(lockView)
lockView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
lockView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
lockView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
lockView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
}
@objc func enteredPasscode(_ passcode: String) {
shouldIgnoreTextFieldDelegateCalls = false
clearPasscode()
}
func clearPasscode() {
invisiblePasscodeField.text = ""
for characterView in lockView.characters {
characterView.setEmpty(true)
}
}
func hideKeyboard() {
invisiblePasscodeField.resignFirstResponder()
}
func showKeyboard() {
invisiblePasscodeField.becomeFirstResponder()
}
func finish(withResult success: Bool, animated: Bool) {
invisiblePasscodeField.resignFirstResponder()
if let finish = willFinishWithResult {
finish(success)
} else {
dismiss(animated: true, completion: nil)
}
}
@objc func keyboardWillShow(_ notification: Notification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.lockView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -keyboardSize.height).isActive = true
})
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension LockPasscodeViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if shouldIgnoreTextFieldDelegateCalls {
return false
}
let newString: String? = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
let newLength: Int = newString?.count ?? 0
if newLength > model.charCount() {
lockView.shake()
textField.text = ""
return false
} else {
for characterView in lockView.characters {
let index: Int = lockView.characters.index(of: characterView)!
characterView.setEmpty(index >= newLength)
}
return true
}
}
@objc func textFieldDidChange(_ textField: UITextField) {
if shouldIgnoreTextFieldDelegateCalls {
return
}
let newString: String? = textField.text
let newLength: Int = newString?.count ?? 0
if newLength == model.charCount() {
shouldIgnoreTextFieldDelegateCalls = true
textField.text = ""
perform(#selector(self.enteredPasscode), with: newString, afterDelay: 0.3)
}
}
}
| gpl-3.0 | 6023529c2849c5388bba45f71b71326c | 39.096774 | 137 | 0.662108 | 5.306297 | false | false | false | false |
bkmunar/firefox-ios | Sync/State.swift | 1 | 13499 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
// TODO: same comment as for SyncAuthState.swift!
private let log = XCGLogger.defaultInstance()
/*
* This file includes types that manage intra-sync and inter-sync metadata
* for the use of synchronizers and the state machine.
*
* See docs/sync.md for details on what exactly we need to persist.
*/
public struct Fetched<T: Equatable>: Equatable {
let value: T
let timestamp: Timestamp
}
public func ==<T: Equatable>(lhs: Fetched<T>, rhs: Fetched<T>) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.value == rhs.value
}
/*
* Persistence pref names.
* Note that syncKeyBundle isn't persisted by us.
*
* Note also that fetched keys aren't kept in prefs: we keep the timestamp ("PrefKeysTS"),
* and we keep a 'label'. This label is used to find the real fetched keys in the Keychain.
*/
private let PrefVersion = "_v"
private let PrefGlobal = "global"
private let PrefGlobalTS = "globalTS"
private let PrefKeyLabel = "keyLabel"
private let PrefKeysTS = "keysTS"
private let PrefLastFetched = "lastFetched"
private let PrefClientName = "clientName"
private let PrefClientGUID = "clientGUID"
/**
* The scratchpad consists of the following:
*
* 1. Cached records. We cache meta/global and crypto/keys until they change.
* 2. Metadata like timestamps, both for cached records and for server fetches.
* 3. User preferences -- engine enablement.
* 4. Client record state.
*
* Note that the scratchpad itself is immutable, but is a class passed by reference.
* Its mutable fields can be mutated, but you can't accidentally e.g., switch out
* meta/global and get confused.
*
* TODO: the Scratchpad needs to be loaded from persistent storage, and written
* back at certain points in the state machine (after a replayable action is taken).
*/
public class Scratchpad {
public class Builder {
var syncKeyBundle: KeyBundle // For the love of god, if you change this, invalidate keys, too!
private var global: Fetched<MetaGlobal>?
private var keys: Fetched<Keys>?
private var keyLabel: String
var collectionLastFetched: [String: Timestamp]
var engineConfiguration: EngineConfiguration?
var clientGUID: String
var clientName: String
var prefs: Prefs
init(p: Scratchpad) {
self.syncKeyBundle = p.syncKeyBundle
self.prefs = p.prefs
self.global = p.global
self.keys = p.keys
self.keyLabel = p.keyLabel
self.collectionLastFetched = p.collectionLastFetched
self.engineConfiguration = p.engineConfiguration
self.clientGUID = p.clientGUID
self.clientName = p.clientName
}
public func setKeys(keys: Fetched<Keys>?) -> Builder {
self.keys = keys
if let keys = keys {
self.collectionLastFetched["crypto"] = keys.timestamp
}
return self
}
public func setGlobal(global: Fetched<MetaGlobal>?) -> Builder {
self.global = global
if let global = global {
self.collectionLastFetched["meta"] = global.timestamp
}
return self
}
public func clearFetchTimestamps() -> Builder {
self.collectionLastFetched = [:]
return self
}
public func build() -> Scratchpad {
return Scratchpad(
b: self.syncKeyBundle,
m: self.global,
k: self.keys,
keyLabel: self.keyLabel,
fetches: self.collectionLastFetched,
engines: self.engineConfiguration,
clientGUID: self.clientGUID,
clientName: self.clientName,
persistingTo: self.prefs
)
}
}
public func evolve() -> Scratchpad.Builder {
return Scratchpad.Builder(p: self)
}
// This is never persisted.
let syncKeyBundle: KeyBundle
// Cached records.
// This cached meta/global is what we use to add or remove enabled engines. See also
// engineConfiguration, below.
// We also use it to detect when meta/global hasn't changed -- compare timestamps.
//
// Note that a Scratchpad held by a Ready state will have the current server meta/global
// here. That means we don't need to track syncIDs separately (which is how desktop and
// Android are implemented).
// If we don't have a meta/global, and thus we don't know syncIDs, it means we haven't
// synced with this server before, and we'll do a fresh sync.
let global: Fetched<MetaGlobal>?
// We don't store these keys (so-called "collection keys" or "bulk keys") in Prefs.
// Instead, we store a label, which is seeded when you first create a Scratchpad.
// This label is used to retrieve the real keys from your Keychain.
//
// Note that we also don't store the syncKeyBundle here. That's always created from kB,
// provided by the Firefox Account.
//
// Why don't we derive the label from your Sync Key? Firstly, we'd like to be able to
// clean up without having your key. Secondly, we don't want to accidentally load keys
// from the Keychain just because the Sync Key is the same -- e.g., after a node
// reassignment. Randomly generating a label offers all of the benefits with none of the
// problems, with only the cost of persisting that label alongside the rest of the state.
let keys: Fetched<Keys>?
let keyLabel: String
// Collection timestamps.
var collectionLastFetched: [String: Timestamp]
// Enablement states.
let engineConfiguration: EngineConfiguration?
// What's our client name?
let clientName: String
let clientGUID: String
// Where do we persist when told?
let prefs: Prefs
init(b: KeyBundle,
m: Fetched<MetaGlobal>?,
k: Fetched<Keys>?,
keyLabel: String,
fetches: [String: Timestamp],
engines: EngineConfiguration?,
clientGUID: String,
clientName: String,
persistingTo prefs: Prefs
) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = k
self.keyLabel = keyLabel
self.global = m
self.engineConfiguration = engines
self.collectionLastFetched = fetches
self.clientGUID = clientGUID
self.clientName = clientName
}
// This should never be used in the end; we'll unpickle instead.
// This should be a convenience initializer, but... Swift compiler bug?
init(b: KeyBundle, persistingTo prefs: Prefs) {
self.syncKeyBundle = b
self.prefs = prefs
self.keys = nil
self.keyLabel = Bytes.generateGUID()
self.global = nil
self.engineConfiguration = nil
self.collectionLastFetched = [String: Timestamp]()
self.clientGUID = Bytes.generateGUID()
self.clientName = DeviceInfo.defaultClientName()
}
// For convenience.
func withGlobal(m: Fetched<MetaGlobal>?) -> Scratchpad {
return self.evolve().setGlobal(m).build()
}
func freshStartWithGlobal(global: Fetched<MetaGlobal>) -> Scratchpad {
// TODO: I *think* a new keyLabel is unnecessary.
return self.evolve()
.setGlobal(global)
.setKeys(nil)
.clearFetchTimestamps()
.build()
}
func applyEngineChoices(old: MetaGlobal?) -> (Scratchpad, MetaGlobal?) {
log.info("Applying engine choices from inbound meta/global.")
log.info("Old meta/global syncID: \(old?.syncID)")
log.info("New meta/global syncID: \(self.global?.value.syncID)")
log.info("HACK: ignoring engine choices.")
// TODO: detect when the sets of declined or enabled engines have changed, and update
// our preferences and generate a new meta/global if necessary.
return (self, nil)
}
private class func unpickleV1FromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad {
let b = Scratchpad(b: syncKeyBundle, persistingTo: prefs).evolve()
// Do this first so that the meta/global and crypto/keys unpickling can overwrite the timestamps.
if let lastFetched: [String: AnyObject] = prefs.dictionaryForKey(PrefLastFetched) {
b.collectionLastFetched = optFilter(mapValues(lastFetched, { ($0 as? NSNumber)?.unsignedLongLongValue }))
}
if let mg = prefs.stringForKey(PrefGlobal) {
if let mgTS = prefs.unsignedLongForKey(PrefGlobalTS) {
if let global = MetaGlobal.fromPayload(mg) {
b.setGlobal(Fetched(value: global, timestamp: mgTS))
} else {
log.error("Malformed meta/global in prefs. Ignoring.")
}
} else {
// This should never happen.
log.error("Found global in prefs, but not globalTS!")
}
}
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
b.keyLabel = keyLabel
if let ckTS = prefs.unsignedLongForKey(PrefKeysTS) {
if let keys = KeychainWrapper.stringForKey("keys." + keyLabel) {
// We serialize as JSON.
let keys = Keys(payload: KeysPayload(keys))
if keys.valid {
log.debug("Read keys from Keychain with label \(keyLabel).")
b.setKeys(Fetched(value: keys, timestamp: ckTS))
} else {
log.error("Invalid keys extracted from Keychain. Discarding.")
}
} else {
log.error("Found keysTS in prefs, but didn't find keys in Keychain!")
}
}
}
b.clientGUID = prefs.stringForKey(PrefClientGUID) ?? {
log.error("No value found in prefs for client GUID! Generating one.")
return Bytes.generateGUID()
}()
b.clientName = prefs.stringForKey(PrefClientName) ?? {
log.error("No value found in prefs for client name! Using default.")
return DeviceInfo.defaultClientName()
}()
// TODO: engineConfiguration
return b.build()
}
/**
* Remove anything that might be left around after prefs is wiped.
*/
public class func clearFromPrefs(prefs: Prefs) {
if let keyLabel = prefs.stringForKey(PrefKeyLabel) {
log.debug("Removing saved key from keychain.")
KeychainWrapper.removeObjectForKey(keyLabel)
} else {
log.debug("No key label; nothing to remove from keychain.")
}
}
public class func restoreFromPrefs(prefs: Prefs, syncKeyBundle: KeyBundle) -> Scratchpad? {
if let ver = prefs.intForKey(PrefVersion) {
switch (ver) {
case 1:
return unpickleV1FromPrefs(prefs, syncKeyBundle: syncKeyBundle)
default:
return nil
}
}
log.debug("No scratchpad found in prefs.")
return nil
}
/**
* Persist our current state to our origin prefs.
* Note that calling this from multiple threads with either mutated or evolved
* scratchpads will cause sadness — individual writes are thread-safe, but the
* overall pseudo-transaction is not atomic.
*/
public func checkpoint() -> Scratchpad {
return pickle(self.prefs)
}
func pickle(prefs: Prefs) -> Scratchpad {
prefs.setInt(1, forKey: PrefVersion)
if let global = global {
prefs.setLong(global.timestamp, forKey: PrefGlobalTS)
prefs.setString(global.value.toPayload().toString(), forKey: PrefGlobal)
} else {
prefs.removeObjectForKey(PrefGlobal)
prefs.removeObjectForKey(PrefGlobalTS)
}
// We store the meat of your keys in the Keychain, using a random identifier that we persist in prefs.
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
if let keys = self.keys {
let payload = keys.value.asPayload().toString(pretty: false)
let label = "keys." + self.keyLabel
log.debug("Storing keys in Keychain with label \(label).")
prefs.setString(self.keyLabel, forKey: PrefKeyLabel)
prefs.setLong(keys.timestamp, forKey: PrefKeysTS)
// TODO: I could have sworn that we could specify kSecAttrAccessibleAfterFirstUnlock here.
KeychainWrapper.setString(payload, forKey: label)
} else {
log.debug("Removing keys from Keychain.")
KeychainWrapper.removeObjectForKey(self.keyLabel)
}
// TODO: engineConfiguration
prefs.setString(clientName, forKey: PrefClientName)
prefs.setString(clientGUID, forKey: PrefClientGUID)
// Thanks, Swift.
let dict = mapValues(collectionLastFetched, { NSNumber(unsignedLongLong: $0) }) as NSDictionary
prefs.setObject(dict, forKey: PrefLastFetched)
return self
}
}
| mpl-2.0 | ea786c5cd99c6310f487157df13d46e7 | 36.387812 | 117 | 0.622138 | 4.842842 | false | false | false | false |
practicalswift/swift | test/IRGen/associated_type_witness.swift | 4 | 7140 | // RUN: %target-swift-frontend -primary-file %s -emit-ir > %t.ll
// RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll
// RUN: %FileCheck %s < %t.ll
// RUN: %target-swift-frontend -primary-file %s -emit-ir -wmo -num-threads 1 > %t.ll.wmo
// RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll.wmo
// RUN: %FileCheck %s < %t.ll.wmo
// REQUIRES: CPU=x86_64
protocol P {}
protocol Q {}
protocol Assocked {
associatedtype Assoc : P, Q
}
struct Universal : P, Q {}
// CHECK-LABEL: @"symbolic _____ 23associated_type_witness12OuterPrivate{{.*}}V" = linkonce_odr hidden constant
// CHECK-SAME: @"$s23associated_type_witness12OuterPrivate{{.*}}5InnerE0V9InnermostVMn"
private struct OuterPrivate {
struct InnerPrivate: HasSimpleAssoc {
struct Innermost { }
typealias Assoc = Innermost
}
}
// CHECK: [[ASSOC_TYPE_NAMES:@.*]] = private constant [29 x i8] c"OneAssoc TwoAssoc ThreeAssoc\00"
// CHECK: @"$s23associated_type_witness18HasThreeAssocTypesMp" =
// CHECK-SAME: [[ASSOC_TYPE_NAMES]] to i64
protocol HasThreeAssocTypes {
associatedtype OneAssoc
associatedtype TwoAssoc
associatedtype ThreeAssoc
}
// Witness table for WithUniversal : Assocked.
// GLOBAL-LABEL: @"$s23associated_type_witness13WithUniversalVAA8AssockedAAWP" = hidden global [4 x i8*] [
// GLOBAL-SAME: @"$s23associated_type_witness13WithUniversalVAA8AssockedAAMc"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness13WithUniversalVAA8AssockedAA5AssocAaDP_AA1P",
// GLOBAL-SAME: @"associated conformance 23associated_type_witness13WithUniversalVAA8AssockedAA5AssocAaDP_AA1Q"
// GLOBAL-SAME: i64 add (i64 ptrtoint (<{ [36 x i8], i8 }>* @"symbolic 23associated_type_witness9UniversalV" to i64), i64 1) to i8*)
// GLOBAL-SAME: ]
struct WithUniversal : Assocked {
typealias Assoc = Universal
}
// Witness table for GenericWithUniversal : Assocked.
// GLOBAL-LABEL: @"$s23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAWP" = hidden global [4 x i8*] [
// GLOBAL-SAME: @"$s23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAMc"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAA5Assoc_AA1P"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAA5Assoc_AA1Q"
// GLOBAL-SAME: @"symbolic 23associated_type_witness9UniversalV"
// GLOBAL-SAME: ]
struct GenericWithUniversal<T> : Assocked {
typealias Assoc = Universal
}
// Witness table for Fulfilled : Assocked.
// GLOBAL-LABEL: @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAAWp" = internal global [4 x i8*] [
// GLOBAL-SAME: @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAAMc"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1P"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1Q"
// GLOBAL-SAME: @"symbolic x"
// GLOBAL-SAME: ]
struct Fulfilled<T : P & Q> : Assocked {
typealias Assoc = T
}
// Associated type witness table access function for Fulfilled.Assoc : P.
// CHECK-LABEL: define internal swiftcc i8** @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1PPWT"(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked")
// CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8***
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 3
// CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load
// CHECK-NEXT: ret i8** [[T2]]
// Associated type witness table access function for Fulfilled.Assoc : Q.
// CHECK-LABEL: define internal swiftcc i8** @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1QPWT"(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked")
// CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8***
// CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 4
// CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load
// CHECK-NEXT: ret i8** [[T2]]
struct Pair<T, U> : P, Q {}
// Generic witness table pattern for Computed : Assocked.
// GLOBAL-LABEL: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWp" = internal global [4 x i8*] [
// GLOBAL-SAME: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAMc"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness8ComputedVyxq_GAA8AssockedAA5Assoc_AA1P"
// GLOBAL-SAME: @"associated conformance 23associated_type_witness8ComputedVyxq_GAA8AssockedAA5Assoc_AA1Q"
// GLOBAL-SAME: @"symbolic 23associated_type_witness4PairVyxq_G"
// GLOBAL-SAME: ]
struct Computed<T, U> : Assocked {
typealias Assoc = Pair<T, U>
}
// Instantiation function for GenericComputed : DerivedFromSimpleAssoc.
// CHECK-LABEL: define internal void @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI"(i8**, %swift.type* %"GenericComputed<T>", i8**)
// CHECK: [[T0:%.*]] = call i8** @swift_getWitnessTable({{.*}}@"$s23associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAMc"
// CHECK-NEXT: [[T1:%.*]] = bitcast i8** [[T0]] to i8*
// CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds i8*, i8** %0, i32 1
// CHECK-NEXT: store i8* [[T1]], i8** [[T2]], align 8
// CHECK-NEXT: ret void
struct PBox<T: P> {}
protocol HasSimpleAssoc {
associatedtype Assoc
}
protocol DerivedFromSimpleAssoc : HasSimpleAssoc {}
// Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc.
// GLOBAL-LABEL: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWp" = internal constant [2 x i8*]
// GLOBAL-SAME: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAMc"
// GLOBAL-SAME: i8* null
// Relative reference to private data
struct GenericComputed<T: P> : DerivedFromSimpleAssoc {
typealias Assoc = PBox<T>
}
protocol HasAssocked {
associatedtype Contents : Assocked
}
struct FulfilledFromAssociatedType<T : HasAssocked> : HasSimpleAssoc {
typealias Assoc = PBox<T.Contents.Assoc>
}
struct UsesVoid : HasSimpleAssoc {
typealias Assoc = ()
}
// Protocol conformance descriptor for Computed : Assocked.
// GLOBAL-LABEL: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAMc" = hidden constant
// GLOBAL-SAME: i16 4,
// GLOBAL-SAME: i16 1,
// No instantiator function
// GLOBAL-SAME: i32 0,
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([16 x i8*]* [[PRIVATE:@.*]] to i64), i64 ptrtoint
// GLOBAL-SAME: }
// Protocol conformance descriptor for GenericComputed : DerivedFromSimpleAssoc.
// GLOBAL-LABEL: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAMc" = hidden constant
// GLOBAL-SAME: i16 2,
// GLOBAL-SAME: i16 1,
// Relative reference to instantiator function
// GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (void (i8**, %swift.type*, i8**)* @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI" to i64),
| apache-2.0 | e0a63bd8e69b5577ace8f8b8becbcfd7 | 45.973684 | 218 | 0.723529 | 3.591549 | false | false | false | false |
sessionm/ios-smp-example | Offers/Reward Store/PurchaseAOfferViewController.swift | 1 | 2246 | //
// PurchaseAOfferViewController.swift
// Offers
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMOffersKit
import UIKit
class PurchaseAOfferViewController: UIViewController {
var item: SMStoreOfferItem? = nil;
@IBOutlet weak var header: UILabel!
@IBOutlet weak var terms: UILabel!
@IBOutlet weak var available: UILabel!
@IBOutlet weak var cost: UILabel!
@IBOutlet weak var afterPurchase: UILabel!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var imgHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let item = self.item {
header.text = item.name
terms.text = "\(item.details)\n\n\(item.terms)"
if let user = SMUserManager.instance().currentUser {
available.text = "\(user.availablePoints)"
afterPurchase.text = "\(Double(user.availablePoints) - item.price)"
}
cost.text = "\(item.price)"
if (item.media.count > 0) {
Common.loadImage(parent: nil, uri: item.media[0].uri, imgView: self.image, imageHeight: self.imgHeight, maxHeight: 200.0)
}
}
}
@IBAction func doDismiss(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func doPurchase(_ sender: Any) {
if let item = self.item {
SMOffersManager.instance().purchaseOffer(havingID: item.offerID, quantity: 1) { (result: SMOfferPurchasedResponse?, error: SMError?) in
if let error = error {
self.present(UIAlertController(title: "No Purchase", message: error.message, preferredStyle: .alert), animated: true, completion: {})
} else if let result = result {
let ctrlr = UIAlertController(title: "Purchased", message: result.userOffer.userOfferID, preferredStyle: .alert)
ctrlr.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(ctrlr, animated: true, completion: {})
}
}
}
}
}
| mit | 4365652162aeee75e1018ab9c83b2401 | 33.015152 | 153 | 0.611136 | 4.436759 | false | false | false | false |
huonw/swift | stdlib/public/core/Builtin.swift | 2 | 35589 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@inlinable // FIXME(sil-serialize-all)
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@inlinable // FIXME(sil-serialize-all)
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of the given instance, interpreted as having the specified
/// type.
///
/// Use this function only to convert the instance passed as `x` to a
/// layout-compatible type when conversion through other means is not
/// possible. Common conversions supported by the Swift standard library
/// include the following:
///
/// - Value conversion from one integer type to another. Use the destination
/// type's initializer or the `numericCast(_:)` function.
/// - Bitwise conversion from one integer type to another. Use the destination
/// type's `init(truncatingIfNeeded:)` or `init(bitPattern:)` initializer.
/// - Conversion from a pointer to an integer value with the bit pattern of the
/// pointer's address in memory, or vice versa. Use the `init(bitPattern:)`
/// initializer for the destination type.
/// - Casting an instance of a reference type. Use the casting operators (`as`,
/// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of the Swift type
/// system; use with extreme care.
///
/// - Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"Can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// Returns `x` as its concrete type `U`.
///
/// This cast can be useful for dispatching to specializations of generic
/// functions.
///
/// - Requires: `x` has type `U`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U {
_precondition(T.self == expectedType, "_identityCast to wrong type")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@inlinable
@_transparent
internal func == (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@inlinable
@_transparent
internal func != (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return !(lhs == rhs)
}
@inlinable
@_transparent
internal func == (
lhs: Builtin.RawPointer, rhs: Builtin.RawPointer
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@inlinable
@_transparent
internal func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether two types are identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if both `t0` and `t1` are `nil` or if they represent the
/// same type; otherwise, `false`.
@inlinable
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
switch (t0, t1) {
case (.none, .none): return true
case let (.some(ty0), .some(ty1)):
return Bool(Builtin.is_same_metatype(ty0, ty1))
default: return false
}
}
/// Returns a Boolean value indicating whether two types are not identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if one, but not both, of `t0` and `t1` are `nil`, or if
/// they represent different types; otherwise, `false`.
@inlinable
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@inlinable // FIXME(sil-serialize-all)
@_silgen_name("_swift_isClassOrObjCExistentialType")
internal func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// Returns the given instance cast unconditionally to the specified type.
///
/// The instance passed as `x` must be an instance of type `T`.
///
/// Use this function instead of `unsafeBitcast(_:to:)` because this function
/// is more restrictive and still performs a check in debug builds. In -O
/// builds, no test is performed to ensure that `x` actually has the dynamic
/// type `T`.
///
/// - Warning: This function trades safety for performance. Use
/// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always
/// evaluates to `true`, and only after `x as! T` has proven to be a
/// performance problem.
///
/// - Parameters:
/// - x: An instance to cast to type `T`.
/// - type: The type `T` to which `x` is cast.
/// - Returns: The instance `x`, cast to type `T`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func _unsafeUncheckedDowncast<T : AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_sanityCheck(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
import SwiftShims
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<SwiftShims.HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@inlinable // FIXME(sil-serialize-all)
@_transparent
@_semantics("branchhint")
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(actual._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@inlinable // FIXME(sil-serialize-all)
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@inlinable // FIXME(sil-serialize-all)
@_silgen_name("_objcClassUsesNativeSwiftReferenceCounting")
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
#else
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@inlinable // FIXME(sil-serialize-all)
@_silgen_name("_getSwiftClassInstanceExtents")
internal func getSwiftClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@inlinable // FIXME(sil-serialize-all)
@_silgen_name("_getObjCClassInstanceExtents")
internal func getObjCClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(getObjCClassInstanceExtents(theClass).positive)
#else
return Int(getSwiftClassInstanceExtents(theClass).positive)
#endif
}
@inlinable
internal
func _isValidAddress(_ address: UInt) -> Bool {
// TODO: define (and use) ABI max valid pointer value
return address >= _swift_abi_LeastValidPointerValue
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
// TODO(<rdar://problem/34837023>): Get rid of superfluous UInt constructor
// calls
@inlinable // FIXME(sil-serialize-all)
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_BridgeObject_TaggedPointerBits) }
}
@inlinable // FIXME(sil-serialize-all)
internal var _objectPointerSpareBits: UInt {
@inline(__always) get {
return UInt(_swift_abi_SwiftSpareBitsMask) & ~_objCTaggedPointerBits
}
}
@inlinable // FIXME(sil-serialize-all)
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get {
_sanityCheck(_swift_abi_ObjCReservedLowBits < 2,
"num bits now differs from num-shift-amount, new platform?")
return UInt(_swift_abi_ObjCReservedLowBits)
}
}
#if arch(i386) || arch(arm) || arch(powerpc64) || arch(powerpc64le) || arch(
s390x)
@inlinable // FIXME(sil-serialize-all)
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
#else
@inlinable // FIXME(sil-serialize-all)
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
#endif
/// Extract the raw bits of `x`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _isObjCTaggedPointer(_ x: UInt) -> Bool {
return (x & _objCTaggedPointerBits) != 0
}
/// TODO: describe extras
@inlinable @inline(__always) public // FIXME
func _isTaggedObject(_ x: Builtin.BridgeObject) -> Bool {
return _bitPattern(x) & _objCTaggedPointerBits != 0
}
@inlinable @inline(__always) public // FIXME
func _isNativePointer(_ x: Builtin.BridgeObject) -> Bool {
return (
_bitPattern(x) & (_objCTaggedPointerBits | _objectPointerIsObjCBit)
) == 0
}
@inlinable @inline(__always) public // FIXME
func _isNonTaggedObjCPointer(_ x: Builtin.BridgeObject) -> Bool {
return !_isTaggedObject(x) && !_isNativePointer(x)
}
@inlinable
@inline(__always)
func _getNonTagBits(_ x: Builtin.BridgeObject) -> UInt {
// Zero out the tag bits, and leave them all at the top.
_sanityCheck(_isTaggedObject(x), "not tagged!")
return (_bitPattern(x) & ~_objCTaggedPointerBits)
>> _objectPointerLowSpareBitShift
}
// Values -> BridgeObject
@inline(__always)
@inlinable
public func _bridgeObject(fromNative x: AnyObject) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(x))
let object = Builtin.castToBridgeObject(x, 0._builtinWordValue)
_sanityCheck(_isNativePointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNonTaggedObjC x: AnyObject
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(x))
let object = _makeObjCBridgeObject(x)
_sanityCheck(_isNonTaggedObjCPointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(fromTagged x: UInt) -> Builtin.BridgeObject {
_sanityCheck(x & _objCTaggedPointerBits != 0)
let object: Builtin.BridgeObject = Builtin.valueToBridgeObject(x)
_sanityCheck(_isTaggedObject(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(taggingPayload x: UInt) -> Builtin.BridgeObject {
let shifted = x &<< _objectPointerLowSpareBitShift
_sanityCheck(x == (shifted &>> _objectPointerLowSpareBitShift),
"out-of-range: limited bit range requires some zero top bits")
_sanityCheck(shifted & _objCTaggedPointerBits == 0,
"out-of-range: post-shift use of tag bits")
return _bridgeObject(fromTagged: shifted | _objCTaggedPointerBits)
}
// BridgeObject -> Values
@inline(__always)
@inlinable
public func _bridgeObject(toNative x: Builtin.BridgeObject) -> AnyObject {
_sanityCheck(_isNativePointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
toNonTaggedObjC x: Builtin.BridgeObject
) -> AnyObject {
_sanityCheck(_isNonTaggedObjCPointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagged x: Builtin.BridgeObject) -> UInt {
_sanityCheck(_isTaggedObject(x))
let bits = _bitPattern(x)
_sanityCheck(bits & _objCTaggedPointerBits != 0)
return bits
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagPayload x: Builtin.BridgeObject) -> UInt {
return _getNonTagBits(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNativeObject x: Builtin.NativeObject
) -> Builtin.BridgeObject {
return _bridgeObject(fromNative: _nativeObject(toNative: x))
}
//
// NativeObject
//
@inline(__always)
@inlinable
public func _nativeObject(fromNative x: AnyObject) -> Builtin.NativeObject {
_sanityCheck(!_isObjCTaggedPointer(x))
let native = Builtin.unsafeCastToNativeObject(x)
// _sanityCheck(native == Builtin.castToNativeObject(x))
return native
}
@inline(__always)
@inlinable
public func _nativeObject(
fromBridge x: Builtin.BridgeObject
) -> Builtin.NativeObject {
return _nativeObject(fromNative: _bridgeObject(toNative: x))
}
@inline(__always)
@inlinable
public func _nativeObject(toNative x: Builtin.NativeObject) -> AnyObject {
return Builtin.castFromNativeObject(x)
}
// FIXME
extension ManagedBufferPointer {
// FIXME: String Guts
@inline(__always)
@inlinable
public init(_nativeObject buffer: Builtin.NativeObject) {
self._nativeBuffer = buffer
}
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
public
func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique and _isUniquePinned cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
@inlinable // FIXME(sil-serialize-all)
@_transparent
internal func _isUniqueOrPinned<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUniqueOrPinned(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if `object` is uniquely referenced or pinned.
/// This provides sanity checks on top of the Builtin.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _isUniqueOrPinned_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUniqueOrPinned_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is nominally an Optional type.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
/// Extract an object reference from an Any known to contain an object.
@inlinable // FIXME(sil-serialize-all)
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_sanityCheck(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// With a SIL instruction, we could more efficiently grab the object reference
// out of the Any's inline storage.
// On Linux, bridging isn't supported, so this is a force cast.
#if _runtime(_ObjC)
return any as AnyObject
#else
return any as! AnyObject
#endif
}
// Game the SIL diagnostic pipeline by inlining this into the transparent
// definitions below after the stdlib's diagnostic passes run, so that the
// `staticReport`s don't fire while building the standard library, but do
// fire if they ever show up in code that uses the standard library.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public // internal with availability
func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}
/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
/// particularly when the dynamic type is different from the static type. The
/// *static type* of a value is the known, compile-time type of the value. The
/// *dynamic type* of a value is the value's actual type at run-time, which
/// can be nested inside its concrete type.
///
/// In the following code, the `count` variable has the same static and dynamic
/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,
/// however, the `value` parameter has a static type of `Any` (the type
/// declared for the parameter) and a dynamic type of `Int`.
///
/// func printInfo(_ value: Any) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// let count: Int = 5
/// printInfo(count)
/// // '5' of type 'Int'
///
/// The dynamic type returned from `type(of:)` is a *concrete metatype*
/// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type
/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol
/// composition `P`. When the static type of the value passed to `type(of:)`
/// is constrained to a class or protocol, you can use that metatype to access
/// initializers or other static members of the class or protocol.
///
/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`
/// function in the example below is an instance of the `Smiley` class or one
/// of its subclasses. The function uses `type(of:)` to find the dynamic type
/// of `value`, which itself is an instance of the `Smiley.Type` metatype.
///
/// class Smiley {
/// class var text: String {
/// return ":)"
/// }
/// }
///
/// class EmojiSmiley : Smiley {
/// override class var text: String {
/// return "😀"
/// }
/// }
///
/// func printSmileyInfo(_ value: Smiley) {
/// let smileyType = type(of: value)
/// print("Smile!", smileyType.text)
/// }
///
/// let emojiSmiley = EmojiSmiley()
/// printSmileyInfo(emojiSmiley)
/// // Smile! 😀
///
/// In this example, accessing the `text` property of the `smileyType` metatype
/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of
/// the `Smiley` class's original definition.
///
/// Finding the Dynamic Type in a Generic Context
/// =============================================
///
/// Normally, you don't need to be aware of the difference between concrete and
/// existential metatypes, but calling `type(of:)` can yield unexpected
/// results in a generic context with a type parameter bound to a protocol. In
/// a case like this, where a generic parameter `T` is bound to a protocol
/// `P`, the type parameter is not statically known to be a protocol type in
/// the body of the generic function. As a result, `type(of:)` can only
/// produce the concrete metatype `P.Protocol`.
///
/// The following example defines a `printGenericInfo(_:)` function that takes
/// a generic parameter and declares the `String` type's conformance to a new
/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has
/// `P` as its static type, the call to `type(of:)` returns `P.self` instead
/// of `String.self` (the dynamic type inside the parameter).
///
/// func printGenericInfo<T>(_ value: T) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// protocol P {}
/// extension String: P {}
///
/// let stringAsP: P = "Hello!"
/// printGenericInfo(stringAsP)
/// // 'Hello!' of type 'P'
///
/// This unexpected result occurs because the call to `type(of: value)` inside
/// `printGenericInfo(_:)` must return a metatype that is an instance of
/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance
/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type
/// inside `value` in this generic context, cast the parameter to `Any` when
/// calling `type(of:)`.
///
/// func betterPrintGenericInfo<T>(_ value: T) {
/// let type = type(of: value as Any)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// betterPrintGenericInfo(stringAsP)
/// // 'Hello!' of type 'String'
///
/// - Parameter value: The value for which to find the dynamic type.
/// - Returns: The dynamic type, which is a metatype instance.
@inlinable // FIXME(sil-serialize-all)
@_transparent
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
// This implementation is never used, since calls to `Swift.type(of:)` are
// resolved as a special case by the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'type(of:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Allows a nonescaping closure to temporarily be used as if it were allowed
/// to escape.
///
/// You can use this function to call an API that takes an escaping closure in
/// a way that doesn't allow the closure to escape in practice. The examples
/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in
/// conjunction with two common APIs that use escaping closures: lazy
/// collection views and asynchronous operations.
///
/// The following code declares an `allValues(in:match:)` function that checks
/// whether all the elements in an array match a predicate. The function won't
/// compile as written, because a lazy collection's `filter(_:)` method
/// requires an escaping closure. The lazy collection isn't persisted, so the
/// `predicate` closure won't actually escape the body of the function;
/// nevertheless, it can't be used in this way.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return array.lazy.filter { !predicate($0) }.isEmpty
/// }
/// // error: closure use of non-escaping parameter 'predicate'...
///
/// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of
/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`
/// method. The second version of `allValues(in:match:)` compiles without
/// error, with the compiler guaranteeing that the `escapablePredicate`
/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return withoutActuallyEscaping(predicate) { escapablePredicate in
/// array.lazy.filter { !escapablePredicate($0) }.isEmpty
/// }
/// }
///
/// Asynchronous calls are another type of API that typically escape their
/// closure arguments. The following code declares a
/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to
/// execute two closures concurrently.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: f)
/// queue.async(execute: g)
/// queue.sync(flags: .barrier) {}
/// }
/// // error: passing non-escaping parameter 'f'...
/// // error: passing non-escaping parameter 'g'...
///
/// The `perform(_:simultaneouslyWith:)` function ends with a call to the
/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the
/// function to wait until both closures have completed running before
/// returning. Even though the barrier guarantees that neither closure will
/// escape the function, the `async(execute:)` method still requires that the
/// closures passed be marked as `@escaping`, so the first version of the
/// function does not compile. To resolve these errors, you can use
/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be
/// passed to `async(execute:)`.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// withoutActuallyEscaping(f) { escapableF in
/// withoutActuallyEscaping(g) { escapableG in
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: escapableF)
/// queue.async(execute: escapableG)
/// queue.sync(flags: .barrier) {}
/// }
/// }
/// }
///
/// - Important: The escapable copy of `closure` passed to `body` is only valid
/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined
/// behavior for the escapable closure to be stored, referenced, or executed
/// after the function returns.
///
/// - Parameters:
/// - closure: A nonescaping closure value that is made escapable for the
/// duration of the execution of the `body` closure. If `body` has a
/// return value, that value is also used as the return value for the
/// `withoutActuallyEscaping(_:do:)` function.
/// - body: A closure that is executed immediately with an escapable copy of
/// `closure` as its argument.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable // FIXME(sil-serialize-all)
@_transparent
@_semantics("typechecker.withoutActuallyEscaping(_:do:)")
public func withoutActuallyEscaping<ClosureType, ResultType>(
_ closure: ClosureType,
do body: (_ escapingClosure: ClosureType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
@_semantics("typechecker._openExistential(_:do:)")
public func _openExistential<ExistentialType, ContainedType, ResultType>(
_ existential: ExistentialType,
do body: (_ escapingClosure: ContainedType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift._openExistential(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
| apache-2.0 | ff157b3ea782824bfaa4e8fe462b8f80 | 35.235234 | 95 | 0.690217 | 4.012969 | false | false | false | false |
jestemnawakacjach/recognizer | Recognizer/CustomRecognizer/FDTSimpleGestureProviderSwift.swift | 1 | 2108 | //
// FDTSimpleGestureProviderSwift.swift
// Recognizer
//
// Created by Karol Wawrzyniak on 16/02/16.
// Copyright © 2016 Karol Wawrzyniak. All rights reserved.
//
import UIKit
class FDTSimpleGestureProviderSwift: NSObject, FDTRecognizerProvider {
var recognitionObject: FDTRecognitionObject
init(fileURL: NSURL) {
self.recognitionObject = FDTRecognitionObject.recognizerWithFileURL(fileURL)
}
var gestureName: String! {
return self.recognitionObject.name;
}
var connectedURLString: String! {
return self.recognitionObject.urlString;
}
func transformPoint(point: CGPoint) -> AnyObject! {
return NSValue(CGPoint: point);
}
func testForGestureWithPoints(points: [AnyObject]!) -> Bool {
let sampled = self.sample(points);
let distance = self.distance(sampled);
return distance <= 0.7;
}
func sample(points: NSArray!) -> NSArray {
let sample = NSMutableArray();
let loadedSampleCount = self.recognitionObject.angles.count;
let c = points.count;
for (var i = 0; i < loadedSampleCount; i++) {
let index = max(0, c - 1) * i / (loadedSampleCount - 1);
sample.addObject(points[index]);
}
return sample;
}
func distanceBetweenAngles(firstAngle: CGFloat, secondAngle: CGFloat) -> CGFloat {
var phi = fabs(secondAngle - firstAngle);
phi = fmod(phi, CGFloat(M_PI * 2));
let distance = phi > CGFloat(M_PI) ? CGFloat(2 * M_PI) - phi : phi;
return distance;
}
func distance(points: NSArray) -> CGFloat {
var distance: CGFloat = 0.0;
let angles = self.recognitionObject.angles;
let minCount = min(angles.count, points.count);
for (var i = 0; i < minCount; i++) {
let aVal = CGFloat(angles[i].floatValue);
let bVal = CGFloat(points[i].floatValue);
distance += self.distanceBetweenAngles(aVal, secondAngle: bVal);
}
distance = fabs(distance / CGFloat(minCount));
return distance;
}
}
| apache-2.0 | 8589cb884b62fe997f06ae203d3d6073 | 27.863014 | 86 | 0.623636 | 4.075435 | false | false | false | false |
zonble/ETCHelperSwift | ETCHelperLib/ZBNode.swift | 1 | 853 | import Foundation
/** Data object for a node. */
class ZBNode :Equatable {
var name :String
var links :[ZBLink] = [ZBLink]()
init(name: String) {
self.name = name
}
var description: String {
return "<ZBNode \(self.name)>"
}
func makeLink(#to: ZBNode, distance :Double, price :Double, holidayDistance :Double, tag :String) {
let link = ZBLink(to: to, distance: distance, price: price, holidayDistance: holidayDistance, tag: tag)
self.links.append(link)
}
}
func makeLinks(#a: ZBNode, b: ZBNode, distance :Double, price: Double, holidayDistance :Double, tag: NSString) {
a.makeLink(to: b, distance: distance, price: price, holidayDistance: holidayDistance, tag: tag)
b.makeLink(to: a, distance: distance, price: price, holidayDistance: holidayDistance, tag: tag)
}
func ==(lhs: ZBNode, rhs: ZBNode) -> Bool {
return lhs === rhs
}
| mit | 0a506c6d8187ed77be09353cc1ee020e | 28.413793 | 112 | 0.69871 | 3.057348 | false | false | false | false |
gorjuspixels/DKImagePickerController | DKImagePickerControllerDemo/CustomLayoutUIDelegate/CustomFlowLayout.swift | 1 | 1360 | //
// CustomFlowLayout.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 03/01/2017.
// Copyright © 2017 ZhangAo. All rights reserved.
//
import UIKit
open class CustomFlowLayout: UICollectionViewFlowLayout {
open override func prepare() {
super.prepare()
self.scrollDirection = .horizontal
let contentWidth = self.collectionView!.bounds.width * 0.7
self.itemSize = CGSize(width: contentWidth, height: contentWidth)
self.minimumInteritemSpacing = 999
// var minItemWidth: CGFloat = 80
// if UI_USER_INTERFACE_IDIOM() == .pad {
// minItemWidth = 100
// }
//
// let interval: CGFloat = 1
// self.minimumInteritemSpacing = interval
// self.minimumLineSpacing = interval
//
// let contentWidth = self.collectionView!.bounds.width
//
// let itemCount = Int(floor(contentWidth / minItemWidth))
// var itemWidth = (contentWidth - interval * (CGFloat(itemCount) - 1)) / CGFloat(itemCount)
// let actualInterval = (contentWidth - CGFloat(itemCount) * itemWidth) / (CGFloat(itemCount) - 1)
// itemWidth += actualInterval - interval
//
// let itemSize = CGSize(width: itemWidth, height: itemWidth)
// self.itemSize = itemSize
}
}
| mit | 4ba10649b2279f468699f078e42ea21c | 31.357143 | 105 | 0.614422 | 4.51495 | false | false | false | false |
matsprea/omim | iphone/Maps/UI/PlacePage/Components/PlacePagePreviewViewController.swift | 1 | 8399 | final class PlacePageDirectionView: UIView {
@IBOutlet var imageView: UIImageView!
@IBOutlet var label: UILabel!
}
protocol PlacePagePreviewViewControllerDelegate: AnyObject {
func previewDidPressAddReview()
func previewDidPressSimilarHotels()
func previewDidPressRemoveAds()
}
final class PlacePagePreviewViewController: UIViewController {
@IBOutlet var stackView: UIStackView!
@IBOutlet var popularView: UIView!
@IBOutlet var subtitleLabel: UILabel!
@IBOutlet var subtitleContainerView: UIStackView!
@IBOutlet var scheduleLabel: UILabel!
@IBOutlet var ratingSummaryView: RatingSummaryView!
@IBOutlet var reviewsLabel: UILabel!
@IBOutlet var addReviewButton: UIButton! {
didSet {
addReviewButton.setTitle("+ \(L("leave_a_review"))", for: .normal)
}
}
@IBOutlet var priceLabel: UILabel!
@IBOutlet var discountView: UIView!
@IBOutlet var discountLabel: UILabel!
@IBOutlet var ugcContainerView: UIStackView!
@IBOutlet var addressLabel: UILabel!
@IBOutlet var addressContainerView: UIStackView!
@IBOutlet var searchSimilarButton: UIButton!
@IBOutlet var scheduleContainerView: UIStackView!
@IBOutlet var searchSimilarContainerView: UIStackView!
@IBOutlet var subtitleDirectionView: PlacePageDirectionView!
@IBOutlet var addressDirectionView: PlacePageDirectionView!
var placePageDirectionView: PlacePageDirectionView?
lazy var fullScreenDirectionView: DirectionView = {
return Bundle.main.load(viewClass: DirectionView.self)!
}()
lazy var adView: AdBannerView = {
let view = Bundle.main.load(viewClass: AdBannerView.self)?.first as! AdBannerView
view.isHidden = true
return view
}()
var placePagePreviewData: PlacePagePreviewData! {
didSet {
if isViewLoaded {
updateViews()
}
}
}
weak var delegate: PlacePagePreviewViewControllerDelegate?
private var distance: String? = nil
private var speedAndAltitude: String? = nil
private var heading: CGFloat? = nil
override func viewDidLoad() {
updateViews()
if let distance = distance {
placePageDirectionView?.isHidden = false
placePageDirectionView?.label.text = distance
}
if let heading = heading {
updateHeading(heading)
} else {
placePageDirectionView?.imageView.isHidden = true
}
stackView.addArrangedSubview(adView)
}
private func updateViews() {
super.viewDidLoad()
if placePagePreviewData.isMyPosition {
if let speedAndAltitude = speedAndAltitude {
subtitleLabel.text = speedAndAltitude
}
} else {
let subtitleString = NSMutableAttributedString()
if placePagePreviewData.isPopular {
subtitleString.append(NSAttributedString(string: L("popular_place"),
attributes: [.foregroundColor : UIColor.linkBlue(),
.font : UIFont.regular14()]))
}
if let subtitle = placePagePreviewData.subtitle ?? placePagePreviewData.coordinates {
subtitleString.append(NSAttributedString(string: placePagePreviewData.isPopular ? " • " + subtitle : subtitle,
attributes: [.foregroundColor : UIColor.blackSecondaryText(),
.font : UIFont.regular14()]))
}
subtitleLabel.attributedText = subtitleString
}
placePageDirectionView = subtitleDirectionView
if let address = placePagePreviewData.address {
addressLabel.text = address
placePageDirectionView = addressDirectionView
} else {
addressContainerView.isHidden = true
}
if let pricing = placePagePreviewData.pricing {
priceLabel.text = pricing
} else {
priceLabel.isHidden = true
}
searchSimilarContainerView.isHidden = placePagePreviewData.hotelType == .none
configSchedule()
configUgc()
ugcContainerView.isHidden = !placePagePreviewData.isBookingPlace
}
func updateBanner(_ banner: MWMBanner) {
adView.isHidden = false
adView.config(ad: banner, containerType: .placePage, canRemoveAds: true) { [weak self] in
self?.delegate?.previewDidPressRemoveAds()
}
}
func updateUgc(_ ugcData: UgcData) {
ugcContainerView.isHidden = false
if let summaryRating = ugcData.summaryRating {
ratingSummaryView.value = summaryRating.ratingString
ratingSummaryView.type = summaryRating.ratingType
reviewsLabel.text = String(format:L("placepage_summary_rating_description"), ugcData.ratingsCount)
} else {
if ugcData.isUpdateEmpty {
ratingSummaryView.setStyleAndApply("RatingSummaryView12")
reviewsLabel.text = ugcData.reviews.count == 0 ? L("placepage_no_reviews") : ""
} else {
ratingSummaryView.setStyleAndApply("RatingSummaryView12User")
reviewsLabel.text = L("placepage_reviewed")
addReviewButton.isHidden = true
}
}
addReviewButton.isHidden = !ugcData.isUpdateEmpty
}
func updateBooking(_ bookingData: HotelBookingData, rooms: HotelRooms?) {
var rawRating: Int
switch bookingData.score {
case 0..<2:
rawRating = 1
case 2..<4:
rawRating = 2
case 4..<6:
rawRating = 3
case 6..<8:
rawRating = 4
case 8...10:
rawRating = 5
default:
rawRating = 0
}
ugcContainerView.isHidden = false
ratingSummaryView.value = NSNumber(value: bookingData.score).stringValue
ratingSummaryView.type = UgcSummaryRatingType(rawValue: rawRating) ?? .none
guard let rooms = rooms else { return }
priceLabel.text = String(coreFormat: L("place_page_starting_from"), arguments: [rooms.minPrice])
priceLabel.isHidden = false
if rooms.discount > 0 {
discountLabel.text = "-\(rooms.discount)%"
discountView.isHidden = false
} else if rooms.isSmartDeal {
discountLabel.text = "%"
discountView.isHidden = false
}
}
func updateDistance(_ distance: String) {
self.distance = distance
placePageDirectionView?.isHidden = false
placePageDirectionView?.label.text = distance
fullScreenDirectionView.updateDistance(distance)
}
func updateHeading(_ angle: CGFloat) {
heading = angle
placePageDirectionView?.imageView.isHidden = false
UIView.animate(withDuration: kDefaultAnimationDuration,
delay: 0,
options: [.beginFromCurrentState, .curveEaseInOut],
animations: { [unowned self] in
self.placePageDirectionView?.imageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2 - angle)
})
fullScreenDirectionView.updateHeading(angle)
}
func updateSpeedAndAltitude(_ speedAndAltitude: String) {
self.speedAndAltitude = speedAndAltitude
subtitleLabel?.text = speedAndAltitude
}
@IBAction func onAddReview(_ sender: UIButton) {
delegate?.previewDidPressAddReview()
}
@IBAction func onSimilarHotels(_ sender: UIButton) {
delegate?.previewDidPressSimilarHotels()
}
@IBAction func onDirectionPressed(_ sender: Any) {
guard let heading = heading else {
return
}
fullScreenDirectionView.updateTitle(placePagePreviewData.title,
subtitle: placePagePreviewData.subtitle ?? placePagePreviewData.coordinates)
fullScreenDirectionView.updateHeading(heading)
fullScreenDirectionView.updateDistance(distance)
fullScreenDirectionView.show()
}
// MARK: private
private func configSchedule() {
switch placePagePreviewData.schedule {
case .openingHoursAllDay:
scheduleLabel.text = L("twentyfour_seven")
case .openingHoursOpen:
scheduleLabel.text = L("editor_time_open")
case .openingHoursClosed:
scheduleLabel.text = L("closed_now")
scheduleLabel.textColor = UIColor.red
case .openingHoursUnknown:
scheduleContainerView.isHidden = true
@unknown default:
fatalError()
}
}
private func configUgc() {
ratingSummaryView.textFont = UIFont.bold12()
ratingSummaryView.backgroundOpacity = 0.05
ratingSummaryView.value = "-"
if placePagePreviewData.isBookingPlace {
reviewsLabel.isHidden = true
addReviewButton.isHidden = true
} else {
priceLabel.isHidden = true
discountView.isHidden = true
}
}
}
| apache-2.0 | bf7290ace2263d79dc9bc1c7e1056816 | 31.929412 | 127 | 0.688937 | 4.672788 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Sources/XCTScheduleComponent/StubScheduleViewModel+RandomValueProviding.swift | 1 | 3789 | import EurofurenceModel
import Foundation
import ScheduleComponent
import TestUtilities
extension CapturingScheduleViewModel: RandomValueProviding {
public static var random: CapturingScheduleViewModel {
return CapturingScheduleViewModel(days: .random, events: .random, currentDay: .random)
}
}
extension ScheduleEventGroupViewModel: RandomValueProviding {
public static var random: ScheduleEventGroupViewModel {
return ScheduleEventGroupViewModel(title: .random, events: [StubScheduleEventViewModel].random)
}
}
public final class StubScheduleEventViewModel: ScheduleEventViewModelProtocol {
public var title: String
public var startTime: String
public var endTime: String
public var location: String
public var bannerGraphicPNGData: Data?
public var isFavourite: Bool
public var isSponsorOnly: Bool
public var isSuperSponsorOnly: Bool
public var isArtShow: Bool
public var isKageEvent: Bool
public var isDealersDenEvent: Bool
public var isMainStageEvent: Bool
public var isPhotoshootEvent: Bool
public var isAcceptingFeedback: Bool
public var isFaceMaskRequired: Bool
public init(
title: String,
startTime: String,
endTime: String,
location: String,
bannerGraphicPNGData: Data?,
isFavourite: Bool,
isSponsorOnly: Bool,
isSuperSponsorOnly: Bool,
isArtShow: Bool,
isKageEvent: Bool,
isDealersDenEvent: Bool,
isMainStageEvent: Bool,
isPhotoshootEvent: Bool,
isAcceptingFeedback: Bool,
isFaceMaskRequired: Bool
) {
self.title = title
self.startTime = startTime
self.endTime = endTime
self.location = location
self.bannerGraphicPNGData = bannerGraphicPNGData
self.isFavourite = isFavourite
self.isSponsorOnly = isSponsorOnly
self.isSuperSponsorOnly = isSuperSponsorOnly
self.isArtShow = isArtShow
self.isKageEvent = isKageEvent
self.isDealersDenEvent = isDealersDenEvent
self.isMainStageEvent = isMainStageEvent
self.isPhotoshootEvent = isPhotoshootEvent
self.isAcceptingFeedback = isAcceptingFeedback
self.isFaceMaskRequired = isFaceMaskRequired
}
private var observers = [ScheduleEventViewModelObserver]()
public func add(_ observer: ScheduleEventViewModelObserver) {
observers.append(observer)
}
public func favourite() {
isFavourite = true
observers.forEach({ $0.eventViewModelDidBecomeFavourite(self) })
}
public func unfavourite() {
isFavourite = false
observers.forEach({ $0.eventViewModelDidBecomeNonFavourite(self) })
}
public private(set) var sharedSender: Any?
public func share(_ sender: Any) {
sharedSender = sender
}
}
extension StubScheduleEventViewModel: RandomValueProviding {
public static var random: StubScheduleEventViewModel {
return StubScheduleEventViewModel(
title: .random,
startTime: .random,
endTime: .random,
location: .random,
bannerGraphicPNGData: .random,
isFavourite: .random,
isSponsorOnly: .random,
isSuperSponsorOnly: .random,
isArtShow: .random,
isKageEvent: .random,
isDealersDenEvent: .random,
isMainStageEvent: .random,
isPhotoshootEvent: .random,
isAcceptingFeedback: .random,
isFaceMaskRequired: .random
)
}
}
extension ScheduleDayViewModel: RandomValueProviding {
public static var random: ScheduleDayViewModel {
return ScheduleDayViewModel(title: .random)
}
}
| mit | 57997172e46a53e3623028af1ce38cef | 29.071429 | 103 | 0.678543 | 5.397436 | false | false | false | false |
manavgabhawala/swift | test/SILGen/c_function_pointers.swift | 1 | 2398 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -verify %s | %FileCheck %s
func values(_ arg: @escaping @convention(c) (Int) -> Int) -> @convention(c) (Int) -> Int {
return arg
}
// CHECK-LABEL: sil hidden @_T019c_function_pointers6valuesS2iXCS2iXCF
// CHECK: bb0(%0 : $@convention(c) (Int) -> Int):
// CHECK: return %0 : $@convention(c) (Int) -> Int
@discardableResult
func calls(_ arg: @convention(c) (Int) -> Int, _ x: Int) -> Int {
return arg(x)
}
// CHECK-LABEL: sil hidden @_T019c_function_pointers5callsS3iXC_SitF
// CHECK: bb0(%0 : $@convention(c) (Int) -> Int, %1 : $Int):
// CHECK: [[RESULT:%.*]] = apply %0(%1)
// CHECK: return [[RESULT]]
@discardableResult
func calls_no_args(_ arg: @convention(c) () -> Int) -> Int {
return arg()
}
func global(_ x: Int) -> Int { return x }
func no_args() -> Int { return 42 }
// CHECK-LABEL: sil hidden @_T019c_function_pointers0B19_to_swift_functionsySiF
func pointers_to_swift_functions(_ x: Int) {
// CHECK: bb0([[X:%.*]] : $Int):
func local(_ y: Int) -> Int { return y }
// CHECK: [[GLOBAL_C:%.*]] = function_ref @_T019c_function_pointers6globalS2iFTo
// CHECK: apply {{.*}}([[GLOBAL_C]], [[X]])
calls(global, x)
// CHECK: [[LOCAL_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiF5localL_S2iFTo
// CHECK: apply {{.*}}([[LOCAL_C]], [[X]])
calls(local, x)
// CHECK: [[CLOSURE_C:%.*]] = function_ref @_T019c_function_pointers0B19_to_swift_functionsySiFS2icfU_To
// CHECK: apply {{.*}}([[CLOSURE_C]], [[X]])
calls({ $0 + 1 }, x)
calls_no_args(no_args)
// CHECK: [[NO_ARGS_C:%.*]] = function_ref @_T019c_function_pointers7no_argsSiyFTo
// CHECK: apply {{.*}}([[NO_ARGS_C]])
}
func unsupported(_ a: Any) -> Int { return 0 }
func pointers_to_bad_swift_functions(_ x: Int) {
calls(unsupported, x) // expected-error{{C function pointer signature '(Any) -> Int' is not compatible with expected type '@convention(c) (Int) -> Int'}}
}
// CHECK-LABEL: sil shared @_T019c_function_pointers22StructWithInitializersV3fn1yyXCvfiyycfU_ : $@convention(thin) () -> () {
// CHECK-LABEL: sil shared [thunk] @_T019c_function_pointers22StructWithInitializersV3fn1yyXCvfiyycfU_To : $@convention(c) () -> () {
struct StructWithInitializers {
let fn1: @convention(c) () -> () = {}
init(a: ()) {}
init(b: ()) {}
}
| apache-2.0 | 1c9c174edee1311438a9823df2b25aa6 | 35.892308 | 155 | 0.618015 | 3.016352 | false | false | false | false |
koher/Argo | Argo/Extensions/RawRepresentable.swift | 1 | 746 | public extension Decodable where Self.DecodedType == Self, Self: RawRepresentable, Self.RawValue == String {
static func decode(json: JSON) -> Decoded<Self> {
switch json {
case let .String(s): return self.init(rawValue: s).map(pure) ?? .typeMismatch("rawValue for \(self)", actual: json)
default: return .typeMismatch("String", actual: json)
}
}
}
public extension Decodable where Self.DecodedType == Self, Self: RawRepresentable, Self.RawValue == Int {
static func decode(json: JSON) -> Decoded<Self> {
switch json {
case let .Number(n): return self.init(rawValue: n.integerValue).map(pure) ?? .typeMismatch("rawValue for \(self)", actual: json)
default: return .typeMismatch("Int", actual: json)
}
}
}
| mit | c510c08b26b5e52afed2ba2b79cdd99b | 42.882353 | 132 | 0.686327 | 3.94709 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloud/WatsonCore/Utilities/NetworkUtils.swift | 1 | 12707 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Alamofire
import ObjectMapper
/**
Watson content types
- Text: Plain text
- JSON: JSON
- XML: XML
- URLEncoded: Form URL Encoded
*/
public enum ContentType: String {
case Text = "text/plain"
case JSON = "application/json"
case XML = "application/xml"
case URLEncoded = "application/x-www-form-urlencoded"
case AUDIO_OPUS = "audio/ogg; codecs=opus"
case AUDIO_WAV = "audio/wav"
case AUDIO_FLAC = "audio/flac"
}
/// Alias to HTTPMethod to remove dependency on Alamofire from individual projects
public typealias HTTPMethod = Alamofire.Method
/// Alias to ParameterEncoding to remove dependency on Alamofire from individual projects
public typealias ParameterEncoding = Alamofire.ParameterEncoding
/// Networking utilities used for performing REST operations into Watson services and parsing the input
public class NetworkUtils {
private static let _httpContentTypeHeader = "Content-Type"
private static let _httpAcceptHeader = "Accept"
private static let _httpAuthorizationHeader = "Authorization"
/**
This helper function will manipulate the header as needed for a proper payload
- parameter contentType: Changes the input to text or JSON. Default is JSON
- returns: The manipulated string for properly invoking the web call
*/
private static func buildHeader(contentType: ContentType = ContentType.JSON, accept: ContentType = ContentType.JSON, apiKey: String? = nil)-> [String: String] {
Log.sharedLogger.debug("Entered buildHeader")
var header = Dictionary<String, String>()
if let localKey = apiKey { header.updateValue(localKey as String, forKey: _httpAuthorizationHeader )}
guard (header.updateValue(contentType.rawValue, forKey: _httpContentTypeHeader) == nil) else {
Log.sharedLogger.error("Error adding Content Type in header")
return [:]
}
guard (header.updateValue(accept.rawValue, forKey: _httpAcceptHeader) == nil) else {
Log.sharedLogger.error("Error adding Accept info in header")
return [:]
}
return header
}
/**
Request a Watson Authentication token. Tokens expire after one hour.
- parameter tokenURL: The URL of the token authentication endpoint (e.g. "https://stream.watsonplatform.net/authorization/api/v1/token")
- parameter serviceURL: The URL of the service for which you want to obtain a token (e.g. "https://stream.watsonplatform.net/text-to-speech/api")
- parameter apiKey: The authentication string used for HTTP basic authorization.
- parameter completionHandler: The closure called when the token request is complete.
*/
public static func requestAuthToken(tokenURL: String, serviceURL: String, apiKey: String? = nil, completionHandler: (token: String?, error: NSError?) -> Void) {
Log.sharedLogger.debug("Entered requestAuthToken")
let parameters = ["url": serviceURL]
Alamofire.request(.GET, tokenURL, parameters: parameters, headers: buildHeader(.URLEncoded, accept: .URLEncoded, apiKey: apiKey))
.responseString {response in
Log.sharedLogger.debug("Entered requestAuthToken.responseString")
completionHandler(token: response.result.value, error: response.result.error)
}
}
/**
This core function will make a basic authorization request by adding header information as part of the authentication.
- parameter url: The full URL to use for the web REST call
- parameter method: Indicates the method type such as POST or GET
- parameter parameters: Dictionary of parameters to use as part of the HTTP query
- parameter contentType: This will switch the input and outout request from text or json
- parameter completionHandler: Returns CoreResponse which is a payload of valid AnyObject data or a NSError
*/
public static func performBasicAuthRequest(url: String, method: HTTPMethod = HTTPMethod.GET, parameters: [String: AnyObject]? = [:], contentType: ContentType = ContentType.JSON, accept: ContentType = ContentType.JSON, encoding: ParameterEncoding = ParameterEncoding.URL, apiKey:String? = nil, completionHandler: (returnValue: CoreResponse) -> Void) {
Log.sharedLogger.debug("Entered performBasicAuthRequest")
Alamofire.request(method, url, parameters: parameters, encoding: encoding, headers: buildHeader(contentType, accept:accept, apiKey: apiKey) )
// This will validate for return status codes between the specified ranges and fail if it falls outside of them
.responseJSON {response in
Log.sharedLogger.debug("Entered performBasicAuthRequest.responseJSON")
if(contentType == ContentType.JSON) { completionHandler( returnValue: CoreResponse.getCoreResponse(response)) }
}
.responseString {response in
Log.sharedLogger.debug("Entered performBasicAuthRequest.responseString")
if(contentType == ContentType.Text) { completionHandler( returnValue: CoreResponse.getCoreResponse(response)) }
}
.responseData { response in
Log.sharedLogger.debug("Entered performBasicAuthRequest.responseData")
if(contentType == ContentType.AUDIO_OPUS ||
contentType == ContentType.AUDIO_WAV ||
contentType == ContentType.AUDIO_FLAC) {
completionHandler ( returnValue: CoreResponse.getCoreResponse(response))
}
}
}
/**
This core function will perform a request passing in parameters. This does not manipulate the request header or request body
- parameter url: The full URL to use for the web REST call
- parameter method: Indicates the method type such as POST or GET
- parameter parameters: Dictionary of parameters to use as part of the HTTP query
- parameter completionHandler: Returns CoreResponse which is a payload of valid AnyObject data or a NSError
*/
public static func performRequest(url: String, method: HTTPMethod = HTTPMethod.GET, parameters: [String: AnyObject] = [:], completionHandler: (returnValue: CoreResponse) -> Void) {
Log.sharedLogger.debug("Entered performRequest")
Alamofire.request(method, url, parameters: parameters)
.responseJSON { response in
Log.sharedLogger.debug("Entered performRequest.responseJSON")
completionHandler( returnValue: CoreResponse.getCoreResponse(response))
}
}
/**
This Core function will upload a file to the give URL. The header is manipulated for authentication
TODO: this has the capability of uploading multiple files so this should be updated to take in a dictionary of fileURL,fielURLKey values
- parameter url: Full URL to use for the web REST call
- parameter fileURLKey: Key used with the fileURL
- parameter fileURL: File passed in as a NSURL
- parameter parameters: Dictionary of parameters to use as part of the HTTP query
- parameter completionHandler: Returns CoreResponse which is a payload of valid AnyObject data or a NSError
*/
public static func performBasicAuthFileUploadMultiPart(url: String, fileURLs: [String:NSURL], parameters: [String: AnyObject]=[:], apiKey: String? = nil, contentType: ContentType = ContentType.URLEncoded, accept: ContentType = ContentType.URLEncoded, completionHandler: (returnValue: CoreResponse) -> Void) {
Log.sharedLogger.debug("Entered performBasicAuthFileUploadMultiPart")
Alamofire.upload(Alamofire.Method.POST, url, headers: buildHeader(contentType, accept: accept, apiKey: apiKey),
multipartFormData: { multipartFormData in
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: key)
}
for (fileKey, fileValue) in fileURLs {
multipartFormData.appendBodyPart(fileURL: fileValue, name: fileKey)
}
},
encodingCompletion: { encodingResult in
Log.sharedLogger.debug("Entered performBasicAuthFileUploadMultiPart.encodingCompletion")
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
Log.sharedLogger.debug("Entered performBasicAuthFileUploadMultiPart.encodingCompletion.responseJSON")
completionHandler(returnValue: CoreResponse.getCoreResponse(response))
}
case .Failure(let encodingError):
Log.sharedLogger.error("\(encodingError)")
}
}
)
}
/**
This Core function will upload one file to the give URL.
- parameter url: Full URL to use for the web REST call
- parameter fileURL: File passed in as a NSURL
- parameter parameters: Dictionary of parameters to use as part of the HTTP query
- parameter completionHandler: Returns CoreResponse which is a payload of valid AnyObject data or a NSError
*/
// TODO: STILL IN PROGRESS
public static func performBasicAuthFileUpload(url: String, fileURL: NSURL, parameters: [String: AnyObject]=[:], apiKey: String? = nil, completionHandler: (returnValue: CoreResponse) -> Void) {
// TODO: This is not optimal but I had to append the params to the url in order for this to work correctly.
// I will get back to looking into this at some point but want to get it working
let appendedUrl = addQueryStringParameter(url,values:parameters)
Alamofire.upload(Alamofire.Method.POST, appendedUrl, headers: buildHeader(ContentType.URLEncoded, accept:ContentType.URLEncoded, apiKey:apiKey), file: fileURL)
.responseJSON { response in
Log.sharedLogger.debug("Entered performBasicAuthFileUpload.responseJSON")
completionHandler( returnValue: CoreResponse.getCoreResponse(response))
}
}
/**
Adds to or updates a query parameter to a URL
- parameter url: Base URL
- parameter key: Parameter key
- parameter value: Parameter value
- returns: URL with key/value pair added/updated
*/
private static func addOrUpdateQueryStringParameter(url: String, key: String, value: String?) -> String {
if let components = NSURLComponents(string: url), v = value {
var queryItems = [NSURLQueryItem]()
if components.queryItems != nil {
queryItems = components.queryItems!
}
queryItems.append(NSURLQueryItem(name: key, value: v))
components.queryItems = queryItems
return components.string!
}
return url
}
/**
Add query parameters to a URL
- parameter url: Base URL to which variables should be added
- parameter values: Dictionary of query parameters
- returns: Base URL with query parameters appended
*/
private static func addQueryStringParameter(url: String, values: [String: AnyObject]) -> String {
var newUrl = url
for item in values {
if case let value as String = item.1 {
newUrl = addOrUpdateQueryStringParameter(newUrl, key: item.0, value: value)
}
else {
Log.sharedLogger.error("error in adding value to parameter \(item) to URL string")
}
}
return newUrl
}
} | mit | ff0c49e4a1efe6128c92a8bee4f182f7 | 49.229249 | 354 | 0.662391 | 5.184415 | false | false | false | false |
tqtifnypmb/armature | Sources/Armature/Connection/MultiplexConnection.swift | 1 | 4294 | //
// MultiplexConnection.swift
// Armature
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public class MultiplexConnection: SingleConnection {
var requests: [UInt16 : FCGIRequest] = [:]
var reqLock = NSLock()
var streamLock = NSLock()
let connectionQueue = NSOperationQueue()
required public init(sock: Int32, server: Server) {
super.init(sock: sock, server: server)
self.isMultiplex = 1
}
override public func readInto(inout buffer: [UInt8]) throws -> Int {
self.streamLock.lock()
defer {
self.streamLock.unlock()
}
return try super.readInto(&buffer)
}
override public func write(inout data: [UInt8]) throws {
self.streamLock.lock()
defer {
self.streamLock.unlock()
}
try super.write(&data)
}
override func handleParams(record: Record) throws {
self.reqLock.lock()
defer {
self.reqLock.unlock()
}
guard let req = self.requests[record.requestId] else {
return
}
self.curRequest = req
try super.handleParams(record)
}
override func handleStdIn(record: Record) {
self.reqLock.lock()
defer {
self.reqLock.unlock()
}
guard let req = self.requests[record.requestId] else {
return
}
self.curRequest = req
super.handleStdIn(record)
}
override func handleBeginRequest(record: Record) throws {
do {
let req = try FCGIRequest(record: record, conn: self)
self.reqLock.lock()
self.requests[record.requestId] = req
self.reqLock.unlock()
} catch DataError.UnknownRole {
// let unknown role error throws will tear down the connection
return
}
}
override func handleData(record: Record) {
self.reqLock.lock()
defer {
self.reqLock.unlock()
}
guard let req = self.requests[record.requestId] else {
return
}
self.curRequest = req
super.handleData(record)
}
override func handleAbortRequest(record: Record) throws {
self.reqLock.lock()
defer {
self.reqLock.unlock()
}
guard let req = self.requests[record.requestId] else {
return
}
if req.isRunning {
req.abort()
} else {
self.requests.removeValueForKey(record.requestId)
}
}
override func serveRequest(req: FCGIRequest) throws {
self.connectionQueue.addOperationWithBlock() {
do {
let fcgiServer = self.server as! FCGIServer
try fcgiServer.handleRequest(req)
} catch {
// One request failed , broke down the whole connection
self.halt()
return
}
self.reqLock.lock()
self.requests.removeValueForKey(req.requestId)
self.reqLock.unlock()
}
}
}
| mit | 9828bbe37a0b8f35e898ef0d0c768ae7 | 29.892086 | 82 | 0.599208 | 4.553552 | false | false | false | false |
tardieu/swift | benchmark/single-source/DictionarySwap.swift | 7 | 2449 | //===--- DictionarySwap.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
// Dictionary element swapping benchmark
// rdar://problem/19804127
import TestsUtils
@inline(never)
public func run_DictionarySwap(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
// Fill dictionary
for i in 1...size {
dict[i] = i
}
CheckResults(dict.count == size,
"Incorrect dict count: \(dict.count) != \(size).")
var swapped = false
for _ in 1...10000*N {
swap(&dict[25]!, &dict[75]!)
swapped = !swapped
if !swappedCorrectly(swapped, dict[25]!, dict[75]!) {
break
}
}
CheckResults(swappedCorrectly(swapped, dict[25]!, dict[75]!),
"Dictionary value swap failed")
}
// Return true if correctly swapped, false otherwise
func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
return swapped && (p25 == 75 && p75 == 25) ||
!swapped && (p25 == 25 && p75 == 75)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionarySwapOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)
// Fill dictionary
for i in 1...size {
dict[Box(i)] = Box(i)
}
CheckResults(dict.count == size,
"Incorrect dict count: \(dict.count) != \(size).")
var swapped = false
for _ in 1...10000*N {
swap(&dict[Box(25)]!, &dict[Box(75)]!)
swapped = !swapped
if !swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value) {
break
}
}
CheckResults(swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value),
"Dictionary value swap failed")
}
| apache-2.0 | 47eb8bbe7c12a40065e09096334af72e | 27.149425 | 87 | 0.56227 | 3.95 | false | false | false | false |
Rochester-Ting/XMLY | XMLY/XMLY/Classes/Other(其他)/NetworkTools.swift | 1 | 864 | //
// NetworkTools.swift
// XMLY
//
// Created by Rochester on 17/1/17.
// Copyright © 2017年 Rochester. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
enum MethodType{
case GET
case POST
}
class NetworkTools: NSObject {
class func requestData(type : MethodType,urlString : String,parameters:[String : NSString]? = nil,finished:@escaping (_ responseObject:AnyObject)->()){
let methodType = type == .GET ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(urlString, method: methodType, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
guard let result = response.result.value else{
print(response.result.error ?? "未知错误")
return
}
finished(result as AnyObject)
}
}
}
| mit | d03d42dc613a6f69afcc8ef6b2162822 | 30.592593 | 155 | 0.655334 | 4.513228 | false | false | false | false |
AlvinL33/TownHunt | TownHunt-1.9/TownHunt/MainGameScreen.swift | 1 | 18169 | //
// ViewController.swift
// TownHunt
//
// Created by iD Student on 7/27/16.
// Copyright © 2016 LeeTech. All rights reserved.
//
import UIKit
import MapKit
import CoreData
var timer = Timer()
protocol MainGameModalDelegate {
func packSelectedHandler(selectedPackKey: String, packCreatorID: String, gameType: String)
}
class MainGameScreenViewController: PinPackMapViewController, MKMapViewDelegate, MainGameModalDelegate {
@IBOutlet weak var viewBelowNav: UIView!
@IBOutlet weak var endGameButtonLabel: UIBarButtonItem!
@IBOutlet weak var menuOpenNavBarButton: UIBarButtonItem!
@IBOutlet weak var pointsButtonLabel: BorderedButton!
@IBOutlet weak var startButtonLabel: UIButton!
@IBOutlet weak var timerButton: BorderedButton!
@IBOutlet weak var pointsButton: BorderedButton!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var selectMapPackButton: BorderedButton!
@IBOutlet weak var packSelectedButton: UIButton!
@IBOutlet weak var gameTypeButton: UIButton!
public var selectedPackKey = ""
public var userPackDictName = ""
public var packCreatorID = ""
private var playerUserID = UserDefaults.standard.string(forKey: "UserID")!
public var gameType = "competitive"
public var filename = ""
private var packData: [String:Any] = [:]
private var isPackLoaded = false
private var countDownTime = 0
private var points = 0
private var isGameOn = false
private var showEndScreen = false
private var timeToNextNewPin = 0
private var activePins: [PinLocation] = []
private var gamePins: [PinLocation] = []
override func viewDidLoad() {
UIApplication.shared.isIdleTimerDisabled = true
menuOpenNavBarButton.target = self.revealViewController()
menuOpenNavBarButton.action = #selector(SWRevealViewController.revealToggle(_:))
// Setting up the map view
mapView.showsUserLocation = true
mapView.mapType = MKMapType.hybrid
mapView.delegate = self
timeToNextNewPin = randomTimeGen(countDownTime/4)
super.viewDidLoad()
checkFirstLaunch()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
if(!isUserLoggedIn){
self.performSegue(withIdentifier: "loginView", sender: self)
}
}
// Checks if user has launched the app before, if not calls the initial file setup
private func checkFirstLaunch(){
let defaults = UserDefaults.standard
if defaults.string(forKey: "isAppAlreadyLaunchedOnce") != nil{
print("App already launched")
//FirstLoadSetup().setupFiles()
} else {
defaults.set(true, forKey: "isAppAlreadyLaunchedOnce")
print("App launched first time")
FirstLoadSetup().initialSetup()
}
}
// [------------------MAP & PIN MECHANICS------------------------------------------------------]
// Controls the Zoom button which zooms into the user
@IBAction func zoomOnUser(_ sender: AnyObject) {
let userLocation = mapView.userLocation
let region = MKCoordinateRegionMakeWithDistance(userLocation.location!.coordinate, 200, 200)
mapView.setRegion(region, animated: true)
}
@IBAction func changeMapButton(_ sender: AnyObject) {
if mapView.mapType == MKMapType.hybrid{
mapView.mapType = MKMapType.standard
viewBelowNav.backgroundColor = UIColor.brown.withAlphaComponent(0.8)
} else{
mapView.mapType = MKMapType.hybrid
viewBelowNav.backgroundColor = UIColor.white.withAlphaComponent(0.8)
}
}
//Controls the functionality of the pop up
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let pinLocation = view.annotation as! PinLocation
let pinTitle = "\(pinLocation.title!) : (\(pinLocation.pointVal) Points)"
let pinHint = pinLocation.hint
let alertCon = UIAlertController(title: pinTitle, message: pinHint, preferredStyle: .alert)
// Adds a text field and checks for points
alertCon.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "Enter code:"})
alertCon.addAction(UIAlertAction(title: "OK", style: .default, handler: {(action) -> Void in
let textField = alertCon.textFields![0] as UITextField
if (textField.text?.lowercased() == pinLocation.codeword.lowercased() && pinLocation.isFound == false && self.isGameOn == true){
self.points += pinLocation.pointVal
self.updatePoints()
pinLocation.isFound = true
let currentPinIndex = self.activePins.index(of: pinLocation)
self.activePins.remove(at: currentPinIndex!)
mapView.removeAnnotation(pinLocation)
self.alertCorrectIncor(true, pointVal: pinLocation.pointVal)
}
else{
self.alertCorrectIncor(false, pointVal: pinLocation.pointVal)
}
}))
present(alertCon, animated: true, completion: nil)
}
// Funcation creates the callout button on the sides of annotation and reuses views
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "PinLocation"
if annotation is PinLocation {
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
//If no free views exist then a new view is created
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
let btn = UIButton(type: .detailDisclosure)
annotationView!.rightCalloutAccessoryView = btn
}
else {
annotationView!.annotation = annotation
}
return annotationView
}
return nil
}
// [------------------------------------ PACK SELECTOR MECHANICS----------------------------------------------------]
@IBAction func selectMapPackButtonTapped(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier :"packSelector") as! MainGamePackSelectorViewController
viewController.delegate = self
self.present(viewController, animated: true)
}
func packSelectedHandler(selectedPackKey: String, packCreatorID: String, gameType: String){
self.selectedPackKey = selectedPackKey
self.packCreatorID = packCreatorID
self.gameType = gameType
if !(self.selectedPackKey.isEmpty || self.packCreatorID.isEmpty || self.gameType.isEmpty){
userPackDictName = "UserID-\(packCreatorID)-LocalPacks"
let defaults = UserDefaults.standard
if let dictOfPacksOnPhone = defaults.dictionary(forKey: userPackDictName){
filename = dictOfPacksOnPhone[selectedPackKey] as! String
packData = loadPackFromFile(filename: filename, userPackDictName: userPackDictName, selectedPackKey: selectedPackKey, userID: packCreatorID)
gamePins = getListOfPinLocations(packData: packData)
isPackLoaded = true
packSelectedButton.isHidden = false
packSelectedButton.setTitle("Pack Selected: \(selectedPackKey)", for: UIControlState())
gameTypeButton.isHidden = false
gameTypeButton.setTitle("Game Type: \(gameType.uppercased())", for: UIControlState())
} else{
displayAlertMessage(alertTitle: "Error", alertMessage: "Data Couldn't be loaded")
}
} else{
displayAlertMessage(alertTitle: "Error", alertMessage: "Selected pack data not passed")
}
}
// [------------------------------- GAME MECHANICS ------------------------------------]
// Resets the game to the default game settings
func resetGame(){
selectMapPackButton.isHidden = false
menuOpenNavBarButton.accessibilityElementsHidden = false
countDownTime = Int(packData["TimeLimit"] as! String)! * 60
points = 0
isGameOn = false
timeToNextNewPin = 0
showEndScreen = false
activePins = []
gamePins = getListOfPinLocations(packData: packData)
pointsButtonLabel.setTitle("Points: 0", for: UIControlState())
menuOpenNavBarButton.isEnabled = true
packSelectedButton.isHidden = false
gameTypeButton.isHidden = false
}
//When the button is pressed the timer is started the the game begins
@IBAction func startButton(_ sender: AnyObject) {
if isGameOn == false{
if isPackLoaded == false {
displayAlertMessage(alertTitle: "No Pin Pack Selected", alertMessage: "Tap 'Select Pin Pack' to chose a pack")
}else if gamePins.count < 4{
displayAlertMessage(alertTitle: "Too Few Pins", alertMessage: "The selected pack has too few pins please add more")
}
else{
resetGame()
packSelectedButton.isHidden = true
gameTypeButton.isHidden = true
selectMapPackButton.isHidden = true
menuOpenNavBarButton.isEnabled = false
endGameButtonLabel.isEnabled = true
isGameOn = true
if playerUserID == packCreatorID{
displayAlertMessage(alertTitle: "You Made This Pack!", alertMessage: "Since you created this pack, your score will not be uploaded to the leaderboard")
}
if gameType == "competitive"{
for _ in 0...3{
addRandomPinToActivePinList()
}
mapView.addAnnotations(activePins)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(MainGameScreenViewController.updateTime), userInfo: nil, repeats: true)
updateTime(timer)
} else{
activePins = gamePins
mapView.addAnnotations(activePins)
startButtonLabel.setTitle("Casual Mode", for: UIControlState())
displayAlertMessage(alertTitle: "Casual Mode Game", alertMessage: "There is no time limit so take your time to explore and hunt for the pins! Once you have finished tap 'End Game'")
}
}
}
}
//Updates points the user has scored
func updatePoints(){
pointsButtonLabel.setTitle("Points: \(points)", for: UIControlState())
}
//This function updates the timer
func updateTime(_ timer: Timer){
print("GP: \(gamePins.count)")
print("AP: \(activePins.count)")
if(countDownTime > 0 && isGameOn == true){
let minutes = String(countDownTime / 60)
let seconds = countDownTime % 60
var disSecs = ""
if seconds < 10{
disSecs = "0" + String(seconds)
} else{
disSecs = String(seconds)
}
startButtonLabel.setTitle(minutes + ":" + disSecs, for: UIControlState())
countDownTime -= 1
if timeToNextNewPin > 0{
timeToNextNewPin -= 1
} else if (timeToNextNewPin == 0 && gamePins.isEmpty == false){
addRandomPinToActivePinList()
timeToNextNewPin = randomTimeGen(countDownTime/2)
}
}
else{
endGame()
}
}
//Creates the alert telling the user if the codework entered is correct or incorrect
func alertCorrectIncor(_ isCorrect: Bool, pointVal: Int){
var alertTitle: String = ""
var alertMessage: String = ""
if isCorrect == true{
alertTitle = "Well Done!"
alertMessage = "\(pointVal) Points Added"
Sound().playSound("CorrectSound")
}else{
alertTitle = "Incorrect!"
alertMessage = "Try Again!"
Sound().playSound("Wrong-answer-sound-effect")
}
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
// Generates a random number between 0 and maxNum
func randomTimeGen(_ maxNum: Int) -> Int{
return Int(arc4random_uniform(UInt32(maxNum)))
}
// Adds a pin from the gamePin array to the map screen
func addRandomPinToActivePinList(){
Sound().playSound("Message-alert-tone")
let newPinIndex = randomTimeGen(gamePins.count)
self.mapView.addAnnotation(gamePins[newPinIndex])
activePins.append(gamePins[newPinIndex])
gamePins.remove(at: newPinIndex)
}
@IBAction func endGameButton(_ sender: AnyObject) {
let alert = UIAlertController(title: "End the Game", message: "Do you really want to end the game ", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .default, handler: {(action) -> Void in
self.endGame()
})
alert.addAction(yesAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
func endScreen(){
if showEndScreen == false{
let alert = UIAlertController(title: "GAME OVER!", message: "You Scored \(points).", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
showEndScreen = true
}
}
func endGame(){
Sound().playSound("Game-over-yeah")
timer.invalidate()
startButtonLabel.setTitle("Start", for: UIControlState())
isGameOn = false
if playerUserID != packCreatorID{
addRecordToDB(score: String(points))
}
self.mapView.removeAnnotations(activePins)
endScreen()
resetGame()
pointsButtonLabel.setTitle("Pack Details", for: UIControlState())
endGameButtonLabel.isEnabled = false
}
func addRecordToDB(score: String){
let packID = packData["PackID"] as! String
let postData = "PackID=\(packID)&PlayerUserID=\(playerUserID)&Score=\(score)&GameType=\(gameType)"
// Initialises database interaction object
let dbInteraction = DatabaseInteraction()
// Tests for internet connectivity
if dbInteraction.connectedToNetwork(){
let responseJSON = dbInteraction.postToDatabase(apiName: "addPlayedPackRecord.php", postData: postData){ (dbResponse: NSDictionary) in
let isError = dbResponse["error"]! as! Bool
let dbMessage = dbResponse["message"]! as! String
print(dbResponse)
// Displays a message to the user indicating the sucessfull/unsucessfull creation of a new pack
DispatchQueue.main.async(execute: {
if isError{
self.displayAlertMessage(alertTitle: "Error", alertMessage: dbMessage)
} else{
print("Score Record added to database")
}
})
}
} else{ // If no internet connectivity, an error message is diplayed asking the user to connect to the internet
let alertCon = UIAlertController(title: "Error: Couldn't Connect to Database", message: "No internet connectivity found. Please check your internet connection", preferredStyle: .alert)
alertCon.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { action in
// Recursion is used to recall the function until internet connectivity is restored
self.addRecordToDB(score: score)
}))
self.present(alertCon, animated: true, completion: nil)
}
}
// [----------------------------System Mechanics-----------------------------------------]
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
if let segueIdentifier = identifier {
if segueIdentifier == "MainGameScreenToPackDetail" {
if isPackLoaded == false {
displayAlertMessage(alertTitle: "No Pack is Loaded", alertMessage: "Tap 'Select Pin Pack' to chose a pack")
return false
} else if isGameOn {
return false
}
}
}
return true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "MainGameScreenToPackDetail" {
if let nextVC = segue.destination as? PackDetailsViewController{
var packDetails = packData
packDetails.removeValue(forKey: "Pins")
nextVC.packDetails = packDetails as! [String : String]
nextVC.isPackDetailsEditable = false
}
}
}
}
| apache-2.0 | a934589dd97d721dfa07dfe6660306d9 | 42.568345 | 201 | 0.609863 | 5.186412 | false | false | false | false |
iOS-Connect/PushNotifications | Pods/PusherSwift/Source/PusherGlobalChannel.swift | 1 | 2683 | //
// PusherGlobalChannel.swift
// PusherSwift
//
// Created by Hamilton Chapman on 01/04/2016.
//
//
open class GlobalChannel: PusherChannel {
open var globalCallbacks: [String : (Any?) -> Void] = [:]
/**
Initializes a new GlobalChannel instance
- parameter connection: The connection associated with the global channel
- returns: A new GlobalChannel instance
*/
init(connection: PusherConnection) {
super.init(name: "pusher_global_internal_channel", connection: connection)
}
/**
Calls the appropriate callbacks for the given event name in the scope of the global channel
- parameter name: The name of the received event
- parameter data: The data associated with the received message
- parameter channelName: The name of the channel that the received message was triggered
to, if relevant
*/
internal func handleEvent(name: String, data: String, channelName: String?) {
for (_, callback) in self.globalCallbacks {
if let channelName = channelName {
callback(["channel": channelName, "event": name, "data": data] as [String: Any])
} else {
callback(["event": name, "data": data] as [String: Any])
}
}
}
/**
Calls the appropriate callbacks for the given event name in the scope of the global channel
- parameter name: The name of the received event
- parameter data: The data associated with the received message
*/
internal func handleErrorEvent(name: String, data: [String: AnyObject]) {
for (_, callback) in self.globalCallbacks {
callback(["event": name, "data": data])
}
}
/**
Binds a callback to the global channel
- parameter callback: The function to call when a message is received
- returns: A unique callbackId that can be used to unbind the callback at a later time
*/
internal func bind(_ callback: @escaping (Any?) -> Void) -> String {
let randomId = UUID().uuidString
self.globalCallbacks[randomId] = callback
return randomId
}
/**
Unbinds the callback with the given callbackId from the global channel
- parameter callbackId: The unique callbackId string used to identify which callback to unbind
*/
internal func unbind(callbackId: String) {
globalCallbacks.removeValue(forKey: callbackId)
}
/**
Unbinds all callbacks from the channel
*/
override open func unbindAll() {
globalCallbacks = [:]
}
}
| mit | 828d1cd5b5f7d955c8450ed1b7b0f875 | 32.123457 | 102 | 0.620947 | 4.950185 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/Swift4Semanas (7.0).playground/Pages/S3 - Classes, Estruturas e Enums.xcplaygroundpage/Contents.swift | 1 | 2027 | //: [Anterior: Enumerações](@previous)
// Playground - noun: a place where people can play
import UIKit
// Classes e Estruturas
struct Resolução {
// Propriedades ; Stored Properties (Propriedades de Armazenamento)
var largura = 0
var altura = 0
}
class AiPhone {
// Propriedades
var resolução = Resolução()
var desbloqueado = false
var peso = 0
var dono: String?
}
var umiPhone = AiPhone() //Initializer Syntax
var umaResolução = Resolução()
umiPhone.desbloqueado //dot syntax
umaResolução.largura
umiPhone.resolução.altura
umiPhone.desbloqueado = true
umaResolução.largura = 1920
// Memberwise Initializers.
var fullHD = Resolução(largura: 1920, altura: 1080)
// Tipo Valor vs Referência
class Pessoa {
var nome = ""
var idade = 18
}
var pessoa = Pessoa()
var antigaResolução = Resolução(largura: 1920, altura: 1080)
var mesmaPessoa = pessoa // Classe: tipo ref.
var novaResolução = antigaResolução // Struct: tipo valor.
mesmaPessoa.nome = "João"
pessoa //alterou aqui também
novaResolução.altura = 480
antigaResolução //altura permaneceu a mesma
// Enumerations também são do tipo valor
enum Cor {
case Vermelho, Laranja, Amarelo, Verde, Ciano, Azul, Violeta
}
var corSelecionada = Cor.Laranja
var corPreferida = corSelecionada
corSelecionada = Cor.Amarelo
if corPreferida == .Laranja {
print("A cor preferida continua sendo laranja")
}
if corSelecionada == .Amarelo {
print("A cor selecionada mudou pra Amarelo")
}
// Operadores Identidade (===, !==)
if pessoa === mesmaPessoa {
print("pessoa e mesmaPessoa se referem a mesma instância")
}
var umaOutraPessoa = Pessoa()
if pessoa !== umaOutraPessoa {
print("pessoa e umaOutraPessoa não se referem a mesma instância")
}
// (===) Idêntico
// (==) Igual
// (=) Atribiução
//: [Próximo: Propriedades](@next)
| mit | ef3d552a2474f7b42b46c542b146bbc2 | 14.137405 | 71 | 0.662632 | 2.882267 | false | false | false | false |
AlexRamey/mbird-iOS | iOS Client/HTTPClient/ArticleDTO.swift | 1 | 1150 | //
// ArticleDTO.swift
// iOS Client
//
// Created by Alex Ramey on 6/24/18.
// Copyright © 2018 Mockingbird. All rights reserved.
//
import UIKit
struct ArticleDTO: Codable {
var articleId: Int
var date: String
var link: String
var title: Content
var authorId: Int
var imageId: Int
var content: Content
var categoryIds: [Int]
enum CodingKeys: String, CodingKey {
case articleId = "id"
case date = "date_gmt"
case link
case title
case authorId = "author"
case imageId = "featured_media"
case content
case categoryIds = "categories"
}
func toDomain() -> Article {
return Article(articleId: self.articleId, date: self.date, link: self.link, title: self.title.rendered, authorId: self.authorId, author: nil, imageId: self.imageId, image: nil, content: self.content.rendered, categoryIds: self.categoryIds, categories: [], isBookmarked: false)
}
}
struct Content: Codable {
var rendered: String
enum CodingKeys: String, CodingKey {
case rendered
}
}
| mit | aa7c4b6ef08667cb6c4f36bbc46da3f2 | 25.72093 | 284 | 0.615318 | 4.088968 | false | false | false | false |
finn-no/Finjinon | Sources/Shared/UIElements/CloseButton.swift | 1 | 2008 | //
// Copyright © 2019 FINN.no. All rights reserved.
//
import UIKit
class CloseButton: UIButton {
var strokeColor = UIColor.black {
didSet { setNeedsDisplay() }
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.lightGray.withAlphaComponent(0.9)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
layer.masksToBounds = true
}
override func draw(_ dirtyRect: CGRect) {
super.draw(dirtyRect)
// Draw a +
let centerPoint = CGPoint(x: bounds.midX, y: bounds.midY)
let radius: CGFloat = bounds.insetBy(dx: floor(bounds.width / 8), dy: floor(bounds.width / 8)).width / 2
let ratio: CGFloat = 0.5
let xPath = UIBezierPath()
xPath.move(to: centerPoint)
xPath.addLine(to: CGPoint(x: centerPoint.x, y: centerPoint.y + (radius * ratio)))
xPath.move(to: centerPoint)
xPath.addLine(to: CGPoint(x: centerPoint.x, y: centerPoint.y - (radius * ratio)))
xPath.move(to: centerPoint)
xPath.addLine(to: CGPoint(x: centerPoint.x + (radius * ratio), y: centerPoint.y))
xPath.move(to: centerPoint)
xPath.addLine(to: CGPoint(x: centerPoint.x - (radius * ratio), y: centerPoint.y))
xPath.move(to: centerPoint)
xPath.close()
// Rotate path by 45° around its center
let pathBounds = xPath.cgPath.boundingBox
xPath.apply(CGAffineTransform(translationX: -pathBounds.midX, y: -pathBounds.midY))
xPath.apply(CGAffineTransform(rotationAngle: CGFloat(45.0 * Double.pi / 180.0)))
xPath.apply(CGAffineTransform(translationX: pathBounds.midX, y: pathBounds.midY))
xPath.lineWidth = 2
xPath.lineCapStyle = CGLineCap.round
strokeColor.setStroke()
xPath.stroke()
}
}
| mit | d70d5eddc0fa5ee14cbf79a6101e9747 | 32.433333 | 112 | 0.633101 | 4.110656 | false | false | false | false |
radazzouz/firefox-ios | Client/Frontend/Browser/BackForwardListViewController.swift | 1 | 9578 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import WebKit
import Storage
import SnapKit
struct BackForwardViewUX {
static let RowHeight = 50
static let BackgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.4)
static let BackgroundColorPrivate = UIColor(colorLiteralRed: 0.5, green: 0.5, blue: 0.5, alpha: 0.4)
}
class BackForwardListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate {
fileprivate let BackForwardListCellIdentifier = "BackForwardListViewController"
fileprivate var profile: Profile
fileprivate lazy var sites = [String: Site]()
fileprivate var isPrivate: Bool
fileprivate var dismissing = false
fileprivate var currentRow = 0
fileprivate var verticalConstraints: [Constraint] = []
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.separatorStyle = .none
tableView.dataSource = self
tableView.delegate = self
tableView.alwaysBounceVertical = false
tableView.register(BackForwardTableViewCell.self, forCellReuseIdentifier: self.BackForwardListCellIdentifier)
tableView.backgroundColor = self.isPrivate ? BackForwardViewUX.BackgroundColorPrivate:BackForwardViewUX.BackgroundColor
let blurEffect = UIBlurEffect(style: self.isPrivate ? .dark : .extraLight)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
return tableView
}()
lazy var shadow: UIView = {
let shadow = UIView()
shadow.backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.2)
return shadow
}()
var tabManager: TabManager!
weak var bvc: BrowserViewController?
var currentItem: WKBackForwardListItem?
var listData = [WKBackForwardListItem]()
var tableHeight: CGFloat {
get {
assert(Thread.isMainThread, "tableHeight interacts with UIKit components - cannot call from background thread.")
return min(CGFloat(BackForwardViewUX.RowHeight*listData.count), self.view.frame.height/2)
}
}
var backForwardTransitionDelegate: UIViewControllerTransitioningDelegate? {
didSet {
self.transitioningDelegate = backForwardTransitionDelegate
}
}
var snappedToBottom: Bool = true
init(profile: Profile, backForwardList: WKBackForwardList, isPrivate: Bool) {
self.profile = profile
self.isPrivate = isPrivate
super.init(nibName: nil, bundle: nil)
loadSites(backForwardList)
loadSitesFromProfile()
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(shadow)
view.addSubview(tableView)
self.snappedToBottom = self.bvc?.toolbar != nil
tableView.snp.makeConstraints { make in
make.height.equalTo(0)
make.left.right.equalTo(self.view)
}
shadow.snp.makeConstraints { make in
make.left.right.equalTo(self.view)
}
remakeVerticalConstraints()
view.layoutIfNeeded()
scrollTableViewToIndex(currentRow)
setupDismissTap()
}
func loadSitesFromProfile() {
let sql = profile.favicons as! SQLiteHistory
let urls = self.listData.flatMap {$0.url.isLocal ? $0.url.getQuery()["url"]?.unescape() : $0.url.absoluteString}
sql.getSitesForURLs(urls).uponQueue(DispatchQueue.main) { result in
guard let results = result.successValue else {
return
}
// Add all results into the sites dictionary
results.flatMap({$0}).forEach({site in
if let url = site?.url {
self.sites[url] = site
}
})
self.tableView.reloadData()
}
}
func loadSites(_ bfList: WKBackForwardList) {
let items = bfList.forwardList.reversed() + [bfList.currentItem].flatMap({$0}) + bfList.backList.reversed()
self.currentItem = bfList.currentItem
//error url's are OK as they are used to populate history on session restore.
listData = items.filter({return !($0.url.isLocal && ($0.url.originalURLFromErrorURL?.isLocal ?? true))})
}
func scrollTableViewToIndex(_ index: Int) {
guard index > 1 else {
return
}
let moveToIndexPath = IndexPath(row: index-2, section: 0)
self.tableView.reloadRows(at: [moveToIndexPath], with: .none)
self.tableView.scrollToRow(at: moveToIndexPath, at: UITableViewScrollPosition.middle, animated: false)
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
guard let bvc = self.bvc else {
return
}
if bvc.shouldShowFooterForTraitCollection(newCollection) != snappedToBottom {
tableView.snp.updateConstraints { make in
if snappedToBottom {
make.bottom.equalTo(self.view).offset(0)
} else {
make.top.equalTo(self.view).offset(0)
}
make.height.equalTo(0)
}
snappedToBottom = !snappedToBottom
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let correctHeight = {
self.tableView.snp.updateConstraints { make in
make.height.equalTo(min(CGFloat(BackForwardViewUX.RowHeight * self.listData.count), size.height / 2))
}
}
coordinator.animate(alongsideTransition: nil) { _ in
self.remakeVerticalConstraints()
correctHeight()
}
}
func remakeVerticalConstraints() {
guard let bvc = self.bvc else {
return
}
for constraint in self.verticalConstraints {
constraint.deactivate()
}
self.verticalConstraints = []
tableView.snp.makeConstraints { make in
if snappedToBottom {
verticalConstraints += [make.bottom.equalTo(self.view).offset(-bvc.footer.frame.height).constraint]
} else {
verticalConstraints += [make.top.equalTo(self.view).offset(bvc.header.frame.height + UIApplication.shared.statusBarFrame.size.height).constraint]
}
}
shadow.snp.makeConstraints() { make in
if snappedToBottom {
verticalConstraints += [
make.bottom.equalTo(tableView.snp.top).constraint,
make.top.equalTo(self.view).constraint
]
} else {
verticalConstraints += [
make.top.equalTo(tableView.snp.bottom).constraint,
make.bottom.equalTo(self.view).constraint
]
}
}
}
func setupDismissTap() {
let tap = UITapGestureRecognizer(target: self, action: #selector(BackForwardListViewController.handleTap))
tap.cancelsTouchesInView = false
tap.delegate = self
view.addGestureRecognizer(tap)
}
func handleTap() {
dismiss(animated: true, completion: nil)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if touch.view?.isDescendant(of: tableView) ?? true {
return false
}
return true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: BackForwardListCellIdentifier, for: indexPath) as! BackForwardTableViewCell
let item = listData[indexPath.item]
let urlString = item.url.isLocal ? item.url.getQuery()["url"]?.unescape() : item.url.absoluteString
guard let url = urlString else {
return cell // This should never happen.
}
if let site = sites[url] {
cell.site = site
} else {
cell.site = Site(url: url, title: item.title ?? "")
}
cell.isCurrentTab = listData[indexPath.item] == self.currentItem
cell.connectingBackwards = indexPath.item != listData.count-1
cell.connectingForwards = indexPath.item != 0
cell.isPrivate = isPrivate
cell.setNeedsDisplay()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tabManager.selectedTab?.goToBackForwardListItem(listData[indexPath.item])
dismiss(animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(BackForwardViewUX.RowHeight)
}
}
| mpl-2.0 | 36a64a46204cb07eadf1325853a295d5 | 37.159363 | 161 | 0.633744 | 5.121925 | false | false | false | false |
dsay/POPDataSources | Sources/POPDataSources/Extensions/DataSource+TableView.swift | 1 | 2697 | import UIKit
public extension UITableView {
func cellView<T: ReuseIdentifier>() -> T? {
return dequeueReusableCell(withIdentifier: T.identifier) as? T
}
func headerFooterView<T: ReuseIdentifier>() -> T? {
return dequeueReusableHeaderFooterView(withIdentifier: T.identifier) as? T
}
func register<T: ReuseIdentifier>(class: T.Type) {
let identifier = T.identifier
self.register(T.self, forCellReuseIdentifier: identifier)
}
func register<T: ReuseIdentifier>(headerFooterViewClass: T.Type) {
let identifier = T.identifier
self.register(T.self, forHeaderFooterViewReuseIdentifier: identifier)
}
func register<T: ReuseIdentifier>(_ headerFooterView: T.Type) {
let identifier = headerFooterView.identifier
self.register(UINib(nibName: identifier , bundle: nil), forHeaderFooterViewReuseIdentifier: identifier)
}
func register<T: ReuseIdentifier>(cell: T.Type) {
let identifier = cell.identifier
self.register(UINib(nibName: identifier , bundle: nil), forCellReuseIdentifier: identifier)
}
}
public extension UITableView {
func collapse<T: Collapsible>(_ dataSource: T, at section: Int = 0) {
let indexPaths = (0..<dataSource.numberOfItems()).map {
IndexPath(row: $0, section: section)
}
dataSource.open = false
self.deleteRows(at: indexPaths, with: .fade)
}
func expand<T: Collapsible>(_ dataSource: T, at section: Int = 0) {
let indexPaths = (0..<dataSource.numberOfItems()).map {
IndexPath(row: $0, section: section)
}
dataSource.open = true
self.insertRows(at: indexPaths, with: .fade)
}
}
public extension UITableView {
func show(_ emptyView: UIView?) {
if let view = emptyView, self.backgroundView != view {
self.backgroundView = view
}
}
func hideEmptyView() {
self.backgroundView = nil
}
}
public extension UITableView {
func filter<T: DataFilterable>(_ dataSource: T, at section: Int = 0, action: () -> Void ) {
let origin = dataSource.filtered()
action()
let diff = origin.changes(to: dataSource.filtered())
let deleted = diff.removed.map({ IndexPath(row: $0, section: section)})
let inserted = diff.inserted.map({ IndexPath(row: $0, section: section)})
beginUpdates()
if !deleted.isEmpty { deleteRows(at: deleted, with: .automatic) }
if !inserted.isEmpty { insertRows(at: inserted, with: .automatic) }
endUpdates()
}
}
| mit | a2e73af3df43c4e15834dd6d0ecd16b4 | 30.729412 | 111 | 0.62106 | 4.618151 | false | false | false | false |
Lee-junha/tvOS-controller | tvOS-controller/ViewController.swift | 1 | 22208 | //
// ViewController.swift
// tvOS-controller
//
// Created by Paul Jones on 02/11/2015.
// Copyright © 2015 Fluid Pixel Limited. All rights reserved.
//
import Foundation
import UIKit
import SceneKit
class ViewController: UIViewController, TVCTVSessionDelegate, SCNSceneRendererDelegate {
@IBOutlet var messageArea: UILabel!
@IBOutlet var button1: UIButton!
@IBOutlet var button2: UIButton!
@IBOutlet var button3: UIButton!
@IBOutlet weak var accelView: SCNView!
@IBOutlet weak var messageView: UITextView!
let remote = TVCTVSession()
@IBOutlet weak var DrawCanvas : UIImageView!
var gameObjects = [GameObject]()
var timer = Timer()
//vehicles
var vehicle: SCNPhysicsVehicle?
var vectorToMoveBy = SCNVector3(0, 0, 1)
var firstRun = true
var initialTime = 0.0
var numberOfPlayers = 4
//testing
let angle = sin(M_PI_4 / 2.0)
//scene nodes
let cameraNode = SCNNode()
let lightNode = SCNNode()
var groundNode = SCNNode()
var carNode = SCNNode()
var trackNode = SCNNode()
//boxes
var boxNode = SCNNode()
var boxNode2 = SCNNode()
//update variables
var accel : Float = 0.0
var speed : Float = 0.0
var previousOrientation = SCNQuaternion()
var glkRepresentation = GLKQuaternion()
var slerp = 0.0
var isSlerping = false
//y, p, r variables
var intialYPR : [Float] = [0.0,0.0,0.0]
var currentYPR : [Float] = [0.0,0.0,0.0]
// draw
var lastPoint = CGPoint.zero
override func viewDidLoad() {
super.viewDidLoad()
self.remote.delegate = self
accelView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
prepareScene()
accelView.play(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
//called first, any pre-render game logic here
}
func renderer(_ renderer: SCNSceneRenderer, didSimulatePhysicsAtTime time: TimeInterval) {
//physics updates here
//print(time)
if firstRun {
//time zero
updateCar(0.0)
initialTime = time
firstRun = false
} else {
updateCar((time - initialTime))
initialTime = time
}
}
func updateCar(_ delta: TimeInterval) {
//move car in the direction it is currently facing
carNode.runAction(SCNAction.moveBy(x: CGFloat(vectorToMoveBy.x * Float(delta) * (accel)), y: 0.0, z: CGFloat(vectorToMoveBy.z * Float(delta) * (accel)), duration: delta))
speed = vectorToMoveBy.magnitudeSquared()
cameraNode.position = SCNVector3(carNode.position.x + 10, carNode.position.y + 10, carNode.position.z)
// if isSlerping {
// slerp += delta
//
// var slerpAmount = slerp / 1.0
//
// if slerpAmount > 1.0 {
// slerpAmount = 1.0
// isSlerping = false
// }
//
// let tempGLK = GLKQuaternionMake(carNode.orientation.x, carNode.orientation.y, carNode.orientation.z, carNode.orientation.w)
// let result = GLKQuaternionSlerp(tempGLK, glkRepresentation, Float(slerpAmount))
//carNode.orientation.y = result.y
//let angle = tempGLK.AngleFromQuaternion(result)
let angle = (currentYPR[0]) //pitch
carNode.runAction((SCNAction.rotate(by: CGFloat(angle * Float(delta)), around: SCNVector3(0, 1, 0), duration: delta)), completionHandler: { () -> Void in
self.intialYPR = self.currentYPR
})
let matrix = SCNMatrix4MakeRotation((angle * Float(delta)), 0, 1, 0)
vectorToMoveBy = vectorToMoveBy.multiplyByMatrix4(matrix)
// intialYPR = [carNode.eulerAngles.x, carNode.eulerAngles.y, carNode.eulerAngles.z]
//let temp = GLKQuaternionRotateVector3(result, GLKVector3(v: (vectorToMoveBy.x, vectorToMoveBy.y, vectorToMoveBy.z)))
//vectorToMoveBy = SCNVector3(temp.x, temp.y, temp.z)
// }
}
func prepareScene(){
accelView.scene = SCNScene()
accelView.scene!.physicsWorld.gravity = SCNVector3(x: 0.0, y: -9.8, z: 0.0)
//camera
let camera = SCNCamera()
cameraNode.camera = camera
cameraNode.position = SCNVector3(-10.0, 10.0, 10.0)
let ambientLight = SCNLight()
ambientLight.type = SCNLight.LightType.ambient
ambientLight.color = UIColor(red: 0.5, green: 0.5, blue: 0.0, alpha: 1.0)
cameraNode.light = ambientLight
//light
let light = SCNLight()
light.type = SCNLight.LightType.directional
light.castsShadow = true
lightNode.light = light
lightNode.position = SCNVector3(x: 1.5, y: 1.5, z: 1.5)
// //object
// let carScene : SCNScene = SCNScene(named: "gameAssets.scnassets/AudiCoupe.dae")!
//
// if let tempNode = carScene.rootNode.childNodeWithName("Car", recursively: true){
// carNode = tempNode
// carNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.0)
// if carNode.geometry == nil {
// carNode.geometry = SCNBox(width: 1.0, height: 1.0, length: 2.0, chamferRadius: 0.0)
// }
// let physicsShape = SCNPhysicsShape(geometry: carNode.geometry!, options: nil)
// let physicsBody = SCNPhysicsBody(type: .Dynamic, shape: physicsShape)
// carNode.physicsBody = physicsBody
//
// accelView.scene!.rootNode.addChildNode(carNode)
//
// //let axisNode = SCNNode()
// }else {
// print("Could not load car")
// }
//add some placed boxes
let box = SCNBox(width: 1.0, height: 1.0, length: 1.0, chamferRadius: 0.0)
let boxMaterial = SCNMaterial()
boxMaterial.diffuse.contents = UIColor.red
box.materials = [boxMaterial]
boxNode.position = SCNVector3(x: 5.0, y: 0.0, z: 5.0)
let physicsBox = SCNPhysicsShape(geometry: box, options: nil)
let boxBody = SCNPhysicsBody(type: .static, shape: physicsBox)
boxNode = SCNNode(geometry: box)
boxNode.physicsBody = boxBody
boxNode2 = boxNode
boxNode2.position = SCNVector3(x: 1.0, y: 0.0, z: 1.0)
//accelView.scene!.rootNode.addChildNode(boxNode)
//accelView.scene!.rootNode.addChildNode(boxNode2)
//track
setupTrack()
setupPlayers()
//ground
let ground = SCNFloor()
ground.reflectivity = 0
let groundMaterial = SCNMaterial()
groundMaterial.diffuse.contents = UIColor.blue
let physicsShape = SCNPhysicsShape(geometry: SCNFloor(), options: nil)
let body = SCNPhysicsBody(type: .static, shape: physicsShape)
ground.materials = [groundMaterial]
groundNode = SCNNode(geometry: ground)
groundNode.physicsBody = body
groundNode.position = SCNVector3(x: 0, y: -0.5, z: 0)
previousOrientation = groundNode.orientation
accelView.scene!.rootNode.addChildNode(cameraNode)
accelView.scene!.rootNode.addChildNode(lightNode)
accelView.scene!.rootNode.addChildNode(groundNode)
}
func setupPlayers() {
//four 'players'
for i in 0 ..< numberOfPlayers {
if let carScene : SCNScene = SCNScene(named: "gameAssets.scnassets/rc_car.dae") {
if let chassisNode : SCNNode = carScene.rootNode.childNode(withName: "rccarBody", recursively: false) {
chassisNode.position = SCNVector3Make(Float(i * 10), 10.0, 0)
chassisNode.rotation = SCNVector4Make(0, 1, 0, Float(M_PI))
if chassisNode.geometry?.materials != nil {
chassisNode.geometry!.materials[0].diffuse.contents = setPlayerColours(i)
}
let body : SCNPhysicsBody = SCNPhysicsBody.dynamic()
body.allowsResting = false
body.mass = 80
body.restitution = 0.1
body.friction = 0.5
body.rollingFriction = 0
chassisNode.physicsBody = body
accelView.scene!.rootNode.addChildNode(chassisNode)
//wheels
if let wheelNode1 : SCNNode = chassisNode.childNode(withName: "wheelLocator_FL", recursively: true) {
if let wheelNode2 : SCNNode = chassisNode.childNode(withName: "wheelLocator_FR", recursively: true) {
if let wheelNode3 : SCNNode = chassisNode.childNode(withName: "wheelLocator_RL", recursively: true) {
if let wheelNode4 : SCNNode = chassisNode.childNode(withName: "wheelLocator_RR", recursively: true) {
let wheel1 = SCNPhysicsVehicleWheel(node: wheelNode1)
let wheel2 = SCNPhysicsVehicleWheel(node: wheelNode2)
let wheel3 = SCNPhysicsVehicleWheel(node: wheelNode3)
let wheel4 = SCNPhysicsVehicleWheel(node: wheelNode4)
var min = SCNVector3Zero
var max = SCNVector3Zero
wheelNode1.__setBoundingBoxMin(&min, max: &max)
let wheelHalfWidth : Float = (Float(0.5) * (max.x - min.x))
wheel1.connectionPosition =
wheelNode1.convertPosition(SCNVector3Zero, to: chassisNode) + SCNVector3(wheelHalfWidth, 0.0, 0.0)
wheel2.connectionPosition =
wheelNode2.convertPosition(SCNVector3Zero, to: chassisNode) - SCNVector3(wheelHalfWidth, 0.0, 0.0)
wheel3.connectionPosition =
wheelNode3.convertPosition(SCNVector3Zero, to: chassisNode) + SCNVector3(wheelHalfWidth, 0.0, 0.0)
wheel4.connectionPosition =
wheelNode4.convertPosition(SCNVector3Zero, to: chassisNode) - SCNVector3(wheelHalfWidth, 0.0, 0.0)
let vehicle = SCNPhysicsVehicle(chassisBody: chassisNode.physicsBody!, wheels: [wheel1, wheel2, wheel3, wheel4])
accelView.scene?.physicsWorld.addBehavior(vehicle)
self.vehicle = vehicle
var gameobject = GameObject()
gameobject.sceneNode = chassisNode
gameobject.ID = i
gameobject.physicsVehicle = vehicle
gameObjects.append(gameobject)
//constraints
let constraint = SCNLookAtConstraint(target: gameObjects[0].sceneNode)
cameraNode.constraints = [constraint]
lightNode.constraints = [constraint]
}
}
}
}
}
}
}
// for i in 0..< numberOfPlayers {
// // }
// }
}
func setupTrack() {
if let trackScene : SCNScene = SCNScene(named: "gameAssets.scnassets/BasicTrack.dae") {
if let tempNode = trackScene.rootNode.childNode(withName: "BezierCircle", recursively: true) {
trackNode = tempNode
trackNode.position = SCNVector3(x: 0.0, y: 0.0, z: 0.0)
//trackNode.scale = SCNVector3(5, 1, 5)
let geometry = trackNode.geometry
let shape = SCNPhysicsShape(geometry: geometry!, options: nil)
let body = SCNPhysicsBody(type: .kinematic, shape: shape)
trackNode.physicsBody = body
accelView.scene?.rootNode.addChildNode(trackNode)
}
}
}
func setPlayerColours( _ i : Int) -> UIColor {
switch i {
case 0:
return UIColor.red
case 1:
return UIColor.yellow
case 2:
return UIColor.green
case 3:
return UIColor.blue
default:
return UIColor.black
}
}
@IBAction func button1Pressed() {
sendButtonPressed("Button 1")
DrawCanvas.isHidden = true
// messageView.hidden = false
}
@IBAction func button2Pressed() {
sendButtonPressed("Button 2")
DrawCanvas.isHidden = false
messageView.isHidden = true
}
@IBAction func button3Pressed() {
sendButtonPressed("Button 3")
}
fileprivate func sendButtonPressed(_ buttonText:String) {
self.write(buttonText)
remote.broadcastMessage(["ButtonPressed":buttonText], replyHandler: {
(deviceID:String, reply:[String : Any]) -> Void in
self.write("Reply from \(deviceID) - \(reply)")
}) {
(error) -> Void in
self.write("Error \(error)")
}
}
fileprivate func write(_ line:String) {
DispatchQueue.main.async {
let existingText = self.messageView.text!
self.messageView.text = "\(existingText)\n\(line)"
}
}
func drawLineFrom(_ fromPoint: CGPoint, toPoint: CGPoint) {
UIGraphicsBeginImageContext(DrawCanvas.frame.size)
let context = UIGraphicsGetCurrentContext()
DrawCanvas.image?.draw(in: CGRect(x : 0 , y: 0, width: DrawCanvas.frame.size.width, height: DrawCanvas.frame.size.height))
context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(5.0)
context?.setStrokeColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
context?.setBlendMode(CGBlendMode.normal)
context?.strokePath()
DrawCanvas.image = UIGraphicsGetImageFromCurrentImageContext()
DrawCanvas.alpha = 1.0
UIGraphicsEndImageContext()
}
func didReceiveMessage(_ message: [String : Any], fromDevice: String) {
self.write("Message received: \(message) from: \(fromDevice)")
}
func didReceiveMessage(_ message: [String : Any], fromDevice: String, replyHandler: ([String : Any]) -> Void) {
self.didReceiveMessage(message, fromDevice: fromDevice)
var foundPlayerFromDevice = -1
//link device to player
// for var i in 0 ..< gameObjects.count && foundPlayerFromDevice == -1 {
// i = i + 1
// if gameObjects[i].playerID == nil { //no device ID
// gameObjects[i].playerID = fromDevice
// foundPlayerFromDevice = i
// } else if gameObjects[i].playerID == fromDevice {
// foundPlayerFromDevice = i
// }
// }
// for (var i = 0; i < gameObjects.count && foundPlayerFromDevice == -1; i += 1 ){
//
//
// }
print("Device \(fromDevice) is attached to Player \(foundPlayerFromDevice)")
//detect which form of data is being sent over
if message.keys.first == "Button" {
switch message.values.first! as! Int {
case 1:
button1Pressed()
break
case 2:
button2Pressed()
break
case 3:
button3Pressed()
break
default:
break
}
}else if message.keys.first == "Accelerometer" {
let tempValue = message.values.first as! [Float]
//check for change first
//quaternions
if tempValue.count == 4 {
if (abs(previousOrientation.x - tempValue[0]) > 0.01 || abs(previousOrientation.y - tempValue[1]) > 0.01 || abs(previousOrientation.z - tempValue[2]) > 0.01) && !previousOrientation.isZero() {
glkRepresentation = GLKQuaternionMake(tempValue[0], tempValue[1], tempValue[2], tempValue[3])
print("rotate by \(tempValue)")
previousOrientation = SCNVector4(x: tempValue[0], y: tempValue[1], z: tempValue[2], w: tempValue[3])
isSlerping = true
}else if previousOrientation.isZero() {
previousOrientation = SCNVector4(x: tempValue[0], y: tempValue[1], z: tempValue[2], w: tempValue[3])
}
}
//yaw/pitch/roll
if tempValue.count == 3 {
if (abs(intialYPR[0] - tempValue[0]) > 0.01 || abs(intialYPR[1] - tempValue[1]) > 0.01 || abs(intialYPR[2] - tempValue[2]) > 0.01) && intialYPR != [0.0, 0.0,0.0]{
print("pitch : \(tempValue[0]), yaw: \(tempValue[1]), roll: \(tempValue[2])")
currentYPR = tempValue
} else if intialYPR == [0.0, 0.0,0.0]{
intialYPR = tempValue
currentYPR = tempValue
}
}
} else if message.keys.first == "DrawBegin" {
let temp = message.values.first as! [Float]
lastPoint = CGPoint(x: CGFloat(temp[0]), y: CGFloat(temp[1]))
} else if message.keys.first == "DrawMove" {
let temp = message.values.first as! [Float]
let currentPoint = CGPoint(x: CGFloat(temp[0]), y: CGFloat(temp[1]))
drawLineFrom(lastPoint, toPoint: currentPoint)
lastPoint = currentPoint
} else if message.keys.first == "DrawEnd" {
drawLineFrom(lastPoint, toPoint: lastPoint)
}else if message.keys.first == "Speed" {
//increase acceleration
let value = (message.values.first as! Float)
accel += value
//this will be redone when integrated w/ the physics
if message.values.first as! Int == 0 {
}else if accel < -50 {
accel = -50
} else if accel > 50 {
accel = 50
}
//timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("OnTimerFired"), userInfo: nil, repeats: true)
}
replyHandler(["Reply": speed as AnyObject])
}
func deviceDidConnect(_ device: String) {
self.write("Connected: \(device)")
}
func deviceDidDisconnect(_ device: String) {
self.write("Disconnected: \(device)")
}
fileprivate func OnTimerFired(_ accelerating : Bool) {
}
}
func +(l: SCNVector3, r:SCNVector3) -> SCNVector3 {
return SCNVector3(l.x + r.x, l.y + r.y, l.z + r.z)
}
func -(l: SCNVector3, r:SCNVector3) -> SCNVector3 {
return SCNVector3(l.x - r.x, l.y - r.y, l.z - r.z)
}
extension SCNQuaternion {
/**
Checks for empty/all zero quaternions
- Returns: returns true if Quaternion is all zero
*/
func isZero() -> Bool {
if self.x == 0.0 && self.y == 0.0 && self.z == 0.0 && self.w == 0.0 {
return true
} else {
return false
}
}
}
extension SCNVector3 {
func multiplyByMatrix4(_ mat4: SCNMatrix4) -> SCNVector3 {
return SCNVector3(
self.x * mat4.m11 + self.y * mat4.m21 + self.z * mat4.m31,
self.x * mat4.m12 + self.y * mat4.m22 + self.z * mat4.m32,
self.x * mat4.m13 + self.y * mat4.m23 + self.z * mat4.m33)
}
func magnitudeSquared() -> Float {
return ((self.x * self.x) + (self.y * self.y) + (self.z + self.z))
}
}
extension GLKQuaternion {
/**
Finds the angle between two quaternions
- Returns: returns the angle in radians
*/
func AngleFromQuaternion(_ quat : GLKQuaternion) -> Float {
let inv = GLKQuaternionInvert(self)
let result = GLKQuaternionMultiply(quat, inv)
let angle = acosf(result.w) * 2.0
if angle > Float(M_PI_2) {
return (Float(M_PI) - angle)
} else {
return angle
}
}
}
| mit | e33bebeaa509ac71fe1fa853cfad1791 | 36.011667 | 204 | 0.519026 | 4.587275 | false | false | false | false |
ZB0106/MCSXY | MCSXY/MCSXY/Macro/APIHeader.swift | 1 | 5260 | //
// APIHeader.swift
// MCSXY
//
// Created by 瞄财网 on 2017/6/21.
// Copyright © 2017年 瞄财网. All rights reserved.
//
import Foundation
//pragma mark - 内网测试
// base url
//let MiaoCaiBaseUrl = "http://192.168.1.88:8080/MiaoCai/";
//let MiaoCaiBaseUrl = "http://192.168.1.203:8080/MiaoCai/";
// image base url
//let BaseImageUrl = "http://112.126.85.213:90";
//pragma mark - 外网测试
// base url
//let MiaoCaiBaseUrl = "http://47.93.117.116:6080/MiaoCai/";
// image base url
//let BaseImageUrl = "http://47.93.117.116:90";
//pragma mark - 生产
// base url
let MiaoCaiBaseUrl = "http://app.miaocaiwang.com/MiaoCai/";
// image base url
let BaseImageUrl = "http://app.miaocaiwang.com";
// 验证验证码
let API_getCheckPhoneCode = "getCheckPhoneCode";
// 注册
let API_Register = "Register";
// 获取未注册验证码
let API_GetRegisterCode = "getNotRegYZCode";
// 获取已注册验证码
let API_GetVerifyCode = "getYZCode";
// 登陆
let API_Login = "Login";
// 修改密码
let API_UpdatePassword = "updatePassword";
// 重置密码
let API_getPassword = "getPassword";
// 修改手机号
let API_UpdateMobile = "updateMobile";
// 修改邮箱
let API_UpdateEmail = "updateEmail";
// 修改头像
let API_UpdateAvatar = "updateAvatar";
// 修改昵称
let API_updateUserNickName = "updateUserNickName";
// 首页
let API_Home = "GetHomePage";
// 公告列表
let API_NoticeList = "getArticleMore";
// 公告详情
let API_getArticleDetail = "getArticleDetail";
// 讲师列表
let API_TeacherList = "getTeacherMore";
// 讲师详情
let API_TeacherDetail = "getTeacherDetail";
// 讲师详情的讲师课程
let API_getTeacherDetailMore = "getTeacherDetailMore";
// 直播列表
let API_LiveList = "getLiveMore";
// 直播详情
let API_getLiveDetail = "getLiveDetail";
// 课程推荐
let API_getLiveDetailMore = "getLiveDetailMore";
// 录播列表筛选课程类型数据
let API_getSysSubjectList = "getSysSubjectList";
// 录播课程推荐
let API_getCourseDetailMore = "getCourseDetailMore";
// 获取录播课程目录
let API_getKpointList = "getKpointList";
// 录播列表
let API_VideoList = "getCourseMore";
// 录播详情
let API_getCourseDetail = "getCourseDetail";
// 已评论列表
let API_getAssessList = "getAssessList";
// 学员评论
let API_insertAssessList = "insertAssessList";
// 顶部课程搜索
let API_getTopSearchCourse = "getTopSearchCourse";
// 顶部讲师搜索
let API_getTopSearchTeacher = "getTopSearchTeacher";
// 热门搜索
let API_getTopSearchDefault = "getTopSearchDefault";
// 系统消息中心
let API_getMsgSystemList = "getMsgSystemList";
// 系统消息中心(编辑)
let API_delAppMsgReceive = "delAppMsgReceive";
// 资产中心
let API_getAccountHistoryList = "getAccountHistoryList";
// 直播课在线报名
let API_insertLiveReg = "insertLiveReg";
// 直播课分院报名
let API_insertCourseReg = "insertCourseReg";
// 直播课分院报名获取分院信息
let API_getCourtsList = "getCourtsList";
// 获取省、直辖市
let API_getProvinceList = "getProvinceList";
// 获取市区
let API_getCityList = "getCityList";
// 获取县
let API_getTownList = "getTownList";
// 观看记录(新增)
let API_insertStudyHistory = "insertStudyHistory";
// 观看记录
let API_getCourseStudyHistoryList = "getCourseStudyHistoryList";
// 会员权益
let API_getEduVipShowList = "getEduVipShowList";
// 会员特权说明
let API_getEduVipPrivilegeDetail = "getEduVipPrivilegeDetail";
// 苹果内购
let API_getApplePay = "getApplePay";
// 苹果内购完成验证
let API_getApplePayNotifyToApp = "getApplePayNotifyToApp";
// 观看记录(编辑)
let API_delStudyHistory = "delStudyHistory";
// 我的收藏(新增)
let API_insertAppCourseFavorites = "insertAppCourseFavorites";
// 我的收藏
let API_getAppCourseFavoritesList = "getAppCourseFavoritesList";
// 我的收藏(编辑)
let API_delAppCourseFavorites = "delAppCourseFavorites";
// 我的关注
let API_getAppUserAttentionList = "getAppUserAttentionList";
// 我的关注(新增)
let API_insertUserAttention = "insertUserAttention";
// 我的关注(取消)
let API_delUserAttention = "delUserAttention";
// 建议反馈
let API_insertAppUserFeedBack = "insertAppUserFeedBack";
// 关于我们
let API_getAppAboutUsDetail = "getAppAboutUsDetail";
// 我的直播课(已直播)
let API_getAppCourseLiveRegList = "getAppCourseLiveRegList";
// 我的直播课(未直播)
let API_getAppCourseLiveRegListNot = "getAppCourseLiveRegListNot";
// 报名成功详情分院信息
let API_getCourseRegSuccess = "getCourseRegSuccess";
// 报名推荐分院
let API_getCourtsDetail = "getCourtsDetail";
// 会员卡类型
let API_getMemberSaleList = "getMemberSaleList";
// 发票内容
let API_getInvoiceApplySetList = "getInvoiceApplySetList";
| mit | 5edea8f5cd9d2f980af0cb6d7e38f5b2 | 28.160256 | 66 | 0.676852 | 2.973203 | false | false | false | false |
coderQuanjun/PigTV | GYJTV/GYJTV/Classes/Live/Model/GiftModel.swift | 1 | 688 | //
// GiftModel.swift
// GYJTV
//
// Created by zcm_iOS on 2017/5/25.
// Copyright © 2017年 Quanjun. All rights reserved.
//
import UIKit
class GiftModel: BaseModel {
var img2 : String = "" // 图片url
var coin : Int = 0 // 价格
var subject : String = "" { // 礼物名称
didSet{
if subject.contains("(有声)") {
subject = subject.replacingOccurrences(of: "(有声)", with: "")
}
}
}
override init(dic : [String : Any]) {
super.init()
img2 = dic["img2"] as? String ?? ""
coin = dic["coin"] as? Int ?? 0
subject = dic["subject"] as? String ?? ""
}
}
| mit | 49ca88d5c6c2087a79e86fc172ca195b | 21.793103 | 76 | 0.494705 | 3.497354 | false | false | false | false |
gnachman/iTerm2 | iTermFileProvider/ItemCreator.swift | 2 | 5710 | //
// ItemCreator.swift
// FileProvider
//
// Created by George Nachman on 6/10/22.
//
import Foundation
import FileProvider
import FileProviderService
actor ItemCreator {
struct Request: CustomDebugStringConvertible {
let itemTemplate: NSFileProviderItem
let fields: NSFileProviderItemFields
let contents: URL?
let options: NSFileProviderCreateItemOptions
let request: NSFileProviderRequest
let progress = Progress()
var debugDescription: String {
return "<ItemCreator.Request template=\(itemTemplate.terseDescription) fields=\(fields.description) contents=\(contents.descriptionOrNil) options=\(options.description) request=\(request.description)>"
}
}
struct Item {
let item: NSFileProviderItem
let fields: NSFileProviderItemFields
let shouldFetchContent: Bool
}
private let domain: NSFileProviderDomain
private let manager: NSFileProviderManager
private let remoteService: RemoteService
init(domain: NSFileProviderDomain, remoteService: RemoteService) {
self.domain = domain
self.remoteService = remoteService
manager = NSFileProviderManager(for: domain)!
}
func create(_ request: Request) async throws -> Item {
try await logging("create(\(request))") {
guard let file = RemoteFile(template: request.itemTemplate,
fields: request.fields) else {
// There isn't an appropriate exception for when we don't support a file
// type (e.g., aliases).
throw NSFileProviderError(.noSuchItem)
}
let data: Data
if request.fields.contains(.contents), let url = request.contents {
data = try Data(contentsOf: url, options: .alwaysMapped)
log("content=\(data.stringOrHex)")
} else {
log("No content - using empty data just in case")
data = Data()
}
switch file.kind {
case .symlink(let target):
log("Create symlink")
_ = try await remoteService.ln(
source: await rebaseLocalFile(manager, path: target),
file: file)
case .folder:
log("Create folder")
try await remoteService.mkdir(file)
case .file(_):
log("Create file")
request.progress.totalUnitCount = Int64(data.count)
try await remoteService.create(file, content: data)
request.progress.completedUnitCount = Int64(data.count)
case .host:
log("Create host")
throw NSFileProviderError(.noSuchItem) // no appropriate error exists
}
return Item(item: await FileProviderItem(file, manager: manager),
fields: [],
shouldFetchContent: false)
}
}
}
extension RemoteFile {
init?(template: NSFileProviderItem,
fields: NSFileProviderItemFields) {
guard let kind = Self.kind(template, fields) else {
return nil
}
self.init(kind: kind,
absolutePath: Self.path(template),
permissions: Self.permissions(template, fields),
ctime: Self.ctime(template, fields),
mtime: Self.mtime(template, fields))
}
private static func ctime(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Date {
if fields.contains(.creationDate),
case let creationDate?? = template.creationDate {
return creationDate
}
return Date()
}
private static func mtime(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Date {
if fields.contains(.contentModificationDate),
case let modifiationDate?? = template.contentModificationDate {
return modifiationDate
}
return Date()
}
private static func permissions(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Permissions {
if fields.contains(.fileSystemFlags), let flags = template.fileSystemFlags {
return Permissions(fileSystemFlags: flags)
}
return Permissions(r: true, w: true, x: true)
}
private static func path(_ template: NSFileProviderItem) -> String {
var url = URL(fileURLWithPath: template.parentItemIdentifier.rawValue)
url.appendPathComponent(template.filename)
return url.path
}
private static func kind(_ template: NSFileProviderItem,
_ fields: NSFileProviderItemFields) -> Kind? {
switch template.contentType {
case .folder?:
return .folder
case .symbolicLink?:
if fields.contains(.contents),
case let target?? = template.symlinkTargetPath {
return .symlink(target)
}
log("symlink without target not allowed")
return nil
case .aliasFile?:
log("aliases not supported")
return nil
default:
return .file(FileInfo(size: nil))
}
}
}
extension RemoteFile.Permissions {
init(fileSystemFlags flags: NSFileProviderFileSystemFlags) {
self.init(r: flags.contains(.userReadable),
w: flags.contains(.userWritable),
x: flags.contains(.userExecutable))
}
}
| gpl-2.0 | b9cba7a66acd6e4d96f9ba852599ea0d | 34.465839 | 213 | 0.585289 | 5.341441 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/MaxArea.swift | 1 | 558 | //
// MaxArea.swift
// LeetCode
//
// Created by jourhuang on 2021/1/9.
// Copyright © 2021 伯驹 黄. All rights reserved.
//
import Foundation
func maxArea(_ height: [Int]) -> Int {
var left = 0
var right = height.count - 1
var maxArea = (right - left) * min(height[left], height[right])
while left < right {
if height[left] > height[right] {
right -= 1
} else {
left += 1
}
maxArea = max(maxArea, (right - left) * min(height[left], height[right]))
}
return maxArea
}
| mit | 61bba734f407ed7b4fc47cb77c08154a | 21.958333 | 81 | 0.551724 | 3.380368 | false | false | false | false |
linggaozhen/Living | LivingApplication/LivingApplication/Classess/Home/Controller/GameViewController.swift | 1 | 4817 | //
// GameViewController.swift
// LivingApplication
//
// Created by ioser on 17/5/22.
// Copyright © 2017年 ioser. All rights reserved.
//------------------------首页‘游戏’控制器--------------------
import UIKit
private let margin : CGFloat = 10
private let gameItemW = (KScreenW - 2 * margin) / 3
private let gameItemH = gameItemW * 6 / 5
private let gameCollectionCellID = "gameCollectionCellID"
private let headerRuserID = "headerID"
private let KTopHeaderViewH : CGFloat = 50
private let KTopGameViewH : CGFloat = 90
class GameViewController: UIViewController {
private var dataSourecArray : [GameModel] = [GameModel]()
// 创建headerView
lazy var topHeaderView : CollectionHeaderView = {
let headerView = CollectionHeaderView.createHeaderView()
headerView.frame = CGRect(x: 0, y: -(KTopHeaderViewH + KTopGameViewH), width: KScreenW, height: KTopHeaderViewH)
headerView.tag_icon.image = UIImage.init(named: "Img_orange")
headerView.tagName.text = "常见"
headerView.moreButton.hidden = true
return headerView
}()
// 创建显示游戏的滚动View
lazy var showGameContentView : RecommerGameView = {
let gameView = NSBundle.mainBundle().loadNibNamed("RecommerGameView", owner: nil, options: nil).first as? RecommerGameView
gameView?.frame = CGRect(x: 0, y: -KTopGameViewH, width: KScreenW, height: KTopGameViewH)
gameView!.backgroundColor = UIColor.redColor()
return gameView!
}()
lazy private var gameCollectionView : UICollectionView = {
// layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: gameItemW, height: gameItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsetsMake(0, margin, 0, margin)
layout.headerReferenceSize = CGSize(width: KScreenW, height: 40)
// colllectionView
let CLTV = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
CLTV.registerNib(UINib(nibName: "GameCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: gameCollectionCellID)
CLTV.registerNib(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerRuserID)
CLTV.backgroundColor = UIColor.whiteColor()
return CLTV
}()
override func viewDidLoad() {
super.viewDidLoad()
UISetting()
requestGameData()
}
}
// MARK: - 请求数据
extension GameViewController {
private func requestGameData() {
HomeViewModel.loadGameData { (modelArray) in
self.dataSourecArray = modelArray
self.showGameContentView.gameControllerData = modelArray
self.gameCollectionView.reloadData()
}
}
}
// MARK: - UI
extension GameViewController {
private func UISetting() {
// 添加CollectionView
gameCollectionView.frame = view.bounds
gameCollectionView.dataSource = self
view.addSubview(gameCollectionView)
// 顶部HeaderView
gameCollectionView.addSubview(topHeaderView)
gameCollectionView.contentInset = UIEdgeInsetsMake(KTopHeaderViewH + KTopGameViewH, 0, 0, 0)
// 顶部游戏View
gameCollectionView.addSubview(showGameContentView)
}
}
// MARK: - DataSource 方法
extension GameViewController : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSourecArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(gameCollectionCellID, forIndexPath: indexPath) as? GameCollectionViewCell
let model = self.dataSourecArray[indexPath.item]
cell?.titleLabel.text = model.tag_name
let url = NSURL(string: model.icon_url)
cell?.iconImageView.kf_setImageWithURL(url!)
return cell!
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerRuserID, forIndexPath: indexPath) as? CollectionHeaderView
headerView?.moreButton.hidden = true
headerView?.tagName.text = "游戏"
headerView?.tag_icon.image = UIImage.init(named: "Img_orange")
return headerView!
}
}
| apache-2.0 | 46ce9940558eb6c56c9333f70f68a4a4 | 37.520325 | 202 | 0.697552 | 5.078242 | false | false | false | false |
megavolt605/CNLFoundationTools | CNLFoundationTools/CNLFT+Date.swift | 1 | 5258 | //
// CNLFT+Date.swift
// CNLFoundationTools
//
// Created by Igor Smirnov on 11/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import Foundation
public extension Date {
/// Convert date from UTC
public var fromUTC: Date {
let calendar: Calendar = Calendar.current
return addingTimeInterval(TimeInterval(calendar.timeZone.secondsFromGMT()))
}
/// Convert date to UTC
public var toUTC: Date {
let calendar: Calendar = Calendar.current
return addingTimeInterval(-TimeInterval(calendar.timeZone.secondsFromGMT()))
}
/// Convert date to string with format specified
///
/// - Parameter format: Format string
/// - Returns: String with date conforming specified format
public func toStringWithFormat(format: String) -> String {
let fmt = DateFormatter()
fmt.dateFormat = format
return fmt.string(from: self)
}
/// String with ISO date
public var ISODate: String {
let f = DateFormatter()
f.timeZone = TimeZone(abbreviation: "UTC")
f.dateFormat = "yyyy-MM-dd"
return f.string(from: self)
}
/// Stirng with ISO time
public var ISOTime: String {
let f = DateFormatter()
f.timeZone = TimeZone(abbreviation: "UTC")
f.dateFormat = "HH:mm:ss.SSSSSS"
return f.string(from: self)
}
/// String with ISO date and time
public var ISODateTime: String {
let f = DateFormatter()
f.timeZone = TimeZone(abbreviation: "UTC")
f.dateFormat = "yyyy:MM:dd HH:mm:ss"
return f.string(from: self)
}
/// Checks for date is in today
public var isToday: Bool {
let calendar = Calendar.autoupdatingCurrent
return calendar.isDateInToday(self)
}
/// Checks for date is in yesterday
public var isYesterday: Bool {
let calendar = Calendar.autoupdatingCurrent
return calendar.isDateInYesterday(self)
}
/// Checks for date is in tomorrow
public var isTomorrow: Bool {
let calendar = Calendar.autoupdatingCurrent
return calendar.isDateInTomorrow(self)
}
/// Return number of days since now
public var daysAgo: Int {
return daysEarlier(than: Date())
}
/// Number of days when self is earlier than argument
///
/// - Parameter date: Source date
/// - Returns: Number of days, or 0 in case self is later than parameter
public func daysEarlier(than date: Date) -> Int {
return abs(min(days(from: date), 0))
}
/// Returns most earlier date form self and parameter
///
/// - Parameter date: Source date
/// - Returns: Most earlier date
public func earlierDate(_ date: Date) -> Date {
return (self.timeIntervalSince1970 <= date.timeIntervalSince1970) ? self : date
}
/// Days between self and parameter using custom calendar
///
/// - Parameters:
/// - date: Source date
/// - calendar: Calendar instance (will used Calendar.autoupdatingCurrent when not specified)
/// - Returns: <#return value description#>
public func days(from date: Date, calendar: Calendar? = nil) -> Int {
var calendarCopy = calendar
if calendar == nil {
calendarCopy = Calendar.autoupdatingCurrent
}
let earliest = earlierDate(date)
let latest = (earliest == self) ? date : self
let multiplier = (earliest == self) ? -1 : 1
let components = calendarCopy!.dateComponents([.day], from: earliest, to: latest)
return multiplier*components.day!
}
/// Weekday of the date
public var weekday: Int {
return component(.weekday)
}
/// Extract calendar component from the date
///
/// - Parameter component: Component to extract
/// - Returns: Result value
public func component(_ component: Calendar.Component) -> Int {
let calendar = Calendar.autoupdatingCurrent
return calendar.component(component, from: self)
}
/// Returns string with relative date information from now (today, yesterday, 2..6 days ago or date in short format)
///
/// - Parameter date: Date to compare with
/// - Returns: Result string
public func relative() -> String {
let dateFormatter = DateFormatter()
dateFormatter.doesRelativeDateFormatting = true
if isToday {
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .none
} else if isYesterday {
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
} else if daysAgo < 6 {
return dateFormatter.weekdaySymbols[weekday - 1]
} else {
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .short
}
return dateFormatter.string(from: self)
}
}
/// Additional date comparision operators (greater or equal)
public func >= (left: Date, right: Date) -> Bool {
return !(left < right)
}
/// Additional date comparision operators (lesser or equal)
public func <= (left: Date, right: Date) -> Bool {
return !(left > right)
}
| mit | bca02f2a8e587fbfca818f42dacfa0a6 | 31.450617 | 120 | 0.620506 | 4.761775 | false | false | false | false |
ProcedureKit/ProcedureKit | Sources/TestingProcedureKit/QueueTestDelegate.swift | 2 | 4860 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
import ProcedureKit
public class QueueTestDelegate: ProcedureQueueDelegate {
public typealias OperationCheckType = (ProcedureQueue, Operation, Any?)
public typealias OperationFinishType = (ProcedureQueue, Operation)
public typealias ProcedureCheckType = (ProcedureQueue, Procedure, Any?)
public typealias ProcedureFinishType = (ProcedureQueue, Procedure, Error?)
public var procedureQueueWillAddOperation: [OperationCheckType] {
get { return _procedureQueueWillAddOperation.read { $0 } }
}
public var procedureQueueDidAddOperation: [OperationCheckType] {
get { return _procedureQueueDidAddOperation.read { $0 } }
}
public var procedureQueueDidFinishOperation: [OperationFinishType] {
get { return _procedureQueueDidFinishOperation.read { $0 } }
}
public var procedureQueueWillAddProcedure: [ProcedureCheckType] {
get { return _procedureQueueWillAddProcedure.read { $0 } }
}
public var procedureQueueDidAddProcedure: [ProcedureCheckType] {
get { return _procedureQueueDidAddProcedure.read { $0 } }
}
public var procedureQueueWillFinishProcedure: [ProcedureFinishType] {
get { return _procedureQueueWillFinishProcedure.read { $0 } }
}
public var procedureQueueDidFinishProcedure: [ProcedureFinishType] {
get { return _procedureQueueDidFinishProcedure.read { $0 } }
}
private var _procedureQueueWillAddOperation = Protector([OperationCheckType]())
private var _procedureQueueDidAddOperation = Protector([OperationCheckType]())
private var _procedureQueueDidFinishOperation = Protector([OperationFinishType]())
private var _procedureQueueWillAddProcedure = Protector([ProcedureCheckType]())
private var _procedureQueueDidAddProcedure = Protector([ProcedureCheckType]())
private var _procedureQueueWillFinishProcedure = Protector([ProcedureFinishType]())
private var _procedureQueueDidFinishProcedure = Protector([ProcedureFinishType]())
private let callbackBlock: CallbackBlock
public enum CallbackKind {
case willAddOperation(ProcedureQueue, Operation, Any?)
case didAddOperation(ProcedureQueue, Operation, Any?)
case didFinishOperation(ProcedureQueue, Operation)
case willAddProcedure(ProcedureQueue, Procedure, Any?)
case didAddProcedure(ProcedureQueue, Procedure, Any?)
case willFinishProcedure(ProcedureQueue, Procedure, Error?)
case didFinishProcedure(ProcedureQueue, Procedure, Error?)
}
public typealias CallbackBlock = (CallbackKind) -> Void
// MARK: - Init
public init(callbackBlock: @escaping CallbackBlock = { _ in }) {
self.callbackBlock = callbackBlock
}
// MARK: - ProcedureQueueDelegate Methods
// Operations
public func procedureQueue(_ queue: ProcedureQueue, willAddOperation operation: Operation, context: Any?) -> ProcedureFuture? {
_procedureQueueWillAddOperation.append((queue, operation, context))
callbackBlock(.willAddOperation(queue, operation, context))
return nil
}
public func procedureQueue(_ queue: ProcedureQueue, didAddOperation operation: Operation, context: Any?) {
_procedureQueueDidAddOperation.append((queue, operation, context))
callbackBlock(.didAddOperation(queue, operation, context))
}
public func procedureQueue(_ queue: ProcedureQueue, didFinishOperation operation: Operation) {
_procedureQueueDidFinishOperation.append((queue, operation))
callbackBlock(.didFinishOperation(queue, operation))
}
// Procedures
public func procedureQueue(_ queue: ProcedureQueue, willAddProcedure procedure: Procedure, context: Any?) -> ProcedureFuture? {
_procedureQueueWillAddProcedure.append((queue, procedure, context))
callbackBlock(.willAddProcedure(queue, procedure, context))
return nil
}
public func procedureQueue(_ queue: ProcedureQueue, didAddProcedure procedure: Procedure, context: Any?) {
_procedureQueueDidAddProcedure.append((queue, procedure, context))
callbackBlock(.didAddProcedure(queue, procedure, context))
}
public func procedureQueue(_ queue: ProcedureQueue, willFinishProcedure procedure: Procedure, with error: Error?) -> ProcedureFuture? {
_procedureQueueWillFinishProcedure.append((queue, procedure, error))
callbackBlock(.willFinishProcedure(queue, procedure, error))
return nil
}
public func procedureQueue(_ queue: ProcedureQueue, didFinishProcedure procedure: Procedure, with error: Error?) {
_procedureQueueDidFinishProcedure.append((queue, procedure, error))
callbackBlock(.didFinishProcedure(queue, procedure, error))
}
}
| mit | 8864798806f57c612949ca53a72ddba8 | 42.383929 | 139 | 0.733484 | 5.098636 | false | false | false | false |
Czajnikowski/TrainTrippin | Pods/RxSwift/RxSwift/Observables/Observable+Single.swift | 3 | 14168 | //
// Observable+Single.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// MARK: distinct until changed
extension ObservableType where E: Equatable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged()
-> Observable<E> {
return self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) })
}
}
extension ObservableType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged<K: Equatable>(_ keySelector: @escaping (E) throws -> K)
-> Observable<E> {
return self.distinctUntilChanged(keySelector, comparer: { $0 == $1 })
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged(_ comparer: @escaping (E, E) throws -> Bool)
-> Observable<E> {
return self.distinctUntilChanged({ $0 }, comparer: comparer)
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func distinctUntilChanged<K>(_ keySelector: @escaping (E) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Observable<E> {
return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer)
}
}
// MARK: doOn
extension ObservableType {
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter eventHandler: Action to invoke for each event in the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)")
public func doOn(_ eventHandler: @escaping (Event<E>) throws -> Void)
-> Observable<E> {
return Do(source: self.asObservable(), eventHandler: eventHandler, onSubscribe: nil, onDispose: nil)
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onNext:onError:onCompleted:)")
public func doOn(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil)
-> Observable<E> {
return Do(source: self.asObservable(), eventHandler: { e in
switch e {
case .next(let element):
try onNext?(element)
case .error(let e):
try onError?(e)
case .completed:
try onCompleted?()
}
},
onSubscribe: nil,
onDispose: nil)
}
/**
Invokes an action for each Next event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onNext: Action to invoke for each element in the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onNext:)")
public func doOnNext(onNext: @escaping (E) throws -> Void)
-> Observable<E> {
return self.do(onNext: onNext)
}
/**
Invokes an action for the Error event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onError:)")
public func doOnError(onError: @escaping (Swift.Error) throws -> Void)
-> Observable<E> {
return self.do(onError: onError)
}
/**
Invokes an action for the Completed event in the observable sequence, and propagates all observer messages through the result sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
@available(*, deprecated, renamed: "do(onCompleted:)")
public func doOnCompleted(onCompleted: @escaping () throws -> Void)
-> Observable<E> {
return self.do(onCompleted: onCompleted)
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> ())? = nil, onDispose: (() -> ())? = nil)
-> Observable<E> {
return Do(source: self.asObservable(), eventHandler: { e in
switch e {
case .next(let element):
try onNext?(element)
case .error(let e):
try onError?(e)
case .completed:
try onCompleted?()
}
}, onSubscribe: onSubscribe, onDispose: onDispose)
}
}
// MARK: startWith
extension ObservableType {
/**
Prepends a sequence of values to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter elements: Elements to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func startWith(_ elements: E ...)
-> Observable<E> {
return StartWith(source: self.asObservable(), elements: elements)
}
}
// MARK: retry
extension ObservableType {
/**
Repeats the source observable sequence until it successfully terminates.
**This could potentially create an infinite sequence.**
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- returns: Observable sequence to repeat until it successfully terminates.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func retry() -> Observable<E> {
return CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()))
}
/**
Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates.
If you encounter an error and want it to retry once, then you must use `retry(2)`
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to repeat the sequence.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func retry(_ maxAttemptCount: Int)
-> Observable<E> {
return CatchSequence(sources: repeatElement(self.asObservable(), count: maxAttemptCount))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> Observable<E> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> Observable<E> {
return RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler)
}
}
// MARK: scan
extension ObservableType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
// @warn_unused_result(message:"http://git.io/rxs.uo")
public func scan<A>(_ seed: A, accumulator: @escaping (A, E) throws -> A)
-> Observable<A> {
return Scan(source: self.asObservable(), seed: seed, accumulator: accumulator)
}
}
| mit | f0c58e90c159cc67f437395a5577a4a4 | 47.187075 | 253 | 0.700007 | 4.817069 | false | false | false | false |
alexmay23/NetworkLayer | Sources/SSE.swift | 1 | 8916 | //
// EventSource.swift
// EventSource
//
// Created by Andres on 2/13/15.
// Copyright (c) 2015 Inaka. All rights reserved.
//
import Foundation
enum EventSourceState {
case connecting
case open
case closed
}
public final class EventSource: NSObject, URLSessionDataDelegate {
let url: URL
private let lastEventIDKey = "com.alexmay.eventSource.lastEventId"
private let receivedString: NSString?
typealias OnMessageCallback = (_ id: String?, _ event: String?, _ data: String?) -> Void
private var onOpenCallback: ((Void) -> Void)?
private var onErrorCallback: ((NSError?) -> Void)?
private var onMessageCallback: OnMessageCallback?
private(set) var readyState: EventSourceState
private(set) var retryTime = 3000
private var eventListeners = Dictionary<String, OnMessageCallback>()
private var headers: Dictionary<String, String>
internal var urlSession: URLSession?
internal var task : URLSessionDataTask?
private var operationQueue: OperationQueue
private var errorBeforeSetErrorCallBack: NSError?
var event = Dictionary<String, String>()
public init(url: URL, headers: [String : String]? = nil) {
self.url = url
self.headers = headers ?? [:]
self.readyState = EventSourceState.closed
self.operationQueue = OperationQueue()
self.receivedString = nil
super.init();
}
//Mark: Connect
public func connect() {
var additionalHeaders = self.headers
if let eventID = lastEventID {
additionalHeaders["Last-Event-Id"] = eventID
}
additionalHeaders["Accept"] = "text/event-stream"
additionalHeaders["Cache-Control"] = "no-cache"
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = TimeInterval(INT_MAX)
configuration.timeoutIntervalForResource = TimeInterval(INT_MAX)
configuration.httpAdditionalHeaders = additionalHeaders
readyState = EventSourceState.connecting
urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue);
task = urlSession!.dataTask(with: self.url);
task!.resume()
}
//Mark: Close
public func close() {
readyState = EventSourceState.closed
urlSession?.invalidateAndCancel()
}
//Mark: EventListeners
public func onOpen(_ onOpenCallback: @escaping (Void) -> Void) {
self.onOpenCallback = onOpenCallback
}
public func onError(_ onErrorCallback: @escaping (NSError?) -> Void) {
self.onErrorCallback = onErrorCallback
if let errorBeforeSet = self.errorBeforeSetErrorCallBack {
self.onErrorCallback!(errorBeforeSet)
self.errorBeforeSetErrorCallBack = nil;
}
}
public func onMessage(_ onMessageCallback: @escaping (_ id: String?, _ event: String?, _ data: String?) -> Void) {
self.onMessageCallback = onMessageCallback
}
public func addEventListener(_ event: String, handler: @escaping (_ id: String?, _ event: String?, _ data: String?) -> Void) {
self.eventListeners[event] = handler
}
//MARK: NSURLSessionDataDelegate
var stringBuffer: String = String()
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if readyState != EventSourceState.open {
return
}
var buffer = [UInt8](repeating: 0, count: data.count)
(data as NSData).getBytes(&buffer, length: data.count)
if let receivedString = String(bytes: buffer, encoding: String.Encoding.utf8) {
if receivedString.contains(EncodingCharacters.LFLF)
{
let components = receivedString.components(separatedBy: EncodingCharacters.LFLF)
components.forEach{
if !$0.isEmpty{
parseEventStream($0)
}
}
}
}
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping ((Foundation.URLSession.ResponseDisposition) -> Void)) {
completionHandler(Foundation.URLSession.ResponseDisposition.allow)
readyState = EventSourceState.open
if(self.onOpenCallback != nil) {
DispatchQueue.main.async {
self.onOpenCallback!()
}
}
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
readyState = EventSourceState.closed
if(error == nil || (error! as NSError).code != -999) {
let nanoseconds = Double(self.retryTime) / 1000.0 * Double(NSEC_PER_SEC)
let delayTime = DispatchTime.now() + Double(Int64(nanoseconds)) / Double(NSEC_PER_SEC);
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.connect()
}
}
DispatchQueue.main.async {
if let errorCallback = self.onErrorCallback {
errorCallback(error as NSError?)
}else {
self.errorBeforeSetErrorCallBack = error as NSError?;
}
}
}
struct EncodingCharacters {
static let LFLF = "\n\n"
}
private func parseEventStream(_ event: String) {
if event.isEmpty {
return
}
if event.hasPrefix(":") {
return
}
if (event as NSString).contains("retry:") {
if let reconnectTime = parseRetryTime(event) {
self.retryTime = reconnectTime
}
}
let parsedEvent = parseEvent(event) as (id: String?, event: String?, data: String?)
self.lastEventID = parsedEvent.id
if parsedEvent.event != nil && parsedEvent.data != nil {
if(self.onMessageCallback != nil) {
DispatchQueue.main.async {
self.onMessageCallback!(self.lastEventID,parsedEvent.event, parsedEvent.data)
}
}
}
}
internal var lastEventID: String? {
set {
if let lastEventID = newValue {
let defaults = UserDefaults.standard
defaults.set(lastEventID, forKey: lastEventIDKey)
defaults.synchronize()
}
}
get {
let defaults = UserDefaults.standard
if let lastEventID = defaults.string(forKey: lastEventIDKey) {
return lastEventID
}
return nil
}
}
private func parseEvent(_ eventString: String) -> (id: String?, event: String?, data: String?) {
var event = Dictionary<String, String>()
for line in eventString.components(separatedBy: CharacterSet.newlines) as [String] {
autoreleasepool {
var key: NSString?, value: NSString?
let scanner = Scanner(string: line)
scanner.scanUpTo(":", into: &key)
scanner.scanString(":",into: nil)
scanner.scanUpTo("\n", into: &value)
if (key != nil && value != nil) {
if (event[key! as String] != nil) {
event[key! as String] = "\(event[key! as String]!)\n\(value!)"
} else {
event[key! as String] = value! as String
}
}
}
}
return (event["id"], event["event"], event["data"])
}
private func parseRetryTime(_ eventString: String) -> Int? {
var reconnectTime: Int?
let separators = CharacterSet(charactersIn: ":")
if let milli = eventString.components(separatedBy: separators).last {
let milliseconds = trim(milli)
if let intMiliseconds = Int(milliseconds) {
reconnectTime = intMiliseconds
}
}
return reconnectTime
}
private func trim(_ string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.whitespaces)
}
class public func basicAuth(_ username: String, password: String) -> String {
let authString = "\(username):\(password)"
let authData = authString.data(using: String.Encoding.utf8)
let base64String = authData!.base64EncodedString(options: Data.Base64EncodingOptions.lineLength76Characters)
return "Basic \(base64String)"
}
}
| mit | ecd5f26081493a448fd52ef5719aced4 | 33.030534 | 199 | 0.579071 | 5.132988 | false | false | false | false |
elegion/ios-Flamingo | Framework/FlamingoTests/NetworkClient/NetworkClientBaseTestCase.swift | 1 | 1857 | ////
//// NetworkClientBaseTestCase.swift
//// FlamingoTests
////
//// Created by Dmitrii Istratov on 05-10-2017.
//// Copyright © 2017 ELN. All rights reserved.
////
//
import Flamingo
public protocol StubbableClient: class {
var stubsManager: StubsManager? { get set }
func enableStubs()
func disableStubs()
}
final class NetworkDefaultClientStubs: NetworkDefaultClient, StubbableClient {
struct Consts {
static let headers = [
(name: "Accept-Language", value: "da, en-gb;q=0.8, en;q=0.7"),
(name: "Cache-Control", value: "no-cache"),
]
}
var isUseCustomizedCustomHeaders = false
var stubsManager: StubsManager? {
didSet {
if let oldValue = oldValue {
removeMutater(oldValue)
}
}
}
func enableStubs() {
if let stubsManager = stubsManager {
addMutater(stubsManager)
}
}
func disableStubs() {
if let stubsManager = stubsManager {
removeMutater(stubsManager)
}
}
override func customHeadersForRequest<T: NetworkRequest>(_ networkRequest: T) -> [String: String]? {
if !isUseCustomizedCustomHeaders {
return super.customHeadersForRequest(networkRequest)
}
return Consts.headers.reduce(into: [:], {
result, tuple in
result[tuple.name] = tuple.value
})
}
}
extension NetworkDefaultClientStubs {
static func defaultForTest() -> NetworkDefaultClientStubs {
let configuration = NetworkDefaultConfiguration(baseURL: "http://example.com/", parallel: false)
let result = NetworkDefaultClientStubs(configuration: configuration, session: .shared)
result.stubsManager = StubsDefaultManager()
result.enableStubs()
return result
}
}
| mit | 77f8a87173ce0a668da9e4324f2a74dd | 25.898551 | 104 | 0.621228 | 4.594059 | false | true | false | false |
atrick/swift | test/type/protocol_types.swift | 5 | 4833 | // RUN: %target-typecheck-verify-swift
protocol HasSelfRequirements {
func foo(_ x: Self)
func returnsOwnProtocol() -> HasSelfRequirements // expected-error {{use of protocol 'HasSelfRequirements' as a type must be written 'any HasSelfRequirements'}}
}
protocol Bar {
// init() methods should not prevent use as an existential.
init()
func bar() -> Bar
}
func useBarAsType(_ x: Bar) {}
protocol Pub : Bar { }
func refinementErasure(_ p: Pub) {
useBarAsType(p)
}
typealias Compo = HasSelfRequirements & Bar
struct CompoAssocType {
typealias Compo = HasSelfRequirements & Bar
}
func useAsRequirement<T: HasSelfRequirements>(_ x: T) { }
func useCompoAsRequirement<T: HasSelfRequirements & Bar>(_ x: T) { }
func useCompoAliasAsRequirement<T: Compo>(_ x: T) { }
func useNestedCompoAliasAsRequirement<T: CompoAssocType.Compo>(_ x: T) { }
func useAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements {}
func useCompoAsWhereRequirement<T>(_ x: T) where T: HasSelfRequirements & Bar {}
func useCompoAliasAsWhereRequirement<T>(_ x: T) where T: Compo {}
func useNestedCompoAliasAsWhereRequirement<T>(_ x: T) where T: CompoAssocType.Compo {}
func useAsType(_: any HasSelfRequirements,
_: any HasSelfRequirements & Bar,
_: any Compo,
_: any CompoAssocType.Compo) { }
struct TypeRequirement<T: HasSelfRequirements> {}
struct CompoTypeRequirement<T: HasSelfRequirements & Bar> {}
struct CompoAliasTypeRequirement<T: Compo> {}
struct NestedCompoAliasTypeRequirement<T: CompoAssocType.Compo> {}
struct CompoTypeWhereRequirement<T> where T: HasSelfRequirements & Bar {}
struct CompoAliasTypeWhereRequirement<T> where T: Compo {}
struct NestedCompoAliasTypeWhereRequirement<T> where T: CompoAssocType.Compo {}
struct Struct1<T> { }
struct Struct2<T : Pub & Bar> { }
struct Struct3<T : Pub & Bar & P3> { } // expected-error {{cannot find type 'P3' in scope}}
struct Struct4<T> where T : Pub & Bar {}
struct Struct5<T : protocol<Pub, Bar>> { } // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}}
struct Struct6<T> where T : protocol<Pub, Bar> {} // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}}
typealias T1 = Pub & Bar
typealias T2 = protocol<Pub , Bar> // expected-error {{'protocol<...>' composition syntax has been removed; join the protocols using '&'}}
// rdar://problem/20593294
protocol HasAssoc {
associatedtype Assoc
func foo()
}
do {
enum MyError : Error {
case bad(Any)
}
func checkIt(_ js: Any) throws {
switch js {
case let dbl as HasAssoc: // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
throw MyError.bad(dbl)
default:
fatalError("wrong")
}
}
}
func testHasAssoc(_ x: Any, _: HasAssoc) { // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
if let p = x as? any HasAssoc {
p.foo() // don't crash here.
}
struct ConformingType : HasAssoc {
typealias Assoc = Int
func foo() {}
func method() -> HasAssoc {} // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
}
}
// SR-38
var b: HasAssoc // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
// Further generic constraint error testing - typealias used inside statements
protocol P {}
typealias MoreHasAssoc = HasAssoc & P
func testHasMoreAssoc(_ x: Any) {
if let p = x as? any MoreHasAssoc {
p.foo() // don't crash here.
}
}
struct Outer {
typealias Any = Int // expected-error {{keyword 'Any' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{13-16=`Any`}}
typealias `Any` = Int
static func aa(a: `Any`) -> Int { return a }
}
typealias X = Struct1<Pub & Bar>
_ = Struct1<Pub & Bar>.self
typealias AliasWhere<T> = T
where T : HasAssoc, T.Assoc == HasAssoc // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
struct StructWhere<T>
where T : HasAssoc,
T.Assoc == any HasAssoc {}
protocol ProtocolWhere where T == HasAssoc { // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
associatedtype T
associatedtype U : HasAssoc
where U.Assoc == any HasAssoc
}
extension HasAssoc where Assoc == HasAssoc {} // expected-error {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
func FunctionWhere<T>(_: T)
where T : HasAssoc,
T.Assoc == any HasAssoc {}
struct SubscriptWhere {
subscript<T>(_: T) -> Int
where T : HasAssoc,
T.Assoc == any HasAssoc {
get {}
set {}
}
}
struct OuterGeneric<T> {
func contextuallyGenericMethod() where T == any HasAssoc {}
}
| apache-2.0 | 673464e133a8b9934c9c070c4b9aef45 | 31.006623 | 184 | 0.689634 | 3.919708 | false | false | false | false |
rhx/SwiftGObject | Sources/GLibObject/GLibObject.swift | 1 | 17783 | //
// GLibObject.swift
// GObject
//
// Created by Rene Hexel on 20/06/2016.
// Copyright © 2016, 2017, 2018, 2019, 2020, 2021 Rene Hexel. All rights reserved.
//
import CGLib
import GLib
import GObjectCHelpers
/// Union of primitive glib values
public typealias GObjectTypeValueUnion = GObjectCHelpers.GObjectTypeValueUnion
/// Protocol for signal name enums
public protocol SignalNameProtocol: Hashable {
var rawValue: String { get }
}
/// Protocol extension for signal name enums
public extension SignalNameProtocol {
@inlinable var name: String { return rawValue }
/// Hashable conformance
@inlinable func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
/// Protocol for property name enums
public protocol PropertyNameProtocol: Hashable {
var rawValue: String { get }
}
/// Protocol extension for signal name enums
public extension PropertyNameProtocol {
@inlinable var name: String { return rawValue }
/// Hashable conformance
@inlinable func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
/// Type representing the name of a property
public struct PropertyName {
public let name: String
@inlinable public init(_ n: String) { name = n }
@inlinable public init<T: PropertyNameProtocol>(_ p: T) { name = p.rawValue }
}
extension PropertyName: PropertyNameProtocol {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@inlinable public static func ==(lhs: PropertyName, rhs: PropertyName) -> Bool {
return lhs.name == rhs.name
}
/// Property name as a String
@inlinable public var rawValue: String { return name }
}
extension PropertyName: ExpressibleByStringLiteral {
public typealias UnicodeScalarLiteralType = String
public typealias ExtendedGraphemeClusterLiteralType = String
public typealias StringLiteralType = String
@inlinable public init(stringLiteral value: StringLiteralType) { self.init(value) }
@inlinable public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { self.init(value) }
@inlinable public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self.init(value) }
}
/// A Void closure to use as a signal handler, that takes no parameters.
public typealias SignalHandler = () -> ()
/// A conversion closure transforming the first value into the second
/// This closure needs to return true if successful, or false otherwise
public typealias ValueTransformer = (ValueRef, ValueRef) -> Bool
/// Internal Class that wraps a binding to make sure it is retained
/// until no longer required
public class BindingHolder<S,T> {
public let transform_from: (S, T) -> Bool
public let transform_to: (T, S) -> Bool
@inlinable public init(_ transform_from: @escaping (S, T) -> Bool, _ transform_to: @escaping (T, S) -> Bool) {
self.transform_from = transform_from
self.transform_to = transform_to
}
}
/// Internal type for SignalHandler closure holder
public typealias SignalHandlerClosureHolder = ClosureHolder<Void,Void>
/// Internal type for a binding closure holder
public typealias BindingClosureHolder = BindingHolder<ValueRef, ValueRef>
/// Convenience extensions for Objects
public extension ObjectProtocol {
/// Create a new instance of a given type
///
/// - Parameter type: a type registered with g_type_register_*()
/// - Returns: pointer to the instance of the given type
@inlinable static func new(type: GType) -> gpointer! {
return gpointer(g_object_new_with_properties(type, 0, nil, nil))
}
/// Create a reference to an instance of a given type
///
/// - Parameter t: a type registered with g_type_register_*()
/// - Returns: `ObjectRef` wrapping the pointer to the given type instance
@inlinable static func newReferenceTo(instanceOf t: GType) -> ObjectRef! {
let ptr: gpointer? = Self.new(type: t)
return ptr.map { ObjectRef($0.assumingMemoryBound(to: GObject.self)) }
}
/// Create an instance of a given type
///
/// - Parameter t: a type registered with g_type_register_*()
/// - Returns: reference-counted object, wrapping the pointer to the given type instance
@inlinable static func new(_ t: GType) -> Object! {
let ptr: gpointer? = Self.new(type: t)
return ptr.map { Object($0.assumingMemoryBound(to: GObject.self)) }
}
/// Connection helper function for signal handler closure
@usableFromInline internal func _connect(signal name: UnsafePointer<gchar>, flags: ConnectFlags, data: SignalHandlerClosureHolder, handler: @convention(c) @escaping (gpointer, gpointer) -> Void) -> Int {
let holder = UnsafeMutableRawPointer(Unmanaged.passRetained(data).toOpaque())
let callback = unsafeBitCast(handler, to: Callback.self)
let rv = signalConnectData(detailedSignal: name, cHandler: callback, data: holder, destroyData: {
if let swift = UnsafeRawPointer($0) {
let holder = Unmanaged<SignalHandlerClosureHolder>.fromOpaque(swift)
holder.release()
}
_ = $1
}, connectFlags: flags)
return rv
}
/// Binding helper function for binding closure
@usableFromInline internal func _bind<T: ObjectProtocol>(_ source: UnsafePointer<gchar>, to t: T, _ target_property: UnsafePointer<gchar>, flags f: BindingFlags = .syncCreate, holder: BindingClosureHolder, transformFrom transform_from: @convention(c) @escaping (gpointer, gpointer, gpointer, gpointer) -> gboolean, transformTo transform_to: @convention(c) @escaping (gpointer, gpointer, gpointer, gpointer) -> gboolean) -> BindingRef! {
let holder = UnsafeMutableRawPointer(Unmanaged.passRetained(holder).toOpaque())
let from = unsafeBitCast(transform_from, to: BindingTransformFunc.self)
let to = unsafeBitCast(transform_to, to: BindingTransformFunc.self)
let rv = bindPropertyFull(sourceProperty: source, target: t, targetProperty: target_property, flags: f, transformTo: to, transformFrom: from, userData: holder) {
if let swift = UnsafeRawPointer($0) {
let holder = Unmanaged<BindingClosureHolder>.fromOpaque(swift)
holder.release()
}
}
return rv.map { BindingRef($0) }
}
/// Connects a (Void) -> Void closure or function to a typed signal for
/// the receiver object. Similar to `g_signal_connect()`, but allows
/// to provide a Swift closure that can capture its surrounding context.
/// - Parameters:
/// - signal: The signal to connect
/// - flags: The connection flags to use
/// - handler: A Swift closure to run whenever the given signal was emitted
/// - Returns: The signal handler ID (always greater than 0 for successful connections)
@discardableResult @inlinable func connect<S: SignalNameProtocol>(_ signal: S, flags f: ConnectFlags = ConnectFlags(0), handler: @escaping SignalHandler) -> Int {
let rv = _connect(signal: signal.name, flags: f, data: ClosureHolder(handler)) {
let ptr = UnsafeRawPointer($1)
let holder = Unmanaged<SignalHandlerClosureHolder>.fromOpaque(ptr).takeUnretainedValue()
let call = holder.call
call(())
}
return rv
}
/// Type-safe wrapper for `g_signal_connect_data()`.
/// Connects a @convention(c) function to a typed signal for
/// the receiver object.
/// - Parameters:
/// - signal: The signal to connect
/// - flags: The connection flags to use
/// - data: A pointer to user data to provide to the callback
/// - destroyData: A `GClosureNotify` C function to destroy the data pointed to by `userData`
/// - handler: The C function to be called on the given signal
/// - Returns: The signal handler ID (always greater than 0 for successful connections)
@discardableResult @inlinable func connectSignal<S: SignalNameProtocol>(_ signal: S, flags f: ConnectFlags = ConnectFlags(0), data userData: gpointer! = nil, destroyData destructor: GClosureNotify? = nil, handler: @escaping GCallback) -> Int {
signalConnectData(detailedSignal: signal.name, cHandler: handler, data: userData, destroyData: destructor, connectFlags: f)
}
/// Creates a binding between @source_property on @source and @target_property
/// on @target. Whenever the @source_property is changed the @target_property is
/// updated using the same value. For instance:
///
/// |[
/// g_object_bind_property (action, "active", widget, "sensitive", 0);
/// ]|
///
/// Will result in the "sensitive" property of the widget #GObject instance to be
/// updated with the same value of the "active" property of the action #GObject
/// instance.
///
/// If @flags contains %G_BINDING_BIDIRECTIONAL then the binding will be mutual:
/// if @target_property on @target changes then the @source_property on @source
/// will be updated as well.
///
/// The binding will automatically be removed when either the @source or the
/// @target instances are finalized. To remove the binding without affecting the
/// @source and the @target you can just call g_object_unref() on the returned
/// #GBinding instance.
///
/// A #GObject can have multiple bindings.
@inlinable @discardableResult func bind<P: PropertyNameProtocol, Q: PropertyNameProtocol, T: ObjectProtocol>(_ source_property: P, target: T, property target_property: Q, flags: BindingFlags = .syncCreate) -> BindingRef! {
guard let rv = g_object_bind_property(ptr, source_property.name, target.ptr, target_property.name, flags.value) else { return nil }
return BindingRef(rv)
}
/// Complete version of bind().
///
/// Creates a binding between @source_property on @source and @target_property
/// on @target, allowing you to set the transformation functions to be used by
/// the binding.
///
/// If @flags contains %G_BINDING_BIDIRECTIONAL then the binding will be mutual:
/// if @target_property on @target changes then the @source_property on @source
/// will be updated as well. The @transform_from function is only used in case
/// of bidirectional bindings, otherwise it will be ignored
///
/// The binding will automatically be removed when either the @source or the
/// @target instances are finalized. To remove the binding without affecting the
/// @source and the @target you can just call g_object_unref() on the returned
/// #GBinding instance.
///
/// A #GObject can have multiple bindings.
@inlinable @discardableResult func bind<P: PropertyNameProtocol, Q: PropertyNameProtocol, T: ObjectProtocol>(_ source_property: P, to target: T, property target_property: Q, flags f: BindingFlags = .syncCreate, transformFrom transform_from: @escaping ValueTransformer = { $0.transform(destValue: $1) }, transformTo transform_to: @escaping ValueTransformer) -> BindingRef! {
let rv = _bind(source_property.name, to: target, target_property.name, flags: f, holder: BindingClosureHolder(transform_from, transform_to), transformFrom: {
let ptr = UnsafeRawPointer($3)
let holder = Unmanaged<BindingClosureHolder>.fromOpaque(ptr).takeUnretainedValue()
return holder.transform_from(ValueRef(raw: $1), ValueRef(raw: $2)) ? 1 : 0
}) {
let ptr = UnsafeRawPointer($3)
let holder = Unmanaged<BindingClosureHolder>.fromOpaque(ptr).takeUnretainedValue()
return holder.transform_to(ValueRef(raw: $1), ValueRef(raw: $2)) ? 1 : 0
}
return rv
}
/// Complete version of bind() with strongly typed transformers.
///
/// Creates a binding between @source_property on @source and @target_property
/// on @target, allowing you to set the transformation functions to be used by
/// the binding.
///
/// If @flags contains %G_BINDING_BIDIRECTIONAL then the binding will be mutual:
/// if @target_property on @target changes then the @source_property on @source
/// will be updated as well. The @transform_from function is only used in case
/// of bidirectional bindings, otherwise it will be ignored
///
/// The binding will automatically be removed when either the @source or the
/// @target instances are finalized. To remove the binding without affecting the
/// @source and the @target you can just call g_object_unref() on the returned
/// #GBinding instance.
///
/// A #GObject can have multiple bindings.
@inlinable @discardableResult func bind<P: PropertyNameProtocol, Q: PropertyNameProtocol, T: ObjectProtocol, U, V>(_ source_property: P, to target: T, property target_property: Q, flags fl: BindingFlags = .syncCreate, convertFrom f: @escaping (U?) -> V? = { _ in nil }, convertTo g: @escaping (V?) -> U?) -> BindingRef! {
let ft: ValueTransformer = { $0.transform(to: $1, f) }
let gt: ValueTransformer = { $1.transform(to: $0, g) }
return bind(source_property, to: target, property: target_property, flags: fl, transformFrom: ft, transformTo: gt)
}
/// Complete version of bind() with strongly typed transformers.
///
/// Creates a binding between @source_property on @source and @target_property
/// on @target, allowing you to set the transformation functions to be used by
/// the binding.
///
/// If @flags contains %G_BINDING_BIDIRECTIONAL then the binding will be mutual:
/// if @target_property on @target changes then the @source_property on @source
/// will be updated as well. The @transform_from function is only used in case
/// of bidirectional bindings, otherwise it will be ignored
///
/// The binding will automatically be removed when either the @source or the
/// @target instances are finalized. To remove the binding without affecting the
/// @source and the @target you can just call g_object_unref() on the returned
/// #GBinding instance.
///
/// A #GObject can have multiple bindings.
@inlinable @discardableResult func bind<P: PropertyNameProtocol, Q: PropertyNameProtocol, T: ObjectProtocol, U, V>(_ source_property: P, to target: T, property target_property: Q, flags fl: BindingFlags = .syncCreate, convertFrom f: @escaping (U) -> V? = { _ in nil }, convertTo g: @escaping (V) -> U?) -> BindingRef! {
let ft: ValueTransformer = {
return $0.transform(to: $1, f)
}
let gt: ValueTransformer = {
return $0.transform(to: $1, g)
}
return bind(source_property, to: target, property: target_property, flags: fl, transformFrom: ft, transformTo: gt)
}
}
//MARK:- Swift Object
@usableFromInline let swiftObjKey = "swiftobj";
@usableFromInline let gtrue: gboolean = 1
@usableFromInline let gfalse: gboolean = 0
public extension GLibObject.ObjectProtocol {
/// The swift wrapper for this object.
@inlinable var swiftObj: AnyObject? {
get {
guard let pointer = getData(key: swiftObjKey) else { return nil }
return Unmanaged<AnyObject>.fromOpaque(pointer).takeUnretainedValue()
}
nonmutating set {
// Setting swift object to the already existing swiftObj is a no-op, in order to avoid duplicate toggleRefs, which never fire and thus cause reference cycles.
guard let newValue = newValue, newValue !== swiftObj else {
return
}
// Get a strong pointer to swiftObj
let pointer = Unmanaged<AnyObject>.passRetained(newValue).toOpaque();
setData(key: swiftObjKey, data: pointer);
// In the majority of cases, swiftObj will be the swift wrapper for this gobject's c implementation. To prevent orphaning, these should be equivalent for memory management purposes; If one is referenced, the other is referenced. A naive way to implement this is to have both strongly reference each other, but this creates a strong reference cycle. Therefore, the wrapper has a strong toggle reference to the gobject, which tells us when there are other references. In this instance, the wrapper should be referenced, so the gobject strongly references it. Otherwise, the gobject weakly references it, allowing it, and thus the gobject, to be released once it is not referenced in swift-space.
addToggleRef { (_, selfPointer, lastRef) in
let swiftObjPointer = Unmanaged<AnyObject>.fromOpaque(g_object_get_data(selfPointer, swiftObjKey))
switch lastRef {
case gfalse:
// Make the gobject strongly reference the wrapper.
_ = swiftObjPointer.retain()
case gtrue:
// Make the gobject weakly reference the wrapper.
swiftObjPointer.release()
default:
break
}
}
// Release the regular reference so we don't have two references from the wrapper.
unref()
}
}
}
public extension GLibObject.Object {
/// Will set this swift instance to be the swiftObj.
@inlinable func becomeSwiftObj() {
swiftObj = self;
}
}
/// Fetches the swift object from the given pointers, if any. Assume pointer is a GObject, so only call this function if this is known.
@inlinable public func swiftObj(fromRaw raw: UnsafeMutableRawPointer) -> AnyObject? {
let objPointer = g_object_get_data(raw.assumingMemoryBound(to: GObject.self), swiftObjKey);
if let objPointer = objPointer {
return Unmanaged<AnyObject>.fromOpaque(objPointer).takeUnretainedValue();
} else {
return nil;
}
}
| bsd-2-clause | 1c4f08115274fe5150e4db1d416fad56 | 48.949438 | 696 | 0.690417 | 4.273492 | false | false | false | false |
Nana-Muthuswamy/TwitterLite | TwitterLite/NetworkManager.swift | 1 | 8548 | //
// NetworkManager.swift
// TwitterLite
//
// Created by Nana on 4/14/17.
// Copyright © 2017 Nana. All rights reserved.
//
import BDBOAuth1Manager
enum NetworkAPIError: Error {
case invalidData(Any?)
case failure(String?)
}
fileprivate let userAccountURL = "1.1/account/verify_credentials.json"
fileprivate let homeTimelineURL = "1.1/statuses/home_timeline.json"
fileprivate let timelineURL = "1.1/statuses/user_timeline.json"
fileprivate let mentionsURL = "1.1/statuses/mentions_timeline.json"
fileprivate let retweetURL = "1.1/statuses/retweet/<tweetId>.json"
fileprivate let unRetweetURL = "1.1/statuses/unretweet/<tweetId>.json"
fileprivate let favoriteURL = "1.1/favorites/create.json"
fileprivate let unFavoriteURL = "1.1/favorites/destroy.json"
fileprivate let updateStatusURL = "1.1/statuses/update.json"
fileprivate let statusURL = "1.1/statuses/show/<tweetId>.json?include_my_retweet=1"
class NetworkManager: BDBOAuth1SessionManager {
// Singleton Shared Instance
static let shared: NetworkManager! = NetworkManager(baseURL: URL(string: "https://api.twitter.com")! , consumerKey: "ImQ10TZvag9Qy6f05yWqHQlF8", consumerSecret: "BGgvmkWBGAeSM5yKZNZ7sGiHbZ1ObdaAJptSkC3cVBeDqKFZb3")
var loginCompletionHandler: ((User?, NetworkAPIError?) -> Void)!
// MARK: - Login & Logout
func login(completion: @escaping ((User?, NetworkAPIError?) -> Void)) {
// Hold the completion handler
loginCompletionHandler = completion
// Deauthorize (recommended approach due to OAuth bug)
deauthorize()
// Fetch Request Token for user
fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL: URL(string: "twitterlite://login") , scope: nil, success: {[weak self] (authCredential) in
if let requestToken = authCredential?.token {
// Load Authorize URL in default browser
UIApplication.shared.open(URL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken)")!, options: [:], completionHandler: nil)
} else {
self?.loginCompletionHandler(nil, NetworkAPIError.failure("Request token not fetched"))
}
}, failure: {[weak self] (error) in
self?.loginCompletionHandler(nil, NetworkAPIError.failure(error?.localizedDescription))
})
}
func handle(url: URL) {
if let queryStr = url.query, let authCredential = BDBOAuth1Credential(queryString: queryStr) {
// Fetch Access Token for the authorized user
fetchAccessToken(withPath: "oauth/access_token", method: "POST", requestToken: authCredential, success: {[weak self] (authCredential) in
if (authCredential?.token) != nil {
self?.fetchUserAccount(completion: (self?.loginCompletionHandler)!)
} else {
self?.loginCompletionHandler(nil, NetworkAPIError.failure("Access token not fetched"))
}
}, failure: {[weak self] (error) in
self?.loginCompletionHandler(nil, NetworkAPIError.failure(error?.localizedDescription))
})
}
}
func logout() {
// Clear the current user
User.currentUser = nil
// Deauthorize the app
deauthorize()
}
// MARK: - Fetch Methods
func fetchUserAccount(completion: @escaping ((User?, NetworkAPIError?) -> Void)) {
// Fetch user's account profile
self.get(userAccountURL, parameters: nil, progress: nil, success: { (task, response) in
if let userDict = response as? Dictionary<String, Any> {
let user = User(dictionary: userDict)
// Update the current user
User.currentUser = user
// Successful login completion
completion(user, nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}, failure: { (task, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
})
}
func fetchHomeTimeline(completion: @escaping (Array<Tweet>?, NetworkAPIError?) -> Void) {
get(homeTimelineURL, parameters: nil, progress: nil, success: { (task, response) in
var tweets = Array<Tweet>()
if let arrayOfTweets = response as? Array<Dictionary<String, Any>> {
tweets = Tweet.tweets(dictionaries: arrayOfTweets)
completion(tweets, nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}) { (task, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
}
}
func fetchTimeline(forId id: String, completion: @escaping (Array<Tweet>?, NetworkAPIError?) -> Void) {
let params = ["user_id" : id]
get(timelineURL, parameters: params, progress: nil, success: { (task, response) in
var tweets = Array<Tweet>()
if let arrayOfTweets = response as? Array<Dictionary<String, Any>> {
tweets = Tweet.tweets(dictionaries: arrayOfTweets)
completion(tweets, nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}) { (task, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
}
}
func fetchMentionsTimeline(completion: @escaping (Array<Tweet>?, NetworkAPIError?) -> Void) {
get(mentionsURL, parameters: nil, progress: nil, success: { (task, response) in
var tweets = Array<Tweet>()
if let arrayOfTweets = response as? Array<Dictionary<String, Any>> {
tweets = Tweet.tweets(dictionaries: arrayOfTweets)
completion(tweets, nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}) { (task, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
}
}
// MARK: - Retweeting
func retweet(tweetID: String, retweet: Bool, completion: @escaping (Tweet?, Error?) -> ()) {
let endPoint: String
if retweet {
endPoint = retweetURL.replacingOccurrences(of: "<tweetId>", with: tweetID)
} else {
endPoint = unRetweetURL.replacingOccurrences(of: "<tweetId>", with: tweetID)
}
post(endPoint, parameters: nil, progress: nil, success: { (task, response) in
if let responseDict = response as? Dictionary<String, Any> {
completion(Tweet(dictionary: responseDict), nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}, failure: { (task, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
})
}
// MARK: - Favoriting
func favorite(tweetID: String, favorite: Bool, completion: @escaping (Tweet?, Error?) -> ()) {
let params = ["id" : tweetID]
let endpoint : String
if favorite {
endpoint = favoriteURL
}else{
endpoint = unFavoriteURL
}
post(endpoint, parameters: params, progress: nil, success: { (task, response) in
if let tweetDict = response as? Dictionary<String, Any> {
let tweet = Tweet(dictionary: tweetDict)
completion(tweet, nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}) { (task, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
}
}
// MARK: - Tweeting
func tweet(text: String, replyToStatusId: String?, completion: @escaping (Tweet?, Error?) -> ()) {
var params = ["status" : text]
if replyToStatusId != nil {
params["in_reply_to_status_id"] = replyToStatusId
}
post(updateStatusURL, parameters: params, progress: nil, success: { (_, response) in
if let responseDict = response as? Dictionary<String, Any> {
completion(Tweet(dictionary: responseDict), nil)
} else {
completion(nil, NetworkAPIError.invalidData(response))
}
}) { (_, error) in
completion(nil, NetworkAPIError.failure(error.localizedDescription))
}
}
}
| mit | a4a10171fed10989636863e1fe86833a | 34.46473 | 218 | 0.611677 | 4.565705 | false | false | false | false |
kidaa/codecombat-ios | CodeCombat/TomeInventoryItem.swift | 2 | 1517 | //
// TomeInventoryItem.swift
// CodeCombat
//
// Created by Michael Schmatz on 8/6/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
class TomeInventoryItem {
let itemData: JSON
var properties: [TomeInventoryItemProperty] = []
var name: String {
return itemData["name"].toString(false)
}
var imageURL: NSURL {
var url: String = itemData["imageURL"].toString(false)
if url.isEmpty {
url = "/file/db/thang.type/53e4108204c00d4607a89f78/programmicon.png"
}
return NSURL(string: url, relativeToURL: rootURL)!
}
init(itemData: JSON) {
self.itemData = itemData
}
convenience init(itemData: JSON, propertiesData: JSON) {
self.init(itemData: itemData)
for (_, prop) in itemData["programmableProperties"] {
for (_, anotherProp) in propertiesData {
if anotherProp["name"].asString! == prop.asString! {
properties.append(TomeInventoryItemProperty(propertyData: anotherProp, primary: true))
break
}
}
}
for (_, prop) in itemData["moreProgrammableProperties"] {
for (_, anotherProp) in propertiesData {
if anotherProp["name"].asString! == prop.asString! {
properties.append(TomeInventoryItemProperty(propertyData: anotherProp, primary: false))
break
}
}
}
}
func addProperty(property: TomeInventoryItemProperty) {
properties.append(property)
}
func removeAllProperties() {
properties.removeAll(keepCapacity: true)
}
}
| mit | 82c3c9884557bcf801e239aa360ba73a | 27.092593 | 97 | 0.658537 | 4.1 | false | false | false | false |
Zane6w/Regular | Regular/Regular/AppDelegate.swift | 1 | 6488 | //
// AppDelegate.swift
// Regular
//
// Created by zhi zhou on 2017/1/5.
// Copyright © 2017年 zhi zhou. All rights reserved.
//
import UIKit
import AudioToolbox
/// SQL 表名
let regularDataBase = "t_regulars"
/// 是否第一次启动
var isFirstLoad: Bool?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
ZxSQLite.shared.isPrint = false
_ = ZxSQLite.shared.openDB(pathName: "regularsData", tableName: regularDataBase)
UINavigationBar.appearance().tintColor = appColor
// 第一次安装并启动判断
let version = ZxVersion.shared.verdict()
if version.isChangedVersion == nil, version.isFirstLaunch! {
isFirstLoad = true
} else {
isFirstLoad = false
}
debugMode(print: "did Finish")
// 3D Touch 选项
let addItem = UIApplicationShortcutItem(type: "Add", localizedTitle: localized(cn: "添加新规律", en: "Add Regular"), localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .add), userInfo: nil)
UIApplication.shared.shortcutItems = [addItem]
var performActionForShortcutItemWhenAppLaunch = false
// 判断应用的启动是否是因为用户选择了Home Screen Quick Actions选项
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem {
performActionForShortcutItemWhenAppLaunch = true
// TODO: 相应的Handle操作
switch shortcutItem.type {
case "Add":
let naviVC = window?.rootViewController as! UINavigationController
if let presentedVC = naviVC.presentedViewController {
presentedVC.dismiss(animated: true, completion: nil)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
(naviVC.viewControllers.first as! ZxHomeViewController).addNewRegular()
})
default:
break
}
}
return !performActionForShortcutItemWhenAppLaunch
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
// 从 widget 打开 App 的通知
if url.scheme == "Regular" {
let naviVC = window?.rootViewController as! UINavigationController
naviVC.popToRootViewController(animated: false)
if let presentedVC = naviVC.presentedViewController {
presentedVC.dismiss(animated: true, completion: nil)
}
NotificationCenter.default.post(Notification(name: widgetOpendAppNotification))
}
return true
}
// 监听 3D Touch 选项点击
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
switch shortcutItem.type {
case "Add":
let naviVC = window?.rootViewController as! UINavigationController
if let presentedVC = naviVC.presentedViewController {
presentedVC.dismiss(animated: true, completion: nil)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
(naviVC.viewControllers.first as! ZxHomeViewController).addNewRegular()
})
default:
break
}
completionHandler(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.
// 将要 "退到桌面" 或 "多任务界面"
NotificationCenter.default.post(Notification(name: appWillResignActiveNotification))
debugMode(print: "will back")
}
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.
// 后台模式(多任务选择了其他的 APP 或 回到了桌面)
debugMode(print: "back")
NotificationCenter.default.post(Notification(name: appDidEnterBackgroundNotification))
}
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.
debugMode(print: "will now")
// 将要进入前台模式
NotificationCenter.default.post(Notification(name: appWillEnterForegroundNotification))
}
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.
debugMode(print: "now")
// 前台运行模式 通知
NotificationCenter.default.post(Notification(name: appDidBecomeActiveNotification))
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
NotificationCenter.default.post(Notification(name: appWillTerminateNotification))
}
}
| apache-2.0 | a171ae48a176305d6f24a1089ea42338 | 41.317568 | 285 | 0.659907 | 5.503515 | false | false | false | false |
RGSSoftware/RGSTextFieldReveal | RGSTextFieldReveal/RGSTextFieldReveal.swift | 1 | 4994 | //
// UITextfieldReveal.swift
// UITextfieldRevealSwift
//
// Created by PC on 6/15/16.
// Copyright © 2016 Randel Smith. All rights reserved.
//
import UIKit
class RGSTextFieldReveal: UIView {
var placeholderButton: UIButton!
var reveralView: UIView!
var textField: UITextField!
var reveralViewMinHeight: CGFloat = 2.0
var reveralViewMaxHeight: CGFloat = 30.0
var openDuration = 0.25
var closeDuration = 0.3
var isOpen = false
private var reveralViewHeightContaint : NSLayoutConstraint!
private var containerView : UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
placeholderButton = UIButton(type: .Custom)
placeholderButton.titleLabel?.font = placeholderButton.titleLabel?.font.fontWithSize(16)
placeholderButton.contentEdgeInsets = UIEdgeInsetsMake(0, 2, 0, 0)
placeholderButton.addTarget(self, action: #selector(self.buttonTap(_:)), forControlEvents: .TouchUpInside)
placeholderButton.translatesAutoresizingMaskIntoConstraints = false;
self.addSubview(placeholderButton)
placeholderButton.topAnchor.constraintEqualToAnchor(self.topAnchor).active = true
placeholderButton.leadingAnchor.constraintEqualToAnchor(self.leadingAnchor).active = true
placeholderButton.trailingAnchor.constraintEqualToAnchor(self.trailingAnchor).active = true
placeholderButton.heightAnchor.constraintEqualToConstant(30).active = true
reveralView = UIView()
reveralView.backgroundColor = UIColor.yellowColor()
reveralView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(reveralView)
reveralView.topAnchor.constraintEqualToAnchor(placeholderButton.bottomAnchor).active = true
reveralView.leadingAnchor.constraintEqualToAnchor(self.leadingAnchor).active = true
reveralView.trailingAnchor.constraintEqualToAnchor(self.trailingAnchor).active = true
reveralViewHeightContaint = reveralView.heightAnchor.constraintEqualToConstant(reveralViewMinHeight)
reveralViewHeightContaint.active = true
reveralView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor).active = true
containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
reveralView.addSubview(containerView)
containerView.topAnchor.constraintEqualToAnchor(reveralView.topAnchor).active = true
containerView.leadingAnchor.constraintEqualToAnchor(reveralView.leadingAnchor).active = true
containerView.trailingAnchor.constraintEqualToAnchor(reveralView.trailingAnchor).active = true
containerView.bottomAnchor.constraintEqualToAnchor(reveralView.bottomAnchor).active = true
textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(textField)
textField.leadingAnchor.constraintEqualToAnchor(containerView.leadingAnchor, constant: 2).active = true
textField.trailingAnchor.constraintEqualToAnchor(containerView.trailingAnchor).active = true
textField.centerYAnchor.constraintEqualToAnchor(containerView.centerYAnchor).active = true
self.layer.masksToBounds = true
self.reveralView.layer.cornerRadius = 1
self.containerView.alpha = 0
self.placeholderButton.contentHorizontalAlignment = .Left;
self.backgroundColor = UIColor.clearColor()
}
func open() {
self.textField.becomeFirstResponder()
self.isOpen = true
UIView.animateWithDuration(openDuration) {
self.reveralViewHeightContaint.constant = self.reveralViewMaxHeight
self.containerView.alpha = 1
self.placeholderButton.titleLabel?.alpha = 0.5
self.placeholderButton.titleLabel?.transform = CGAffineTransformScale(self.placeholderButton.transform, 0.8, 0.8)
self.superview!.layoutIfNeeded()
}
}
func close() {
self.textField.resignFirstResponder()
self.isOpen = false
UIView.animateWithDuration(closeDuration) {
self.reveralViewHeightContaint.constant = self.reveralViewMinHeight
self.containerView.alpha = 0
self.placeholderButton.titleLabel?.alpha = 1
self.placeholderButton.titleLabel?.transform = CGAffineTransformScale(self.placeholderButton.transform, 1, 1)
self.superview!.layoutIfNeeded()
}
}
@objc private func buttonTap(button: UIButton) {
if isOpen {
self.close()
} else {
self.open()
}
}
}
| mit | 492efab745c52f0004de5d6ded774850 | 36.541353 | 125 | 0.679351 | 5.693273 | false | false | false | false |
ismailbozk/ObjectScanner | ObjectScanner/ObjectScanner/Categories/OSVectorMath.swift | 1 | 3528 | //
// OSVectorMath.swift
// ObjectScanner
//
// Created by Ismail Bozkurt on 02/08/2015.
// The MIT License (MIT)
//
// Copyright (c) 2015 Ismail Bozkurt
//
// 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.
//
extension Matrix4
{
static func rotation(axis: Vector3, angle: Scalar) -> Matrix4
{
let c: Scalar = cos(angle);
let s: Scalar = sin(angle);
var X = Vector4.Zero;
X.x = axis.x * axis.x + (1 - axis.x * axis.x) * c;
X.y = axis.x * axis.y * (1 - c) - axis.z*s;
X.z = axis.x * axis.z * (1 - c) + axis.y * s;
X.w = 0.0;
var Y = Vector4.Zero;
Y.x = axis.x * axis.y * (1 - c) + axis.z * s;
Y.y = axis.y * axis.y + (1 - axis.y * axis.y) * c;
Y.z = axis.y * axis.z * (1 - c) - axis.x * s;
Y.w = 0.0;
var Z = Vector4.Zero;
Z.x = axis.x * axis.z * (1 - c) - axis.y * s;
Z.y = axis.y * axis.z * (1 - c) + axis.x * s;
Z.z = axis.z * axis.z + (1 - axis.z * axis.z) * c;
Z.w = 0.0;
var W = Vector4.Zero;
W.x = 0.0;
W.y = 0.0;
W.z = 0.0;
W.w = 1.0;
let rotationMatrix: Matrix4 =
Matrix4(m11: X.x, m12: Y.x, m13: Z.x, m14: W.x,
m21: X.y, m22: Y.y, m23: Z.y, m24: W.y,
m31: X.z, m32: Y.z, m33: Z.z, m34: W.z,
m41: X.w, m42: Y.w, m43: Z.w, m44: W.w);
return rotationMatrix;
}
static func perspectiveProjection(aspect: Float, fovy: Float, near: Float, far: Float) -> Matrix4
{
let yScale: Float = 1 / tan(fovy * 0.5);
let xScale: Float = yScale / aspect;
let zRange: Float = far - near;
let zScale: Float = -(far + near) / zRange;
let wzScale: Float = -2 * far * near / zRange;
let P: Vector4 = Vector4(xScale, 0.0, 0.0, 0.0);
let Q: Vector4 = Vector4(0.0, yScale, 0.0, 0.0);
let R: Vector4 = Vector4(0.0, 0.0, zScale, -1.0);
let S: Vector4 = Vector4(0.0, 0.0, wzScale, 0.0);
let perspectiveProjection =
Matrix4(m11: P.x, m12: Q.x, m13: R.x, m14: S.x,
m21: P.y, m22: Q.y, m23: R.y, m24: S.y,
m31: P.z, m32: Q.z, m33: R.z, m34: S.z,
m41: P.w, m42: Q.w, m43: R.w, m44: S.w);
return perspectiveProjection;
}
}
extension Float
{
static func degToRad(_ degree: Float) -> Float
{
return degree * (Float(M_PI) / 180.0);
}
}
| mit | a933470688581f026e8b11386867a3ee | 36.935484 | 101 | 0.559524 | 3.005111 | false | false | false | false |
arnaudbenard/my-npm | Pods/Charts/Charts/Classes/Highlight/ChartHighlight.swift | 69 | 3381 | //
// ChartHighlight.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class ChartHighlight: NSObject
{
/// the x-index of the highlighted value
private var _xIndex = Int(0)
/// the index of the dataset the highlighted value is in
private var _dataSetIndex = Int(0)
/// index which value of a stacked bar entry is highlighted
/// :default: -1
private var _stackIndex = Int(-1)
/// the range of the bar that is selected (only for stacked-barchart)
private var _range: ChartRange?
public override init()
{
super.init()
}
public init(xIndex x: Int, dataSetIndex: Int)
{
super.init()
_xIndex = x
_dataSetIndex = dataSetIndex
}
public init(xIndex x: Int, dataSetIndex: Int, stackIndex: Int)
{
super.init()
_xIndex = x
_dataSetIndex = dataSetIndex
_stackIndex = stackIndex
}
/// Constructor, only used for stacked-barchart.
///
/// :param: x the index of the highlighted value on the x-axis
/// :param: dataSet the index of the DataSet the highlighted value belongs to
/// :param: stackIndex references which value of a stacked-bar entry has been selected
/// :param: range the range the selected stack-value is in
public convenience init(xIndex x: Int, dataSetIndex: Int, stackIndex: Int, range: ChartRange)
{
self.init(xIndex: x, dataSetIndex: dataSetIndex, stackIndex: stackIndex)
_range = range
}
public var dataSetIndex: Int { return _dataSetIndex; }
public var xIndex: Int { return _xIndex; }
public var stackIndex: Int { return _stackIndex; }
/// :returns: the range of values the selected value of a stacked bar is in. (this is only relevant for stacked-barchart)
public var range: ChartRange? { return _range }
// MARK: NSObject
public override var description: String
{
return "Highlight, xIndex: \(_xIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)"
}
public override func isEqual(object: AnyObject?) -> Bool
{
if (object === nil)
{
return false
}
if (!object!.isKindOfClass(self.dynamicType))
{
return false
}
if (object!.xIndex != _xIndex)
{
return false
}
if (object!.dataSetIndex != _dataSetIndex)
{
return false
}
if (object!.stackIndex != _stackIndex)
{
return false
}
return true
}
}
func ==(lhs: ChartHighlight, rhs: ChartHighlight) -> Bool
{
if (lhs === rhs)
{
return true
}
if (!lhs.isKindOfClass(rhs.dynamicType))
{
return false
}
if (lhs._xIndex != rhs._xIndex)
{
return false
}
if (lhs._dataSetIndex != rhs._dataSetIndex)
{
return false
}
if (lhs._stackIndex != rhs._stackIndex)
{
return false
}
return true
} | mit | fd8dd3e18d117c7283fe58472cdbced2 | 23.157143 | 130 | 0.577344 | 4.581301 | false | false | false | false |
overtake/TelegramSwift | packages/TGUIKit/Sources/RadialProgressView.swift | 1 | 20871 | //
// RadialProgressLayer.swift
// TGUIKit
//
// Created by keepcoder on 17/09/16.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
private func progressInteractiveThumb(backgroundColor: NSColor, foregroundColor: NSColor) -> CGImage {
let context = DrawingContext(size: NSMakeSize(40, 40), scale: 1.0, clear: true)
context.withContext { (ctx) in
ctx.round(context.size, context.size.height/2.0)
ctx.setFillColor(backgroundColor.cgColor)
let image = #imageLiteral(resourceName: "Icon_MessageFile").precomposed(foregroundColor)
ctx.fill(NSMakeRect(0, 0, context.size.width, context.size.height))
ctx.draw(image, in: NSMakeRect(floorToScreenPixels(System.backingScale, (context.size.width - image.backingSize.width) / 2.0), floorToScreenPixels(System.backingScale, (context.size.height - image.backingSize.height) / 2.0), image.backingSize.width, image.backingSize.height))
}
return context.generateImage()!
}
public struct FetchControls {
public let fetch: () -> Void
public init(fetch:@escaping()->Void) {
self.fetch = fetch
}
}
private class RadialProgressParameters: NSObject {
let theme: RadialProgressTheme
let diameter: CGFloat
let twist: Bool
let state: RadialProgressState
let clockwise: Bool
init(theme: RadialProgressTheme, diameter: CGFloat, state: RadialProgressState, twist: Bool = true) {
self.theme = theme
self.diameter = diameter
self.state = state
self.twist = twist
self.clockwise = theme.clockwise
super.init()
}
}
public struct RadialProgressTheme : Equatable {
public let backgroundColor: NSColor
public let foregroundColor: NSColor
public let icon: CGImage?
public let cancelFetchingIcon: CGImage?
public let iconInset:NSEdgeInsets
public let diameter:CGFloat?
public let lineWidth: CGFloat
public let clockwise: Bool
public init(backgroundColor:NSColor, foregroundColor:NSColor, icon:CGImage? = nil, cancelFetchingIcon: CGImage? = nil, iconInset:NSEdgeInsets = NSEdgeInsets(), diameter: CGFloat? = nil, lineWidth: CGFloat = 2, clockwise: Bool = true) {
self.iconInset = iconInset
self.backgroundColor = backgroundColor
self.foregroundColor = foregroundColor
self.icon = icon
self.cancelFetchingIcon = cancelFetchingIcon
self.diameter = diameter
self.lineWidth = lineWidth
self.clockwise = clockwise
}
}
public func ==(lhs:RadialProgressTheme, rhs:RadialProgressTheme) -> Bool {
return lhs.backgroundColor == rhs.backgroundColor && lhs.foregroundColor == rhs.foregroundColor && ((lhs.icon == nil) == (rhs.icon == nil))
}
public enum RadialProgressState: Equatable {
case None
case Remote
case Fetching(progress: Float, force: Bool)
case ImpossibleFetching(progress: Float, force: Bool)
case Play
case Icon(image:CGImage, mode:CGBlendMode)
case Success
}
public func ==(lhs:RadialProgressState, rhs:RadialProgressState) -> Bool {
switch lhs {
case .None:
if case .None = rhs {
return true
} else {
return false
}
case .Remote:
if case .Remote = rhs {
return true
} else {
return false
}
case .Success:
if case .Success = rhs {
return true
} else {
return false
}
case .Play:
if case .Play = rhs {
return true
} else {
return false
}
case let .Fetching(lhsProgress):
if case let .Fetching(rhsProgress) = rhs, lhsProgress == rhsProgress {
return true
} else {
return false
}
case let .ImpossibleFetching(lhsProgress):
if case let .ImpossibleFetching(rhsProgress) = rhs, lhsProgress == rhsProgress {
return true
} else {
return false
}
case .Icon:
if case .Icon = rhs {
return true
} else {
return false
}
}
}
private class RadialProgressOverlayLayer: SimpleLayer {
var theme: RadialProgressTheme
let twist: Bool
private var timer: SwiftSignalKit.Timer?
private var _progress: Float = 0
private var progress: Float = 0
var parameters:RadialProgressParameters {
return RadialProgressParameters(theme: self.theme, diameter: theme.diameter ?? frame.width, state: self.state, twist: twist)
}
var state: RadialProgressState = .None {
didSet {
switch state {
case .None, .Play, .Remote, .Icon, .Success:
self.progress = 0
self._progress = 0
mayAnimate(false)
case let .Fetching(progress, f), let .ImpossibleFetching(progress, f):
self.progress = twist ? max(progress, 0.05) : progress
if f {
_progress = progress
}
mayAnimate(true)
}
let fps: Float = 60
let difference = progress - _progress
let tick: Float = Float(difference / (fps * 0.2))
let clockwise = theme.clockwise
if (clockwise && difference > 0) || (!clockwise && difference != 0) {
timer = SwiftSignalKit.Timer(timeout: TimeInterval(1 / fps), repeat: true, completion: { [weak self] in
if let strongSelf = self {
strongSelf._progress += tick
strongSelf.setNeedsDisplay()
if strongSelf._progress == strongSelf.progress || strongSelf._progress < 0 || (strongSelf._progress >= 1 && !clockwise) || (strongSelf._progress > strongSelf.progress && clockwise) {
strongSelf.stopAnimation()
}
}
}, queue: Queue.mainQueue())
timer?.start()
} else {
stopAnimation()
_progress = progress
}
self.setNeedsDisplay()
}
}
func stopAnimation() {
timer?.invalidate()
timer = nil
self.setNeedsDisplay()
}
init(theme: RadialProgressTheme, twist: Bool) {
self.theme = theme
self.twist = twist
super.init()
}
override func removeAllAnimations() {
super.removeAllAnimations()
}
override init(layer: Any) {
let layer = layer as! RadialProgressOverlayLayer
self.theme = layer.theme
self.twist = layer.twist
super.init(layer: layer)
}
fileprivate override func draw(in ctx: CGContext) {
ctx.setStrokeColor(theme.foregroundColor.cgColor)
let startAngle = 2.0 * (CGFloat.pi) * CGFloat(_progress) - CGFloat.pi / 2
let endAngle = -(CGFloat.pi / 2)
let pathDiameter = !twist ? parameters.diameter - parameters.theme.lineWidth : parameters.diameter - parameters.theme.lineWidth - parameters.theme.lineWidth * parameters.theme.lineWidth
ctx.addArc(center: NSMakePoint(parameters.diameter / 2.0, floorToScreenPixels(System.backingScale, parameters.diameter / 2.0)), radius: pathDiameter / 2.0, startAngle: startAngle, endAngle: endAngle, clockwise: parameters.clockwise)
ctx.setLineWidth(parameters.theme.lineWidth);
ctx.setLineCap(.round);
ctx.strokePath()
}
fileprivate func mayAnimate(_ animate: Bool) {
if animate, parameters.twist {
let fromValue: Float = 0
if animation(forKey: "progressRotation") != nil {
return
}
removeAllAnimations()
CATransaction.begin()
let basicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
basicAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
basicAnimation.duration = 2.0
basicAnimation.fromValue = NSNumber(value: fromValue)
basicAnimation.toValue = NSNumber(value: Float.pi * 2.0)
basicAnimation.repeatCount = .infinity
basicAnimation.isRemovedOnCompletion = false
basicAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
self.add(basicAnimation, forKey: "progressRotation")
CATransaction.commit()
} else {
removeAllAnimations()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public class RadialProgressView: Control {
public var fetchControls:FetchControls? {
didSet {
self.removeAllHandlers()
if let fetchControls = fetchControls {
set(handler: { _ in
fetchControls.fetch()
}, for: .Click)
}
}
}
public var theme:RadialProgressTheme {
didSet {
overlay.theme = theme
self.setNeedsDisplay()
}
}
private let overlay: RadialProgressOverlayLayer
private var parameters:RadialProgressParameters {
return RadialProgressParameters(theme: self.theme, diameter: NSWidth(self.frame), state: self.state)
}
public var state: RadialProgressState = .None {
didSet {
self.overlay.state = self.state
if case .Fetching = state {
if self.overlay.superlayer == nil {
self.layer?.addSublayer(self.overlay)
}
} else if case .ImpossibleFetching = state {
if self.overlay.superlayer == nil {
self.layer?.addSublayer(self.overlay)
}
} else {
if self.overlay.superlayer != nil {
self.overlay.removeFromSuperlayer()
}
}
switch oldValue {
case .Fetching:
switch self.state {
case .Fetching:
break
default:
self.setNeedsDisplay()
}
case .ImpossibleFetching:
switch self.state {
case .ImpossibleFetching:
break
default:
self.setNeedsDisplay()
}
case .Remote:
switch self.state {
case .Remote:
break
default:
self.setNeedsDisplay()
}
case .None:
switch self.state {
case .None:
break
default:
self.setNeedsDisplay()
}
case .Play:
switch self.state {
case .Play:
break
default:
self.setNeedsDisplay()
}
case .Success:
switch self.state {
case .Success:
break
default:
self.setNeedsDisplay()
}
case .Icon:
switch self.state {
case .Icon:
self.setNeedsDisplay()
default:
self.setNeedsDisplay()
}
}
}
}
public override func viewDidMoveToSuperview() {
overlay.mayAnimate(superview != nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required public init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
override public var frame: CGRect {
get {
return super.frame
} set (value) {
let redraw = value.size != self.frame.size
super.frame = value
if redraw {
self.overlay.frame = CGRect(origin: CGPoint(), size: value.size)
self.setNeedsDisplay()
self.overlay.setNeedsDisplay()
}
}
}
public init(theme: RadialProgressTheme = RadialProgressTheme(backgroundColor: .blackTransparent, foregroundColor: .white, icon: nil), twist: Bool = true, size: NSSize = NSMakeSize(40, 40)) {
self.theme = theme
self.overlay = RadialProgressOverlayLayer(theme: theme, twist: twist)
super.init()
self.overlay.contentsScale = backingScaleFactor
self.frame = NSMakeRect(0, 0, size.width, size.height)
}
public override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
// overlay.mayAnimate(superview != nil && window != nil)
}
public override func draw(_ layer: CALayer, in context: CGContext) {
context.setFillColor(parameters.theme.backgroundColor.cgColor)
context.fillEllipse(in: CGRect(origin: CGPoint(), size: CGSize(width: parameters.diameter, height: parameters.diameter)))
switch parameters.state {
case .None:
break
case .Success:
let diameter = bounds.size.width
let progress: CGFloat = 1.0
var pathLineWidth: CGFloat = 2.0
var pathDiameter: CGFloat = diameter - pathLineWidth
if (abs(diameter - 37.0) < 0.1) {
pathLineWidth = 2.5
pathDiameter = diameter - pathLineWidth * 2.0 - 1.5
} else if (abs(diameter - 32.0) < 0.1) {
pathLineWidth = 2.0
pathDiameter = diameter - pathLineWidth * 2.0 - 1.5
} else {
pathLineWidth = 2.5
pathDiameter = diameter - pathLineWidth * 2.0 - 1.5
}
let center = CGPoint(x: diameter / 2.0, y: diameter / 2.0)
context.setStrokeColor(parameters.theme.foregroundColor.cgColor)
context.setLineWidth(pathLineWidth)
context.setLineCap(.round)
context.setLineJoin(.round)
context.setMiterLimit(10.0)
let firstSegment: CGFloat = max(0.0, min(1.0, progress * 3.0))
var s = CGPoint(x: center.x - 10.0, y: center.y + 1.0)
var p1 = CGPoint(x: 7.0, y: 7.0)
var p2 = CGPoint(x: 15.0, y: -16.0)
if diameter < 36.0 {
s = CGPoint(x: center.x - 7.0, y: center.y + 1.0)
p1 = CGPoint(x: 4.5, y: 4.5)
p2 = CGPoint(x: 10.0, y: -11.0)
}
if !firstSegment.isZero {
if firstSegment < 1.0 {
context.move(to: CGPoint(x: s.x + p1.x * firstSegment, y: s.y + p1.y * firstSegment))
context.addLine(to: s)
} else {
let secondSegment = (progress - 0.33) * 1.5
context.move(to: CGPoint(x: s.x + p1.x + p2.x * secondSegment, y: s.y + p1.y + p2.y * secondSegment))
context.addLine(to: CGPoint(x: s.x + p1.x, y: s.y + p1.y))
context.addLine(to: s)
}
}
context.strokePath()
case .Fetching:
if let icon = parameters.theme.cancelFetchingIcon {
var f = focus(icon.backingSize)
f.origin.x += parameters.theme.iconInset.left
f.origin.x -= parameters.theme.iconInset.right
f.origin.y += parameters.theme.iconInset.top
f.origin.y -= parameters.theme.iconInset.bottom
context.draw(icon, in: f)
} else {
context.setStrokeColor(parameters.theme.foregroundColor.cgColor)
context.setLineWidth(2.0)
context.setLineCap(.round)
let crossSize: CGFloat = parameters.diameter < 40 ? 9 : 14.0
context.move(to: CGPoint(x: parameters.diameter / 2.0 - crossSize / 2.0, y: parameters.diameter / 2.0 - crossSize / 2.0))
context.addLine(to: CGPoint(x: parameters.diameter / 2.0 + crossSize / 2.0, y: parameters.diameter / 2.0 + crossSize / 2.0))
context.strokePath()
context.move(to: CGPoint(x: parameters.diameter / 2.0 + crossSize / 2.0, y: parameters.diameter / 2.0 - crossSize / 2.0))
context.addLine(to: CGPoint(x: parameters.diameter / 2.0 - crossSize / 2.0, y: parameters.diameter / 2.0 + crossSize / 2.0))
context.strokePath()
}
case .Remote:
let color = parameters.theme.foregroundColor
let diameter = layer.frame.height
context.setStrokeColor(color.cgColor)
var lineWidth: CGFloat = 2.0
if diameter < 24.0 {
lineWidth = 1.3
}
context.setLineWidth(lineWidth)
context.setLineCap(.round)
context.setLineJoin(.round)
let factor = diameter / 50.0
let arrowHeadSize: CGFloat = 15.0 * factor
let arrowLength: CGFloat = 18.0 * factor
let arrowHeadOffset: CGFloat = 1.0 * factor
context.move(to: CGPoint(x: diameter / 2.0, y: diameter / 2.0 - arrowLength / 2.0 + arrowHeadOffset))
context.addLine(to: CGPoint(x: diameter / 2.0, y: diameter / 2.0 + arrowLength / 2.0 - 1.0 + arrowHeadOffset))
context.strokePath()
context.move(to: CGPoint(x: diameter / 2.0 - arrowHeadSize / 2.0, y: diameter / 2.0 + arrowLength / 2.0 - arrowHeadSize / 2.0 + arrowHeadOffset))
context.addLine(to: CGPoint(x: diameter / 2.0, y: diameter / 2.0 + arrowLength / 2.0 + arrowHeadOffset))
context.addLine(to: CGPoint(x: diameter / 2.0 + arrowHeadSize / 2.0, y: diameter / 2.0 + arrowLength / 2.0 - arrowHeadSize / 2.0 + arrowHeadOffset))
context.strokePath()
case .Play:
let color = parameters.theme.foregroundColor
let diameter = layer.frame.height
context.setFillColor(color.cgColor)
let factor = diameter / 50.0
let size = CGSize(width: 15.0, height: 18.0)
context.translateBy(x: (diameter - size.width) / 2.0 + 1.5, y: (diameter - size.height) / 2.0)
if (diameter < 40.0) {
context.translateBy(x: size.width / 2.0, y: size.height / 2.0)
context.scaleBy(x: factor, y: factor)
context.translateBy(x: -size.width / 2.0, y: -size.height / 2.0)
}
let _ = try? drawSvgPath(context, path: "M1.71891969,0.209353049 C0.769586558,-0.350676705 0,0.0908839327 0,1.18800046 L0,16.8564753 C0,17.9569971 0.750549162,18.357187 1.67393713,17.7519379 L14.1073836,9.60224049 C15.0318735,8.99626906 15.0094718,8.04970371 14.062401,7.49100858 L1.71891969,0.209353049 ")
context.fillPath()
if (diameter < 40.0) {
context.translateBy(x: size.width / 2.0, y: size.height / 2.0)
context.scaleBy(x: 1.0 / 0.8, y: 1.0 / 0.8)
context.translateBy(x: -size.width / 2.0, y: -size.height / 2.0)
}
context.translateBy(x: -(diameter - size.width) / 2.0 - 1.5, y: -(diameter - size.height) / 2.0)
case .ImpossibleFetching:
break
case let .Icon(image: icon, mode:blendMode):
var f = focus(icon.backingSize)
f.origin.x += parameters.theme.iconInset.left
f.origin.x -= parameters.theme.iconInset.right
f.origin.y += parameters.theme.iconInset.top
f.origin.y -= parameters.theme.iconInset.bottom
context.setBlendMode(blendMode)
context.draw(icon, in: f)
}
}
public override func copy() -> Any {
let view = NSView()
view.wantsLayer = true
view.frame = self.frame
view.layer?.contents = progressInteractiveThumb(backgroundColor: parameters.theme.backgroundColor, foregroundColor: parameters.theme.foregroundColor)
return view
}
public override func apply(state: ControlState) {
}
}
| gpl-2.0 | e20a1be0f93cd4c65f32a8b3348e13c4 | 35.614035 | 318 | 0.550311 | 4.60097 | false | false | false | false |
buguanhu/THLiveSmart | THLiveSmart/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Scheduler.swift | 8 | 15162 | //
// Scheduler.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-06-02.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
/// Represents a serial queue of work items.
public protocol SchedulerType {
/// Enqueues an action on the scheduler.
///
/// When the work is executed depends on the scheduler in use.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
func schedule(action: () -> Void) -> Disposable?
}
/// A particular kind of scheduler that supports enqueuing actions at future
/// dates.
public protocol DateSchedulerType: SchedulerType {
/// The current date, as determined by this scheduler.
///
/// This can be implemented to deterministically return a known date (e.g.,
/// for testing purposes).
var currentDate: NSDate { get }
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: Starting time.
/// - action: Closure of the action to perform.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
func scheduleAfter(date: NSDate, action: () -> Void) -> Disposable?
/// Schedules a recurring action at the given interval, beginning at the
/// given date.
///
/// - parameters:
/// - date: Starting time.
/// - repeatingEvery: Repetition interval.
/// - withLeeway: Some delta for repetition.
/// - action: Closure of the action to perform.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval, action: () -> Void) -> Disposable?
}
/// A scheduler that performs all work synchronously.
public final class ImmediateScheduler: SchedulerType {
public init() {}
/// Immediately calls passed in `action`.
///
/// - parameters:
/// - action: Closure of the action to perform.
///
/// - returns: `nil`.
public func schedule(action: () -> Void) -> Disposable? {
action()
return nil
}
}
/// A scheduler that performs all work on the main queue, as soon as possible.
///
/// If the caller is already running on the main queue when an action is
/// scheduled, it may be run synchronously. However, ordering between actions
/// will always be preserved.
public final class UIScheduler: SchedulerType {
private static var dispatchOnceToken: dispatch_once_t = 0
private static var dispatchSpecificKey: UInt8 = 0
private static var dispatchSpecificContext: UInt8 = 0
private var queueLength: Int32 = 0
/// Initializes `UIScheduler`
public init() {
dispatch_once(&UIScheduler.dispatchOnceToken) {
dispatch_queue_set_specific(
dispatch_get_main_queue(),
&UIScheduler.dispatchSpecificKey,
&UIScheduler.dispatchSpecificContext,
nil
)
}
}
/// Queues an action to be performed on main queue. If the action is called
/// on the main thread and no work is queued, no scheduling takes place and
/// the action is called instantly.
///
/// - parameters:
/// - action: Closure of the action to perform on the main thread.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
public func schedule(action: () -> Void) -> Disposable? {
let disposable = SimpleDisposable()
let actionAndDecrement = {
if !disposable.disposed {
action()
}
OSAtomicDecrement32(&self.queueLength)
}
let queued = OSAtomicIncrement32(&queueLength)
// If we're already running on the main queue, and there isn't work
// already enqueued, we can skip scheduling and just execute directly.
if queued == 1 && dispatch_get_specific(&UIScheduler.dispatchSpecificKey) == &UIScheduler.dispatchSpecificContext {
actionAndDecrement()
} else {
dispatch_async(dispatch_get_main_queue(), actionAndDecrement)
}
return disposable
}
}
/// A scheduler backed by a serial GCD queue.
public final class QueueScheduler: DateSchedulerType {
internal let queue: dispatch_queue_t
internal init(internalQueue: dispatch_queue_t) {
queue = internalQueue
}
/// Initializes a scheduler that will target the given queue with its
/// work.
///
/// - note: Even if the queue is concurrent, all work items enqueued with
/// the `QueueScheduler` will be serial with respect to each other.
///
/// - warning: Obsoleted in OS X 10.11.
@available(OSX, deprecated=10.10, obsoleted=10.11, message="Use init(qos:, name:) instead")
public convenience init(queue: dispatch_queue_t, name: String = "org.reactivecocoa.ReactiveCocoa.QueueScheduler") {
self.init(internalQueue: dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL))
dispatch_set_target_queue(self.queue, queue)
}
/// A singleton `QueueScheduler` that always targets the main thread's GCD
/// queue.
///
/// - note: Unlike `UIScheduler`, this scheduler supports scheduling for a
/// future date, and will always schedule asynchronously (even if
/// already running on the main thread).
public static let mainQueueScheduler = QueueScheduler(internalQueue: dispatch_get_main_queue())
public var currentDate: NSDate {
return NSDate()
}
/// Initializes a scheduler that will target a new serial queue with the
/// given quality of service class.
///
/// - parameters:
/// - qos: Dispatch queue's QoS value.
/// - name: Name for the queue in the form of reverse domain.
@available(iOS 8, watchOS 2, OSX 10.10, *)
public convenience init(qos: dispatch_qos_class_t = QOS_CLASS_DEFAULT, name: String = "org.reactivecocoa.ReactiveCocoa.QueueScheduler") {
self.init(internalQueue: dispatch_queue_create(name, dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos, 0)))
}
/// Schedules action for dispatch on internal queue
///
/// - parameters:
/// - action: Closure of the action to schedule.
///
/// - returns: `Disposable` that can be used to cancel the work before it
/// begins.
public func schedule(action: () -> Void) -> Disposable? {
let d = SimpleDisposable()
dispatch_async(queue) {
if !d.disposed {
action()
}
}
return d
}
private func wallTimeWithDate(date: NSDate) -> dispatch_time_t {
let (seconds, frac) = modf(date.timeIntervalSince1970)
let nsec: Double = frac * Double(NSEC_PER_SEC)
var walltime = timespec(tv_sec: Int(seconds), tv_nsec: Int(nsec))
return dispatch_walltime(&walltime, 0)
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: Starting time.
/// - action: Closure of the action to perform.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func scheduleAfter(date: NSDate, action: () -> Void) -> Disposable? {
let d = SimpleDisposable()
dispatch_after(wallTimeWithDate(date), queue) {
if !d.disposed {
action()
}
}
return d
}
/// Schedules a recurring action at the given interval and beginning at the
/// given start time. A reasonable default timer interval leeway is
/// provided.
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, action: () -> Void) -> Disposable? {
// Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of
// at least 10% of the timer interval.
return scheduleAfter(date, repeatingEvery: repeatingEvery, withLeeway: repeatingEvery * 0.1, action: action)
}
/// Schedules a recurring action at the given interval with provided leeway,
/// beginning at the given start time.
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway leeway: NSTimeInterval, action: () -> Void) -> Disposable? {
precondition(repeatingEvery >= 0)
precondition(leeway >= 0)
let nsecInterval = repeatingEvery * Double(NSEC_PER_SEC)
let nsecLeeway = leeway * Double(NSEC_PER_SEC)
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
dispatch_source_set_timer(timer, wallTimeWithDate(date), UInt64(nsecInterval), UInt64(nsecLeeway))
dispatch_source_set_event_handler(timer, action)
dispatch_resume(timer)
return ActionDisposable {
dispatch_source_cancel(timer)
}
}
}
/// A scheduler that implements virtualized time, for use in testing.
public final class TestScheduler: DateSchedulerType {
private final class ScheduledAction {
let date: NSDate
let action: () -> Void
init(date: NSDate, action: () -> Void) {
self.date = date
self.action = action
}
func less(rhs: ScheduledAction) -> Bool {
return date.compare(rhs.date) == .OrderedAscending
}
}
private let lock = NSRecursiveLock()
private var _currentDate: NSDate
/// The virtual date that the scheduler is currently at.
public var currentDate: NSDate {
let d: NSDate
lock.lock()
d = _currentDate
lock.unlock()
return d
}
private var scheduledActions: [ScheduledAction] = []
/// Initializes a TestScheduler with the given start date.
///
/// - parameters:
/// - startDate: The start date of the scheduler.
public init(startDate: NSDate = NSDate(timeIntervalSinceReferenceDate: 0)) {
lock.name = "org.reactivecocoa.ReactiveCocoa.TestScheduler"
_currentDate = startDate
}
private func schedule(action: ScheduledAction) -> Disposable {
lock.lock()
scheduledActions.append(action)
scheduledActions.sortInPlace { $0.less($1) }
lock.unlock()
return ActionDisposable {
self.lock.lock()
self.scheduledActions = self.scheduledActions.filter { $0 !== action }
self.lock.unlock()
}
}
/// Enqueues an action on the scheduler.
///
/// - note: The work is executed on `currentDate` as it is understood by the
/// scheduler.
///
/// - parameters:
/// - action: An action that will be performed on scheduler's
/// `currentDate`.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func schedule(action: () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: currentDate, action: action))
}
/// Schedules an action for execution at or after the given date.
///
/// - parameters:
/// - date: Starting date.
/// - action: Closure of the action to perform.
///
/// - returns: Optional disposable that can be used to cancel the work
/// before it begins.
public func scheduleAfter(interval: NSTimeInterval, action: () -> Void) -> Disposable? {
return scheduleAfter(currentDate.dateByAddingTimeInterval(interval), action: action)
}
public func scheduleAfter(date: NSDate, action: () -> Void) -> Disposable? {
return schedule(ScheduledAction(date: date, action: action))
}
/// Schedules a recurring action at the given interval, beginning at the
/// given start time
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
private func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, disposable: SerialDisposable, action: () -> Void) {
precondition(repeatingEvery >= 0)
disposable.innerDisposable = scheduleAfter(date) { [unowned self] in
action()
self.scheduleAfter(date.dateByAddingTimeInterval(repeatingEvery), repeatingEvery: repeatingEvery, disposable: disposable, action: action)
}
}
/// Schedules a recurring action at the given interval, beginning at the
/// given interval (counted from `currentDate`).
///
/// - parameters:
/// - interval: Interval to add to `currentDate`.
/// - repeatingEvery: Repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func scheduleAfter(interval: NSTimeInterval, repeatingEvery: NSTimeInterval, withLeeway leeway: NSTimeInterval = 0, action: () -> Void) -> Disposable? {
return scheduleAfter(currentDate.dateByAddingTimeInterval(interval), repeatingEvery: repeatingEvery, withLeeway: leeway, action: action)
}
/// Schedules a recurring action at the given interval with
/// provided leeway, beginning at the given start time.
///
/// - parameters:
/// - date: Date to schedule the first action for.
/// - repeatingEvery: Repetition interval.
/// - leeway: Some delta for repetition interval.
/// - action: Closure of the action to repeat.
///
/// - returns: Optional `Disposable` that can be used to cancel the work
/// before it begins.
public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval = 0, action: () -> Void) -> Disposable? {
let disposable = SerialDisposable()
scheduleAfter(date, repeatingEvery: repeatingEvery, disposable: disposable, action: action)
return disposable
}
/// Advances the virtualized clock by an extremely tiny interval, dequeuing
/// and executing any actions along the way.
///
/// This is intended to be used as a way to execute actions that have been
/// scheduled to run as soon as possible.
public func advance() {
advanceByInterval(DBL_EPSILON)
}
/// Advances the virtualized clock by the given interval, dequeuing and
/// executing any actions along the way.
///
/// - parameters:
/// - interval: Interval by which the current date will be advanced.
public func advanceByInterval(interval: NSTimeInterval) {
lock.lock()
advanceToDate(currentDate.dateByAddingTimeInterval(interval))
lock.unlock()
}
/// Advances the virtualized clock to the given future date, dequeuing and
/// executing any actions up until that point.
///
/// - parameters:
/// - newDate: Future date to which the virtual clock will be advanced.
public func advanceToDate(newDate: NSDate) {
lock.lock()
assert(currentDate.compare(newDate) != .OrderedDescending)
while scheduledActions.count > 0 {
if newDate.compare(scheduledActions[0].date) == .OrderedAscending {
break
}
_currentDate = scheduledActions[0].date
let scheduledAction = scheduledActions.removeAtIndex(0)
scheduledAction.action()
}
_currentDate = newDate
lock.unlock()
}
/// Dequeues and executes all scheduled actions, leaving the scheduler's
/// date at `NSDate.distantFuture()`.
public func run() {
advanceToDate(NSDate.distantFuture())
}
}
| apache-2.0 | d934db2cb924810a34699d121d76bde1 | 32.396476 | 160 | 0.695357 | 3.913784 | false | false | false | false |
tjw/swift | test/SILOptimizer/infinite_recursion.swift | 1 | 2628 | // RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
func a() { // expected-warning {{all paths through this function will call itself}}
a()
}
func b(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
if x != 0 {
b(x)
} else {
b(x+1)
}
}
func c(_ x : Int) {
if x != 0 {
c(5)
}
}
func d(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
if x != 0 {
x += 1
}
return d(x)
}
// Doesn't warn on mutually recursive functions
func e() { f() }
func f() { e() }
func g() { // expected-warning {{all paths through this function will call itself}}
while true { // expected-note {{condition always evaluates to true}}
g()
}
g() // expected-warning {{will never be executed}}
}
func h(_ x : Int) {
while (x < 5) {
h(x+1)
}
}
func i(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
while (x < 5) {
x -= 1
}
i(0)
}
func j() -> Int { // expected-warning {{all paths through this function will call itself}}
return 5 + j()
}
func k() -> Any { // expected-warning {{all paths through this function will call itself}}
return type(of: k())
}
class S {
convenience init(a: Int) { // expected-warning {{all paths through this function will call itself}}
self.init(a: a)
}
init(a: Int?) {}
static func a() { // expected-warning {{all paths through this function will call itself}}
return a()
}
func b() { // expected-warning {{all paths through this function will call itself}}
var i = 0
repeat {
i += 1
b()
} while (i > 5)
}
}
class T: S {
// No warning, calls super
override func b() {
var i = 0
repeat {
i += 1
super.b()
} while (i > 5)
}
}
func == (l: S?, r: S?) -> Bool { // expected-warning {{all paths through this function will call itself}}
if l == nil && r == nil { return true }
guard let l = l, let r = r else { return false }
return l === r
}
public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool { // expected-warning {{all paths through this function will call itself}}
return lhs == rhs
}
func factorial(_ n : UInt) -> UInt { // expected-warning {{all paths through this function will call itself}}
return (n != 0) ? factorial(n - 1) * n : factorial(1)
}
func tr(_ key: String) -> String { // expected-warning {{all paths through this function will call itself}}
return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}}
}
| apache-2.0 | cd5cd63464c359ad7c3e221a9a04fb44 | 22.890909 | 149 | 0.597032 | 3.339263 | false | false | false | false |
IrenaChou/IRDouYuZB | IRDouYuZBSwift/IRDouYuZBSwift/Classes/Home/Controller/IRRecommendViewController.swift | 1 | 3755 | //
// IRRecommendViewController.swift
// IRDouYuZBSwift
//
// Created by zhongdai on 2017/1/10.
// Copyright © 2017年 ir. All rights reserved.
//
import UIKit
// MARK:- 定义常量
private let kPrettyItemHeight : CGFloat = kItemWidth * 4 / 3
private let kPrettyCellID : String = "kPrettyCellID"
private let kCycleViewHeight : CGFloat = kScreenWidth * 3 / 8
private let krecommendGameViewHeight : CGFloat = 90
class IRRecommendViewController: IRBaseAnchorViewController {
// MARK:- 懒加载
fileprivate lazy var recommendVM : IRRecommendViewModel = IRRecommendViewModel()
fileprivate lazy var recommendCycleView : IRCycleView = {
let cycleView = IRCycleView.cycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewHeight+krecommendGameViewHeight), width: kScreenWidth, height: kCycleViewHeight)
return cycleView
}()
fileprivate lazy var recommendGameView : IRRecommendGameView = {
let gameView = IRRecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -krecommendGameViewHeight, width: kScreenWidth, height: krecommendGameViewHeight)
return gameView
}()
}
// MARK: - 设置UI界面的内容
extension IRRecommendViewController{
override func setupUI(){
super.setupUI()
//将cycleView添加到collectionView中
collectView.addSubview(recommendCycleView)
//将recommendGameView添加到collectionView中
collectView.addSubview(recommendGameView)
//设置collectionView的内边距
collectView.contentInset = UIEdgeInsets(top: kCycleViewHeight+krecommendGameViewHeight, left: 0, bottom: 0, right: 0)
collectView.register(UINib(nibName: "IRCollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
}
}
// MARK: - 请求数据
extension IRRecommendViewController {
override func loadData(){
baseViewModel = recommendVM
recommendVM.requestData {[weak self] in
self?.collectView.reloadData()
//将推荐数据传递给gameView
var groups = self?.recommendVM.anchorGroups
groups!.removeFirst()
groups!.removeFirst()
//添加更多组
let moreGroup = IRAnchorGroup()
moreGroup.tag_name = "更多"
groups!.append(moreGroup)
self?.recommendGameView.groups = groups
//数据请求完成
self?.loadDataFinish()
}
// 请求图片轮播数据
recommendVM.requestCycleData {
self.recommendCycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
extension IRRecommendViewController : UICollectionViewDelegateFlowLayout{
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! IRCollectionPrettyCell
prettyCell.anchor = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return prettyCell
}else{
return super.collectionView(collectionView,cellForItemAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if (indexPath.section == 1){
return CGSize(width: kItemWidth, height: kPrettyItemHeight)
}else{
return CGSize(width: kItemWidth, height: kNormalItemHeight)
}
}
}
| mit | da61d48610969c55d618ba6c55518967 | 33.865385 | 160 | 0.673194 | 5.460843 | false | false | false | false |
Ahyufei/DouYuTV | DYTV/DYTV/Classes/Main/Model/AnchorModel.swift | 1 | 829 | //
// AnchorModel.swift
// DYTV
//
// Created by Yufei on 2017/1/16.
// Copyright © 2017年 张玉飞. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
/// 房间ID
var room_id : Int = 0
/// 房间图片对应的URLString
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
// 0 : 电脑直播(普通房间) 1 : 手机直播(秀场房间)
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | 2de3ef7836fded782572b431bfe2e684 | 19.342857 | 73 | 0.551966 | 3.490196 | false | false | false | false |
lorentey/GlueKit | Sources/SetSortingByMappingToObservableComparable.swift | 1 | 5990 | //
// SetSortingByMappingToObservableComparable.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-07.
// Copyright © 2015–2017 Károly Lőrentey.
//
import SipHash
import BTree
extension ObservableSetType where Element: AnyObject {
/// Given a transformation into an observable of a comparable type, return an observable array
/// containing transformed versions of elements in this set, in increasing order.
public func sortedMap<Field: ObservableValueType>(by transform: @escaping (Element) -> Field) -> AnyObservableArray<Field.Value> where Field.Value: Comparable {
return SetSortingByMappingToObservableComparable(parent: self, transform: transform).anyObservableArray
}
}
private class SetSortingByMappingToObservableComparable<Parent: ObservableSetType, Field: ObservableValueType>: _BaseObservableArray<Field.Value>
where Parent.Element: AnyObject, Field.Value: Comparable {
typealias Element = Field.Value
typealias Change = ArrayChange<Element>
private struct ParentSink: UniqueOwnedSink {
typealias Owner = SetSortingByMappingToObservableComparable
unowned(unsafe) let owner: Owner
func receive(_ update: SetUpdate<Parent.Element>) {
owner.applyParentUpdate(update)
}
}
private struct FieldSink: SinkType, SipHashable {
typealias Owner = SetSortingByMappingToObservableComparable
unowned(unsafe) let owner: Owner
let element: Parent.Element
func receive(_ update: ValueUpdate<Field.Value>) {
owner.applyFieldUpdate(update, from: element)
}
func appendHashes(to hasher: inout SipHasher) {
hasher.append(ObjectIdentifier(owner))
hasher.append(element)
}
static func ==(left: FieldSink, right: FieldSink) -> Bool {
return left.owner === right.owner && left.element == right.element
}
}
private let parent: Parent
private let transform: (Parent.Element) -> Field
private var contents: Map<Element, Int> = [:]
private var fields: Dictionary<FieldSink, Field> = [:]
init(parent: Parent, transform: @escaping (Parent.Element) -> Field) {
self.parent = parent
self.transform = transform
super.init()
for element in parent.value {
_ = self._insert(newElement(element))
}
parent.add(ParentSink(owner: self))
}
deinit {
parent.remove(ParentSink(owner: self))
for (sink, field) in fields {
field.remove(sink)
}
}
private func newElement(_ element: Parent.Element) -> Element {
let field = transform(element)
let sink = FieldSink(owner: self, element: element)
let old = fields.updateValue(field, forKey: sink)
field.add(sink)
precondition(old == nil)
return field.value
}
private func removeElement(_ element: Parent.Element) {
let sink = FieldSink(owner: self, element: element)
let field = fields.removeValue(forKey: sink)!
field.remove(sink)
}
private func _insert(_ key: Element) -> Bool {
if let count = contents[key] {
contents[key] = count + 1
return false
}
contents[key] = 1
return true
}
private func insert(_ key: Element) -> ArrayModification<Element>? {
return _insert(key) ? .insert(key, at: contents.offset(of: key)!) : nil
}
private func remove(_ key: Element) -> ArrayModification<Element>? {
guard let count = self.contents[key] else {
fatalError("Inconsistent change: element removed is not in sorted set")
}
if count > 1 {
contents[key] = count - 1
return nil
}
let oldOffset = contents.offset(of: key)!
contents.removeValue(forKey: key)
return .remove(key, at: oldOffset)
}
func applyParentUpdate(_ update: SetUpdate<Parent.Element>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
var arrayChange = ArrayChange<Element>(initialCount: contents.count)
for element in change.removed {
let key = transform(element).value
removeElement(element)
if let mod = self.remove(key) {
arrayChange.add(mod)
}
}
for element in change.inserted {
let key = newElement(element)
if let mod = self.insert(key) {
arrayChange.add(mod)
}
}
if !arrayChange.isEmpty {
sendChange(arrayChange)
}
case .endTransaction:
endTransaction()
}
}
func applyFieldUpdate(_ update: ValueUpdate<Element>, from element: Parent.Element) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
var arrayChange = ArrayChange<Element>(initialCount: self.contents.count)
if change.old == change.new { return }
if let mod = remove(change.old) {
arrayChange.add(mod)
}
if let mod = insert(change.new) {
arrayChange.add(mod)
}
if !arrayChange.isEmpty {
sendChange(arrayChange)
}
case .endTransaction:
endTransaction()
}
}
override var isBuffered: Bool { return false }
override subscript(index: Int) -> Element { return contents.element(atOffset: index).0 }
override subscript(bounds: Range<Int>) -> ArraySlice<Element> { return ArraySlice(contents.submap(withOffsets: bounds).lazy.map { $0.0 }) }
override var value: Array<Element> { return Array(contents.lazy.map { $0.0 }) }
override var count: Int { return contents.count }
}
| mit | e888605788a61a60eeda15011d9412d3 | 33.385057 | 164 | 0.611065 | 4.663289 | false | false | false | false |
TrustWallet/trust-wallet-ios | TrustTests/Browser/Types/BrowserURLParserTests.swift | 1 | 2179 | // Copyright DApps Platform Inc. All rights reserved.
import XCTest
@testable import Trust
class BrowserURLParserTests: XCTestCase {
func testQueryReturnsSearchEngineURL() {
let parser = BrowserURLParser()
let query = "1"
let result = parser.url(from: query)
let expected = "https://\(parser.engine.host)/search?q=1"
XCTAssertEqual(result?.absoluteString, expected)
}
func testEscapeQuery() {
let parser = BrowserURLParser()
let query = "1 2?a=b&c"
let result = parser.url(from: query)
let expected = "https://\(parser.engine.host)/search?q=1%202?a%3Db%26c"
XCTAssertEqual(result?.absoluteString, expected)
}
func testParseDomain() {
let parser = BrowserURLParser()
let query = "trustwalletapp.com"
let result = parser.url(from: query)
XCTAssertEqual(result?.absoluteString, "http://trustwalletapp.com")
}
func testParseHttp() {
let parser = BrowserURLParser()
let string = "http://trustwalletapp.com"
let result = parser.url(from: string)
XCTAssertEqual(string, result?.absoluteString)
}
func testParseHttps() {
let parser = BrowserURLParser()
let string = "https://trustwalletapp.com"
let result = parser.url(from: string)
XCTAssertEqual(string, result?.absoluteString)
}
func testParseDomainWithPath() {
let parser = BrowserURLParser()
let string = "trustwalletapp.com/path?q=1"
let result = parser.url(from: string)
XCTAssertEqual(result?.absoluteString, "http://\(string)")
}
func testParseLongDomain() {
let parser = BrowserURLParser()
let string = "test.trustwalletapp.info"
let result = parser.url(from: string)
XCTAssertEqual(result?.absoluteString, "http://\(string)")
}
func testSearchURL() {
let parser = BrowserURLParser()
let query = "test"
let result = parser.buildSearchURL(for: query)
let expeted = "https://\(parser.engine.host)/search?q=test"
XCTAssertEqual(result.absoluteString, expeted)
}
}
| gpl-3.0 | f2cd55f90696a45db9d66dd281bd0d70 | 28.445946 | 79 | 0.631941 | 4.272549 | false | true | false | false |
PANDA-Guide/PandaGuideApp | PandaGuide/UIColor+Variants.swift | 1 | 1226 | //
// UIColor+Variants.swift
// TAZ
//
// Created by Pierre Dulac on 13/08/2014.
// Copyright (c) 2014 Amande&Pierre. All rights reserved.
//
import UIKit
extension UIColor {
/**
Create a ligher color
*/
func lighter(by percentage: CGFloat = 30.0) -> UIColor {
return adjustBrightness(by: abs(percentage))
}
/**
Create a darker color
*/
func darker(by percentage: CGFloat = 30.0) -> UIColor {
return adjustBrightness(by: -abs(percentage))
}
/**
Try to increase brightness or decrease saturation
*/
func adjustBrightness(by percentage: CGFloat = 30.0) -> UIColor {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
if getHue(&h, saturation: &s, brightness: &b, alpha: &a) {
if b < 1.0 {
let newB: CGFloat = max(min(b + (percentage/100.0)*b, 1.0), 0,0)
return UIColor(hue: h, saturation: s, brightness: newB, alpha: a)
} else {
let newS: CGFloat = min(max(s - (percentage/100.0)*s, 0.0), 1.0)
return UIColor(hue: h, saturation: newS, brightness: b, alpha: a)
}
}
return self
}
}
| gpl-3.0 | e8efa11118c5cc1a553ef815f3e6204f | 26.863636 | 81 | 0.550571 | 3.574344 | false | false | false | false |
joemcbride/outlander-osx | src/Outlander/HighlightCellView.swift | 1 | 1452 | //
// HighlightCellView.swift
// Outlander
//
// Created by Joseph McBride on 5/16/15.
// Copyright (c) 2015 Joe McBride. All rights reserved.
//
import Cocoa
class HighlightCellView: NSView {
@IBOutlet weak var colorField: NSTextField!
@IBOutlet weak var pattern: NSTextField!
@IBOutlet weak var filterClass: NSTextField!
var selected:Bool = false {
didSet {
self.needsDisplay = true
}
}
var backgroundColor:NSColor? {
didSet {
self.needsDisplay = true
}
}
var selectedColor:NSColor = NSColor(hex:"#3399ff") {
didSet {
self.needsDisplay = true
}
}
override func drawRect(dirtyRect: NSRect) {
let strokeWidth:CGFloat = 3.5
NSBezierPath.setDefaultLineWidth(strokeWidth)
NSBezierPath.setDefaultLineCapStyle(NSLineCapStyle.RoundLineCapStyle)
if let bg = backgroundColor {
bg.setFill()
NSRectFill(self.bounds)
}
if self.selected {
self.selectedColor.setStroke()
let border = NSBezierPath()
let borderRect = NSMakeRect(self.bounds.origin.x, self.bounds.origin.y, self.bounds.width-2, self.bounds.height)
border.appendBezierPathWithRect(borderRect)
border.stroke()
}
super.drawRect(dirtyRect)
}
}
| mit | b65f1b4e81ed8a212ed2bdde5c8bf92e | 24.034483 | 124 | 0.584022 | 4.729642 | false | false | false | false |
crazypoo/PTools | Pods/CryptoSwift/Sources/CryptoSwift/SHA1.swift | 2 | 4779 | //
// CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public final class SHA1: DigestType {
@usableFromInline
static let digestLength: Int = 20 // 160 / 8
@usableFromInline
static let blockSize: Int = 64
@usableFromInline
static let hashInitialValue: ContiguousArray<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]
@usableFromInline
var accumulated = Array<UInt8>()
@usableFromInline
var processedBytesTotalCount: Int = 0
@usableFromInline
var accumulatedHash: ContiguousArray<UInt32> = SHA1.hashInitialValue
public init() {
}
@inlinable
public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
do {
return try update(withBytes: bytes.slice, isLast: true)
} catch {
return []
}
}
@usableFromInline
func process(block chunk: ArraySlice<UInt8>, currentHash hh: inout ContiguousArray<UInt32>) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into eighty 32-bit words:
let M = UnsafeMutablePointer<UInt32>.allocate(capacity: 80)
M.initialize(repeating: 0, count: 80)
defer {
M.deinitialize(count: 80)
M.deallocate()
}
for x in 0..<80 {
switch x {
case 0...15:
let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout<UInt32>.size
M[x] = UInt32(bytes: chunk, fromIndex: start)
default:
M[x] = rotateLeft(M[x - 3] ^ M[x - 8] ^ M[x - 14] ^ M[x - 16], by: 1)
}
}
var A = hh[0]
var B = hh[1]
var C = hh[2]
var D = hh[3]
var E = hh[4]
// Main loop
for j in 0...79 {
var f: UInt32 = 0
var k: UInt32 = 0
switch j {
case 0...19:
f = (B & C) | ((~B) & D)
k = 0x5a827999
case 20...39:
f = B ^ C ^ D
k = 0x6ed9eba1
case 40...59:
f = (B & C) | (B & D) | (C & D)
k = 0x8f1bbcdc
case 60...79:
f = B ^ C ^ D
k = 0xca62c1d6
default:
break
}
let temp = rotateLeft(A, by: 5) &+ f &+ E &+ M[j] &+ k
E = D
D = C
C = rotateLeft(B, by: 30)
B = A
A = temp
}
hh[0] = hh[0] &+ A
hh[1] = hh[1] &+ B
hh[2] = hh[2] &+ C
hh[3] = hh[3] &+ D
hh[4] = hh[4] &+ E
}
}
extension SHA1: Updatable {
@discardableResult @inlinable
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
self.accumulated += bytes
if isLast {
let lengthInBits = (processedBytesTotalCount + self.accumulated.count) * 8
let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b
// Step 1. Append padding
bitPadding(to: &self.accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8)
// Step 2. Append Length a 64-bit representation of lengthInBits
self.accumulated += lengthBytes
}
var processedBytes = 0
for chunk in self.accumulated.batched(by: SHA1.blockSize) {
if isLast || (self.accumulated.count - processedBytes) >= SHA1.blockSize {
self.process(block: chunk, currentHash: &self.accumulatedHash)
processedBytes += chunk.count
}
}
self.accumulated.removeFirst(processedBytes)
self.processedBytesTotalCount += processedBytes
// output current hash
var result = Array<UInt8>(repeating: 0, count: SHA1.digestLength)
var pos = 0
for idx in 0..<self.accumulatedHash.count {
let h = self.accumulatedHash[idx]
result[pos + 0] = UInt8((h >> 24) & 0xff)
result[pos + 1] = UInt8((h >> 16) & 0xff)
result[pos + 2] = UInt8((h >> 8) & 0xff)
result[pos + 3] = UInt8(h & 0xff)
pos += 4
}
// reset hash value for instance
if isLast {
self.accumulatedHash = SHA1.hashInitialValue
}
return result
}
}
| mit | 1eb92f4c005aa4c6290f3df113e61348 | 29.21519 | 217 | 0.61814 | 3.692189 | false | false | false | false |
TimurBK/SwiftSampleProject | Pods/JSQCoreDataKit/Source/Utils.swift | 1 | 1513 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://www.jessesquires.com/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import CoreData
import Foundation
/// Describes a child managed object context.
public typealias ChildContext = NSManagedObjectContext
/// Describes the initialization options for a persistent store.
public typealias PersistentStoreOptions = [NSObject : AnyObject]
/// Describes default persistent store options.
public let defaultStoreOptions: PersistentStoreOptions = [
NSMigratePersistentStoresAutomaticallyOption as NSObject: true as AnyObject,
NSInferMappingModelAutomaticallyOption as NSObject: true as AnyObject
]
// MARK: Internal
internal func defaultDirectoryURL() -> URL {
do {
#if os(tvOS)
let searchPathDirectory = FileManager.SearchPathDirectory.cachesDirectory
#else
let searchPathDirectory = FileManager.SearchPathDirectory.documentDirectory
#endif
return try FileManager.default.url(for: searchPathDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
}
catch {
fatalError("*** Error finding default directory: \(error)")
}
}
| mit | b13a7ecf572a4c8d322b7a0f92d87a81 | 26.490909 | 87 | 0.666005 | 5.419355 | false | false | false | false |
soapyigu/LeetCode_Swift | DP/MinimumWindowSubsequence.swift | 1 | 1174 | /**
* Question Link: https://leetcode.com/problems/minimum-window-subsequence/
* Primary idea: Dynamic Programming, dp[i][j] = dp[i][j - 1] || dp[i - 1][j - 1]
* Time Complexity: O(mn), Space Complexity: O(mn)
*
*/
class MinimumWindowSubsequence {
func minWindow(_ S: String, _ T: String) -> String {
let m = T.count, n = S.count, sChars = Array(S), tChars = Array(T)
var dp = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)
var start = 0, len = n + 1
for i in 0...n {
dp[0][i] = i + 1
}
for i in 1...m {
for j in 1...n {
if tChars[i - 1] == sChars[j - 1] {
dp[i][j] = dp[i - 1][j - 1]
} else {
dp[i][j] = dp[i][j - 1]
}
}
}
for i in 1...n {
if dp[m][i] != 0 {
if i - dp[m][i] + 1 < len {
len = i - dp[m][i] + 1
start = dp[m][i] - 1
}
}
}
return len == n + 1 ? "" : String(sChars[start..<start + len])
}
} | mit | d46b1a9fb45fb563142064272a8a3337 | 29.128205 | 82 | 0.388416 | 3.335227 | false | false | false | false |
Barry-Wang/iOS-Animation-Guide-Swift | YMPopMenu/YMPopMenu/YMPopMenu.swift | 1 | 4355 | //
// YMPopMenu.swift
// YMPopMenu
//
// Created by barryclass on 15/11/21.
// Copyright © 2015年 barry. All rights reserved.
//
import UIKit
class YMPopMenu: UIView {
var innderDiameter:CGFloat = 0
var boudsCenterX:CGFloat = 0
var boudsCenterY:CGFloat = 0
var buttonArray:[YMCirCleButton] = [YMCirCleButton]()
var centerButton = YMCirCleButton(frame: CGRectMake(0,0,0,0))
var avergeRadius = 0
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.innderDiameter = self.frame.size.width / 2 - 30
self.boudsCenterX = self.frame.size.width / 2
self.boudsCenterY = self.frame.size.height / 2
}
convenience init(frame:CGRect, count:NSInteger) {
self.init(frame: frame)
self.avergeRadius = 360 / count
self.centerButton.frame = CGRectMake(0, 0, self.boudsCenterX, self.boudsCenterX)
self.centerButton.center = CGPointMake(self.boudsCenterX, self.boudsCenterY)
self.centerButton.addEvent { () -> Void in
print("come here")
self.showMenu()
}
self.addSubview(centerButton)
for var i = 0; i < count; i++ {
let button = YMCirCleButton(frame: CGRectMake(self.boudsCenterX - 15, self.boudsCenterY - 15, 0, 0))
self.buttonArray.append(button)
self.addSubview(button)
}
}
func getCirclePoint(radius:CGFloat)->(x:CGFloat, y:CGFloat) {
switch radius {
case 0:
return(self.boudsCenterX, self.boudsCenterY - self.innderDiameter)
case 90:
return(self.boudsCenterX + self.innderDiameter, self.boudsCenterY)
case 180:
return (self.boudsCenterX, self.boudsCenterY + self.innderDiameter)
case 270:
return (self.boudsCenterX - self.innderDiameter, self.boudsCenterY)
default:
let x = sin(Double(radius) * M_PI / 180) * Double(self.innderDiameter)
let y = cos(Double(radius) * M_PI / 180) * Double(self.innderDiameter)
return(self.boudsCenterX + CGFloat(x), self.boudsCenterY - CGFloat(y))
}
}
func showMenu () {
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.6, options: [UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.BeginFromCurrentState], animations: { () -> Void in
for var i = 0; i < self.buttonArray.count; i++ {
let button = self.buttonArray[i]
let centerPoint:(x:CGFloat, y:CGFloat) = self.getCirclePoint(CGFloat(self.avergeRadius * i))
button.frame = CGRectMake(centerPoint.x - 15, centerPoint.y - 15, 30, 30)
button.setNeedsDisplay()
}
self.transform = CGAffineTransformMakeRotation(-360)
self.centerButton.alpha = 0.0
}) { (sucess:Bool) -> Void in
}
}
func disappearMenu() {
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.6, options: [UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.BeginFromCurrentState], animations: { () -> Void in
for var i = 0; i < self.buttonArray.count; i++ {
let button = self.buttonArray[i]
button.frame = CGRectMake(self.boudsCenterX - 15, self.boudsCenterY - 15, 30, 30)
button.setNeedsDisplay()
}
self.centerButton.alpha = 1.0
self.transform = CGAffineTransformMakeRotation(360)
}) { (sucess:Bool) -> Void in
for button in self.buttonArray {
button.frame = CGRectMake(self.boudsCenterX - 15, self.boudsCenterY - 15, 0, 0)
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| apache-2.0 | 45967adcbaa07f328823b31160363c92 | 35.571429 | 238 | 0.597197 | 4.094073 | false | false | false | false |
tqtifnypmb/SwiftyImage | Framenderer/Sources/Filters/Blur/GaussianBlur/GaussianBlurFilter.swift | 2 | 2563 | //
// GaussianBlurFilter.swift
// Framenderer
//
// Created by tqtifnypmb on 12/12/2016.
// Copyright © 2016 tqitfnypmb. All rights reserved.
//
import Foundation
import OpenGLES.ES3.gl
import OpenGLES.ES3.glext
import CoreMedia
import AVFoundation
public class GaussianBlurFilter: TwoPassFilter {
private let _radius: Int
private let _sigma: Double
/// sigma value used by Gaussian algorithm
public var gaussianSigma: Double = 0
/**
init a [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) filter
- parameter radius: specifies the distance from the center of the blur effect.
- parameter implement: specifies which implement to use.
- box: mimic Gaussian blur by applying box blur mutiple times
- normal: use Gaussian algorithm
*/
public init(radius: Int = 3, sigma: Double = 0) {
if sigma == 0 {
_radius = radius
// source from OpenCV (http://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html)
_sigma = 0.3 * Double(_radius - 1) + 0.8
} else {
// kernel size <= 6sigma is good enough
// reference: https://en.wikipedia.org/wiki/Gaussian_blur
_radius = min(radius, Int(floor(6 * sigma)))
_sigma = sigma
}
}
override public var name: String {
return "GaussianBlurFilter"
}
override public func setUniformAttributs(context ctx: Context) {
super.setUniformAttributs(context: ctx)
let texelWidth = 1 / GLfloat(ctx.inputWidth)
_program.setUniform(name: kXOffset, value: texelWidth)
_program.setUniform(name: kYOffset, value: GLfloat(0))
_program.setUniform(name: "radius", value: _radius)
_program.setUniform(name: "sigma", value: Float(_sigma))
}
override public func setUniformAttributs2(context ctx: Context) {
super.setUniformAttributs2(context: ctx)
let texelHeight = 1 / GLfloat(ctx.inputHeight)
_program2.setUniform(name: kXOffset, value: GLfloat(0))
_program2.setUniform(name: kYOffset, value: texelHeight)
_program2.setUniform(name: "radius", value: _radius)
_program2.setUniform(name: "sigma", value: Float(_sigma))
}
override func buildProgram() throws {
_program = try Program.create(fragmentSourcePath: "GaussianBlurFragmentShader")
_program2 = try Program.create(fragmentSourcePath: "GaussianBlurFragmentShader")
}
}
| mit | b232a1d8b28e42e4244367705856d073 | 34.583333 | 99 | 0.636222 | 4.213816 | false | false | false | false |
kristinathai/WatchOS2WatchConnectivityDemos | sendMessage/WatchOS2CounterSwiftStarter/WatchOS2CounterSwift/ViewController.swift | 1 | 1022 | //
// ViewController.swift
// WatchOS2CounterSwift
//
// Created by Thai, Kristina on 6/20/15.
// Copyright © 2015 Kristina Thai. All rights reserved.
//
import UIKit
import WatchConnectivity
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var mainTableView: UITableView!
var counterData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counterData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CounterCell"
let cell = self.mainTableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
let counterValueString = self.counterData[indexPath.row]
cell.textLabel?.text = counterValueString
return cell
}
}
| mit | 2522fab4be173405e62d20e2c4e5c3ae | 25.868421 | 105 | 0.680705 | 5.105 | false | false | false | false |
richardpiazza/XCServerCoreData | Example/Pods/CodeQuickKit/Sources/Reusable.swift | 2 | 5289 | #if os(iOS) || os(tvOS)
import UIKit
/// Reusable is meant to make working with UIStoryboard/UINibs
/// easier by requiring certain naming conventions.
///
/// The default implementation of Reusable will return a string
/// representation of the adopting class.
///
/// * **UIViewController**: When creating a UIViewController, set
/// the 'Storyboard ID' in Interface Builder, to the same subclass
/// name.
///
/// * **UITableViewCell**: When creating UITableViewCell subclasses
/// with XIBs, be sure to keep the nib and class names in sync.
///
public protocol Reusable: class {
static var reuseIdentifier: String { get }
}
public extension Reusable {
public static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UIView: Reusable {}
extension UIViewController: Reusable {}
public extension UIStoryboard {
/// Instantiates a UIViewController for the provided `Reusable` type.
/// - throws: NSInvalidArgumentException (when unable to locate view with identifier)
public func instantiateViewController<T: Reusable>(withType type: T.Type) -> T {
return self.instantiateViewController(withIdentifier: type.reuseIdentifier) as! T
}
}
public extension UITableView {
/// Registers a UITableViewCell.Type with the tableView.
/// This implementation relys on the `Reusable` protocol for
/// supplyings a 'reuseIdentifier'.
///
/// When creating UITableViewCell subclasses, if you are using
/// a XIB, be sure to name the file exactly after the class name.
/// (This is the default behavior).
///
/// - example:
/// class MyCustomTableViewCell: UITableViewCell {}
/// * MyCustomTableViewCell.swift
/// * MyCustomTableViewCell.xib
///
public func register<T: UITableViewCell>(reusableType: T.Type) {
let bundle = Bundle(for: T.self)
if let _ = bundle.url(forResource: T.reuseIdentifier, withExtension: "nib") {
let nib = UINib(nibName: T.reuseIdentifier, bundle: bundle)
self.register(nib, forCellReuseIdentifier: T.reuseIdentifier)
} else {
self.register(reusableType, forCellReuseIdentifier: T.reuseIdentifier)
}
}
/// Dequeue a UITableViewCell for the specific type.
/// This implementation relys on the `Reusable` protocol for
/// suppling the needed 'reuseIdentifier'.
public func dequeueReusableCell<T: UITableViewCell>(withType: T.Type, for indexPath: IndexPath) -> T {
guard let cell = self.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("\(#function); Failed to dequeue cell with identifier '\(T.reuseIdentifier)'")
}
return cell
}
}
public extension UICollectionView {
/// Registers a UICollectionViewCell.Type with the `collectionView`.
public func register<T: UICollectionViewCell>(reusableType: T.Type) {
let bundle = Bundle(for: T.self)
if let _ = bundle.url(forResource: T.reuseIdentifier, withExtension: "nib") {
let nib = UINib(nibName: T.reuseIdentifier, bundle: bundle)
self.register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
} else {
self.register(reusableType, forCellWithReuseIdentifier: T.reuseIdentifier)
}
}
/// Dequeue a typed UICollectionViewCell from the `collectionView`.
public func dequeueReusableCell<T: UICollectionViewCell>(withType: T.Type, for indexPath: IndexPath) -> T {
guard let cell = self.dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("\(#function); Failed to dequeue cell with identifier '\(T.reuseIdentifier)'")
}
return cell
}
/// Registers a UICollectionReusableView.Type with the `collectionView`.
///
/// Default/Defined kinds:
/// * UICollectionView.elementKindSectionHeader
/// * UICollectionView.elementKindSectionFooter
public func register<T: UICollectionReusableView>(reusableType: T.Type, supplementaryViewOfKind ofKind: String) {
let bundle = Bundle(for: T.self)
if let _ = bundle.url(forResource: T.reuseIdentifier, withExtension: "nib") {
let nib = UINib(nibName: T.reuseIdentifier, bundle: bundle)
self.register(nib, forSupplementaryViewOfKind: ofKind, withReuseIdentifier: T.reuseIdentifier)
} else {
self.register(reusableType, forSupplementaryViewOfKind: ofKind, withReuseIdentifier: T.reuseIdentifier)
}
}
/// Dequeue a typed UICollectionReusableView from the `collectionView`.
///
/// Default/Defined kinds:
/// * UICollectionView.elementKindSectionHeader
/// * UICollectionView.elementKindSectionFooter
public func dequeueReusableSupplementaryView<T: UICollectionReusableView>(withType: T.Type, ofKind: String, for indexPath: IndexPath) -> T {
guard let view = self.dequeueReusableSupplementaryView(ofKind: ofKind, withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("\(#function); Failed to dequeue supplementary view with identifier '\(T.reuseIdentifier)'")
}
return view
}
}
#endif
| mit | 429916f7f60d5d8909252a36e06c67a0 | 41.312 | 147 | 0.687654 | 5.090472 | false | false | false | false |
finn93/FoodTracker | FoodTracker/MealTableViewController.swift | 1 | 6266 | //
// MealTableViewController.swift
// FoodTracker
//
// Created by wangshuang on 2017/8/17.
// Copyright © 2017年 wangshuang. All rights reserved.
//
import UIKit
import os.log
class MealTableViewController: UITableViewController {
// MARK: - Properties
var meals = [Meal]()
override func viewDidLoad() {
super.viewDidLoad()
// Use the edit button item provided by the table view controller.
navigationItem.leftBarButtonItem = editButtonItem
// Load any saved meals, otherwise load sample data.
if let savedMeals = loadMeals() {
meals += savedMeals
} else {
// load the sample data
loadSampleMeals()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return meals.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "MealTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell else {
fatalError("The dequeue cell is not an instance of MealTableViewCell.")
}
// Fetches the appropriate meal for the data source layout.
let meal = meals[indexPath.row]
// Configure the cell...
cell.photoImageView?.image = meal.photo
cell.nameLabel.text = meal.name
cell.ratingControl.rating = meal.rating
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
meals.remove(at: indexPath.row)
saveMeals()
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
// 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?) {
super.prepare(for: segue, sender: sender)
switch segue.identifier ?? "" {
case "AddItem":
os_log("Adding a new meal.", log: OSLog.default, type: .debug)
case "ShowDetail":
guard let mealDetailViewController = segue.destination as? MealViewController else {
fatalError("Unexpected destination: \(segue.destination)")
}
guard let selectedMealCell = sender as? MealTableViewCell else {
fatalError("Unexpected sender: \(String(describing: sender))")
}
guard let indexPath = tableView.indexPath(for: selectedMealCell) else {
fatalError("The selected cell is not being displayed by the table")
}
let selectedMeal = meals[indexPath.row]
mealDetailViewController.meal = selectedMeal
default:
fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
}
}
// MARK: - Actions
@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
// Update an existing meal.
meals[selectedIndexPath.row] = meal
tableView.reloadRows(at: [selectedIndexPath], with: .none)
} else {
// Add a new meal.
let newIndexPath = IndexPath(row: meals.count, section: 0)
meals.append(meal)
tableView.insertRows(at: [newIndexPath], with: .automatic)
}
// Save the meals
saveMeals()
}
}
// MARK: - Private Methods
private func loadSampleMeals() {
let photo1 = UIImage(named: "meal1")
let photo2 = UIImage(named: "meal2")
let photo3 = UIImage(named: "meal3")
guard let meal1 = Meal.init(name: "蒜蓉蒸金针菇", photo: photo1, rating: 5) else {
fatalError("Unable the instantiate meal1")
}
guard let meal2 = Meal.init(name: "蒜香炒花甲", photo: photo2, rating: 4) else {
fatalError("Unable the instantiate meal2")
}
guard let meal3 = Meal.init(name: "苍蝇头", photo: photo3, rating: 4) else {
fatalError("Unable the instantiate meal3")
}
meals += [meal1, meal2, meal3]
}
private func saveMeals() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path)
if isSuccessfulSave {
os_log("Meals successfully saved.", log: OSLog.default, type: .debug)
} else {
os_log("Failed to save meals...", log: OSLog.default, type: .debug)
}
}
private func loadMeals() -> [Meal]? {
return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal]
}
}
| apache-2.0 | 6d814775e81190dc140462f0651519ba | 35.040462 | 136 | 0.598557 | 5.102291 | false | false | false | false |
pavellitvinko/RubyParser | parser/ConditionStatement.swift | 1 | 1324 | //
// Condition.swift
// parser
//
// Created by Pavel Litvinko on 17.10.14.
// Copyright (c) 2014 pavellitvinko. All rights reserved.
//
import Cocoa
import ExSwift
class ConditionStatement: Statement {
var isModifierStatement: Bool = false
var predicatesCount = 0
override func test(line: String, reader: StreamReader) -> Bool {
//orig: (^\s*?(if|unless)\s)|(\?\s.*:)
isModifierStatement = (line =~ "(\\s*?(if|unless)\\s)|(\\?\\s.*:)") &&
!(line =~ "(^\\s*?(if|unless)\\s)|(\\?\\s.*:)")
//orig: (!|=|>|<|==|\+|-|\*|\/|%|\*|\||&|\^|~)+=?
let matches = line.matches("(!|=|>|<|==|\\+|-|\\*|\\/|%|\\*|\\||&|\\^|~)+=?")!
predicatesCount = max(matches.count - 1, 0)
if isModifierStatement {
return true
} else {
//orig: (\s*?(if|unless)\s)|(\?\s.*:)
return line =~ "(\\s*?(if|unless)\\s)|(\\?\\s.*:)"
}
}
override func buildNode(title: String) -> Node? {
return ConditionNode(title, predicatesCount: predicatesCount)
}
override func getAfterBlockAffect() -> BlockType {
if !isModifierStatement {
return BlockType.StartsBlock
} else {
return BlockType.Continues
}
}
}
| mit | 298c92d1575518c621e0f67173ed8d99 | 28.422222 | 86 | 0.48716 | 3.617486 | false | false | false | false |
MrZoidberg/metapp | metapp/Pods/RxSwift/RxSwift/Observables/Implementations/SingleAsync.swift | 46 | 2214 | //
// SingleAsync.swift
// RxSwift
//
// Created by Junior B. on 09/11/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class SingleAsyncSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType {
typealias Parent = SingleAsync<ElementType>
typealias E = ElementType
private let _parent: Parent
private var _seenValue: Bool = false
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<E>) {
switch event {
case .next(let value):
do {
let forward = try _parent._predicate?(value) ?? true
if !forward {
return
}
}
catch let error {
forwardOn(.error(error as Swift.Error))
dispose()
return
}
if _seenValue == false {
_seenValue = true
forwardOn(.next(value))
} else {
forwardOn(.error(RxError.moreThanOneElement))
dispose()
}
case .error:
forwardOn(event)
dispose()
case .completed:
if (!_seenValue) {
forwardOn(.error(RxError.noElements))
} else {
forwardOn(.completed)
}
dispose()
}
}
}
class SingleAsync<Element>: Producer<Element> {
typealias Predicate = (Element) throws -> Bool
fileprivate let _source: Observable<Element>
fileprivate let _predicate: Predicate?
init(source: Observable<Element>, predicate: Predicate? = nil) {
_source = source
_predicate = predicate
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mpl-2.0 | 1c2c44c534b69bfdce6fba2a823d67ee | 28.118421 | 145 | 0.54451 | 4.800434 | false | false | false | false |
NjrSea/FlickTransition | FlickTransition/DismissAnimationController.swift | 1 | 2710 | //
// DismissAnimationController.swift
// FlickTransition
//
// Created by paul on 16/9/18.
// Copyright © 2016年 paul. All rights reserved.
//
import UIKit
class DismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
fileprivate let scaling: CGFloat = 0.95
var dismissDirection: Direction = .Left
var dismissDuration = 0.2
fileprivate var dimmingView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(white: 0, alpha: 0.4)
return view
}()
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return dismissDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else {
return
}
let containerView = transitionContext.containerView
guard let snapshot = toVC.view.snapshotView(afterScreenUpdates: true) else {
return
}
snapshot.addSubview(dimmingView)
snapshot.frame = toVC.view.bounds
dimmingView.frame = snapshot.bounds
dimmingView.alpha = 1.0
snapshot.layer.transform = CATransform3DScale(CATransform3DIdentity, self.scaling, self.scaling, 1)
containerView.insertSubview(snapshot, at: 0)
toVC.view.isHidden = true
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, delay: 0, options: .curveLinear, animations: {
snapshot.layer.transform = CATransform3DIdentity
self.dimmingView.alpha = 0.0
var frame = fromVC.view.frame
switch self.dismissDirection {
case .Left:
frame.origin.x = -frame.width
fromVC.view.frame = frame
case .Right:
frame.origin.x = frame.width
fromVC.view.frame = frame
case .Up:
frame.origin.y = -frame.height
fromVC.view.frame = frame
case .Down:
frame.origin.y = frame.height
fromVC.view.frame = frame
}
}) { _ in
snapshot.removeFromSuperview()
self.dimmingView.removeFromSuperview()
toVC.view.isHidden = false
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
| mit | fdac12463b427ccd6f5e78c81550bd03 | 33.705128 | 111 | 0.623938 | 5.490872 | false | false | false | false |
pasmall/WeTeam | WeTools/WeTools/ViewModel/View/SweetAlert.swift | 1 | 24676 | //
// SweetAlert.swift
// SweetAlert
//
// Created by Codester on 11/3/14.
// Copyright (c) 2014 Codester. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
public enum AlertStyle {
case success,error,warning,none
case customImag(imageFile:String)
}
open class SweetAlert: UIViewController {
let kBakcgroundTansperancy: CGFloat = 0.7
let kHeightMargin: CGFloat = 10.0
let KTopMargin: CGFloat = 20.0
let kWidthMargin: CGFloat = 10.0
let kAnimatedViewHeight: CGFloat = 70.0
let kMaxHeight: CGFloat = 300.0
var kContentWidth: CGFloat = 300.0
let kButtonHeight: CGFloat = 35.0
var textViewHeight: CGFloat = 90.0
let kTitleHeight:CGFloat = 30.0
var strongSelf:SweetAlert?
var contentView = UIView()
var titleLabel: UILabel = UILabel()
var buttons: [UIButton] = []
var animatedView: AnimatableView?
var imageView:UIImageView?
var subTitleTextView = UITextView()
var userAction:((_ isOtherButton: Bool) -> Void)? = nil
let kFont = "Helvetica"
init() {
super.init(nibName: nil, bundle: nil)
self.view.frame = UIScreen.main.bounds
self.view.autoresizingMask = [UIViewAutoresizing.flexibleHeight, UIViewAutoresizing.flexibleWidth]
self.view.backgroundColor = UIColor(red:0, green:0, blue:0, alpha:kBakcgroundTansperancy)
self.view.addSubview(contentView)
//Retaining itself strongly so can exist without strong refrence
strongSelf = self
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupContentView() {
contentView.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
contentView.layer.cornerRadius = 5.0
contentView.layer.masksToBounds = true
contentView.layer.borderWidth = 0.5
contentView.addSubview(titleLabel)
contentView.addSubview(subTitleTextView)
contentView.backgroundColor = UIColor.colorFromRGB(0xFFFFFF)
contentView.layer.borderColor = UIColor.colorFromRGB(0xCCCCCC).cgColor
view.addSubview(contentView)
}
fileprivate func setupTitleLabel() {
titleLabel.text = ""
titleLabel.numberOfLines = 1
titleLabel.textAlignment = .center
titleLabel.font = UIFont(name: kFont, size:25)
titleLabel.textColor = UIColor.colorFromRGB(0x575757)
}
fileprivate func setupSubtitleTextView() {
subTitleTextView.text = ""
subTitleTextView.textAlignment = .center
subTitleTextView.font = UIFont(name: kFont, size:16)
subTitleTextView.textColor = UIColor.colorFromRGB(0x797979)
subTitleTextView.isEditable = false
}
fileprivate func resizeAndRelayout() {
let mainScreenBounds = UIScreen.main.bounds
self.view.frame.size = mainScreenBounds.size
let x: CGFloat = kWidthMargin
var y: CGFloat = KTopMargin
let width: CGFloat = kContentWidth - (kWidthMargin*2)
if animatedView != nil {
animatedView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight)
contentView.addSubview(animatedView!)
y += kAnimatedViewHeight + kHeightMargin
}
if imageView != nil {
imageView!.frame = CGRect(x: (kContentWidth - kAnimatedViewHeight) / 2.0, y: y, width: kAnimatedViewHeight, height: kAnimatedViewHeight)
contentView.addSubview(imageView!)
y += imageView!.frame.size.height + kHeightMargin
}
// Title
if self.titleLabel.text != nil {
titleLabel.frame = CGRect(x: x, y: y, width: width, height: kTitleHeight)
contentView.addSubview(titleLabel)
y += kTitleHeight + kHeightMargin
}
// Subtitle
if self.subTitleTextView.text.isEmpty == false {
let subtitleString = subTitleTextView.text! as NSString
let rect = subtitleString.boundingRect(with: CGSize(width: width, height: 0.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName:subTitleTextView.font!], context: nil)
textViewHeight = ceil(rect.size.height) + 10.0
subTitleTextView.frame = CGRect(x: x, y: y, width: width, height: textViewHeight)
contentView.addSubview(subTitleTextView)
y += textViewHeight + kHeightMargin
}
var buttonRect:[CGRect] = []
for button in buttons {
let string = button.title(for: UIControlState())! as NSString
buttonRect.append(string.boundingRect(with: CGSize(width: width, height:0.0), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:[NSFontAttributeName:button.titleLabel!.font], context:nil))
}
var totalWidth: CGFloat = 0.0
if buttons.count == 2 {
totalWidth = buttonRect[0].size.width + buttonRect[1].size.width + kWidthMargin + 40.0
}
else{
totalWidth = buttonRect[0].size.width + 20.0
}
y += kHeightMargin
var buttonX = (kContentWidth - totalWidth ) / 2.0
for i in 0 ..< buttons.count {
buttons[i].frame = CGRect(x: buttonX, y: y, width: buttonRect[i].size.width + 20.0, height: buttonRect[i].size.height + 10.0)
buttonX = buttons[i].frame.origin.x + kWidthMargin + buttonRect[i].size.width + 20.0
buttons[i].layer.cornerRadius = 5.0
self.contentView.addSubview(buttons[i])
buttons[i].addTarget(self, action: #selector(SweetAlert.pressed(_:)), for: UIControlEvents.touchUpInside)
}
y += kHeightMargin + buttonRect[0].size.height + 10.0
if y > kMaxHeight {
let diff = y - kMaxHeight
let sFrame = subTitleTextView.frame
subTitleTextView.frame = CGRect(x: sFrame.origin.x, y: sFrame.origin.y, width: sFrame.width, height: sFrame.height - diff)
for button in buttons {
let bFrame = button.frame
button.frame = CGRect(x: bFrame.origin.x, y: bFrame.origin.y - diff, width: bFrame.width, height: bFrame.height)
}
y = kMaxHeight
}
contentView.frame = CGRect(x: (mainScreenBounds.size.width - kContentWidth) / 2.0, y: (mainScreenBounds.size.height - y) / 2.0, width: kContentWidth, height: y)
contentView.clipsToBounds = true
}
open func pressed(_ sender: UIButton!) {
self.closeAlert(sender.tag)
}
open override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var sz = UIScreen.main.bounds.size
let sver = UIDevice.current.systemVersion as NSString
let ver = sver.floatValue
if ver < 8.0 {
// iOS versions before 7.0 did not switch the width and height on device roration
if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
let ssz = sz
sz = CGSize(width:ssz.height, height:ssz.width)
}
}
self.resizeAndRelayout()
}
func closeAlert(_ buttonIndex:Int){
if userAction != nil {
let isOtherButton = buttonIndex == 0 ? true: false
SweetAlertContext.shouldNotAnimate = true
userAction!(isOtherButton)
SweetAlertContext.shouldNotAnimate = false
}
UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.view.alpha = 0.0
}) { (Bool) -> Void in
self.view.removeFromSuperview()
self.cleanUpAlert()
//Releasing strong refrence of itself.
self.strongSelf = nil
}
}
func cleanUpAlert() {
if self.animatedView != nil {
self.animatedView!.removeFromSuperview()
self.animatedView = nil
}
self.contentView.removeFromSuperview()
self.contentView = UIView()
}
open func showAlert(_ title: String) -> SweetAlert {
_ = showAlert(title, subTitle: nil, style: .none)
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle) -> SweetAlert {
_ = showAlert(title, subTitle: subTitle, style: style, buttonTitle: "好的")
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String, action: ((_ isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
_ = showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: UIColor.colorFromRGB(0xAEDEF4))
userAction = action
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,action: ((_ isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
_ = showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle:
nil)
userAction = action
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle:
String?, action: ((_ isOtherButton: Bool) -> Void)? = nil) -> SweetAlert {
self.showAlert(title, subTitle: subTitle, style: style, buttonTitle: buttonTitle,buttonColor: buttonColor,otherButtonTitle:
otherButtonTitle,otherButtonColor: UIColor.red)
userAction = action
return self
}
open func showAlert(_ title: String, subTitle: String?, style: AlertStyle,buttonTitle: String,buttonColor: UIColor,otherButtonTitle:
String?, otherButtonColor: UIColor?,action: ((_ isOtherButton: Bool) -> Void)? = nil) {
userAction = action
let window: UIWindow = UIApplication.shared.keyWindow!
window.addSubview(view)
window.bringSubview(toFront: view)
view.frame = window.bounds
self.setupContentView()
self.setupTitleLabel()
self.setupSubtitleTextView()
switch style {
case .success:
self.animatedView = SuccessAnimatedView()
case .error:
self.animatedView = CancelAnimatedView()
case .warning:
self.animatedView = InfoAnimatedView()
case let .customImag(imageFile):
if let image = UIImage(named: imageFile) {
self.imageView = UIImageView(image: image)
}
case .none:
self.animatedView = nil
}
self.titleLabel.text = title
if subTitle != nil {
self.subTitleTextView.text = subTitle
}
buttons = []
if buttonTitle.isEmpty == false {
let button: UIButton = UIButton(type: UIButtonType.custom)
button.setTitle(buttonTitle, for: UIControlState())
button.backgroundColor = buttonColor
button.isUserInteractionEnabled = true
button.tag = 0
buttons.append(button)
}
if otherButtonTitle != nil && otherButtonTitle!.isEmpty == false {
let button: UIButton = UIButton(type: UIButtonType.custom)
button.setTitle(otherButtonTitle, for: UIControlState())
button.backgroundColor = otherButtonColor
button.addTarget(self, action: #selector(SweetAlert.pressed(_:)), for: UIControlEvents.touchUpInside)
button.tag = 1
buttons.append(button)
}
resizeAndRelayout()
if SweetAlertContext.shouldNotAnimate == true {
//Do not animate Alert
if self.animatedView != nil {
self.animatedView!.animate()
}
}
else {
animateAlert()
}
}
func animateAlert() {
view.alpha = 0;
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.view.alpha = 1.0;
})
let previousTransform = self.contentView.transform
self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0);
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0.0);
}, completion: { (Bool) -> Void in
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0);
}, completion: { (Bool) -> Void in
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.contentView.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0);
if self.animatedView != nil {
self.animatedView!.animate()
}
}, completion: { (Bool) -> Void in
self.contentView.transform = previousTransform
})
})
})
}
fileprivate struct SweetAlertContext {
static var shouldNotAnimate = false
}
}
// MARK: -
// MARK: Animatable Views
class AnimatableView: UIView {
func animate(){
print("Should overide by subclasss", terminator: "")
}
}
class CancelAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var crossPathLayer = CAShapeLayer()
override required init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
var t = CATransform3DIdentity;
t.m34 = 1.0 / -500.0;
t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0);
circleLayer.transform = t
crossPathLayer.opacity = 0.0
}
override func layoutSubviews() {
setupLayers()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate var outlineCircle: CGPath {
let path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path.cgPath
}
fileprivate var crossPath: CGPath {
let path = UIBezierPath()
let factor:CGFloat = self.frame.size.width / 5.0
path.move(to: CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0-factor))
path.addLine(to: CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0+factor))
path.move(to: CGPoint(x: self.frame.size.height/2.0+factor,y: self.frame.size.height/2.0-factor))
path.addLine(to: CGPoint(x: self.frame.size.height/2.0-factor,y: self.frame.size.height/2.0+factor))
return path.cgPath
}
fileprivate func setupLayers() {
circleLayer.path = outlineCircle
circleLayer.fillColor = UIColor.clear.cgColor;
circleLayer.strokeColor = UIColor.colorFromRGB(0xF27474).cgColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(circleLayer)
crossPathLayer.path = crossPath
crossPathLayer.fillColor = UIColor.clear.cgColor;
crossPathLayer.strokeColor = UIColor.colorFromRGB(0xF27474).cgColor;
crossPathLayer.lineCap = kCALineCapRound
crossPathLayer.lineWidth = 4;
crossPathLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
crossPathLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(crossPathLayer)
}
override func animate() {
var t = CATransform3DIdentity;
t.m34 = 1.0 / -500.0;
t = CATransform3DRotate(t, CGFloat(90.0 * M_PI / 180.0), 1, 0, 0);
var t2 = CATransform3DIdentity;
t2.m34 = 1.0 / -500.0;
t2 = CATransform3DRotate(t2, CGFloat(-M_PI), 1, 0, 0);
let animation = CABasicAnimation(keyPath: "transform")
let time = 0.3
animation.duration = time;
animation.fromValue = NSValue(caTransform3D: t)
animation.toValue = NSValue(caTransform3D:t2)
animation.isRemovedOnCompletion = false
animation.fillMode = kCAFillModeForwards
self.circleLayer.add(animation, forKey: "transform")
var scale = CATransform3DIdentity;
scale = CATransform3DScale(scale, 0.3, 0.3, 0)
let crossAnimation = CABasicAnimation(keyPath: "transform")
crossAnimation.duration = 0.3;
crossAnimation.beginTime = CACurrentMediaTime() + time
crossAnimation.fromValue = NSValue(caTransform3D: scale)
crossAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.25, 0.8, 0.7, 2.0)
crossAnimation.toValue = NSValue(caTransform3D:CATransform3DIdentity)
self.crossPathLayer.add(crossAnimation, forKey: "scale")
let fadeInAnimation = CABasicAnimation(keyPath: "opacity")
fadeInAnimation.duration = 0.3;
fadeInAnimation.beginTime = CACurrentMediaTime() + time
fadeInAnimation.fromValue = 0.3
fadeInAnimation.toValue = 1.0
fadeInAnimation.isRemovedOnCompletion = false
fadeInAnimation.fillMode = kCAFillModeForwards
self.crossPathLayer.add(fadeInAnimation, forKey: "opacity")
}
}
class InfoAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var crossPathLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
}
override func layoutSubviews() {
setupLayers()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var outlineCircle: CGPath {
let path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.width/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
let factor:CGFloat = self.frame.size.width / 1.5
path.move(to: CGPoint(x: self.frame.size.width/2.0 , y: 15.0))
path.addLine(to: CGPoint(x: self.frame.size.width/2.0,y: factor))
path.move(to: CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0))
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0,y: factor + 10.0), radius: 1.0, startAngle: startAngle, endAngle: endAngle, clockwise: true)
return path.cgPath
}
func setupLayers() {
circleLayer.path = outlineCircle
circleLayer.fillColor = UIColor.clear.cgColor;
circleLayer.strokeColor = UIColor.colorFromRGB(0xF8D486).cgColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
circleLayer.position = CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0)
self.layer.addSublayer(circleLayer)
}
override func animate() {
let colorAnimation = CABasicAnimation(keyPath:"strokeColor")
colorAnimation.duration = 1.0;
colorAnimation.repeatCount = HUGE
colorAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
colorAnimation.autoreverses = true
colorAnimation.fromValue = UIColor.colorFromRGB(0xF7D58B).cgColor
colorAnimation.toValue = UIColor.colorFromRGB(0xF2A665).cgColor
circleLayer.add(colorAnimation, forKey: "strokeColor")
}
}
class SuccessAnimatedView: AnimatableView {
var circleLayer = CAShapeLayer()
var outlineLayer = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayers()
circleLayer.strokeStart = 0.0
circleLayer.strokeEnd = 0.0
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
setupLayers()
}
var outlineCircle: CGPath {
let path = UIBezierPath()
let startAngle: CGFloat = CGFloat((0) / 180.0 * M_PI) //0
let endAngle: CGFloat = CGFloat((360) / 180.0 * M_PI) //360
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
return path.cgPath
}
var path: CGPath {
let path = UIBezierPath()
let startAngle:CGFloat = CGFloat((60) / 180.0 * M_PI) //60
let endAngle:CGFloat = CGFloat((200) / 180.0 * M_PI) //190
path.addArc(withCenter: CGPoint(x: self.frame.size.width/2.0, y: self.frame.size.height/2.0), radius: self.frame.size.width/2.0, startAngle: startAngle, endAngle: endAngle, clockwise: false)
path.addLine(to: CGPoint(x: 36.0 - 10.0 ,y: 60.0 - 10.0))
path.addLine(to: CGPoint(x: 85.0 - 20.0, y: 30.0 - 20.0))
return path.cgPath
}
func setupLayers() {
outlineLayer.position = CGPoint(x: 0,
y: 0);
outlineLayer.path = outlineCircle
outlineLayer.fillColor = UIColor.clear.cgColor;
outlineLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).cgColor;
outlineLayer.lineCap = kCALineCapRound
outlineLayer.lineWidth = 4;
outlineLayer.opacity = 0.1
self.layer.addSublayer(outlineLayer)
circleLayer.position = CGPoint(x: 0,
y: 0);
circleLayer.path = path
circleLayer.fillColor = UIColor.clear.cgColor;
circleLayer.strokeColor = UIColor(red: 150.0/255.0, green: 216.0/255.0, blue: 115.0/255.0, alpha: 1.0).cgColor;
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 4;
circleLayer.actions = [
"strokeStart": NSNull(),
"strokeEnd": NSNull(),
"transform": NSNull()
]
self.layer.addSublayer(circleLayer)
}
override func animate() {
let strokeStart = CABasicAnimation(keyPath: "strokeStart")
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
let factor = 0.045
strokeEnd.fromValue = 0.00
strokeEnd.toValue = 0.93
strokeEnd.duration = 10.0*factor
let timing = CAMediaTimingFunction(controlPoints: 0.3, 0.6, 0.8, 1.2)
strokeEnd.timingFunction = timing
strokeStart.fromValue = 0.0
strokeStart.toValue = 0.68
strokeStart.duration = 7.0*factor
strokeStart.beginTime = CACurrentMediaTime() + 3.0*factor
strokeStart.fillMode = kCAFillModeBackwards
strokeStart.timingFunction = timing
circleLayer.strokeStart = 0.68
circleLayer.strokeEnd = 0.93
self.circleLayer.add(strokeEnd, forKey: "strokeEnd")
self.circleLayer.add(strokeStart, forKey: "strokeStart")
}
}
extension UIColor {
class func colorFromRGB(_ rgbValue: UInt) -> UIColor {
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
| apache-2.0 | 21cc30dc736b238d4fc5870b30a75cf9 | 39.18241 | 219 | 0.61661 | 4.503011 | false | false | false | false |
cubixlabs/SocialGIST | Pods/GISTFramework/GISTFramework/Classes/BaseClasses/BaseUITextField.swift | 1 | 11358 | //
// BaseTextField.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/06/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUITextField is a subclass of UITextField and implements UITextFieldDelegate, BaseView. It has some extra proporties and support for SyncEngine.
open class BaseUITextField: UITextField, UITextFieldDelegate, BaseView {
//MARK: - Properties
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Background color key from Sync Engine.
@IBInspectable open var bgColorStyle:String? = nil {
didSet {
self.backgroundColor = SyncedColors.color(forKey: bgColorStyle);
}
}
/// Width of View Border.
@IBInspectable open var border:Int = 0 {
didSet {
if let borderCStyle:String = borderColorStyle {
self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border)
}
}
}
/// Border color key from Sync Engine.
@IBInspectable open var borderColorStyle:String? = nil {
didSet {
if let borderCStyle:String = borderColorStyle {
self.addBorder(SyncedColors.color(forKey: borderCStyle), width: border)
}
}
}
/// Corner Radius for View.
@IBInspectable open var cornerRadius:Int = 0 {
didSet {
self.addRoundedCorners(GISTUtility.convertToRatio(CGFloat(cornerRadius), sizedForIPad: sizeForIPad));
}
}
/// Flag for making circle/rounded view.
@IBInspectable open var rounded:Bool = false {
didSet {
if rounded {
self.addRoundedCorners();
}
}
}
/// Flag for Drop Shadow.
@IBInspectable open var hasDropShadow:Bool = false {
didSet {
if (hasDropShadow) {
self.addDropShadow();
} else {
// TO HANDLER
}
}
}
/// Font name key from Sync Engine.
@IBInspectable open var fontName:String = GIST_CONFIG.fontName {
didSet {
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
}
}
/// Font size/style key from Sync Engine.
@IBInspectable open var fontStyle:String = GIST_CONFIG.fontStyle {
didSet {
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
}
}
/// Font color key from Sync Engine.
@IBInspectable open var fontColorStyle:String? = nil {
didSet {
self.textColor = SyncedColors.color(forKey: fontColorStyle);
}
}
/// Placeholder Text Font color key from SyncEngine.
@IBInspectable open var placeholderColor:String? = nil {
didSet {
if let colorStyl:String = placeholderColor {
if let plcHolder:String = self.placeholder {
self.attributedPlaceholder = NSAttributedString(string:plcHolder, attributes: [NSForegroundColorAttributeName: SyncedColors.color(forKey: colorStyl)!]);
}
}
}
} //P.E.
/// Text Vertical Padding - Default Value is Zero
@IBInspectable open var verticalPadding:CGFloat = 0
/// Text Horizontal Padding - Default Value is Zero
@IBInspectable open var horizontalPadding:CGFloat = 0
private var _maxCharLimit: Int = 50;
/// Max Character Count Limit for the text field.
@IBInspectable open var maxCharLimit: Int {
get {
return _maxCharLimit;
}
set {
if (_maxCharLimit != newValue)
{_maxCharLimit = newValue;}
}
} //P.E.
private weak var _delegate:UITextFieldDelegate?;
///Maintainig Own delegate.
open override weak var delegate: UITextFieldDelegate? {
get {
return _delegate;
}
set {
_delegate = newValue;
}
} //P.E.
private var _placeholderKey:String?
/// Overridden property to set placeholder text from SyncEngine (Hint '#' prefix).
override open var placeholder: String? {
get {
return super.placeholder;
}
set {
guard let key:String = newValue else {
_placeholderKey = nil;
super.placeholder = newValue;
return;
}
let newPlaceHolder:String;
if (key.hasPrefix("#") == true) {
_placeholderKey = key; // holding key for using later
newPlaceHolder = SyncedText.text(forKey: key);
} else {
_placeholderKey = nil;
newPlaceHolder = key;
}
if let colorStyl:String = placeholderColor {
self.attributedPlaceholder = NSAttributedString(string:newPlaceHolder, attributes: [NSForegroundColorAttributeName: SyncedColors.color(forKey: colorStyl)!]);
} else {
super.placeholder = newPlaceHolder;
}
}
} //P.E.
//MARK: - Constructors
/// Overridden method to setup/ initialize components.
///
/// - Parameter frame: View Frame
override public init(frame: CGRect) {
super.init(frame: frame);
self.commonInit();
} //C.E.
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
} //C.E.
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func awakeFromNib() {
super.awakeFromNib()
self.commonInit();
} //F.E.
/// Overridden methed to update layout.
override open func layoutSubviews() {
super.layoutSubviews();
if rounded {
self.addRoundedCorners();
}
} //F.E.
/// Overridden method to handle text paddings
///
/// - Parameter bounds: Text Bounds
/// - Returns: Calculated bounds with paddings.
override open func textRect(forBounds bounds: CGRect) -> CGRect {
//??super.textRectForBounds(bounds)
let x:CGFloat = bounds.origin.x + horizontalPadding
let y:CGFloat = bounds.origin.y + verticalPadding
let widht:CGFloat = bounds.size.width - (horizontalPadding * 2)
let height:CGFloat = bounds.size.height - (verticalPadding * 2)
return CGRect(x: x,y: y,width: widht,height: height)
} //F.E.
/// Overridden method to handle text paddings when editing.
///
/// - Parameter bounds: Text Bounds
/// - Returns: Calculated bounds with paddings.
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
super.editingRect(forBounds: bounds)
return self.textRect(forBounds: bounds)
} //F.E.
//MARK: - Methods
/// A common initializer to setup/initialize sub components.
private func commonInit() {
super.delegate = self;
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
if let placeHoldertxt:String = self.placeholder , placeHoldertxt.hasPrefix("#") == true{
self.placeholder = placeHoldertxt; // Assigning again to set value from synced data
}
} //F.E.
/// Updates layout and contents from SyncEngine. this is a protocol method BaseView that is called when the view is refreshed.
func updateView() {
//Setting font
self.font = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
//Re-assigning if there are any changes from server
if let bgCStyle:String = self.bgColorStyle {
self.bgColorStyle = bgCStyle;
}
if let borderCStyle:String = self.borderColorStyle {
self.borderColorStyle = borderCStyle;
}
if let fntClrStyle = self.fontColorStyle {
self.fontColorStyle = fntClrStyle;
}
if let placeHolderKey:String = _placeholderKey {
self.placeholder = placeHolderKey;
}
} //F.E.
//Mark: - UITextField Delegate Methods
/// Protocol method of textFieldShouldBeginEditing.
///
/// - Parameter textField: Text Field
/// - Returns: Bool flag for should begin edititng
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldBeginEditing?(textField) ?? true;
} //F.E.
/// Protocol method of textFieldDidBeginEditing.
///
/// - Parameter textField: Text Field
open func textFieldDidBeginEditing(_ textField: UITextField) {
_delegate?.textFieldDidBeginEditing?(textField);
} //F.E.
/// Protocol method of textFieldShouldEndEditing. - Default value is true
///
/// - Parameter textField: Text Field
/// - Returns: Bool flag for should end edititng
open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldEndEditing?(textField) ?? true;
} //F.E.
/// Protocol method of textFieldDidEndEditing
///
/// - Parameter textField: Text Field
open func textFieldDidEndEditing(_ textField: UITextField) {
_delegate?.textFieldDidEndEditing?(textField);
} //F.E.
/// Protocol method of shouldChangeCharactersIn for limiting the character limit. - Default value is true
///
/// - Parameters:
/// - textField: Text Field
/// - range: Change Characters Range
/// - string: Replacement String
/// - Returns: Bool flag for should change characters in range
open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let rtn = _delegate?.textField?(textField, shouldChangeCharactersIn:range, replacementString:string) ?? true;
//IF CHARACTERS-LIMIT <= ZERO, MEANS NO RESTRICTIONS ARE APPLIED
if (self.maxCharLimit <= 0) {
return rtn;
}
guard let text = textField.text else { return true }
let newLength = text.utf16.count + string.utf16.count - range.length
return (newLength <= self.maxCharLimit) && rtn // Bool
} //F.E.
/// Protocol method of textFieldShouldClear. - Default value is true
///
/// - Parameter textField: Text Field
/// - Returns: Bool flag for should clear text field
open func textFieldShouldClear(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldClear?(textField) ?? true;
} //F.E.
/// Protocol method of textFieldShouldReturn. - Default value is true
///
/// - Parameter textField: Text Field
/// - Returns: Bool flag for text field should return.
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return _delegate?.textFieldShouldReturn?(textField) ?? true;
} //F.E.
} //CLS END
| gpl-3.0 | 5119353bbf224391eb81fef7823b3f35 | 32.501475 | 173 | 0.598838 | 5.025221 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift | CoreDataPlatform/Entities/CDPost+Ext.swift | 1 | 1151 | //
// CDPost+CoreDataClass.swift
// NetworkAndSecurity
//
// Created by sergdort on 07/01/2017.
// Copyright © 2017 sergdort. All rights reserved.
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
import Domain
import QueryKit
import RxSwift
extension CDPost {
static var title: Attribute<String> { return Attribute("title")}
static var body: Attribute<String> { return Attribute("body")}
static var userId: Attribute<String> { return Attribute("userId")}
static var uid: Attribute<String> { return Attribute("uid")}
}
extension CDPost: DomainConvertibleType {
func asDomain() -> Post {
return Post(body: body!,
title: title!,
uid: uid!,
userId: userId!)
}
}
extension CDPost: Persistable {
static var entityName: String {
return "CDPost"
}
}
extension Post: CoreDataRepresentable {
typealias CoreDataType = CDPost
func update(entity: CDPost) {
entity.uid = uid
entity.title = title
entity.body = body
entity.userId = userId
}
}
| mit | 6e7bf084444fab040f870174ef93e1d9 | 23.468085 | 70 | 0.643478 | 4.323308 | false | false | false | false |
gerardogrisolini/iWebretail | iWebretail/IoCContainer.swift | 1 | 582 | //
// IoCContainer.swift
// iWebretail
//
// Created by Gerardo Grisolini on 16/04/17.
// Copyright © 2017 Gerardo Grisolini. All rights reserved.
//
import Foundation
class IoCContainer {
static let shared = IoCContainer()
var factories = [String: Any]()
func register<T>(factory: @escaping () -> T) {
let key = String(describing: T.self)
factories[key] = factory
}
func resolve<T>() -> T {
let key = String(describing: T.self)
if let factory = factories[key] as? () -> T {
return factory()
} else {
fatalError("Registration not found")
}
}
}
| apache-2.0 | e7acddfd5367acd7bd0cb5c19068db97 | 18.366667 | 60 | 0.64716 | 3.106952 | false | false | false | false |
Edig/EDImageCache | String+Extension.swift | 1 | 766 | //
// String+Extension.swift
// Tutton
//
// Created by Eduardo Iglesias on 8/14/15.
// Copyright (c) 2015 CreApps. All rights reserved.
//
import UIKit
extension String {
var md5: String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.dealloc(digestLen)
return String(format: hash as String)
}
}
| mit | e1505d7879a3cc453ef6457aebcd3ec5 | 25.413793 | 83 | 0.616188 | 4.163043 | false | false | false | false |
tecgirl/firefox-ios | Client/Frontend/Browser/ContextMenuHelper.swift | 1 | 3971 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import WebKit
protocol ContextMenuHelperDelegate: AnyObject {
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer)
func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer)
}
class ContextMenuHelper: NSObject {
struct Elements {
let link: URL?
let image: URL?
}
fileprivate weak var tab: Tab?
weak var delegate: ContextMenuHelperDelegate?
fileprivate var nativeHighlightLongPressRecognizer: UILongPressGestureRecognizer?
fileprivate var elements: Elements?
required init(tab: Tab) {
super.init()
self.tab = tab
nativeHighlightLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_highlightLongPressRecognized:") as? UILongPressGestureRecognizer
if let nativeLongPressRecognizer = gestureRecognizerWithDescriptionFragment("action=_longPressRecognized:") as? UILongPressGestureRecognizer {
nativeLongPressRecognizer.removeTarget(nil, action: nil)
nativeLongPressRecognizer.addTarget(self, action: #selector(longPressGestureDetected))
}
}
func gestureRecognizerWithDescriptionFragment(_ descriptionFragment: String) -> UIGestureRecognizer? {
return tab?.webView?.scrollView.subviews.compactMap({ $0.gestureRecognizers }).joined().first(where: { $0.description.contains(descriptionFragment) })
}
@objc func longPressGestureDetected(_ sender: UIGestureRecognizer) {
if sender.state == .cancelled {
delegate?.contextMenuHelper(self, didCancelGestureRecognizer: sender)
return
}
guard sender.state == .began, let elements = self.elements else {
return
}
delegate?.contextMenuHelper(self, didLongPressElements: elements, gestureRecognizer: sender)
// To prevent the tapped link from proceeding with navigation, "cancel" the native WKWebView
// `_highlightLongPressRecognizer`. This preserves the original behavior as seen here:
// https://github.com/WebKit/webkit/blob/d591647baf54b4b300ca5501c21a68455429e182/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm#L1600-L1614
if let nativeHighlightLongPressRecognizer = self.nativeHighlightLongPressRecognizer,
nativeHighlightLongPressRecognizer.isEnabled {
nativeHighlightLongPressRecognizer.isEnabled = false
nativeHighlightLongPressRecognizer.isEnabled = true
}
self.elements = nil
}
}
extension ContextMenuHelper: TabContentScript {
class func name() -> String {
return "ContextMenuHelper"
}
func scriptMessageHandlerName() -> String? {
return "contextMenuMessageHandler"
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let data = message.body as? [String: AnyObject] else {
return
}
var linkURL: URL?
if let urlString = data["link"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
linkURL = URL(string: escapedURLString)
}
var imageURL: URL?
if let urlString = data["image"] as? String,
let escapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .URLAllowed) {
imageURL = URL(string: escapedURLString)
}
if linkURL != nil || imageURL != nil {
elements = Elements(link: linkURL, image: imageURL)
} else {
elements = nil
}
}
}
| mpl-2.0 | 7c6e26b694bf561faaaaceb174173898 | 39.111111 | 165 | 0.704357 | 5.469697 | false | false | false | false |
nicksweet/Clink | Clink/Classes/PropertyDescriptor.swift | 1 | 1281 | //
// PropertyDescriptor.swift
// Clink
//
// Created by Nick Sweet on 7/27/17.
//
import Foundation
internal class PropertyDescriptor: NSObject, NSCoding {
let name: Clink.PeerPropertyKey
let value: Any
let characteristicId: String
override var description: String {
return "name: \(name), value: \(value), characteristicId: \(characteristicId)"
}
init(name: Clink.PeerPropertyKey, value: Any, characteristicId: String) {
self.name = name
self.value = value
self.characteristicId = characteristicId
super.init()
}
required init?(coder aDecoder: NSCoder) {
guard
let name = aDecoder.decodeObject(forKey: "name") as? String,
let value = aDecoder.decodeObject(forKey: "value"),
let characteristicId = aDecoder.decodeObject(forKey: "characteristicId") as? String
else {
return nil
}
self.name = name
self.value = value
self.characteristicId = characteristicId
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(value, forKey: "value")
aCoder.encode(characteristicId, forKey: "characteristicId")
}
}
| mit | 686a3c3c7b2e4f5557e21ea9ba80ae64 | 26.255319 | 95 | 0.615144 | 4.526502 | false | false | false | false |
benrosen78/2015-WWDC-Scholarship-app | Ben Rosen/Objects/BRUser.swift | 1 | 1668 | //
// BRUser.swift
// Ben Rosen
//
// Created by Ben Rosen on 4/25/15.
// Copyright (c) 2015 Ben Rosen. All rights reserved.
//
import UIKit
struct BRUser {
var fullName: String
var profileImage: UIImage
var userBio: String
var longDetailedBio: String
var userPictures: [UIImage?]
static func benRosenUser () -> BRUser {
var user = BRUser()
user.fullName = "Ben Rosen"
user.profileImage = UIImage(named: "profilepic")!
user.userBio = "I'm a 12 year old full stack developer. In my free time, I like to program and run outside. I live in the suburbs of Chicago"
user.longDetailedBio = "I started learning to program the summer of 2014 and I found it really interesting. I'm 100% self taught, I learned all from books, no courses or anything. I'm still relatively new so I don't have much released. What inspired me to start is a process called Jailbreaking, which allows you to modify your iPhone/iPod/iPad the way you want to. I started programming what are called Jailbreak tweaks and I then I was able to modify SpringBoard's code, with just the interface- no implementation. I met a bunch of awesome people and learned a lot through open sourced code. See some pictures of my family and I below. Enjoy my app and have a nice day! :)"
user.userPictures = [UIImage(named: "slideshow1"), UIImage(named: "slideshow2"), UIImage(named: "slideshow3"), UIImage(named: "slideshow4")]
return user;
}
}
extension BRUser {
init() {
fullName = ""
profileImage = UIImage()
userBio = ""
longDetailedBio = ""
userPictures = []
}
}
| lgpl-3.0 | c76a4ec89f7de415ee0d1b470e4ce1eb | 41.769231 | 683 | 0.681055 | 4.068293 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/FacebookCore/Sources/Core/AppEvents/AppEventParameterName.swift | 19 | 4990 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit.FBSDKAppEvents
/**
Represents a parameter name of the Facebook Analytics application event.
*/
public enum AppEventParameterName {
/// Identifier for the specific piece of content.
case contentId
/// Type of the content, e.g. "music"/"photo"/"video".
case contentType
/// Currency. E.g. "USD"/"EUR"/"GBP". See ISO-4217 for specific values.
case currency
/// Appropriate description for the event.
case Description
/// Current level or level achieved.
case level
/// Maximum rating available. E.g. "5"/"10".
case maxRatingValue
/// Count of items being proccessed.
case itemCount
/// Boolean value indicating whether payment information is available.
case paymentInfoAvailable
/// Registration method used. E.g. "Facebook"/"email"/"sms".
case registrationMethod
/// String provided by the user for a search operation.
case searchedString
/// Boolean value indicating wehtehr an activity being logged was succesful.
case successful
/// Custom name of the parameter that is represented by a string.
case custom(String)
/**
Create an `AppEventParameterName` from `String`.
- parameter string: String to create an app event name from.
*/
public init(_ string: String) {
self = .custom(string)
}
}
extension AppEventParameterName: RawRepresentable {
/**
Create an `AppEventParameterName` from `String`.
- parameter rawValue: String to create an app event name from.
*/
public init?(rawValue: String) {
self = .custom(rawValue)
}
/// The corresponding `String` value.
public var rawValue: String {
switch self {
case .contentId: return FBSDKAppEventParameterNameContentID
case .contentType: return FBSDKAppEventParameterNameContentType
case .currency: return FBSDKAppEventParameterNameCurrency
case .Description: return FBSDKAppEventParameterNameDescription
case .level: return FBSDKAppEventNameAchievedLevel
case .maxRatingValue: return FBSDKAppEventParameterNameMaxRatingValue
case .itemCount: return FBSDKAppEventParameterNameNumItems
case .paymentInfoAvailable: return FBSDKAppEventParameterNamePaymentInfoAvailable
case .registrationMethod: return FBSDKAppEventParameterNameRegistrationMethod
case .searchedString: return FBSDKAppEventParameterNameSearchString
case .successful: return FBSDKAppEventParameterNameSuccess
case .custom(let string): return string
}
}
}
extension AppEventParameterName: ExpressibleByStringLiteral {
/**
Create an `AppEventParameterName` from a string literal.
- parameter value: The string literal to create from.
*/
public init(stringLiteral value: StringLiteralType) {
self = .custom(value)
}
/**
Create an `AppEventParameterName` from a unicode scalar literal.
- parameter value: The string literal to create from.
*/
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
/**
Create an `AppEventParameterName` from an extended grapheme cluster.
- parameter value: The string literal to create from.
*/
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
extension AppEventParameterName: Hashable {
/// The hash value.
public var hashValue: Int {
return self.rawValue.hashValue
}
/**
Compare two `AppEventParameterName`s for equality.
- parameter lhs: The first parameter name to compare.
- parameter rhs: The second parameter name to compare.
- returns: Whether or not the parameter names are equal.
*/
public static func == (lhs: AppEventParameterName, rhs: AppEventParameterName) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension AppEventParameterName: CustomStringConvertible {
/// Textual representation of an app event parameter name.
public var description: String {
return rawValue
}
}
| apache-2.0 | 3c96d70019cf48acef7c90784c01189f | 34.140845 | 90 | 0.746894 | 4.63324 | false | false | false | false |
zmeyc/telegram-bot-swift | Examples/word-reverse-bot/Sources/word-reverse-bot/main.swift | 1 | 4637 | //
// main.swift
//
// This file containing the example code is in public domain.
// Feel free to copy-paste it and edit it in any way you like.
//
import Foundation
import TelegramBotSDK
let token = readToken(from: "WORD_REVERSE_BOT_TOKEN")
class Controller {
let bot: TelegramBot
var startedInChatId = Set<Int64>()
func started(in chatId: Int64) -> Bool {
return startedInChatId.contains(chatId)
}
init(bot: TelegramBot) {
self.bot = bot
}
func start(context: Context) -> Bool {
guard let chatId = context.chatId else { return false }
guard !started(in: chatId) else {
context.respondAsync("@\(bot.username) already started.")
return true
}
startedInChatId.insert(chatId)
var startText: String
if !context.privateChat {
startText = "@\(bot.username) started. Use '/reverse some text' to reverse the text.\n"
} else {
startText = "@\(bot.username) started. Please type some text to reverse.\n"
}
startText += "To stop, type /stop"
context.respondAsync(startText)
return true
}
func stop(context: Context) -> Bool {
guard let chatId = context.chatId else { return false }
guard started(in: chatId) else {
context.respondAsync("@\(bot.username) already stopped.")
return true
}
startedInChatId.remove(chatId)
context.respondSync("@\(bot.username) stopped. To restart, type /start")
return true
}
func help(context: Context) -> Bool {
guard let from = context.message?.from else { return false }
let helpText = "What can this bot do?\n" +
"\n" +
"This is a sample bot which reverses sentences or words. " +
"If you want to invite friends, simply open the bot's profile " +
"and use the 'Add to group' button to invite them.\n" +
"\n" +
"Send /start to begin reversing sentences.\n" +
"Tell the bot to /stop when you're done.\n" +
"\n" +
"In private chat simply type some text and it will be reversed.\n" +
"In group chats use this command:\n" +
"/reverse Sentence\n" +
"\n" +
"To reverse words, use /word_reverse word1 word2 word3..."
context.respondPrivatelyAsync(helpText,
groupText: "\(from.firstName), please find usage instructions in a personal message.")
return true
}
func settings(context: Context) -> Bool {
guard let from = context.message?.from else { return false }
let settingsText = "Settings\n" +
"\n" +
"No settings are available for this bot."
context.respondPrivatelyAsync(settingsText,
groupText: "\(from.firstName), please find a list of settings in a personal message.")
return true
}
func partialMatchHandler(context: Context) -> Bool {
context.respondAsync("❗ Part of your input was ignored: \(context.args.scanRestOfString())")
return true
}
func reverseText(context: Context) -> Bool {
guard let chatId = context.chatId else { return false }
guard started(in: chatId) else { return false }
let text = context.args.scanRestOfString()
context.respondAsync(String(text.reversed()))
return true
}
func reverseWords(context: Context) -> Bool {
guard let chatId = context.chatId else { return false }
guard started(in: chatId) else { return false }
let words = context.args.scanWords()
switch words.isEmpty {
case true: context.respondAsync("Please specify some words to reverse.")
case false: context.respondAsync(words.reversed().joined(separator: " "))
}
return true
}
}
let bot = TelegramBot(token: token)
let controller = Controller(bot: bot)
let router = Router(bot: bot)
router["start"] = controller.start
router["stop"] = controller.stop
router["help"] = controller.help
router["settings"] = controller.settings
router["reverse", .slashRequired] = controller.reverseText
router["word_reverse"] = controller.reverseWords
// Default handler
router.unmatched = controller.reverseText
// If command has unprocessed arguments, report them:
router.partialMatch = controller.partialMatchHandler
print("Ready to accept commands")
while let update = bot.nextUpdateSync() {
print("--- update: \(update.debugDescription)")
try router.process(update: update)
}
print("Server stopped due to error: \(bot.lastError.unwrapOptional)")
exit(1)
| apache-2.0 | c20f81ba48ba1e368c1787f48f8d596c | 31.640845 | 100 | 0.632794 | 4.134701 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/Logic/Result/CIOGroup.swift | 1 | 1264 | //
// CIOGroup.swift
// AutocompleteClient
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating a group
*/
@objc
public class CIOGroup: NSObject {
/**
Display name of the group (or category)
*/
public let displayName: String
/**
Group ID
*/
public let groupID: String
/**
The full path of the group hierarchy
*/
public let path: String?
/**
Create a group
- Parameters:
- displayName: Display nam eof the group
- groupID: Group ID
- path: The full path of the group hierarchy
*/
public init(displayName: String, groupID: String, path: String?) {
self.displayName = displayName
self.groupID = groupID
self.path = path
}
/**
Create a group (from JSON)
- Parameters:
- json: JSON data from the server response
*/
init?(json: JSONObject) {
guard let name = json["display_name"] as? String else { return nil }
guard let groupID = json["group_id"] as? String else { return nil }
self.displayName = name
self.groupID = groupID
self.path = json["path"] as? String
}
}
| mit | ad894455a99477b6c4f746c10525f172 | 20.40678 | 76 | 0.585115 | 4.325342 | false | false | false | false |
marcoconti83/Battipista | Sources/VisitStrategies/GenericVisitStartegyWithFringe.swift | 1 | 3466 | //
//The MIT License (MIT)
//
//Copyright (c) 2015 Marco Conti<[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 Foundation
open class GenericVisitStartegyWithFringe<Node : GraphNode> : GraphVisitStrategy {
/// Function usable to select the next node to visit from the fringe
public typealias FringeSelectionFunction = ([[Node]]) -> Int
/// Nodes that have been already visited
private var visitedNodes = Set<Node>()
/// Fringe of the visit, with full path of how the node was reached
private var fringe = Array<[Node]>()
/// Fringe lookup set, for faster `is in` test
private var fringeLookup = Set<Node>()
/// The function used to select the next node to visit from the fringe
private let fringeSelectionFunction : FringeSelectionFunction
/// Creates a generic visit strategy with the given fringe selection function
/// - param fringeSelectionFunction: this function will be called when the fringe is not empty and there is the need
/// to select the next path from the fringe. It has to return a valid index in the fringe. The path at that index
/// will be used as the next node to visit
public init(root: Node, fringeSelectionFunction : @escaping FringeSelectionFunction) {
self.fringeSelectionFunction = fringeSelectionFunction
self.fringe.append([root])
}
public func next() -> [Node]? {
if let path = removeFirstFromFringe() {
let node = path.last!
self.visitedNodes.insert(node)
node.children
.filter { !visitedNodes.contains($0) && !fringeLookup.contains($0) && $0 != node}
.forEach { self.addToFringe(node: $0, previousPath: path) }
return path
}
return .none
}
/// Adds an element to the fringe
private func addToFringe(node: Node, previousPath: [Node]) {
self.fringe.append(previousPath + [node])
self.fringeLookup.insert(node)
}
/// Removes and returns the first element in the fringe
private func removeFirstFromFringe() -> [Node]? {
if(self.fringe.isEmpty) {
return .none
}
let index = self.fringeSelectionFunction(self.fringe)
let nodes = self.fringe[index]
self.fringe.remove(at: index)
self.fringeLookup.remove(nodes.last!)
return nodes
}
}
| mit | 5bbd1baa54521374dd4680b2474a4340 | 40.759036 | 121 | 0.684939 | 4.211422 | false | false | false | false |
justinlevi/asymptotik-rnd-scenekit-kaleidoscope | Atk_Rnd_VisualToys/Queue.swift | 2 | 1487 | //
// Queue.swift
// Atk_Rnd_VisualToys
//
// Created by Rick Boykin on 8/6/14.
// Copyright (c) 2014 Asymptotik Limited. All rights reserved.
//
import Foundation
//
// should be an inner class of Queue, but inner classes and generics
// crash the compiler, SourceKit (repeatedly) and occasionally XCode.
//
class _QueueItem<T> {
let value: T!
var next: _QueueItem?
init(_ newvalue: T?) {
self.value = newvalue
}
}
//
// A standard queue (FIFO - First In First Out). Supports simultaneous
// adding and removing, but only one item can be added at a time, and
// only one item can be removed at a time.
//
class Queue<T> {
typealias Element = T
private var _front: _QueueItem<Element>
private var _back: _QueueItem<Element>
var count = 0
init () {
// Insert dummy item. Will disappear when the first item is added.
_back = _QueueItem(nil)
_front = _back
}
/// Add a new item to the back of the queue.
func enqueue (value: Element) {
_back.next = _QueueItem(value)
_back = _back.next!
++count
}
/// Return and remove the item at the front of the queue.
func dequeue () -> Element? {
if let newhead = _front.next {
_front = newhead
--count
return newhead.value
} else {
return nil
}
}
func isEmpty() -> Bool {
return _front === _back
}
} | mit | 27af623c25aee2a7477078fe7522662a | 22.25 | 74 | 0.575656 | 3.822622 | false | false | false | false |
serp1412/LazyTransitions | LazyTransitions/TransitionAnimatorType.swift | 1 | 2006 | //
// TransitionAnimatorType.swift
// LazyTransitions
//
// Created by Serghei Catraniuc on 11/24/16.
// Copyright © 2016 BeardWare. All rights reserved.
//
import Foundation
public protocol TransitionAnimatorType : UIViewControllerAnimatedTransitioning {
var delegate: TransitionAnimatorDelegate? { get set }
var orientation: TransitionOrientation { get set }
init(orientation: TransitionOrientation)
var supportedOrientations: [TransitionOrientation] { get }
var allowedOrientations: [TransitionOrientation]? { get set }
}
extension TransitionAnimatorType {
public var supportedOrientations: [TransitionOrientation] {
return [.topToBottom, .bottomToTop, .leftToRight, .rightToLeft]
}
public var isOrientationAllowed: Bool {
return allowedOrientations?.contains(orientation) ?? true
}
public var isOrientationSupported: Bool {
return supportedOrientations.contains(orientation)
}
}
public protocol TransitionAnimatorDelegate: class {
func transitionDidFinish(_ completed: Bool)
}
extension TransitionAnimatorType {
public func finalFrame(for view: UIView, for orientation: TransitionOrientation) -> CGRect {
let size = view.frame.size
switch orientation {
case .topToBottom:
let bottomLeftCorner = CGPoint(x: view.frame.origin.x, y: size.height)
return CGRect(origin: bottomLeftCorner, size: size)
case .bottomToTop:
let upperLeftCorner = CGPoint(x: view.frame.origin.x, y: -size.height)
return CGRect(origin: upperLeftCorner, size: size)
case .leftToRight:
let topRightCorner = CGPoint(x: size.width, y: view.frame.origin.y)
return CGRect(origin: topRightCorner, size: size)
case .rightToLeft:
let topLeftCorner = CGPoint(x: -size.width, y: view.frame.origin.y)
return CGRect(origin: topLeftCorner, size: size)
default: return view.frame
}
}
}
| bsd-2-clause | 4b2e52ca8fc5e2962284236d0d2ebbdb | 34.803571 | 96 | 0.692768 | 4.641204 | false | false | false | false |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/UILibrary/Views/SFTextField.swift | 1 | 3101 | //
// SFTextField.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 06/02/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
open class SFTextField: UITextField, SFViewColorStyle {
// MARK: - Instance Properties
open var automaticallyAdjustsColorStyle: Bool = false
open var useAlternativeColors: Bool = false
public var leftPadding: CGFloat = 0 {
didSet {
updateLeftView()
}
}
public var leftImageSize: CGSize = .zero {
didSet {
updateLeftView()
}
}
public var leftImage: UIImage? = nil {
didSet {
updateLeftView()
}
}
public var rightPadding: CGFloat = 0 {
didSet {
updateRightView()
}
}
public var rightImageSize: CGSize = .zero {
didSet {
updateRightView()
}
}
public var rightImage: UIImage? = nil {
didSet {
updateRightView()
}
}
private func updateLeftView() {
var size = leftImageSize == .zero && leftImage != nil ? CGSize(width: 16, height: 16) : leftImageSize
size.width = leftImage != nil ? size.width + leftPadding * 2 : size.width + leftPadding
let imageView = UIImageView(frame: CGRect(origin: .zero, size: size))
imageView.contentMode = .scaleAspectFit
imageView.image = leftImage
leftView = imageView
leftViewMode = .always
}
private func updateRightView() {
var size = rightImageSize == .zero && rightImage != nil ? CGSize(width: 16, height: 16) : rightImageSize
size.width = rightImage != nil ? size.width + rightPadding * 2 : size.width + rightPadding
let imageView = UIImageView(frame: CGRect(origin: .zero, size: size))
imageView.contentMode = .scaleAspectFit
imageView.image = rightImage
rightView = imageView
rightViewMode = .always
}
// MARK: - Initializers
public init(automaticallyAdjustsColorStyle: Bool = true, useAlternativeColors: Bool = false, frame: CGRect = .zero) {
self.automaticallyAdjustsColorStyle = automaticallyAdjustsColorStyle
self.useAlternativeColors = useAlternativeColors
super.init(frame: frame)
if automaticallyAdjustsColorStyle {
updateColors()
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Instance Methods
open func updateColors() {
backgroundColor = useAlternativeColors ? colorStyle.contrastColor : colorStyle.alternativeColor
if let placeholder = placeholder {
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: colorStyle.placeholderColor])
}
textColor = colorStyle.textColor
keyboardAppearance = colorStyle.keyboardStyle
updateSubviewsColors()
}
}
| mit | 709e0b53b1b7d7c59b66e97cb0a5b3ee | 29.097087 | 158 | 0.618065 | 5.317324 | false | false | false | false |
AdamSliwakowski/solid-succotash | Succotash/Carthage/Checkouts/Koloda/Example/Koloda/ExampleOverlayView.swift | 27 | 974 | //
// ExampleOverlayView.swift
// KolodaView
//
// Created by Eugene Andreyev on 6/21/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import UIKit
import Koloda
private let overlayRightImageName = "yesOverlayImage"
private let overlayLeftImageName = "noOverlayImage"
class ExampleOverlayView: OverlayView {
@IBOutlet lazy var overlayImageView: UIImageView! = {
[unowned self] in
var imageView = UIImageView(frame: self.bounds)
self.addSubview(imageView)
return imageView
}()
override var overlayState:OverlayMode {
didSet {
switch overlayState {
case .Left :
overlayImageView.image = UIImage(named: overlayLeftImageName)
case .Right :
overlayImageView.image = UIImage(named: overlayRightImageName)
default:
overlayImageView.image = nil
}
}
}
}
| mit | cec627601aa697f901c61a7e487409ff | 23.974359 | 78 | 0.609856 | 4.79803 | false | false | false | false |
albertinopadin/SwiftBreakout | Breakout/Paddle.swift | 1 | 2803 | //
// Paddle.swift
// Breakout
//
// Created by Albertino Padin on 11/2/14.
// Copyright (c) 2014 Albertino Padin. All rights reserved.
//
import Foundation
import SceneKit
class Paddle: SCNNode
{
let defaultPaddleRadius: CGFloat = 1.0
let defaultPaddleHeight: CGFloat = 8
init(color: UIColor)
{
super.init()
self.geometry = Paddle.constructGeometry(color, radius: self.defaultPaddleRadius, height: self.defaultPaddleHeight)
let paddleShape = SCNPhysicsShape(geometry: self.geometry!, options: nil)
self.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Kinematic, shape: paddleShape)
// Rotate pill 90 degrees
self.rotation = SCNVector4Make(0, 0, 1, Float(M_PI_4 * 2))
Paddle.setContactBitMasks(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class func constructGeometry(color: UIColor, radius: CGFloat, height: CGFloat) -> SCNGeometry
{
let paddleGeometry = SCNCapsule(capRadius: radius, height: height)
paddleGeometry.firstMaterial!.diffuse.contents = UIColor.lightGrayColor()
paddleGeometry.firstMaterial!.diffuse.contents = color
return paddleGeometry
}
// class func createPaddle() -> SCNNode
// {
// //let paddle = SCNBox(width: 8, height: 2, length: 1, chamferRadius: 2.0)
// let paddle = SCNCapsule(capRadius: 1.0, height: 8)
// paddle.firstMaterial!.diffuse.contents = UIColor.lightGrayColor()
// paddle.firstMaterial!.specular.contents = UIColor.whiteColor()
//
// let paddleNode = SCNNode(geometry: paddle)
// let paddleShape = SCNPhysicsShape(geometry: paddle, options: nil)
// paddleNode.physicsBody = SCNPhysicsBody(type: SCNPhysicsBodyType.Kinematic, shape: paddleShape)
// //paddleNode.geometry!.subdivisionLevel = 1
// // Rotate pill 90 degrees
// paddleNode.rotation = SCNVector4Make(0, 0, 1, Float(M_PI_4 * 2))
// //paddleNode.physicsBody!.restitution = 1.0
// //paddleNode.physicsBody!.mass = CGFloat.infinity // Infinite mass, so collisions do not move it
//
// setContactBitMasks(paddleNode)
//
// return paddleNode
// }
class func setContactBitMasks(paddleNode: SCNNode)
{
paddleNode.physicsBody!.categoryBitMask = 1 << 0
paddleNode.physicsBody!.collisionBitMask = 1 << 0
if #available(iOS 9.0, *) {
print("Setting contact test bit mask")
paddleNode.physicsBody!.contactTestBitMask = 1
} else {
// Fallback on earlier versions
// By default will be the same as the collisionBitMask
}
}
} | gpl-2.0 | 4adfa8c94acd01986d53c72aa922044a | 34.948718 | 123 | 0.642169 | 3.987198 | false | false | false | false |
liufengting/FTChatMessageDemoProject | FTChatMessage/FTChatMessageCell/FTChatMessageBubbleItem/FTChatMessageBubbleAudioItem.swift | 1 | 3586 | //
// FTChatMessageBubbleAudioItem.swift
// FTChatMessage
//
// Created by liufengting on 16/5/7.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
class FTChatMessageBubbleAudioItem: FTChatMessageBubbleItem {
var playImageView : UIImageView!
var mediaInfoLabel : UILabel!
convenience init(frame: CGRect, aMessage : FTChatMessageModel, for indexPath: IndexPath) {
self.init(frame:frame)
self.backgroundColor = UIColor.clear
message = aMessage
let messageBubblePath = self.getAudioBubblePath(frame.size, isUserSelf: aMessage.isUserSelf)
messageBubbleLayer.path = messageBubblePath.cgPath
messageBubbleLayer.fillColor = aMessage.messageSender.isUserSelf ? FTDefaultOutgoingColor.cgColor : FTDefaultIncomingColor.cgColor
self.layer.addSublayer(messageBubbleLayer)
let mediaImageRect = self.getPlayImageViewFrame(aMessage.isUserSelf)
playImageView = UIImageView(frame : mediaImageRect)
playImageView.backgroundColor = UIColor.clear
playImageView.tintColor = aMessage.messageSender.isUserSelf ? UIColor.white : UIColor.black
if let image = UIImage(named: "Media_Play") {
playImageView.image = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
}
self.addSubview(playImageView)
let mediaInfoLabelRect = self.getMediaInfoLabelFrame(aMessage.isUserSelf)
mediaInfoLabel = UILabel(frame : mediaInfoLabelRect)
mediaInfoLabel.backgroundColor = UIColor.clear
mediaInfoLabel.font = FTDefaultFontSize
mediaInfoLabel.textColor = aMessage.messageSender.isUserSelf ? UIColor.white : UIColor.black
mediaInfoLabel.textAlignment = aMessage.isUserSelf ? NSTextAlignment.left : NSTextAlignment.right
mediaInfoLabel.text = "1′ 22″"
self.addSubview(mediaInfoLabel)
}
fileprivate func getAudioBubblePath(_ size:CGSize , isUserSelf : Bool) -> UIBezierPath {
let bubbleRect = CGRect(x: isUserSelf ? 0 : FTDefaultMessageBubbleAngleWidth, y: 0, width: size.width - FTDefaultMessageBubbleAngleWidth , height: size.height)
let path = UIBezierPath.init(roundedRect: bubbleRect, cornerRadius: size.height/2)
return path;
}
fileprivate func getPlayImageViewFrame(_ isUserSelf : Bool) -> CGRect {
let margin = (FTDefaultMessageBubbleAudioHeight - FTDefaultMessageBubbleAudioIconHeight)/2
return isUserSelf ?
CGRect(x: margin, y: margin, width: FTDefaultMessageBubbleAudioIconHeight, height: FTDefaultMessageBubbleAudioIconHeight) :
CGRect(x: self.frame.size.width - FTDefaultMessageBubbleAudioHeight + margin , y: margin, width: FTDefaultMessageBubbleAudioIconHeight, height: FTDefaultMessageBubbleAudioIconHeight)
}
fileprivate func getMediaInfoLabelFrame(_ isUserSelf : Bool) -> CGRect {
let margin = (FTDefaultMessageBubbleAudioHeight - FTDefaultMessageBubbleAudioIconHeight)/2
return isUserSelf ?
CGRect(x: FTDefaultMessageBubbleAudioHeight, y: margin, width: self.frame.size.width - FTDefaultMessageBubbleAudioHeight - FTDefaultMessageBubbleAngleWidth - margin, height: FTDefaultMessageBubbleAudioIconHeight) :
CGRect( x: FTDefaultMessageBubbleAngleWidth + margin, y: margin, width: self.frame.size.width - FTDefaultMessageBubbleAudioHeight - FTDefaultMessageBubbleAngleWidth - margin, height: FTDefaultMessageBubbleAudioIconHeight)
}
}
| mit | c8c124b63f33ce2865676bb973cd01a8 | 53.227273 | 233 | 0.735401 | 4.709211 | false | false | false | false |
leetmorry/WLHelpers | Example/Pods/FBSnapshotTestCase/FBSnapshotTestCase/SwiftSupport.swift | 2 | 3169 | /*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
public extension FBSnapshotTestCase {
public func FBSnapshotVerifyView(_ view: UIView, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
FBSnapshotVerifyViewOrLayer(view, identifier: identifier, suffixes: suffixes, tolerance: tolerance, file: file, line: line)
}
public func FBSnapshotVerifyLayer(_ layer: CALayer, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
FBSnapshotVerifyViewOrLayer(layer, identifier: identifier, suffixes: suffixes, tolerance: tolerance, file: file, line: line)
}
fileprivate func FBSnapshotVerifyViewOrLayer(_ viewOrLayer: AnyObject, identifier: String = "", suffixes: NSOrderedSet = FBSnapshotTestCaseDefaultSuffixes(), tolerance: CGFloat = 0, file: StaticString = #file, line: UInt = #line) {
let envReferenceImageDirectory = self.getReferenceImageDirectory(withDefault: FB_REFERENCE_IMAGE_DIR)
var error: NSError?
var comparisonSuccess = false
if let envReferenceImageDirectory = envReferenceImageDirectory {
for suffix in suffixes {
let referenceImagesDirectory = "\(envReferenceImageDirectory)\(suffix)"
if viewOrLayer.isKind(of: UIView) {
do {
try compareSnapshot(of: viewOrLayer as! UIView, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: tolerance)
comparisonSuccess = true
} catch let error1 as NSError {
error = error1
comparisonSuccess = false
}
} else if viewOrLayer.isKind(of: CALayer) {
do {
try compareSnapshot(of: viewOrLayer as! CALayer, referenceImagesDirectory: referenceImagesDirectory, identifier: identifier, tolerance: tolerance)
comparisonSuccess = true
} catch let error1 as NSError {
error = error1
comparisonSuccess = false
}
} else {
assertionFailure("Only UIView and CALayer classes can be snapshotted")
}
assert(recordMode == false, message: "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file: file, line: line)
if comparisonSuccess || recordMode {
break
}
assert(comparisonSuccess, message: "Snapshot comparison failed: \(error)", file: file, line: line)
}
} else {
XCTFail("Missing value for referenceImagesDirectory - Set FB_REFERENCE_IMAGE_DIR as Environment variable in your scheme.")
}
}
func assert(_ assertion: Bool, message: String, file: StaticString, line: UInt) {
if !assertion {
XCTFail(message, file: file, line: line)
}
}
}
| mit | c0721eb2725109c49b1068e6297e94e8 | 47.015152 | 233 | 0.695172 | 5.136143 | false | true | false | false |
clappr/clappr-ios | Tests/Clappr_Tests/Classes/Base/Layers/LayerComposerTests.swift | 1 | 5025 | import Foundation
import Quick
import Nimble
@testable import Clappr
class LayerComposerTests: QuickSpec {
override func spec() {
describe(".LayerComposer") {
context("When LayerComposer composes its layers") {
it("adds BackgroundLayer as the first layer"){
let index = 0
let fakeLayer = FakeLayer()
let rootView = UIView()
rootView.insertSubview(fakeLayer, at: 0)
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
let layer = getLayer(from: rootView, at: index)
expect(layer).to(
beAKindOf(BackgroundLayer.self),
description: "BackgroundLayer should be the first subview of rootView, got \(String(describing: type(of: layer)))"
)
}
it("adds PlaybackLayer as the second layer"){
let index = 1
let rootView = UIView()
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
let layer = getLayer(from: rootView, at: index)
expect(layer).to(
beAKindOf(PlaybackLayer.self),
description: "PlaybackLayer should be the second subview of rootView, got \(String(describing: type(of: layer)))"
)
}
it("adds MediaControlLayer as the third layer"){
let index = 2
let rootView = UIView()
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
let layer = getLayer(from: rootView, at: index)
expect(layer).to(
beAKindOf(MediaControlLayer.self),
description: "MediaControlLayer should be the third subview of rootView, got \(String(describing: type(of: layer)))"
)
}
it("adds CoreLayer as the fourth layer"){
let index = 3
let rootView = UIView()
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
let layer = getLayer(from: rootView, at: index)
expect(layer).to(
beAKindOf(CoreLayer.self),
description: "CoreLayer should be the fourth subview of rootView, got \(String(describing: type(of: layer)))"
)
}
it("adds OverlayLayer as the fifth layer"){
let index = 4
let rootView = UIView()
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
let layer = getLayer(from: rootView, at: index)
expect(layer).to(
beAKindOf(OverlayLayer.self),
description: "OverlayLayer should be the fifth subview of rootView, got \(String(describing: type(of: layer)))"
)
}
}
}
context("When LayerComposer changes its layers visibility") {
it("show all visual layers") {
let rootView = UIView()
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
layerComposer.showUI()
let mediaControlLayer = getLayer(from: rootView, at: 2)
let coreLayer = getLayer(from: rootView, at: 3)
let overlayLayer = getLayer(from: rootView, at: 4)
expect(mediaControlLayer?.isHidden).to(beFalse())
expect(coreLayer?.isHidden).to(beFalse())
expect(overlayLayer?.isHidden).to(beFalse())
}
it("hides all visual layers") {
let rootView = UIView()
let layerComposer = LayerComposer()
layerComposer.compose(inside: rootView)
layerComposer.hideUI()
let mediaControlLayer = getLayer(from: rootView, at: 2)
let coreLayer = getLayer(from: rootView, at: 3)
let overlayLayer = getLayer(from: rootView, at: 4)
expect(mediaControlLayer?.isHidden).to(beTrue())
expect(coreLayer?.isHidden).to(beTrue())
expect(overlayLayer?.isHidden).to(beTrue())
}
}
func getLayer(from rootView: UIView, at index: Int) -> Layer? {
return rootView.subviews[index] as? Layer
}
}
class FakeLayer: UIView {}
}
| bsd-3-clause | b1cfb45e569302f4ebfdf9abeb825d3f | 39.853659 | 140 | 0.494129 | 5.782509 | false | false | false | false |
yanil3500/acoustiCast | AcoustiCastr/AcoustiCastr/RSS.swift | 1 | 4135 | //
// RSS.swift
// AcoustiCastr
//
// Created by David Porter on 4/10/17.
// Copyright © 2017 Elyanil Liranzo Castro. All rights reserved.
//
import UIKit
typealias RSSCompletionHandler = ([Episode]?) -> Void
class RSS: XMLParser {
private var parser = XMLParser()
internal var element : String = ""
internal var textNode : String = ""
internal var episodeDictionary = [String : String]()
internal var episodes = [Episode]()
var rssFeed = ""
static let shared = RSS()
var descriptionCount = 0
private func beginParsing() {
print("Inside of beginParsing: \(self.rssFeed)")
guard let url = URL(string: rssFeed) else {
print("This does not work.")
return; }
self.episodeDictionary = [String : String]()
guard let parser = XMLParser(contentsOf: url) else {
print("Inside of parser:")
return;}
self.episodes = [Episode]()
self.parser = parser
self.parser.delegate = self
self.parser.parse()
}
func getEpisodes(completion: @escaping RSSCompletionHandler){
self.beginParsing()
func returnToMain(results: [Episode]?){
OperationQueue.main.addOperation {
completion(results)
}
}
returnToMain(results: self.episodes)
}
}
//MARK: RSS conforms to XMLParserDelegate
extension RSS: XMLParserDelegate {
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
self.element = elementName
if elementName == "enclosure" {
guard let url = attributeDict["url"] else { print("Failed to unwrap url."); return }
self.episodeDictionary["audiolink"] = url
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "description" {
if self.descriptionCount == 0 {
self.episodeDictionary["podDescription"] = self.textNode
print("Inside of didEndElement: \(self.textNode)")
}
}
if elementName == "item" {
if let episode = Episode(episode: self.episodeDictionary) {
self.episodes.append(episode)
}
}
if elementName == "title" {
self.episodeDictionary["title"] = self.textNode
}
if elementName == "itunes:subtitle" {
self.episodeDictionary["summary"] = self.textNode
}
if elementName == "itunes:duration" {
self.episodeDictionary["duration"] = self.textNode
}
if elementName == "pubDate" {
self.episodeDictionary["pubDate"] = self.textNode
}
self.textNode = ""
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if self.element == "title" {
self.textNode += data
} else if self.element == "itunes:subtitle" {
self.textNode += data
} else if self.element == "itunes:duration" {
self.textNode += data
} else if self.element == "pubDate" {
self.textNode += data
} else if self.element == "description"{
if self.descriptionCount == 0 {
self.textNode += data
}
self.descriptionCount += 1
}
}
func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
if let data = String(data: CDATABlock, encoding: .utf8)?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines){
if self.element == "itunes:subtitle"{
self.textNode += data
} else if self.element == "description"{
self.textNode += data
}
}
}
func parserDidEndDocument(_ parser: XMLParser){
}
}
| mit | 24c5f34ab8764ce1ac38bfbd6c1f6cf0 | 30.318182 | 179 | 0.574504 | 4.886525 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 16 - Intermediate CloudKit/BabiFud-Starter/BabiFud/DetailViewController.swift | 1 | 11706 | /*
* Copyright (c) 2014 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.
*
* 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 UIWidgets
import CloudKit
class DetailViewController: UITableViewController, UISplitViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var masterPopoverController: UIPopoverController? = nil
@IBOutlet var coverView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var starRating: StarRatingControl!
@IBOutlet var kidsMenuButton: CheckedButton!
@IBOutlet var healthyChoiceButton: CheckedButton!
@IBOutlet var womensRoomButton: UIButton!
@IBOutlet var mensRoomButton: UIButton!
@IBOutlet var boosterButton: UIButton!
@IBOutlet var highchairButton: UIButton!
@IBOutlet var addPhotoButton: UIButton!
@IBOutlet var photoScrollView: UIScrollView!
@IBOutlet var noteTextView: UITextView!
var detailItem: Establishment! {
didSet {
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: Establishment = self.detailItem {
title = detail.name
detail.loadCoverPhoto() { image in
dispatch_async(dispatch_get_main_queue()) {
self.coverView.image = image
}
}
titleLabel.text = detail.name
starRating.maxRating = 5
starRating.enabled = false
Model.sharedInstance().userInfo.loggedInToICloud() {
accountStatus, error in
let enabled = accountStatus == .Available || accountStatus == .CouldNotDetermine
self.starRating.enabled = enabled
self.healthyChoiceButton.enabled = enabled
self.kidsMenuButton.enabled = enabled
self.mensRoomButton.enabled = enabled
self.womensRoomButton.enabled = enabled
self.boosterButton.enabled = enabled
self.highchairButton.enabled = enabled
self.addPhotoButton.enabled = enabled
}
self.kidsMenuButton.checked = detailItem.kidsMenu
self.healthyChoiceButton.checked = detailItem.healthyChoice
self.womensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Womens).boolValue
self.mensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Mens).boolValue
self.highchairButton.selected = (detailItem.seatingType() & SeatingType.HighChair).boolValue
self.boosterButton.selected = (detailItem.seatingType() & SeatingType.Booster).boolValue
detail.fetchRating() { rating, isUser in
dispatch_async(dispatch_get_main_queue()) {
self.starRating.maxRating = 5
self.starRating.rating = Float(rating)
self.starRating.setNeedsDisplay()
self.starRating.emptyColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
self.starRating.solidColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
}
}
detail.fetchPhotos() { assets in
if assets != nil {
var x = 10
for record in assets {
if let asset = record.objectForKey("Photo") as? CKAsset {
let image: UIImage? = UIImage(contentsOfFile: asset.fileURL.path!)
if image != nil {
let imView = UIImageView(image: image)
imView.frame = CGRect(x: x, y: 0, width: 60, height: 60)
imView.clipsToBounds = true
imView.layer.cornerRadius = 8
x += 70
imView.layer.borderWidth = 0.0
//if the user has discovered the photo poster, color the photo with a green border
if let photoUserRef = record.objectForKey("User") as? CKReference {
let photoUserId = photoUserRef.recordID
let contactList = Model.sharedInstance().userInfo.contacts
let contacts = contactList.filter {$0.userRecordID == photoUserId}
if contacts.count > 0 {
imView.layer.borderWidth = 1.0
imView.layer.borderColor = UIColor.greenColor().CGColor
}
}
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(imView)
}
}
}
}
}
}
detail.fetchNote() { note in
println("note \(note)")
if let noteText = note {
dispatch_async(dispatch_get_main_queue()) {
self.noteTextView.text = noteText
}
}
}
}
}
func saveRating(rating: NSNumber) {
let ratingRecord = CKRecord(recordType: "Rating")
ratingRecord.setObject(rating, forKey: "Rating")
let ref = CKReference(record: self.detailItem.record,
action: .DeleteSelf)
ratingRecord.setObject(ref, forKey: "Establishment")
Model.sharedInstance().userInfo.userID() {
userID, error in
if let userRecord = userID {
let userRef = CKReference(recordID: userRecord,
action: .None)
ratingRecord.setObject(userRef, forKey: "User")
self.detailItem.database.saveRecord(ratingRecord) {
record, error in
if error != nil {
//low priority error on saving the rating
println("error saving rating: \(error)")
} else {
dispatch_async(dispatch_get_main_queue()) {
//use yellow to signify the user's rating
self.starRating.emptyColor = UIColor.yellowColor()
self.starRating.solidColor = UIColor.yellowColor()
self.starRating.setNeedsDisplay()
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
coverView.clipsToBounds = true
coverView.layer.cornerRadius = 10.0
starRating.editingChangedBlock = { rating in
self.saveRating(rating)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
configureView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "EditNote" {
let noteController = segue.destinationViewController as NotesViewController
noteController.establishment = self.detailItem
}
}
//MARK: - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = NSLocalizedString("Places", comment: "Places")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
//MARK: - Image Picking
@IBAction func addPhoto(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .SavedPhotosAlbum
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!) {
dismissViewControllerAnimated(true, completion: nil)
if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.addPhotoToEstablishment(selectedImage)
}
}
}
func generateFileURL() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let fileArray: NSArray = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
let fileURL = fileArray.lastObject?.URLByAppendingPathComponent(NSUUID().UUIDString).URLByAppendingPathExtension("jpg")
if let filePath = fileArray.lastObject?.path {
if !fileManager.fileExistsAtPath(filePath!) {
fileManager.createDirectoryAtPath(filePath!, withIntermediateDirectories: true, attributes: nil, error: nil)
}
}
return fileURL!
}
func addNewPhotoToScrollView(photo:UIImage) {
let newImView = UIImageView(image: photo)
let offset = self.detailItem.assetCount * 70 + 10
var frame: CGRect = CGRect(x: offset, y: 0, width: 60, height: 60)
newImView.frame = frame
newImView.clipsToBounds = true
newImView.layer.cornerRadius = 8
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(newImView)
self.photoScrollView.contentSize = CGSize(width: CGRectGetMaxX(frame), height: CGRectGetHeight(frame));
}
}
func addPhotoToEstablishment(photo: UIImage) {
let fileURL = generateFileURL()
let data = UIImageJPEGRepresentation(photo, 0.9)
var error : NSError?
let wrote = data.writeToURL(fileURL, options: .AtomicWrite, error: &error)
if (error != nil) {
UIAlertView(title: "Error Saving Photo",
message: error?.localizedDescription, delegate: nil,
cancelButtonTitle: "OK").show()
return
}
let asset = CKAsset(fileURL: fileURL)
let ref = CKReference(record: self.detailItem.record,
action: .DeleteSelf)
Model.sharedInstance().userInfo.userID() {
userID, error in
if let userRecordID = userID {
let userRef = CKReference(recordID: userRecordID, action: .None)
let record = CKRecord(recordType: "EstablishmentPhoto")
record.setObject(asset, forKey: "Photo")
record.setObject(ref, forKey: "Establishment")
record.setObject(userRef, forKey: "User")
self.detailItem.database.saveRecord(record) {record, error in
if error == nil {
self.addNewPhotoToScrollView(photo)
}
NSFileManager.defaultManager().removeItemAtURL(fileURL, error: nil)
}
}
}
}
}
| mit | b6d2bddd9620aa36d468a9d1bfefe2a1 | 38.681356 | 236 | 0.68529 | 4.904064 | false | false | false | false |
ahoppen/swift | test/decl/protocol/req/associated_type_inference_fixed_type.swift | 6 | 20321 | // RUN: %target-typecheck-verify-swift
protocol P1 where A == Never {
associatedtype A
}
struct S1: P1 {}
protocol P2a {
associatedtype A
}
protocol P2b: P2a where A == Never {}
protocol P2c: P2b {}
struct S2a: P2b {}
struct S2b: P2c {}
// Fixed type witnesses can reference dependent members.
protocol P3a {
associatedtype A
associatedtype B
}
protocol P3b: P3a where A == [B] {}
struct S3: P3b {
typealias B = Never
}
protocol P4a where A == [B] {
associatedtype A
associatedtype B
}
protocol P4b {}
extension P4b {
typealias B = Self
}
struct S4: P4a, P4b {}
// Self is a valid fixed type witness.
protocol P5a {
associatedtype A
}
protocol P5b: P5a where A == Self {}
struct S5<X>: P5b {} // OK, A := S5<X>
protocol P6 where A == Never { // expected-error {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A : P6'}}
// expected-note@+1 {{protocol requires nested type 'A}}
associatedtype A: P6
}
struct S6: P6 {} // expected-error {{type 'S6' does not conform to protocol 'P6'}}
protocol P7a where A == Never {
associatedtype A
}
// expected-error@+1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Bool'}}
protocol P7b: P7a where A == Bool {}
struct S7: P7b {}
protocol P8a where A == Never {
associatedtype A
}
protocol P8b where A == Bool {
associatedtype A
}
do {
struct Conformer: P8a, P8b {}
// expected-error@-1 {{'P8b' requires the types 'Conformer.A' (aka 'Never') and 'Bool' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.A' == 'Bool' [with Self = Conformer]}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P8b'}}
}
protocol P9a where A == Never {
associatedtype A
}
protocol P9b: P9a {
associatedtype A
}
struct S9a: P9b {}
// expected-error@+3 {{type 'S9b' does not conform to protocol 'P9a'}}
// expected-error@+2 {{'P9a' requires the types 'S9b.A' (aka 'Bool') and 'Never' be equivalent}}
// expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S9b]}}
struct S9b: P9b {
typealias A = Bool
}
struct S9c: P9b { // OK, S9c.A does not contradict Self.A == Never.
typealias Sugar = Never
typealias A = Sugar
}
protocol P10a where A == Never {
associatedtype A
}
protocol P10b {}
extension P10b {
typealias A = Bool
}
// FIXME: 'P10 extension.A' should not be considered a viable type witness;
// instead, the compiler should infer A := Never and synthesize S10.A.
// expected-error@+3 {{type 'S10' does not conform to protocol 'P10a'}}
// expected-error@+2 {{'P10a' requires the types 'S10.A' (aka 'Bool') and 'Never' be equivalent}}
// expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S10]}}
struct S10: P10b, P10a {}
protocol P11a {
associatedtype A
}
protocol P11b: P11a where A == Never {}
protocol Q11 {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
}
do {
struct Conformer: Q11, P11b {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P11b'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P11a'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'Q11'}}
}
protocol P12 where A == B {
associatedtype A
associatedtype B
func foo(arg: A)
}
struct S12: P12 {
func foo(arg: Never) {}
}
protocol P13a {
associatedtype A
func foo(arg: A)
}
protocol P13b {
associatedtype B
}
protocol P13c: P13a, P13b where A == B {}
struct S13: P13c {
func foo(arg: Never) {}
}
protocol P14 {
associatedtype A = Array<Self>
}
do {
struct Outer<Element> {
struct Conformer: P14 {}
}
}
protocol P15a {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = Never // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P15b: P15a where A == B {}
do {
struct Conformer: P15b {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P15a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P15b'}}
}
protocol P16a where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = Never // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P16b: P16a {}
do {
struct Conformer: P16b {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P16a'}}
}
protocol P17a where A == Never {
associatedtype A = B // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P17b {
associatedtype A = B // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P17c where A == Never {
associatedtype A
associatedtype B = A
}
protocol P17d {
associatedtype A = B
associatedtype B = Int
}
do {
struct Conformer1: P17a {} // expected-error {{type 'Conformer1' does not conform to protocol 'P17a'}}
struct Conformer2<A>: P17b {} // expected-error {{type 'Conformer2<A>' does not conform to protocol 'P17b'}}
struct Conformer3: P17c {}
struct Conformer4<A>: P17d {}
}
protocol P18 {
associatedtype A = B
associatedtype B = C
associatedtype C = (D) -> D
associatedtype D
}
do {
struct Conformer<D>: P18 {}
}
protocol P19 where Self == A {
associatedtype A
associatedtype B = (A, A)
}
do {
struct Conformer: P19 {}
}
protocol P20 where A == B.Element, B == B.SubSequence, C.Element == B.Element {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: Collection
associatedtype C: Collection = Array<Character> // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer: P20 { // expected-error {{type 'Conformer' does not conform to protocol 'P20'}}
typealias B = Substring
}
}
protocol P21 where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = C // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer<C>: P21 {} // expected-error {{type 'Conformer<C>' does not conform to protocol 'P21'}}
}
protocol P22 where A == B, C == D {
associatedtype A
associatedtype B
associatedtype C = B
associatedtype D
}
do {
struct Conformer<A>: P22 {}
}
protocol P23 {
associatedtype A: P23 = B.A // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P23 = A.B // expected-note 2 {{protocol requires nested type 'B'; do you want to add it?}}
}
do {
struct Conformer: P23 {} // expected-error {{type 'Conformer' does not conform to protocol 'P23'}}
struct ConformerGeneric<T>: P23 {} // expected-error {{type 'ConformerGeneric<T>' does not conform to protocol 'P23'}}
}
protocol P24 where A == B.A {
associatedtype A: P24 // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P24 = A.B // expected-note 2 {{protocol requires nested type 'B'; do you want to add it?}}
}
do {
struct Conformer: P24 {} // expected-error {{type 'Conformer' does not conform to protocol 'P24'}}
struct ConformerGeneric<T>: P24 {} // expected-error {{type 'ConformerGeneric<T>' does not conform to protocol 'P24'}}
}
protocol P25a_1 where A == Int, B == C.Element {
associatedtype A
associatedtype B
associatedtype C: Sequence
}
protocol P25a_2 where A == C.Element, B == Int {
associatedtype A
associatedtype B
associatedtype C: Sequence
}
protocol P25b where A == B {
associatedtype A
associatedtype B
}
protocol P25c_1: P25a_1, P25b {}
protocol P25c_2: P25a_2, P25b {}
do {
struct Conformer1<C: Sequence>: P25c_1 where C.Element == Int {}
struct Conformer2<C: Sequence>: P25c_2 where C.Element == Int {}
}
protocol P26 where C == B, F == G {
associatedtype A = Int // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = A // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
associatedtype D // expected-note {{protocol requires nested type 'D'; do you want to add it?}}
associatedtype E = D // expected-note {{protocol requires nested type 'E'; do you want to add it?}}
associatedtype F // expected-note {{protocol requires nested type 'F'; do you want to add it?}}
associatedtype G = [B] // expected-note {{protocol requires nested type 'G'; do you want to add it?}}
}
do {
struct Conformer<D>: P26 {} // expected-error {{type 'Conformer<D>' does not conform to protocol 'P26'}}
}
protocol P27a where A == Int {
associatedtype A
}
protocol P27b where A == B.Element {
associatedtype A
associatedtype B: Sequence
}
protocol P27c_1: P27a, P27b {}
protocol P27c_2: P27b, P27a {}
do {
struct Conformer1<B: Sequence>: P27c_1 where B.Element == Int {}
struct Conformer2<B: Sequence>: P27c_2 where B.Element == Int {}
}
protocol P28a where A == Int {
associatedtype A
}
protocol P28b where A == Bool {
associatedtype A
}
protocol P28c where A == Never {
associatedtype A
}
protocol Q28a: P28a, P28b {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Bool' and 'Self.A == Int'}}
protocol Q28b: P28a, P28b, P28c {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Bool'}}
// expected-error@-2 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Int'}}
// expected-error@-3 {{no type for 'Self.A' can satisfy both 'Self.A == Bool' and 'Self.A == Int'}}
do {
struct Conformer1: Q28a {}
// expected-error@-1 {{'P28b' requires the types 'Conformer1.A' (aka 'Int') and 'Bool' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.A' == 'Bool' [with Self = Conformer1]}}
// expected-error@-3 {{type 'Conformer1' does not conform to protocol 'P28b'}}
struct Conformer2: Q28b {}
// expected-error@-1 {{'P28c' requires the types 'Conformer2.A' (aka 'Int') and 'Never' be equivalent}}
// expected-error@-2 {{'P28b' requires the types 'Conformer2.A' (aka 'Int') and 'Bool' be equivalent}}
// expected-note@-3 {{requirement specified as 'Self.A' == 'Never' [with Self = Conformer2]}}
// expected-note@-4 {{requirement specified as 'Self.A' == 'Bool' [with Self = Conformer2]}}
// expected-error@-5 {{type 'Conformer2' does not conform to protocol 'P28b'}}
// expected-error@-6 {{type 'Conformer2' does not conform to protocol 'P28c'}}
}
protocol P29a where A == Int {
associatedtype A
associatedtype B
}
protocol P29b where B == Never {
associatedtype B
}
protocol P29c where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q29a: P29a, P29b, P29c {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Int'}}
protocol Q29b: P29c, P29a, P29b {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Int'}}
do {
struct Conformer1: Q29a {}
// expected-error@-1 {{'P29b' requires the types 'Conformer1.B' (aka 'Int') and 'Never' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.B' == 'Never' [with Self = Conformer1]}}
// expected-error@-3 {{type 'Conformer1' does not conform to protocol 'P29b'}}
struct Conformer2: Q29b {}
// expected-error@-1 {{type 'Conformer2' does not conform to protocol 'P29a'}}
// expected-error@-2 {{type 'Conformer2' does not conform to protocol 'P29b'}}
// expected-error@-3 {{type 'Conformer2' does not conform to protocol 'P29c'}}
}
protocol P30a where A == Int {
associatedtype A
}
protocol P30b where A == Never {
associatedtype A
}
protocol P30c where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q30: P30c, P30a, P30b {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Int'}}
do {
struct Conformer: Q30 {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P30a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P30b'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P30c'}}
}
protocol P31a where B == Int {
associatedtype B
}
protocol P31b where B == Never {
associatedtype B
}
protocol P31c where B == A {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q31: P31c, P31a, P31b {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Int'}}
do {
struct Conformer: Q31 {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P31a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P31b'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P31c'}}
}
protocol P32a where A == Int {
associatedtype A
}
protocol P32b where A == Bool {
associatedtype A
}
protocol P32c where B == Void {
associatedtype B
}
protocol P32d where B == Never {
associatedtype B
}
protocol P32e where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q32: P32e, P32a, P32b, P32c, P32d {}
// expected-error@-1 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == ()'}}
// expected-error@-2 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Bool'}}
// expected-error@-3 {{no type for 'Self.A' can satisfy both 'Self.A == Never' and 'Self.A == Int'}}
// expected-error@-4 {{no type for 'Self.A' can satisfy both 'Self.A == Bool' and 'Self.A == Int'}}
// expected-error@-5 {{no type for 'Self.A' can satisfy both 'Self.A == ()' and 'Self.A == Int'}}
// expected-error@-6 {{no type for 'Self.A' can satisfy both 'Self.A == ()' and 'Self.A == Bool'}}
do {
struct Conformer: Q32 {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P32a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P32b'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P32c'}}
// expected-error@-4 {{type 'Conformer' does not conform to protocol 'P32d'}}
// expected-error@-5 {{type 'Conformer' does not conform to protocol 'P32e'}}
}
protocol P33a where A == Int {
associatedtype A
}
protocol P33b where A == Int {
associatedtype A
}
protocol Q33: P33a, P33b {}
do {
struct Conformer: Q33 {}
}
protocol P34a {
associatedtype A = Void
}
protocol P34b {
associatedtype A = Never
}
protocol Q34a: P34a, P34b {}
protocol Q34b: P34b, P34a {}
protocol Q34c: P34a, P34b {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
}
do {
struct Conformer1: Q34a {}
struct Conformer2: Q34b {}
struct Conformer3: Q34c {} // expected-error {{type 'Conformer3' does not conform to protocol 'Q34c'}}
}
protocol P35 {
associatedtype A
associatedtype B = Array<C>
associatedtype C = Array<D>
associatedtype D = Array<A>
}
do {
struct Conformer: P35 {
typealias A = Never
}
struct ConformerGeneric<A>: P35 {}
}
struct G36<S: P36> {}
protocol P36 {
// FIXME: Don't create and expose malformed types like 'G36<Never>' -- check
// non-dependent type witnesses first.
// expected-note@+1 {{default type 'G36<Never>' for associated type 'A' (from protocol 'P36') does not conform to 'P36'}}
associatedtype A: P36 = G36<B>
associatedtype B: P36 = Never
}
do {
struct Conformer: P36 {} // expected-error {{type 'Conformer' does not conform to protocol 'P36'}}
}
protocol P37a {
associatedtype A
}
protocol P37b {
associatedtype B : P37a
associatedtype C where C == B.A // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer1<C>: P37b {
struct Inner: P37a { typealias A = C }
typealias B = Inner
}
struct Conformer2<T>: P37b { // expected-error {{type 'Conformer2<T>' does not conform to protocol 'P37b'}}
struct Inner: P37a { typealias A = T }
typealias B = Inner
}
}
protocol P38a {
associatedtype A
}
protocol P38b {
associatedtype B
}
protocol P38c: P38a, P38b where A == B {}
do {
struct Conformer<T>: P38c {
typealias A = Self
}
}
protocol P39 {
associatedtype A: P39
associatedtype B = A.C
associatedtype C = Never
}
do {
struct Conformer: P39 {
typealias A = Self
}
}
protocol P40a {
associatedtype A
associatedtype B = (A, A)
}
protocol P40b: P40a {
override associatedtype A = Int
}
protocol P40c: P40b {
override associatedtype A
override associatedtype B
}
do {
struct Conformer: P40c {}
}
protocol P41 {
associatedtype A where A == B.A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P41 = Self // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
do {
struct Conformer: P41 {} // expected-error{{type 'Conformer' does not conform to protocol 'P41'}}
}
protocol P42a {
associatedtype B: P42b
}
protocol P42b: P42a {
associatedtype A = B.A
}
do {
struct Conformer<B: P42b>: P42b {}
}
protocol P43a {
associatedtype A: P43a
associatedtype B
}
protocol P43b: P43a {
associatedtype C where C == A.B // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer<B: P43a>: P43b { // expected-error {{type 'Conformer<B>' does not conform to protocol 'P43b'}}
typealias A = Conformer<B.A>
}
}
protocol P44 {
associatedtype A: P44
associatedtype B // expected-note 2{{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C where C == A.B // expected-note 3{{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer1<T: P44>: P44 { // expected-error {{type 'Conformer1<T>' does not conform to protocol 'P44'}}
typealias B = T.A
typealias A = Conformer1<T.A>
}
struct Conformer2<B: P44>: P44 { // expected-error {{type 'Conformer2<B>' does not conform to protocol 'P44'}}
typealias A = Conformer2<B.A>
}
struct Conformer3<B>: P44 { // expected-error {{type 'Conformer3<B>' does not conform to protocol 'P44'}}
typealias A = Conformer3<Int>
}
}
protocol P45 {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P45 = Conformer45<D> // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C where C == B.A // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
associatedtype D = Never // expected-note {{protocol requires nested type 'D'; do you want to add it?}}
}
struct Conformer45<A>: P45 {} // expected-error {{type 'Conformer45<A>' does not conform to protocol 'P45'}}
protocol P46 {
associatedtype A: P46
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C where C == A.B // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
func method(_: B)
}
do {
struct Conformer<T: P46>: P46 { // expected-error {{type 'Conformer<T>' does not conform to protocol 'P46'}}
typealias A = Conformer<T.A>
func method(_: T) {}
}
}
protocol P47 {
associatedtype A
}
do {
struct Outer<A> {
struct Inner: P47 {}
}
}
protocol P48a { associatedtype A = Int }
protocol P48b { associatedtype B }
protocol P48c: P48a, P48b where A == B {}
do {
struct Conformer: P48c {}
}
| apache-2.0 | dad7cc68e5fb0c6b0acce3fd2ba67128 | 30.951258 | 128 | 0.674032 | 3.34447 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/DiscoveryV2/Models/TableResultTable.swift | 1 | 2948 | /**
* (C) Copyright IBM Corp. 2019, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
Full table object retrieved from Table Understanding Enrichment.
*/
public struct TableResultTable: Codable, Equatable {
/**
The numeric location of the identified element in the document, represented with two integers labeled `begin` and
`end`.
*/
public var location: TableElementLocation?
/**
The textual contents of the current table from the input document without associated markup content.
*/
public var text: String?
/**
Text and associated location within a table.
*/
public var sectionTitle: TableTextLocation?
/**
Text and associated location within a table.
*/
public var title: TableTextLocation?
/**
An array of table-level cells that apply as headers to all the other cells in the current table.
*/
public var tableHeaders: [TableHeaders]?
/**
An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current
table.
*/
public var rowHeaders: [TableRowHeaders]?
/**
An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the
current table.
*/
public var columnHeaders: [TableColumnHeaders]?
/**
An array of key-value pairs identified in the current table.
*/
public var keyValuePairs: [TableKeyValuePairs]?
/**
An array of cells that are neither table header nor column header nor row header cells, of the current table with
corresponding row and column header associations.
*/
public var bodyCells: [TableBodyCells]?
/**
An array of lists of textual entries across the document related to the current table being parsed.
*/
public var contexts: [TableTextLocation]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case location = "location"
case text = "text"
case sectionTitle = "section_title"
case title = "title"
case tableHeaders = "table_headers"
case rowHeaders = "row_headers"
case columnHeaders = "column_headers"
case keyValuePairs = "key_value_pairs"
case bodyCells = "body_cells"
case contexts = "contexts"
}
}
| apache-2.0 | d79e11499c9360149b4e04115803b2eb | 31.043478 | 118 | 0.682836 | 4.613459 | false | false | false | false |
samodom/TestableCoreLocation | TestableCoreLocation/CLLocationManager/CLLocationManagerStopMonitoringSignificantLocationChangesSpy.swift | 1 | 2312 | //
// CLLocationManagerStopMonitoringSignificantLocationChangesSpy.swift
// TestableCoreLocation
//
// Created by Sam Odom on 3/6/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import CoreLocation
import FoundationSwagger
import TestSwagger
public extension CLLocationManager {
private static let stopMonitoringSignificantLocationChangesCalledKeyString = UUIDKeyString()
private static let stopMonitoringSignificantLocationChangesCalledKey =
ObjectAssociationKey(stopMonitoringSignificantLocationChangesCalledKeyString)
private static let stopMonitoringSignificantLocationChangesCalledReference =
SpyEvidenceReference(key: stopMonitoringSignificantLocationChangesCalledKey)
/// Spy controller for ensuring that a location manager has had `stopMonitoringSignificantLocationChanges`
/// called on it.
public enum StopMonitoringSignificantLocationChangesSpyController: SpyController {
public static let rootSpyableClass: AnyClass = CLLocationManager.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(CLLocationManager.stopMonitoringSignificantLocationChanges),
spy: #selector(CLLocationManager.spy_stopMonitoringSignificantLocationChanges)
)
] as Set
public static let evidence = [stopMonitoringSignificantLocationChangesCalledReference] as Set
public static let forwardsInvocations = false
}
/// Spy method that replaces the true implementation of `stopMonitoringSignificantLocationChanges`
dynamic public func spy_stopMonitoringSignificantLocationChanges() {
stopMonitoringSignificantLocationChangesCalled = true
}
/// Indicates whether the `stopMonitoringSignificantLocationChanges` method has been called on this object.
public final var stopMonitoringSignificantLocationChangesCalled: Bool {
get {
return loadEvidence(with: CLLocationManager.stopMonitoringSignificantLocationChangesCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: CLLocationManager.stopMonitoringSignificantLocationChangesCalledReference)
}
}
}
| mit | 1811abceaffb6a3008cb810fe461a9ce | 40.267857 | 130 | 0.762008 | 6.960843 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/WMFAuthenticationManager.swift | 2 | 11090 |
/**
* This class provides a simple interface for performing authentication tasks.
*/
public class WMFAuthenticationManager: Fetcher {
public enum AuthenticationResult {
case success(_: WMFAccountLoginResult)
case alreadyLoggedIn(_: WMFCurrentlyLoggedInUser)
case failure(_: Error)
}
public typealias AuthenticationResultHandler = (AuthenticationResult) -> Void
public enum AuthenticationError: LocalizedError {
case missingLoginURL
public var errorDescription: String? {
switch self {
default:
return WMFLocalizedString("error-generic-description", value: "An unexpected error occurred", comment: "Generic error message for when the error isn't recoverable by the user.")
}
}
public var recoverySuggestion: String? {
switch self {
default:
return WMFLocalizedString("error-generic-recovery-suggestion", value: "Please try again later", comment: "Generic recovery suggestion for when the error isn't recoverable by the user.")
}
}
}
/**
* The current logged in user. If nil, no user is logged in
*/
@objc dynamic public private(set) var loggedInUsername: String? = nil
/**
* Returns YES if a user is logged in, NO otherwise
*/
@objc public var isLoggedIn: Bool {
return (loggedInUsername != nil)
}
@objc public var hasKeychainCredentials: Bool {
guard
let userName = KeychainCredentialsManager.shared.username,
!userName.isEmpty,
let password = KeychainCredentialsManager.shared.password,
!password.isEmpty
else {
return false
}
return true
}
fileprivate let loginInfoFetcher = WMFAuthLoginInfoFetcher()
fileprivate let accountLogin = WMFAccountLogin()
fileprivate let currentlyLoggedInUserFetcher = WMFCurrentlyLoggedInUserFetcher()
/**
* Get the shared instance of this class
*
* @return The shared Authentication Manager
*/
@objc public static let sharedInstance = WMFAuthenticationManager()
var loginSiteURL: URL? {
return MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() ?? NSURL.wmf_URLWithDefaultSiteAndCurrentLocale()
}
public func attemptLogin(reattemptOn401Response: Bool = false, completion: @escaping AuthenticationResultHandler) {
self.loginWithSavedCredentials(reattemptOn401Response: reattemptOn401Response) { (loginResult) in
switch loginResult {
case .success(let result):
DDLogDebug("\n\nSuccessfully logged in with saved credentials for user \(result.username).\n\n")
self.session.cloneCentralAuthCookies()
case .alreadyLoggedIn(let result):
DDLogDebug("\n\nUser \(result.name) is already logged in.\n\n")
self.session.cloneCentralAuthCookies()
case .failure(let error):
DDLogDebug("\n\nloginWithSavedCredentials failed with error \(error).\n\n")
}
DispatchQueue.main.async {
completion(loginResult)
}
}
}
/**
* Login with the given username and password
*
* @param username The username to authenticate
* @param password The password for the user
* @param retypePassword The password used for confirming password changes. Optional.
* @param oathToken Two factor password required if user's account has 2FA enabled. Optional.
* @param loginSuccess The handler for success - at this point the user is logged in
* @param failure The handler for any errors
*/
public func login(username: String, password: String, retypePassword: String?, oathToken: String?, captchaID: String?, captchaWord: String?, reattemptOn401Response: Bool = false, completion: @escaping AuthenticationResultHandler) {
guard let siteURL = loginSiteURL else {
DispatchQueue.main.async {
completion(.failure(AuthenticationError.missingLoginURL))
}
return
}
accountLogin.login(username: username, password: password, retypePassword: retypePassword, oathToken: oathToken, captchaID: captchaID, captchaWord: captchaWord, siteURL: siteURL, reattemptOn401Response: reattemptOn401Response, success: {result in
DispatchQueue.main.async {
let normalizedUserName = result.username
self.loggedInUsername = normalizedUserName
KeychainCredentialsManager.shared.username = normalizedUserName
KeychainCredentialsManager.shared.password = password
self.session.cloneCentralAuthCookies()
SessionSingleton.sharedInstance()?.dataStore.clearMemoryCache()
completion(.success(result))
}
}, failure: { (error) in
DispatchQueue.main.async {
completion(.failure(error))
}
})
}
/**
* Logs in a user using saved credentials in the keychain
*
* @param success The handler for success - at this point the user is logged in
* @param completion
*/
public func loginWithSavedCredentials(reattemptOn401Response: Bool = false, completion: @escaping AuthenticationResultHandler) {
guard hasKeychainCredentials,
let userName = KeychainCredentialsManager.shared.username,
let password = KeychainCredentialsManager.shared.password
else {
let error = WMFCurrentlyLoggedInUserFetcherError.blankUsernameOrPassword
completion(.failure(error))
return
}
guard let siteURL = loginSiteURL else {
completion(.failure(AuthenticationError.missingLoginURL))
return
}
currentlyLoggedInUserFetcher.fetch(siteURL: siteURL, success: { result in
DispatchQueue.main.async {
self.loggedInUsername = result.name
completion(.alreadyLoggedIn(result))
}
}, failure:{ error in
DispatchQueue.main.async {
guard !(error is URLError) else {
self.loggedInUsername = userName
let loginResult = WMFAccountLoginResult(status: WMFAccountLoginResult.Status.offline, username: userName, message: nil)
completion(.success(loginResult))
return
}
self.login(username: userName, password: password, retypePassword: nil, oathToken: nil, captchaID: nil, captchaWord: nil, reattemptOn401Response: reattemptOn401Response, completion: { (loginResult) in
DispatchQueue.main.async {
switch loginResult {
case .success(let result):
completion(.success(result))
case .failure(let error):
guard !(error is URLError) else {
self.loggedInUsername = userName
let loginResult = WMFAccountLoginResult(status: WMFAccountLoginResult.Status.offline, username: userName, message: nil)
completion(.success(loginResult))
return
}
self.loggedInUsername = nil
self.logout(initiatedBy: .app)
completion(.failure(error))
default:
break
}
}
})
}
})
}
fileprivate func resetLocalUserLoginSettings() {
KeychainCredentialsManager.shared.username = nil
KeychainCredentialsManager.shared.password = nil
self.loggedInUsername = nil
session.removeAllCookies()
SessionSingleton.sharedInstance()?.dataStore.clearMemoryCache()
SessionSingleton.sharedInstance().dataStore.readingListsController.setSyncEnabled(false, shouldDeleteLocalLists: false, shouldDeleteRemoteLists: false)
// Reset so can show for next logged in user.
UserDefaults.wmf.wmf_setDidShowEnableReadingListSyncPanel(false)
UserDefaults.wmf.wmf_setDidShowSyncEnabledPanel(false)
}
/**
* Logs out any authenticated user and clears out any associated cookies
*/
@objc(logoutInitiatedBy:completion:)
public func logout(initiatedBy logoutInitiator: LogoutInitiator, completion: @escaping () -> Void = {}){
if logoutInitiator == .app || logoutInitiator == .server {
isUserUnawareOfLogout = true
}
let postDidLogOutNotification = {
NotificationCenter.default.post(name: WMFAuthenticationManager.didLogOutNotification, object: nil)
}
performTokenizedMediaWikiAPIPOST(to: loginSiteURL, with: ["action": "logout", "format": "json"], reattemptLoginOn401Response: false) { (result, response, error) in
DispatchQueue.main.async {
if let error = error {
// ...but if "action=logout" fails we *still* want to clear local login settings, which still effectively logs the user out.
DDLogDebug("Failed to log out, delete login tokens and other browser cookies: \(error)")
self.resetLocalUserLoginSettings()
completion()
postDidLogOutNotification()
return
}
DDLogDebug("Successfully logged out, deleted login tokens and other browser cookies")
// It's best to call "action=logout" API *before* clearing local login settings...
self.resetLocalUserLoginSettings()
completion()
postDidLogOutNotification()
}
}
}
}
// MARK: @objc login
extension WMFAuthenticationManager {
@objc public func attemptLogin(completion: @escaping () -> Void = {}) {
let completion: AuthenticationResultHandler = { result in
completion()
}
attemptLogin(completion: completion)
}
}
// MARK: @objc logout
extension WMFAuthenticationManager {
@objc public enum LogoutInitiator: Int {
case user
case app
case server
}
@objc public static let didLogOutNotification = Notification.Name("WMFAuthenticationManagerDidLogOut")
@objc public func userDidAcknowledgeUnintentionalLogout() {
isUserUnawareOfLogout = false
}
@objc public var isUserUnawareOfLogout: Bool {
get {
return UserDefaults.wmf.isUserUnawareOfLogout
}
set {
UserDefaults.wmf.isUserUnawareOfLogout = newValue
}
}
}
| mit | 0ce38f72c1d85ecd47f1f6c46959b58b | 41.1673 | 254 | 0.614067 | 5.556112 | false | false | false | false |
TheDarkCode/Example-Swift-Apps | Exercises and Basic Principles/core-data-basics/core-data-basics/ViewController.swift | 1 | 2130 | //
// ViewController.swift
// core-data-basics
//
// Created by Mark Hamilton on 2/29/16.
// Copyright © 2016 dryverless. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var recipes = [Recipe]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
fetchAndSetResults()
tableView.reloadData()
}
func fetchAndSetResults() {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Recipe")
do {
let results = try context.executeFetchRequest(fetchRequest)
self.recipes = results as! [Recipe]
} catch let err as NSError {
NSLog(err.debugDescription)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCellWithIdentifier("recipeCell") as? RecipeCell {
if let recipe = recipes[indexPath.row] as Recipe! {
cell.configureCell(recipe)
return cell
} else {
return RecipeCell()
}
} else {
return RecipeCell()
}
}
}
| mit | 8d07ac77ded50d3a7a951a6e6bb7b5db | 22.395604 | 109 | 0.532644 | 6.225146 | false | false | false | false |
SereivoanYong/Charts | Source/Charts/Animation/ChartAnimationEasing.swift | 1 | 11604 | //
// ChartAnimationUtils.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
public enum ChartEasingOption {
case linear
case easeInQuad
case easeOutQuad
case easeInOutQuad
case easeInCubic
case easeOutCubic
case easeInOutCubic
case easeInQuart
case easeOutQuart
case easeInOutQuart
case easeInQuint
case easeOutQuint
case easeInOutQuint
case easeInSine
case easeOutSine
case easeInOutSine
case easeInExpo
case easeOutExpo
case easeInOutExpo
case easeInCirc
case easeOutCirc
case easeInOutCirc
case easeInElastic
case easeOutElastic
case easeInOutElastic
case easeInBack
case easeOutBack
case easeInOutBack
case easeInBounce
case easeOutBounce
case easeInOutBounce
}
public typealias ChartEasingFunctionBlock = (_ elapsed: TimeInterval, _ duration: TimeInterval) -> CGFloat
internal func easingFunctionFromOption(_ easing: ChartEasingOption) -> ChartEasingFunctionBlock {
switch easing {
case .linear:
return EasingFunctions.linear
case .easeInQuad:
return EasingFunctions.easeInQuad
case .easeOutQuad:
return EasingFunctions.easeOutQuad
case .easeInOutQuad:
return EasingFunctions.easeInOutQuad
case .easeInCubic:
return EasingFunctions.easeInCubic
case .easeOutCubic:
return EasingFunctions.easeOutCubic
case .easeInOutCubic:
return EasingFunctions.easeInOutCubic
case .easeInQuart:
return EasingFunctions.easeInQuart
case .easeOutQuart:
return EasingFunctions.easeOutQuart
case .easeInOutQuart:
return EasingFunctions.easeInOutQuart
case .easeInQuint:
return EasingFunctions.easeInQuint
case .easeOutQuint:
return EasingFunctions.easeOutQuint
case .easeInOutQuint:
return EasingFunctions.easeInOutQuint
case .easeInSine:
return EasingFunctions.easeInSine
case .easeOutSine:
return EasingFunctions.easeOutSine
case .easeInOutSine:
return EasingFunctions.easeInOutSine
case .easeInExpo:
return EasingFunctions.easeInExpo
case .easeOutExpo:
return EasingFunctions.easeOutExpo
case .easeInOutExpo:
return EasingFunctions.easeInOutExpo
case .easeInCirc:
return EasingFunctions.easeInCirc
case .easeOutCirc:
return EasingFunctions.easeOutCirc
case .easeInOutCirc:
return EasingFunctions.easeInOutCirc
case .easeInElastic:
return EasingFunctions.easeInElastic
case .easeOutElastic:
return EasingFunctions.easeOutElastic
case .easeInOutElastic:
return EasingFunctions.easeInOutElastic
case .easeInBack:
return EasingFunctions.easeInBack
case .easeOutBack:
return EasingFunctions.easeOutBack
case .easeInOutBack:
return EasingFunctions.easeInOutBack
case .easeInBounce:
return EasingFunctions.easeInBounce
case .easeOutBounce:
return EasingFunctions.easeOutBounce
case .easeInOutBounce:
return EasingFunctions.easeInOutBounce
}
}
internal struct EasingFunctions {
internal static let linear: ChartEasingFunctionBlock = { elapsed, duration in
return CGFloat(elapsed / duration)
}
internal static let easeInQuad: ChartEasingFunctionBlock = { elapsed, duration in
let position = CGFloat(elapsed / duration)
return position * position
}
internal static let easeOutQuad: ChartEasingFunctionBlock = { elapsed, duration in
let position = CGFloat(elapsed / duration)
return -position * (position - 2.0)
}
internal static let easeInOutQuad: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
return 0.5 * position * position
}
return -0.5 * ((position - 1.0) * (position - 3.0) - 1.0)
}
internal static let easeInCubic: ChartEasingFunctionBlock = { elapsed, duration in
let position = CGFloat(elapsed / duration)
return position * position * position
}
internal static let easeOutCubic: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
position -= 1.0
return position * position * position + 1.0
}
internal static let easeInOutCubic: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
return 0.5 * position * position * position
}
position -= 2.0
return 0.5 * (position * position * position + 2.0)
}
internal static let easeInQuart: ChartEasingFunctionBlock = { elapsed, duration in
let position = CGFloat(elapsed / duration)
return position * position * position * position
}
internal static let easeOutQuart: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
position -= 1.0
return -(position * position * position * position - 1.0)
}
internal static let easeInOutQuart: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
return 0.5 * position * position * position * position
}
position -= 2.0
return -0.5 * (position * position * position * position - 2.0)
}
internal static let easeInQuint: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
return position * position * position * position * position
}
internal static let easeOutQuint: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
position -= 1.0
return (position * position * position * position * position + 1.0)
}
internal static let easeInOutQuint: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
return 0.5 * position * position * position * position * position
} else {
position -= 2.0
return 0.5 * (position * position * position * position * position + 2.0)
}
}
internal static let easeInSine: ChartEasingFunctionBlock = { elapsed, duration in
let position = CGFloat(elapsed / duration)
return -cos(position * .pi / 2) + 1.0
}
internal static let easeOutSine: ChartEasingFunctionBlock = { elapsed, duration in
let position = CGFloat(elapsed / duration)
return sin(position * .pi / 2)
}
internal static let easeInOutSine: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
return -0.5 * (cos(.pi * position) - 1.0)
}
internal static let easeInExpo: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed == 0 {
return 0.0
} else {
return pow(2.0, 10.0 * CGFloat(elapsed / duration - 1.0))
}
}
internal static let easeOutExpo: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed == duration {
return 1.0
} else {
return -pow(2.0, CGFloat(-10.0 * elapsed / duration)) + 1.0
}
}
internal static let easeInOutExpo: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed == 0 {
return 0.0
}
if elapsed == duration {
return 1.0
}
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
return 0.5 * pow(2.0, 10.0 * (position - 1.0))
}
position = position - 1.0
return 0.5 * (-pow(2.0, -10.0 * position) + 2.0)
}
internal static let easeInCirc: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
return -(sqrt(1.0 - position * position) - 1.0)
}
internal static let easeOutCirc: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
position -= 1.0
return sqrt(1 - position * position)
}
internal static let easeInOutCirc: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
return -0.5 * (sqrt(1.0 - position * position) - 1.0)
}
position -= 2.0
return 0.5 * (sqrt(1.0 - position * position) + 1.0)
}
internal static let easeInElastic: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed == 0.0 {
return 0.0
}
var position = CGFloat(elapsed / duration)
if position == 1.0 {
return 1.0
}
var p = CGFloat(duration * 0.3)
var s = p / (2.0 * CGFloat.pi) * asin(1.0)
position -= 1.0
return -(pow(2.0, 10.0 * position) * sin((position * CGFloat(duration) - s) * (2.0 * .pi) / p))
}
internal static let easeOutElastic: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed == 0.0 {
return 0.0
}
var position = CGFloat(elapsed / duration)
if position == 1.0 {
return 1.0
}
var p = CGFloat(duration * 0.3)
var s = p / (2.0 * CGFloat.pi) * asin(1.0)
return pow(2.0, -10.0 * position) * sin((position * CGFloat(duration) - s) * (2.0 * .pi) / p) + 1.0
}
internal static let easeInOutElastic: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed == 0.0 {
return 0.0
}
var position = CGFloat(elapsed / (duration / 2.0))
if position == 2.0 {
return 1.0
}
var p = CGFloat(duration * (0.3 * 1.5))
var s = p / (2.0 * .pi) * asin(1.0)
if position < 1.0 {
position -= 1.0
return -0.5 * (pow(2.0, 10.0 * position) * sin((position * CGFloat(duration) - s) * (2.0 * .pi) / p))
}
position -= 1.0
return pow(2.0, -10.0 * position) * sin((position * CGFloat(duration) - s) * (2.0 * .pi) / p) * 0.5 + 1.0
}
internal static let easeInBack: ChartEasingFunctionBlock = { elapsed, duration in
let s = 1.70158 as CGFloat
let position = CGFloat(elapsed / duration)
return position * position * ((s + 1.0) * position - s)
}
internal static let easeOutBack: ChartEasingFunctionBlock = { elapsed, duration in
let s = 1.70158 as CGFloat
var position = CGFloat(elapsed / duration)
position -= 1.0
return position * position * ((s + 1.0) * position + s) + 1.0
}
internal static let easeInOutBack: ChartEasingFunctionBlock = { elapsed, duration in
var s = 1.70158 as CGFloat
var position = CGFloat(elapsed / (duration / 2.0))
if position < 1.0 {
s *= 1.525
return 0.5 * (position * position * ((s + 1.0) * position - s))
}
s *= 1.525
position -= 2.0
return 0.5 * (position * position * ((s + 1.0) * position + s) + 2.0)
}
internal static let easeInBounce: ChartEasingFunctionBlock = { elapsed, duration in
return 1.0 - easeOutBounce(duration - elapsed, duration)
}
internal static let easeOutBounce: ChartEasingFunctionBlock = { elapsed, duration in
var position = CGFloat(elapsed / duration)
if position < (1.0 / 2.75) {
return 7.5625 * position * position
}
else if position < (2.0 / 2.75) {
position -= (1.5 / 2.75)
return 7.5625 * position * position + 0.75
}
else if position < (2.5 / 2.75) {
position -= (2.25 / 2.75)
return 7.5625 * position * position + 0.9375
}
else {
position -= (2.625 / 2.75)
return 7.5625 * position * position + 0.984375
}
}
internal static let easeInOutBounce: ChartEasingFunctionBlock = { elapsed, duration in
if elapsed < (duration / 2.0) {
return easeInBounce(elapsed * 2.0, duration) * 0.5
} else {
return easeOutBounce(elapsed * 2.0 - duration, duration) * 0.5 + 0.5
}
}
}
| apache-2.0 | 5c6778ebc6ea04aee794399a7908866d | 29.617414 | 109 | 0.669597 | 4.154672 | false | false | false | false |
BrobotDubstep/BurningNut | BurningNut/BurningNut/Controller/GameViewController.swift | 1 | 1372 | //
// GameViewController.swift
// BurningNut
//
// Created by Tim Olbrich on 21.09.17.
// Copyright © 2017 Tim Olbrich. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
}
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | e5713011e7624e1835132dfcc44b105e | 22.637931 | 77 | 0.589351 | 5.293436 | false | false | false | false |
Sionarch/cordova-plugin-geofence | src/ios/GeofencePlugin.swift | 1 | 16400 | //
// GeofencePlugin.swift
// ionic-geofence
//
// Created by tomasz on 07/10/14.
//
//
import Foundation
import AudioToolbox
let TAG = "GeofencePlugin"
let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1)
let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1)
func log(message: String){
NSLog("%@ - %@", TAG, message)
}
@objc(HWPGeofencePlugin) class GeofencePlugin : CDVPlugin {
var isDeviceReady: Bool = false
let geoNotificationManager = GeoNotificationManager()
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
override func pluginInitialize () {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "didReceiveLocalNotification:",
name: "CDVLocalNotification",
object: nil
)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "didReceiveTransition:",
name: "handleTransition",
object: nil
)
}
func initialize(command: CDVInvokedUrlCommand) {
log("Plugin initialization")
//let faker = GeofenceFaker(manager: geoNotificationManager)
//faker.start()
if iOS8 {
promptForNotificationPermission()
}
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
func ping(command: CDVInvokedUrlCommand) {
log("Ping")
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
func promptForNotificationPermission() {
if #available(iOS 8.0, *) {
UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(
forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge],
categories: nil
)
)
} else {
// Fallback on earlier versions
}
}
func addOrUpdate(command: CDVInvokedUrlCommand) {
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
for geo in command.arguments {
self.geoNotificationManager.addOrUpdateGeoNotification(JSON(geo))
}
dispatch_async(dispatch_get_main_queue()) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
}
}
func deviceReady(command: CDVInvokedUrlCommand) {
isDeviceReady = true
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
func getWatched(command: CDVInvokedUrlCommand) {
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let watched = self.geoNotificationManager.getWatchedGeoNotifications()!
let watchedJsonString = watched.description
dispatch_async(dispatch_get_main_queue()) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: watchedJsonString)
self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
}
}
func remove(command: CDVInvokedUrlCommand) {
dispatch_async(dispatch_get_global_queue(priority, 0)) {
for id in command.arguments {
self.geoNotificationManager.removeGeoNotification(id as! String)
}
dispatch_async(dispatch_get_main_queue()) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
}
}
func removeAll(command: CDVInvokedUrlCommand) {
dispatch_async(dispatch_get_global_queue(priority, 0)) {
self.geoNotificationManager.removeAllGeoNotifications()
dispatch_async(dispatch_get_main_queue()) {
let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId)
}
}
}
func didReceiveTransition (notification: NSNotification) {
log("didReceiveTransition")
if let geoNotificationString = notification.object as? String {
let geoNotification = JSON(geoNotificationString)
var mustBeArray = [JSON]()
mustBeArray.append(geoNotification)
let js = "setTimeout('geofence.onTransitionReceived(" + mustBeArray.description + ")',0)"
evaluateJs(js)
}
}
func didReceiveLocalNotification (notification: NSNotification) {
log("didReceiveLocalNotification")
if UIApplication.sharedApplication().applicationState != UIApplicationState.Active {
var data = "undefined"
if let uiNotification = notification.object as? UILocalNotification {
if let notificationData = uiNotification.userInfo?["geofence.notification.data"] as? String {
data = notificationData
}
let js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)"
evaluateJs(js)
}
}
}
func evaluateJs (script: String) {
if webView != nil {
webView!.stringByEvaluatingJavaScriptFromString(script)
} else {
log("webView is null")
}
}
}
// class for faking crossing geofences
class GeofenceFaker {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
let geoNotificationManager: GeoNotificationManager
init(manager: GeoNotificationManager) {
geoNotificationManager = manager
}
func start() {
dispatch_async(dispatch_get_global_queue(priority, 0)) {
while (true) {
log("FAKER")
let notify = arc4random_uniform(4)
if notify == 0 {
log("FAKER notify chosen, need to pick up some region")
var geos = self.geoNotificationManager.getWatchedGeoNotifications()!
if geos.count > 0 {
//WTF Swift??
let index = arc4random_uniform(UInt32(geos.count))
let geo = geos[Int(index)]
let id = geo["id"].asString!
dispatch_async(dispatch_get_main_queue()) {
if let region = self.geoNotificationManager.getMonitoredRegion(id) {
log("FAKER Trigger didEnterRegion")
self.geoNotificationManager.locationManager(
self.geoNotificationManager.locationManager,
didEnterRegion: region
)
}
}
}
}
NSThread.sleepForTimeInterval(3)
}
}
}
func stop() {
}
}
class GeoNotificationManager : NSObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
let store = GeoNotificationStore()
override init() {
log("GeoNotificationManager init")
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if (!CLLocationManager.locationServicesEnabled()) {
log("Location services is not enabled")
} else {
log("Location services enabled")
}
if iOS8 {
if #available(iOS 8.0, *) {
locationManager.requestAlwaysAuthorization()
} else {
// Fallback on earlier versions
}
}
if (!CLLocationManager.isMonitoringAvailableForClass(CLRegion)) {
log("Geofencing not available")
}
}
func addOrUpdateGeoNotification(geoNotification: JSON) {
log("GeoNotificationManager addOrUpdate")
if (!CLLocationManager.locationServicesEnabled()) {
log("Locationservices is not enabled")
}
var location = CLLocationCoordinate2DMake(
geoNotification["latitude"].asDouble!,
geoNotification["longitude"].asDouble!
)
log("AddOrUpdate geo: \(geoNotification)")
var radius = geoNotification["radius"].asDouble! as CLLocationDistance
//let uuid = NSUUID().UUIDString
let id = geoNotification["id"].asString
var region = CLCircularRegion(
center: location,
radius: radius,
identifier: id!
)
var transitionType = 0
if let i = geoNotification["transitionType"].asInt {
transitionType = i
}
region.notifyOnEntry = 0 != transitionType & 1
region.notifyOnExit = 0 != transitionType & 2
//store
store.addOrUpdate(geoNotification)
locationManager.startMonitoringForRegion(region)
}
func getWatchedGeoNotifications() -> [JSON]? {
return store.getAll()
}
func getMonitoredRegion(id: String) -> CLRegion? {
for object in locationManager.monitoredRegions {
let region = object
if (region.identifier == id) {
return region
}
}
return nil
}
func removeGeoNotification(id: String) {
store.remove(id)
var region = getMonitoredRegion(id)
if (region != nil) {
log("Stoping monitoring region \(id)")
locationManager.stopMonitoringForRegion(region!)
}
}
func removeAllGeoNotifications() {
store.clear()
for object in locationManager.monitoredRegions {
let region = object
log("Stoping monitoring region \(region.identifier)")
locationManager.stopMonitoringForRegion(region)
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
log("update location")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
log("fail with error: \(error)")
}
func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) {
log("deferred fail error: \(error)")
}
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) {
log("Entering region \(region.identifier)")
handleTransition(region)
}
func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) {
log("Exiting region \(region.identifier)")
handleTransition(region)
}
func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) {
let lat = (region as! CLCircularRegion).center.latitude
let lng = (region as! CLCircularRegion).center.longitude
let radius = (region as! CLCircularRegion).radius
log("Starting monitoring for region \(region) lat \(lat) lng \(lng)")
}
func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
log("State for region " + region.identifier)
}
func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) {
log("Monitoring region " + region!.identifier + " failed " + error.description)
}
func handleTransition(region: CLRegion!) {
if let geo = store.findById(region.identifier) {
if let notification = geo["notification"].asDictionary {
notifyAbout(geo)
}
NSNotificationCenter.defaultCenter().postNotificationName("handleTransition", object: geo.description)
}
}
func notifyAbout(geo: JSON) {
log("Creating notification")
let notification = UILocalNotification()
notification.timeZone = NSTimeZone.defaultTimeZone()
let dateTime = NSDate()
notification.fireDate = dateTime
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertBody = geo["notification"]["text"].asString!
if let json = geo["notification"]["data"] as? JSON {
notification.userInfo = ["geofence.notification.data": json.description]
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
if let vibrate = geo["notification"]["vibrate"].asArray {
if (!vibrate.isEmpty && vibrate[0].asInt > 0) {
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
}
}
class GeoNotificationStore {
init() {
createDBStructure()
}
func createDBStructure() {
let (tables, err) = SD.existingTables()
if (err != nil) {
log("Cannot fetch sqlite tables: \(err)")
return
}
if (tables.filter { $0 == "GeoNotifications" }.count == 0) {
if let err = SD.executeChange("CREATE TABLE GeoNotifications (ID TEXT PRIMARY KEY, Data TEXT)") {
//there was an error during this function, handle it here
log("Error while creating GeoNotifications table: \(err)")
} else {
//no error, the table was created successfully
log("GeoNotifications table was created successfully")
}
}
}
func addOrUpdate(geoNotification: JSON) {
if (findById(geoNotification["id"].asString!) != nil) {
update(geoNotification)
}
else {
add(geoNotification)
}
}
func add(geoNotification: JSON) {
let id = geoNotification["id"].asString!
let err = SD.executeChange("INSERT INTO GeoNotifications (Id, Data) VALUES(?, ?)",
withArgs: [id, geoNotification.description])
if err != nil {
log("Error while adding \(id) GeoNotification: \(err)")
}
}
func update(geoNotification: JSON) {
let id = geoNotification["id"].asString!
let err = SD.executeChange("UPDATE GeoNotifications SET Data = ? WHERE Id = ?",
withArgs: [geoNotification.description, id])
if err != nil {
log("Error while adding \(id) GeoNotification: \(err)")
}
}
func findById(id: String) -> JSON? {
let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications WHERE Id = ?", withArgs: [id])
if err != nil {
//there was an error during the query, handle it here
log("Error while fetching \(id) GeoNotification table: \(err)")
return nil
} else {
if (resultSet.count > 0) {
return JSON(string: resultSet[0]["Data"]!.asString()!)
}
else {
return nil
}
}
}
func getAll() -> [JSON]? {
let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications")
if err != nil {
//there was an error during the query, handle it here
log("Error while fetching from GeoNotifications table: \(err)")
return nil
} else {
var results = [JSON]()
for row in resultSet {
if let data = row["Data"]?.asString() {
results.append(JSON(string: data))
}
}
return results
}
}
func remove(id: String) {
let err = SD.executeChange("DELETE FROM GeoNotifications WHERE Id = ?", withArgs: [id])
if err != nil {
log("Error while removing \(id) GeoNotification: \(err)")
}
}
func clear() {
let err = SD.executeChange("DELETE FROM GeoNotifications")
if err != nil {
log("Error while deleting all from GeoNotifications: \(err)")
}
}
}
| apache-2.0 | 897fafc631ecfb2658d538d1385ecac5 | 33.968017 | 126 | 0.600549 | 5.285208 | false | false | false | false |
tensorflow/swift-models | DCGAN/main.swift | 1 | 6051 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Datasets
import Foundation
import ModelSupport
import TensorFlow
let batchSize = 512
let epochCount = 20
let zDim = 100
let outputFolder = "./output/"
let dataset = MNIST(batchSize: batchSize, device: Device.default,
entropy: SystemRandomNumberGenerator(), flattening: false, normalizing: true)
// MARK: - Models
// MARK: Generator
struct Generator: Layer {
var flatten = Flatten<Float>()
var dense1 = Dense<Float>(inputSize: zDim, outputSize: 7 * 7 * 256)
var batchNorm1 = BatchNorm<Float>(featureCount: 7 * 7 * 256)
var transConv2D1 = TransposedConv2D<Float>(
filterShape: (5, 5, 128, 256),
strides: (1, 1),
padding: .same
)
var batchNorm2 = BatchNorm<Float>(featureCount: 7 * 7 * 128)
var transConv2D2 = TransposedConv2D<Float>(
filterShape: (5, 5, 64, 128),
strides: (2, 2),
padding: .same
)
var batchNorm3 = BatchNorm<Float>(featureCount: 14 * 14 * 64)
var transConv2D3 = TransposedConv2D<Float>(
filterShape: (5, 5, 1, 64),
strides: (2, 2),
padding: .same
)
@differentiable
public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let x1 = leakyRelu(input.sequenced(through: dense1, batchNorm1))
let x1Reshape = x1.reshaped(to: TensorShape(x1.shape.contiguousSize / (7 * 7 * 256), 7, 7, 256))
let x2 = leakyRelu(x1Reshape.sequenced(through: transConv2D1, flatten, batchNorm2))
let x2Reshape = x2.reshaped(to: TensorShape(x2.shape.contiguousSize / (7 * 7 * 128), 7, 7, 128))
let x3 = leakyRelu(x2Reshape.sequenced(through: transConv2D2, flatten, batchNorm3))
let x3Reshape = x3.reshaped(to: TensorShape(x3.shape.contiguousSize / (14 * 14 * 64), 14, 14, 64))
return tanh(transConv2D3(x3Reshape))
}
}
@differentiable
func generatorLoss(fakeLabels: Tensor<Float>) -> Tensor<Float> {
sigmoidCrossEntropy(logits: fakeLabels,
labels: Tensor(ones: fakeLabels.shape))
}
// MARK: Discriminator
struct Discriminator: Layer {
var conv2D1 = Conv2D<Float>(
filterShape: (5, 5, 1, 64),
strides: (2, 2),
padding: .same
)
var dropout = Dropout<Float>(probability: 0.3)
var conv2D2 = Conv2D<Float>(
filterShape: (5, 5, 64, 128),
strides: (2, 2),
padding: .same
)
var flatten = Flatten<Float>()
var dense = Dense<Float>(inputSize: 6272, outputSize: 1)
@differentiable
public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let x1 = dropout(leakyRelu(conv2D1(input)))
let x2 = dropout(leakyRelu(conv2D2(x1)))
return x2.sequenced(through: flatten, dense)
}
}
@differentiable
func discriminatorLoss(realLabels: Tensor<Float>, fakeLabels: Tensor<Float>) -> Tensor<Float> {
let realLoss = sigmoidCrossEntropy(logits: realLabels,
labels: Tensor(ones: realLabels.shape))
let fakeLoss = sigmoidCrossEntropy(logits: fakeLabels,
labels: Tensor(zeros: fakeLabels.shape))
return realLoss + fakeLoss
}
// MARK: - Training
// Create instances of models.
var discriminator = Discriminator()
var generator = Generator()
// Define optimizers.
let optG = Adam(for: generator, learningRate: 0.0001)
let optD = Adam(for: discriminator, learningRate: 0.0001)
// Test noise so we can track progress.
let noise = Tensor<Float>(randomNormal: TensorShape(1, zDim))
print("Begin training...")
for (epoch, epochBatches) in dataset.training.prefix(epochCount).enumerated() {
Context.local.learningPhase = .training
for batch in epochBatches {
let realImages = batch.data
// Train generator.
let noiseG = Tensor<Float>(randomNormal: TensorShape(batchSize, zDim))
let 𝛁generator = TensorFlow.gradient(at: generator) { generator -> Tensor<Float> in
let fakeImages = generator(noiseG)
let fakeLabels = discriminator(fakeImages)
let loss = generatorLoss(fakeLabels: fakeLabels)
return loss
}
optG.update(&generator, along: 𝛁generator)
// Train discriminator.
let noiseD = Tensor<Float>(randomNormal: TensorShape(batchSize, zDim))
let fakeImages = generator(noiseD)
let 𝛁discriminator = TensorFlow.gradient(at: discriminator) { discriminator -> Tensor<Float> in
let realLabels = discriminator(realImages)
let fakeLabels = discriminator(fakeImages)
let loss = discriminatorLoss(realLabels: realLabels, fakeLabels: fakeLabels)
return loss
}
optD.update(&discriminator, along: 𝛁discriminator)
}
// Test the networks.
Context.local.learningPhase = .inference
// Render images.
let generatedImage = generator(noise).normalizedToGrayscale().reshaped(to: [28, 28, 1])
try generatedImage.saveImage(directory: outputFolder, name: "\(epoch)", format: .png)
// Print loss.
let generatorLoss_ = generatorLoss(fakeLabels: generatedImage)
print("epoch: \(epoch) | Generator loss: \(generatorLoss_)")
}
// Generate another image.
let noise1 = Tensor<Float>(randomNormal: TensorShape(1, 100))
let generatedImage = generator(noise1).normalizedToGrayscale().reshaped(to: [28, 28, 1])
try generatedImage.saveImage(directory: outputFolder, name: "final", format: .png)
| apache-2.0 | 842c91296dc30077a331bfd46befbad2 | 35.6 | 106 | 0.667163 | 3.805293 | false | false | false | false |
jloloew/JellyBelly | JellyBelly-iOS/JellyBelly/DataSource.swift | 1 | 2088 | //
// DataSource.swift
// JellyBelly
//
// Created by Justin Loew on 6/27/15.
// Copyright (c) 2015 Justin Loew. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
/// Handles networking.
class DataSource {
private struct Static {
static let defaultDataSource = DataSource()
}
class func defaultDataSource() -> DataSource {
return Static.defaultDataSource
}
var allChefs = [Chef]()
private(set) var lastUpdated: NSDate!
let serverAddress = "45.55.192.30"
let serverPort = 3000
var host: String { return "http://\(serverAddress):\(serverPort)" }
/// Refresh the data from the server.
func refresh(completion: ((error: NSError?) -> Void)? = nil) {
let url = host + "/api"
println("sending refresh")
Alamofire.request(.GET, url, parameters: ["chefs": "*"])
.responseJSON { (_, _, json, error) -> Void in
println("finished refresh")
if let error = error {
println(error)
} else {
let json = JSON(json!)
self.allChefs = [Chef]()
for chef in json["chefs"] {
// deserialize this chef
debugPrintln(chef)
let chefDict = JSONToDictionary(chef.1) as NSDictionary?
self.allChefs.append(Chef(dict: chefDict! as! [String : AnyObject]))
}
self.lastUpdated = NSDate()
}
completion?(error: error)
}
}
/// Fetch an image from a path on the server.
func fetchImage(#path: String, _ completion: (image: UIImage!, error: NSError!) -> Void) {
let url = host + path
println("requesting image " + url)
Alamofire.request(.GET, url)
.response { (_, _, data, error) -> Void in
let image: UIImage!
if let error = error {
println(error)
image = nil
} else {
image = UIImage(data: data! as! NSData)
}
completion(image: image, error: error)
}
}
}
/// Recursively unwrap JSON into a Dictionary
func JSONToDictionary(json: JSON) -> [String : AnyObject]? {
var dict = json.dictionaryObject
if dict != nil {
for (k, v) in dict! {
if let vJson = v as? JSON {
dict![k] = JSONToDictionary(vJson)
}
}
}
return dict
}
| gpl-2.0 | 21f3c392120eb7560b65778af03270f7 | 23.564706 | 91 | 0.636015 | 3.351525 | false | false | false | false |
srn214/Floral | Floral/Pods/CLImagePickerTool/CLImagePickerTool/CLImagePickerTool/controller/CLBaseImagePickerViewController.swift | 2 | 9252 | //
// BaseNavViewController.swift
// CloudscmSwift
//
// Created by Darren on 17/5/2.
// Copyright © 2017年 RexYoung. All rights reserved.
//
import UIKit
class CLBaseImagePickerViewController: UIViewController {
// 自定义导航栏
lazy var customNavBar: CustomNavgationView = {
let nav = CustomNavgationView()
return nav
}()
// 右边第一个按钮
lazy var rightBtn: UIButton = {
let btn = UIButton()
btn.adjustsImageWhenHighlighted = false
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
btn.setTitleColor(UIColor.black, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
btn.addTarget(self, action: #selector(CLBaseImagePickerViewController.rightBtnClick), for: UIControl.Event.touchUpInside)
return btn
}()
// 标题
var navTitle = "" {
didSet{
customNavBar.titleLable.text = navTitle
}
}
// 返回按钮
lazy var backBtn: UIButton = {
let btn = UIButton()
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -12, bottom: 0, right: 0)
btn.setImage(UIImage(named: "btn_back2", in: BundleUtil.getCurrentBundle(), compatibleWith: nil), for:UIControl.State())
btn.addTarget(self, action: #selector(CLBaseImagePickerViewController.backBtnclick), for: .touchUpInside)
return btn
}()
lazy var toobar: UIToolbar = {
// 添加磨玻璃
let toolBar = UIToolbar.init()
toolBar.barStyle = .default
return toolBar
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.automaticallyAdjustsScrollViewInsets = false
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.navigationBar.isTranslucent = false
self.setupNav()
initLayout()
}
func initLayout() {
let titleY: CGFloat = UIDevice.current.isX() == true ? 40:20
self.customNavBar.translatesAutoresizingMaskIntoConstraints = false
self.toobar.translatesAutoresizingMaskIntoConstraints = false
self.rightBtn.translatesAutoresizingMaskIntoConstraints = false
self.backBtn.translatesAutoresizingMaskIntoConstraints = false
// 导航栏
self.customNavBar.addConstraint(NSLayoutConstraint.init(item: self.customNavBar, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: KNavgationBarHeight))
self.view.addConstraints([
NSLayoutConstraint.init(item: self.customNavBar, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.customNavBar, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.customNavBar, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
])
// toolbar
self.toobar.addConstraint(NSLayoutConstraint.init(item: self.toobar, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: KNavgationBarHeight))
self.customNavBar.addConstraints([
NSLayoutConstraint.init(item: self.toobar, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.toobar, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint.init(item: self.toobar, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
])
// 右边的按钮
self.rightBtn.addConstraint(NSLayoutConstraint.init(item: self.rightBtn, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 44))
self.rightBtn.addConstraint(NSLayoutConstraint.init(item: self.rightBtn, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 64))
self.customNavBar.addConstraints([
NSLayoutConstraint.init(item: self.rightBtn, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: titleY),
NSLayoutConstraint.init(item: self.rightBtn, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0)
])
// 返回按钮
self.backBtn.addConstraint(NSLayoutConstraint.init(item: self.backBtn, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 44))
self.backBtn.addConstraint(NSLayoutConstraint.init(item: self.backBtn, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 0, constant: 50))
self.customNavBar.addConstraints([
NSLayoutConstraint.init(item: self.backBtn, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: titleY),
NSLayoutConstraint.init(item: self.backBtn, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.customNavBar, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0)
])
}
// 先不要写在initview中,因为如果写在initview中就需要在子类中必须实现initView方法,并且调用super.initView()
fileprivate func setupNav(){
// 添加导航栏
self.view.addSubview(self.customNavBar)
// 右边按钮
self.customNavBar.addSubview(self.rightBtn)
// 毛玻璃效果
self.customNavBar.addSubview(self.toobar)
self.customNavBar.sendSubviewToBack(self.toobar)
self.customNavBar.addSubview(self.backBtn)
self.backBtn.isHidden = true
// 设置位置,适配iphonex
let titleY: CGFloat = UIDevice.current.isX() == true ? 40:20
self.rightBtn.cl_y = titleY
self.backBtn.cl_y = titleY
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if CLPickersTools.instence.navColor == nil {
self.toobar.isHidden = false
self.customNavBar.backgroundColor = UIColor.clear
} else {
self.customNavBar.backgroundColor = CLPickersTools.instence.navColor
self.toobar.isHidden = true
}
if CLPickersTools.instence.navTitleColor != nil {
self.backBtn.imageView?.tintColor = CLPickersTools.instence.navTitleColor
let img = self.backBtn.image(for: .normal)?.withRenderingMode(.alwaysTemplate)
self.backBtn.setImage(img, for: .normal)
self.customNavBar.titleLable.textColor = CLPickersTools.instence.navTitleColor
self.rightBtn.setTitleColor(CLPickersTools.instence.navTitleColor, for: .normal)
} else {
self.backBtn.imageView?.tintColor = UIColor.black
let img = self.backBtn.image(for: .normal)?.withRenderingMode(.alwaysTemplate)
self.backBtn.setImage(img, for: .normal)
self.customNavBar.titleLable.textColor = UIColor.black
self.rightBtn.setTitleColor(UIColor.black, for: .normal)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if CLPickersTools.instence.statusBarType == .black {
return .default
}
return .lightContent
}
@objc func rightBtnClick(){
}
@objc func backBtnclick(){
}
}
| mit | 1921dfd4e865753b3a9b204e1fd57bca | 55.341615 | 298 | 0.711167 | 4.900594 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.