repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
vitorvmiguel/instaping | instaping/DiscoverDetailViewController.swift | 1 | 1634 | //
// DiscoverDetailViewController.swift
// instaping
//
// Created by Vítor Vazquez Miguel on 26/06/17.
// Copyright © 2017 BTS. All rights reserved.
//
import UIKit
import Firebase
import FirebaseDatabase
class DiscoverDetailViewController: UIViewController {
@IBOutlet weak var postImage: UIImageView!
@IBOutlet weak var followButton: UIButton!
var post : PostModel?
var ref : DatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
self.ref = Database.database().reference()
postImage.sd_setImage(with: URL(string: (post?.image!)!))
}
@IBAction func followButtonClicked(_ sender: UIButton) {
let postUserId = self.post?.userUid
let currentUserId = Auth.auth().currentUser?.uid
self.ref!.child("follows").child(currentUserId!).observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(postUserId!) {
self.ref!.child("follows").child(currentUserId!).child(postUserId!).removeValue()
self.ref!.child("followedBy").child(postUserId!).child(currentUserId!).removeValue()
self.followButton.setTitle("Follow", for: .normal)
} else {
self.ref!.child("follows").child(currentUserId!).updateChildValues([postUserId! : true])
self.ref!.child("followedBy").child(postUserId!).updateChildValues([currentUserId! : true])
self.followButton.setTitle("Unfollow", for: .normal)
}
})
}
}
| mit |
NoryCao/zhuishushenqi | zhuishushenqi/RightSide/Topic/Controllers/TopicDetail/QSTopicDetailPresenter.swift | 1 | 1350 | //
// QSTopicDetailPresenter.swift
// zhuishushenqi
//
// Created yung on 2017/4/20.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
import UIKit
class QSTopicDetailPresenter: QSTopicDetailPresenterProtocol {
weak var view: QSTopicDetailViewProtocol?
let interactor: QSTopicDetailInteractorProtocol
let router: QSTopicDetailWireframeProtocol
init(interface: QSTopicDetailViewProtocol, interactor: QSTopicDetailInteractorProtocol, router: QSTopicDetailWireframeProtocol) {
self.view = interface
self.interactor = interactor
self.router = router
}
func viewDidLoad(){
interactor.requestDetail()
interactor.showTitle()
view?.showActivityView()
}
func didSelectAt(indexPath:IndexPath,models:[TopicDetailModel]){
router.presentDetail(indexPath: indexPath, models: models)
}
}
extension QSTopicDetailPresenter:QSTopicDetailInteractorOutputProtocol{
func fetchListSuccess(list: [TopicDetailModel], header: TopicDetailHeader) {
view?.hideActivityView()
view?.showList(list: list, header: header)
}
func fetchListFailed() {
view?.hideActivityView()
}
func showTitle(title:String){
view?.showTitle(title: title)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/25513-swift-constraints-constraintsystem-simplifyconformstoconstraint.swift | 7 | 210 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
1
class b<T{class A:b
var f=Dictionary<a
| mit |
huangboju/Moots | UICollectionViewLayout/uicollectionview-layouts-kit-master/vertical-snap-flow/Core/Layout/VerticalSnapCollectionFlowLayout.swift | 1 | 3514 | //
// SnapCollectionFlowLayout.swift
// snap-flow-layout
//
// Created by Astemir Eleev on 21/05/2018.
// Copyright © 2018 Astemir Eleev. All rights reserved.
//
import UIKit
class VerticalSnapCollectionFlowLayout: UICollectionViewFlowLayout {
// MARK: - Properties
private var firstSetupDone = false
var spacingMultiplier: CGFloat = 6 {
didSet {
invalidateLayout()
}
}
var minLineSpacing: CGFloat = 20 {
didSet {
minimumLineSpacing = minLineSpacing
invalidateLayout()
}
}
var itemHeight: CGFloat = 0 {
didSet {
recalculateItemSize(for: itemHeight)
}
}
// MARK: - Overrides
override func prepare() {
super.prepare()
if !firstSetupDone {
setup()
firstSetupDone = true
}
guard let unwrappedCollectionView = collectionView else {
return
}
let height = unwrappedCollectionView.frame.height
recalculateItemSize(for: height)
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
let layoutAttributes = layoutAttributesForElements(in: collectionView!.bounds)
let centerOffset = collectionView!.bounds.size.height / 2
let offsetWithCenter = proposedContentOffset.y + centerOffset
guard let unwrappedLayoutAttributes = layoutAttributes else {
return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
}
let closestAttribute = unwrappedLayoutAttributes
.sorted { abs($0.center.y - offsetWithCenter) < abs($1.center.y - offsetWithCenter) }
.first ?? UICollectionViewLayoutAttributes()
return CGPoint(x: 0, y: closestAttribute.center.y - centerOffset)
}
// MARK: - Private helpers
private func setup() {
guard let unwrappedCollectionView = collectionView else {
return
}
scrollDirection = .vertical
minimumLineSpacing = minLineSpacing
itemSize = CGSize(width: unwrappedCollectionView.bounds.width, height: itemHeight)
collectionView!.decelerationRate = UIScrollView.DecelerationRate.fast
}
private func recalculateItemSize(for itemHeight: CGFloat) {
guard let unwrappedCollectionView = collectionView else {
return
}
let horizontalContentInset = unwrappedCollectionView.contentInset.left + unwrappedCollectionView.contentInset.right
let verticalContentInset = unwrappedCollectionView.contentInset.bottom + unwrappedCollectionView.contentInset.top
var divider: CGFloat = 1.0
if unwrappedCollectionView.bounds.width > unwrappedCollectionView.bounds.height {
// collection view bounds are in landscape so we change the item width in a way where 2 rows can be displayed
divider = 2.0
}
itemSize = CGSize(width: unwrappedCollectionView.bounds.width / divider - horizontalContentInset, height: itemHeight - (minLineSpacing * spacingMultiplier) - verticalContentInset)
invalidateLayout()
}
}
| mit |
kazuhidet/fastlane | fastlane/swift/Gymfile.swift | 1 | 778 | // Gymfile.swift
// Copyright (c) 2021 FastlaneTools
// This class is automatically included in FastlaneRunner during build
// This autogenerated file will be overwritten or replaced during build time, or when you initialize `gym`
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
public class Gymfile: GymfileProtocol {
// If you want to enable `gym`, run `fastlane gym init`
// After, this file will be replaced with a custom implementation that contains values you supplied
// during the `init` process, and you won't see this message
}
// Generated with fastlane 2.173.0
| mit |
HongliYu/firefox-ios | Client/Frontend/Browser/TopTabsViewController.swift | 1 | 10211 | /* 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 Storage
import WebKit
struct TopTabsUX {
static let TopTabsViewHeight: CGFloat = 44
static let TopTabsBackgroundShadowWidth: CGFloat = 12
static let TabWidth: CGFloat = 190
static let FaderPading: CGFloat = 8
static let SeparatorWidth: CGFloat = 1
static let HighlightLineWidth: CGFloat = 3
static let TabNudge: CGFloat = 1 // Nudge the favicon and close button by 1px
static let TabTitlePadding: CGFloat = 10
static let AnimationSpeed: TimeInterval = 0.1
static let SeparatorYOffset: CGFloat = 7
static let SeparatorHeight: CGFloat = 32
}
protocol TopTabsDelegate: AnyObject {
func topTabsDidPressTabs()
func topTabsDidPressNewTab(_ isPrivate: Bool)
func topTabsDidTogglePrivateMode()
func topTabsDidChangeTab()
}
class TopTabsViewController: UIViewController {
let tabManager: TabManager
weak var delegate: TopTabsDelegate?
fileprivate var tabDisplayManager: TabDisplayManager!
var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TopTabCell.Identifier
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: TopTabsViewLayout())
collectionView.register(TopTabCell.self, forCellWithReuseIdentifier: TopTabCell.Identifier)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.clipsToBounds = false
collectionView.accessibilityIdentifier = "Top Tabs View"
collectionView.semanticContentAttribute = .forceLeftToRight
return collectionView
}()
fileprivate lazy var tabsButton: TabsButton = {
let tabsButton = TabsButton.tabTrayButton()
tabsButton.semanticContentAttribute = .forceLeftToRight
tabsButton.addTarget(self, action: #selector(TopTabsViewController.tabsTrayTapped), for: .touchUpInside)
tabsButton.accessibilityIdentifier = "TopTabsViewController.tabsButton"
return tabsButton
}()
fileprivate lazy var newTab: UIButton = {
let newTab = UIButton.newTabButton()
newTab.semanticContentAttribute = .forceLeftToRight
newTab.addTarget(self, action: #selector(TopTabsViewController.newTabTapped), for: .touchUpInside)
newTab.accessibilityIdentifier = "TopTabsViewController.newTabButton"
return newTab
}()
lazy var privateModeButton: PrivateModeButton = {
let privateModeButton = PrivateModeButton()
privateModeButton.semanticContentAttribute = .forceLeftToRight
privateModeButton.accessibilityIdentifier = "TopTabsViewController.privateModeButton"
privateModeButton.addTarget(self, action: #selector(TopTabsViewController.togglePrivateModeTapped), for: .touchUpInside)
return privateModeButton
}()
fileprivate lazy var tabLayoutDelegate: TopTabsLayoutDelegate = {
let delegate = TopTabsLayoutDelegate()
delegate.tabSelectionDelegate = tabDisplayManager
return delegate
}()
init(tabManager: TabManager) {
self.tabManager = tabManager
super.init(nibName: nil, bundle: nil)
tabDisplayManager = TabDisplayManager(collectionView: self.collectionView, tabManager: self.tabManager, tabDisplayer: self, reuseID: TopTabCell.Identifier)
collectionView.dataSource = tabDisplayManager
collectionView.delegate = tabLayoutDelegate
[UICollectionElementKindSectionHeader, UICollectionElementKindSectionFooter].forEach {
collectionView.register(TopTabsHeaderFooter.self, forSupplementaryViewOfKind: $0, withReuseIdentifier: "HeaderFooter")
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabDisplayManager.refreshStore(evenIfHidden: true)
}
deinit {
tabManager.removeDelegate(self.tabDisplayManager)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dragDelegate = tabDisplayManager
collectionView.dropDelegate = tabDisplayManager
let topTabFader = TopTabFader()
topTabFader.semanticContentAttribute = .forceLeftToRight
view.addSubview(topTabFader)
topTabFader.addSubview(collectionView)
view.addSubview(tabsButton)
view.addSubview(newTab)
view.addSubview(privateModeButton)
// Setup UIDropInteraction to handle dragging and dropping
// links onto the "New Tab" button.
let dropInteraction = UIDropInteraction(delegate: tabDisplayManager)
newTab.addInteraction(dropInteraction)
newTab.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(tabsButton.snp.leading)
make.size.equalTo(view.snp.height)
}
tabsButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.trailing.equalTo(view).offset(-10)
make.size.equalTo(view.snp.height)
}
privateModeButton.snp.makeConstraints { make in
make.centerY.equalTo(view)
make.leading.equalTo(view).offset(10)
make.size.equalTo(view.snp.height)
}
topTabFader.snp.makeConstraints { make in
make.top.bottom.equalTo(view)
make.leading.equalTo(privateModeButton.snp.trailing)
make.trailing.equalTo(newTab.snp.leading)
}
collectionView.snp.makeConstraints { make in
make.edges.equalTo(topTabFader)
}
tabsButton.applyTheme()
applyUIMode(isPrivate: tabManager.selectedTab?.isPrivate ?? false)
updateTabCount(tabDisplayManager.dataStore.count, animated: false)
}
func switchForegroundStatus(isInForeground reveal: Bool) {
// Called when the app leaves the foreground to make sure no information is inadvertently revealed
if let cells = self.collectionView.visibleCells as? [TopTabCell] {
let alpha: CGFloat = reveal ? 1 : 0
for cell in cells {
cell.titleText.alpha = alpha
cell.favicon.alpha = alpha
}
}
}
func updateTabCount(_ count: Int, animated: Bool = true) {
self.tabsButton.updateTabCount(count, animated: animated)
}
@objc func tabsTrayTapped() {
delegate?.topTabsDidPressTabs()
}
@objc func newTabTapped() {
self.delegate?.topTabsDidPressNewTab(self.tabDisplayManager.isPrivate)
LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Add tab button in the URL Bar on iPad"])
}
@objc func togglePrivateModeTapped() {
tabDisplayManager.togglePrivateMode(isOn: !tabDisplayManager.isPrivate, createTabOnEmptyPrivateMode: true)
delegate?.topTabsDidTogglePrivateMode()
self.privateModeButton.setSelected(tabDisplayManager.isPrivate, animated: true)
}
func scrollToCurrentTab(_ animated: Bool = true, centerCell: Bool = false) {
assertIsMainThread("Only animate on the main thread")
guard let currentTab = tabManager.selectedTab, let index = tabDisplayManager.dataStore.index(of: currentTab), !collectionView.frame.isEmpty else {
return
}
if let frame = collectionView.layoutAttributesForItem(at: IndexPath(row: index, section: 0))?.frame {
if centerCell {
collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false)
} else {
// Padding is added to ensure the tab is completely visible (none of the tab is under the fader)
let padFrame = frame.insetBy(dx: -(TopTabsUX.TopTabsBackgroundShadowWidth+TopTabsUX.FaderPading), dy: 0)
if animated {
UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: {
self.collectionView.scrollRectToVisible(padFrame, animated: true)
})
} else {
collectionView.scrollRectToVisible(padFrame, animated: false)
}
}
}
}
}
extension TopTabsViewController: TabDisplayer {
func focusSelectedTab() {
self.scrollToCurrentTab(true)
}
func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell {
guard let tabCell = cell as? TopTabCell else { return UICollectionViewCell() }
tabCell.delegate = self
let isSelected = (tab == tabManager.selectedTab)
tabCell.configureWith(tab: tab, isSelected: isSelected)
return tabCell
}
}
extension TopTabsViewController: TopTabCellDelegate {
func tabCellDidClose(_ cell: UICollectionViewCell) {
tabDisplayManager.closeActionPerformed(forCell: cell)
}
}
extension TopTabsViewController: Themeable, PrivateModeUI {
func applyUIMode(isPrivate: Bool) {
tabDisplayManager.togglePrivateMode(isOn: isPrivate, createTabOnEmptyPrivateMode: true)
privateModeButton.onTint = UIColor.theme.topTabs.privateModeButtonOnTint
privateModeButton.offTint = UIColor.theme.topTabs.privateModeButtonOffTint
privateModeButton.applyUIMode(isPrivate: tabDisplayManager.isPrivate)
}
func applyTheme() {
tabsButton.applyTheme()
newTab.tintColor = UIColor.theme.topTabs.buttonTint
view.backgroundColor = UIColor.theme.topTabs.background
collectionView.backgroundColor = view.backgroundColor
tabDisplayManager.refreshStore()
}
}
// Functions for testing
extension TopTabsViewController {
func test_getDisplayManager() -> TabDisplayManager {
assert(AppConstants.IsRunningTest)
return tabDisplayManager
}
}
| mpl-2.0 |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Layers/Hillshade renderer/HillshadeSettingsViewController.swift | 1 | 3938 | // Copyright 2016 Esri.
//
// 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 UIKit
import ArcGIS
protocol HillshadeSettingsViewControllerDelegate: AnyObject {
func hillshadeSettingsViewController(_ controller: HillshadeSettingsViewController, selectedAltitude altitude: Double, azimuth: Double, slopeType: AGSSlopeType)
}
class HillshadeSettingsViewController: UITableViewController {
@IBOutlet weak var altitudeSlider: UISlider?
@IBOutlet weak var azimuthSlider: UISlider?
@IBOutlet weak var azimuthLabel: UILabel?
@IBOutlet weak var altitudeLabel: UILabel?
@IBOutlet weak var slopeTypeCell: UITableViewCell?
weak var delegate: HillshadeSettingsViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
updateSlopeTypeUI()
updateAltitudeUI()
updateAzimuthUI()
}
private var slopeTypeOptions: [AGSSlopeType] = [.none, .degree, .percentRise, .scaled]
private let numberFormatter = NumberFormatter()
private func labelForSlopeType(_ slopeType: AGSSlopeType) -> String {
switch slopeType {
case .none: return "None"
case .degree: return "Degree"
case .percentRise: return "Percent Rise"
case .scaled: return "Scaled"
@unknown default: return "Unknown"
}
}
var slopeType: AGSSlopeType = .none {
didSet {
updateSlopeTypeUI()
}
}
private func updateSlopeTypeUI() {
slopeTypeCell?.detailTextLabel?.text = labelForSlopeType(slopeType)
}
var altitude: Double = 0 {
didSet {
updateAltitudeUI()
}
}
private func updateAltitudeUI() {
altitudeLabel?.text = numberFormatter.string(from: altitude as NSNumber)
altitudeSlider?.value = Float(altitude)
}
var azimuth: Double = 0 {
didSet {
updateAzimuthUI()
}
}
private func updateAzimuthUI() {
azimuthLabel?.text = numberFormatter.string(from: azimuth as NSNumber)
azimuthSlider?.value = Float(azimuth)
}
private func hillshadeParametersChanged() {
delegate?.hillshadeSettingsViewController(self, selectedAltitude: altitude, azimuth: azimuth, slopeType: slopeType)
}
// MARK: - Actions
@IBAction func azimuthSliderValueChanged(_ slider: UISlider) {
azimuth = Double(slider.value)
hillshadeParametersChanged()
}
@IBAction func altitudeSliderValueChanged(_ slider: UISlider) {
altitude = Double(slider.value)
hillshadeParametersChanged()
}
// UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard tableView.cellForRow(at: indexPath) == slopeTypeCell else {
return
}
let labels = slopeTypeOptions.map { (slopeType) -> String in
return labelForSlopeType(slopeType)
}
let selectedIndex = slopeTypeOptions.firstIndex(of: slopeType)!
let optionsViewController = OptionsTableViewController(labels: labels, selectedIndex: selectedIndex) { (newIndex) in
self.slopeType = self.slopeTypeOptions[newIndex]
self.hillshadeParametersChanged()
}
optionsViewController.title = "Slope Type"
show(optionsViewController, sender: self)
}
}
| apache-2.0 |
kuler90/OrangeLibrary | Extensions/IBInspectable/UITableViewCell+IBInspectable.swift | 1 | 673 | //
// UITableViewCell+IBInspectable.swift
// Orange Library
//
// Created by Kulesha Raman on 22.11.15.
//
import UIKit
extension UITableViewCell {
@IBInspectable var separatorL: CGFloat {
get {
return separatorInset.left
}
set {
separatorInset = separatorInset.with(left: newValue)
layoutMargins = layoutMargins.with(left: min(newValue, layoutMargins.left))
}
}
@IBInspectable var separatorR: CGFloat {
get {
return separatorInset.right
}
set {
separatorInset = separatorInset.with(right: newValue)
layoutMargins = layoutMargins.with(right: min(newValue, layoutMargins.right))
}
}
} | mit |
jpush/jchat-swift | JChat/Src/Utilites/ExJMessage/Extensions/JMSGMessage+.swift | 1 | 8009 | //
// JMSGMessage+.swift
// JChat
//
// Created by JIGUANG on 2017/10/1.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
let kLargeEmoticon = "kLargeEmoticon"
let kShortVideo = "video"
let kBusinessCard = "businessCard"
let kBusinessCardName = "userName"
let kBusinessCardAppKey = "appKey"
let kFileType = "fileType"
let kFileSize = "fileSize"
extension ExJMessage where Base: JMSGMessage {
var state: JCMessageState {
switch base.status {
case .sendFailed, .sendUploadFailed:
return .sendError
case .sending:
return .sending
default:
return .sendSucceed
}
}
var isFile: Bool {
guard let extras = _messageExtras(.file) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
return key == kFileType || key == kFileSize
}
return false
}) {
return true
}
return false
}
var fileType: String? {
if !self.isFile {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
return extras[kFileType] as? String
}
var fileSize: String? {
if !self.isFile {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
if let size = extras[kFileSize] as? Int {
if size > 1024 * 1024 {
return String(format: "%.1fM", Double(size) / 1024.0 / 1024.0)
}
if size > 1024 {
return "\(size / 1024)K"
}
return "\(size)B"
}
return nil
}
var businessCardName: String? {
if !self.isBusinessCard {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
return extras[kBusinessCardName] as? String
}
var businessCardAppKey: String? {
if !self.isBusinessCard {
return nil
}
guard let extras = base.content?.extras else {
return nil
}
return extras[kBusinessCardAppKey] as? String
}
var isBusinessCard: Bool {
get {
guard let extras = _messageExtras(.text) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
return key == kBusinessCard
}
return false
}) {
return true
}
return false
}
set {
if let content = base.content as? JMSGTextContent {
content.addStringExtra(kBusinessCard, forKey: kBusinessCard)
}
}
}
var isShortVideo: Bool {
get {
guard let extras = _messageExtras(.file) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
return key == kShortVideo
}
return false
}) {
return true
}
return false
}
// set {
// if let content = base.content as? JMSGFileContent {
// content.addStringExtra("mov", forKey: kShortVideo)
// }
// }
}
var isLargeEmoticon: Bool {
get {
guard let extras = _messageExtras(.image) else {
return false
}
if extras.keys.contains(where: { (key) -> Bool in
if let key = key as? String {
// android 的扩展字段:jiguang
return key == kLargeEmoticon || key == "jiguang"
}
return false
}) {
return true
}
return false
}
set {
if let content = base.content as? JMSGImageContent {
content.addStringExtra(kLargeEmoticon, forKey: kLargeEmoticon)
}
}
}
static func createBusinessCardMessage(_ conversation: JMSGConversation, _ userName: String, _ appKey: String) -> JMSGMessage {
let message: JMSGMessage!
let content = JMSGTextContent(text: "推荐了一张名片")
content.addStringExtra(userName, forKey: "userName")
content.addStringExtra(appKey, forKey: "appKey")
if conversation.ex.isGroup {
let group = conversation.target as! JMSGGroup
message = JMSGMessage.createGroupMessage(with: content, groupId: group.gid)
} else if conversation.ex.isChatRoom{
let chatRoom = conversation.target as! JMSGChatRoom
message = JMSGMessage.createChatRoomMessage(with: content, chatRoomId: chatRoom.roomID)
} else{
let user = conversation.target as! JMSGUser
message = JMSGMessage.createSingleMessage(with: content, username: user.username)
}
message.ex.isBusinessCard = true
return message
}
static func createBusinessCardMessage(gid: String, userName: String, appKey: String) -> JMSGMessage {
let message: JMSGMessage!
let content = JMSGTextContent(text: "推荐了一张名片")
content.addStringExtra(userName, forKey: "userName")
content.addStringExtra(appKey, forKey: "appKey")
message = JMSGMessage.createGroupMessage(with: content, groupId: gid)
message.ex.isBusinessCard = true
return message
}
/**
create a @ message
*/
static func createMessage(_ conversation: JMSGConversation, _ content: JMSGAbstractContent, _ reminds: [JCRemind]?) -> JMSGMessage {
var message: JMSGMessage?
if conversation.ex.isGroup {
let group = conversation.target as! JMSGGroup
if reminds != nil && reminds!.count > 0 {
var users: [JMSGUser] = []
var isAtAll = false
for remind in reminds! {
guard let user = remind.user else {
isAtAll = true
break
}
users.append(user)
}
if isAtAll {
message = JMSGMessage.createGroupAtAllMessage(with: content, groupId: group.gid)
} else {
message = JMSGMessage.createGroupMessage(with: content, groupId: group.gid, at_list: users)
}
} else {
message = JMSGMessage.createGroupMessage(with: content, groupId: group.gid)
}
} else if conversation.ex.isChatRoom {
let room = conversation.target as! JMSGChatRoom
message = JMSGMessage.createChatRoomMessage(with: content, chatRoomId: room.roomID)
} else {// conversation.ex.isSingle
let user = conversation.target as! JMSGUser
message = JMSGMessage.createSingleMessage(with: content, username: user.username)
}
return message!
}
// MARK: - private method
/**
get current message extras
*/
private func _messageExtras(_ contentType: JMSGContentType) -> [AnyHashable : Any]? {
let content: JMSGAbstractContent?
switch contentType {
case .text:
content = base.content as? JMSGTextContent
case .image:
content = base.content as? JMSGImageContent
case .file:
content = base.content as? JMSGFileContent
default:
return nil
}
guard let messsageContent = content else {
return nil
}
guard let extras = messsageContent.extras else {
return nil
}
return extras
}
}
| mit |
steelwheels/iGlyphTrainer | GTGameData/Source/Preference/GTGUIPreference.swift | 1 | 1656 | /**
* @file GTGUIPreference.m
* @brief Define GTGUIPreference
* @par Copyright
* Copyright (C) 2016-2017 Steel Wheels Project
*/
import Foundation
import KiwiGraphics
import KiwiControls
public class GTGUIPreference
{
public static let backgroundColor: CGColor = KGColorTable.black.cgColor
public static func progressColor(scene s:GTScene) -> CGColor {
var result: CGColor
switch s {
case .StartScene: result = KGColorTable.gold.cgColor
case .QuestionScene: result = KGColorTable.gold.cgColor
case .AnswerScene: result = KGColorTable.cyan.cgColor
case .CheckScene: result = KGColorTable.cyan.cgColor
}
return result
}
public static let progressStrokeWidth: CGFloat = 2.0
public static let hintTextColor = KGColorPreference.TextColors(foreground: KGColorTable.darkGoldenrod4,
background: KGColorTable.darkGoldenrod3)
public static let glyphNameTextColor = KGColorPreference.TextColors(foreground: KGColorTable.gold,
background: KGColorTable.black)
public static let timerFontColor:CGColor = KGColorTable.gold.cgColor
public static let maxGlyphSize: CGFloat = 375
public static let glyphVertexColor: CGColor = KGColorTable.white.cgColor
public static let glyphStrokeWidth: CGFloat = 10.0
public static let glyphStrokeColor: CGColor = KGColorTable.gold.cgColor
public static let buttonColor = KGColorPreference.ButtonColors(title: KGColorTable.cyan,
background: KGColorPreference.BackgroundColors(highlight: KGColorTable.darkGray, normal: KGColorTable.black))
}
| gpl-2.0 |
sapphirezzz/ZInAppPurchase | ZInAppPurchase/Classes/ZInAppPurchase.swift | 1 | 4771 | //
// ZInAppPurchase.swift
// Meijiabang
//
// Created by Zack on 16/5/26.
// Copyright © 2016年 Double. All rights reserved.
//
import Foundation
import StoreKit
enum ZInAppPurchaseError: String {
case ProductIdNil
case ProductInfoRequestFailed
case ProductNotExisited
case PurchaseWasForbidden
case ErrorUnknown
case ClientInvalid
case PaymentCancelled
case PaymentInvalid
case PaymentNotAllowed
case StoreProductNotAvailable
}
class ZInAppPurchase: NSObject {
static let sharedInstance = ZInAppPurchase()
private override init() {super.init()}
var successAction: ((receipt: String)->Void)?
var failureAction: ((error: ZInAppPurchaseError)->Void)?
func purchaseProduct(productId: String?, successAction: ((receipt: String)->Void)? = nil, failureAction: ((error: ZInAppPurchaseError)->Void)? = nil) {
self.successAction = successAction
self.failureAction = failureAction
guard let productId = productId else {
failureAction?(error: ZInAppPurchaseError.ProductIdNil)
return
}
let productRequest = SKProductsRequest(productIdentifiers: Set<String>(arrayLiteral: productId))
productRequest.delegate = self
productRequest.start()
}
}
extension ZInAppPurchase: SKProductsRequestDelegate {
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
if let product = response.products.first {
if SKPaymentQueue.canMakePayments() {
let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(payment)
}else {
failureAction?(error: ZInAppPurchaseError.PurchaseWasForbidden)
}
}else {
failureAction?(error: ZInAppPurchaseError.ProductNotExisited)
}
}
func requestDidFinish(request: SKRequest) {
print("ZInAppPurchase request requestDidFinish")
}
func request(request: SKRequest, didFailWithError error: NSError) {
print("ZInAppPurchase request didFailWithError error = ", error)
failureAction?(error: ZInAppPurchaseError.ProductInfoRequestFailed)
}
}
extension ZInAppPurchase: SKPaymentTransactionObserver {
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .Purchased: // Transaction is in queue, user has been charged. Client should complete the transaction.
if let receiptUrl = NSBundle.mainBundle().appStoreReceiptURL, let receiptData = NSData(contentsOfURL: receiptUrl) {
let receiptString = receiptData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
successAction?(receipt: receiptString)
}else {
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
}
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Failed: // Transaction was cancelled or failed before being added to the server queue.
if let code = transaction.error?.code , let errorCode = SKErrorCode(rawValue: code) {
switch errorCode {
case SKErrorCode.Unknown:
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
case SKErrorCode.ClientInvalid:
failureAction?(error: ZInAppPurchaseError.ClientInvalid)
case SKErrorCode.PaymentCancelled:
failureAction?(error: ZInAppPurchaseError.PaymentCancelled)
case SKErrorCode.PaymentInvalid:
failureAction?(error: ZInAppPurchaseError.PaymentInvalid)
case SKErrorCode.PaymentNotAllowed:
failureAction?(error: ZInAppPurchaseError.PaymentNotAllowed)
case SKErrorCode.StoreProductNotAvailable:
failureAction?(error: ZInAppPurchaseError.StoreProductNotAvailable)
default:
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
}
}else {
failureAction?(error: ZInAppPurchaseError.ErrorUnknown)
}
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
default:
break
}
}
}
}
| mit |
MisterZhouZhou/Objective-C-Swift-StudyDemo | SwiftDemo/SwiftDemo/classes/Category/ZWClassFromString.swift | 1 | 805 | //
// ZWClassFromString.swift
// Swift-Demo
//
// Created by rayootech on 16/6/17.
// Copyright © 2016年 rayootech. All rights reserved.
//
import Foundation
import UIKit
extension NSObject {
func swiftClassFromString(className: String) -> UIViewController! {
// get the project name
if let appName: String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? {
//拼接控制器名
let classStringName = "\(appName).\(className)"
//将控制名转换为类
let classType = NSClassFromString(classStringName) as? UIViewController.Type
if let type = classType {
let newVC = type.init()
return newVC
}
}
return nil;
}
}
| apache-2.0 |
netguru/inbbbox-ios | Inbbbox/Source Files/Helpers/Formatter.swift | 1 | 1195 | //
// Formatter.swift
// Inbbbox
//
// Created by Radoslaw Szeja on 14/12/15.
// Copyright © 2015 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
struct Formatter {
struct Date {
/// Basic date formatter with format yyyy-MM-dd
static var Basic: DateFormatter {
return Date.basicDateFormatter
}
/// Timestamp date formatter with ISO 8601 format yyyy-MM-dd'T'HH:mm:ssZZZZZ
static var Timestamp: DateFormatter {
return Date.timestampDateFormatter
}
}
}
private extension Formatter.Date {
static var basicDateFormatter = { Void -> DateFormatter in
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
static var timestampDateFormatter = { Void -> DateFormatter in
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
| gpl-3.0 |
austinzheng/swift | validation-test/stdlib/Slice/Slice_Of_DefaultedCollection_WithSuffix.swift | 16 | 3065 | // -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// FIXME: the test is too slow when the standard library is not optimized.
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
var SliceTests = TestSuite("Collection")
let prefix: [Int] = []
let suffix: [Int] = []
func makeCollection(elements: [OpaqueValue<Int>])
-> Slice<DefaultedCollection<OpaqueValue<Int>>> {
var baseElements = prefix.map(OpaqueValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(OpaqueValue.init))
let base = DefaultedCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count))
let endIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count + elements.count))
return Slice(base: base, bounds: startIndex..<endIndex)
}
func makeCollectionOfEquatable(elements: [MinimalEquatableValue])
-> Slice<DefaultedCollection<MinimalEquatableValue>> {
var baseElements = prefix.map(MinimalEquatableValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init))
let base = DefaultedCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count))
let endIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count + elements.count))
return Slice(base: base, bounds: startIndex..<endIndex)
}
func makeCollectionOfComparable(elements: [MinimalComparableValue])
-> Slice<DefaultedCollection<MinimalComparableValue>> {
var baseElements = prefix.map(MinimalComparableValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init))
let base = DefaultedCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count))
let endIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count + elements.count))
return Slice(base: base, bounds: startIndex..<endIndex)
}
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap
resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap
SliceTests.addCollectionTests(
"Slice_Of_DefaultedCollection_WithSuffix.swift.",
makeCollection: makeCollection,
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: 6
)
runAllTests()
| apache-2.0 |
LetItPlay/iOSClient | blockchainapp/UndBlurLabel.swift | 1 | 3605 | //
// UndBlurLabel.swift
// blockchainapp
//
// Created by Aleksey Tyurnin on 21/11/2017.
// Copyright © 2017 Ivan Gorbulin. All rights reserved.
//
import UIKit
import SnapKit
class UndBlurLabel: UIView {
// let blurView = UIVisualEffectView.init(effect: UIBlurEffect.init(style: UIBlurEffectStyle.regular))
let label: UILabel = UILabel.init(frame: CGRect.zero)
let shapeLayer: CAShapeLayer = CAShapeLayer()
init() {
super.init(frame: CGRect.zero)
self.backgroundColor = AppColor.Element.redBlur.withAlphaComponent(0.9)
// self.addSubview(blurView)
// blurView.snp.makeConstraints { (make) in
// make.edges.equalToSuperview()
// }
self.addSubview(label)
label.numberOfLines = 3
self.label.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(4)
}
// self.layer.mask = shapeLayer
}
// override func layoutSubviews() {
// super.layoutSubviews()
//// if let title = label.text, title != "" {
//// self.updateShape(text: title)
//// } else {
//// self.updateShape(text: " ")
//// }
// }
func setTitle(title: String) {
self.label.attributedText = formatString(text: title)
// self.layoutSubviews()
}
func updateShape(text: String) {
let widths = self.calcLinesWidths(text: formatString(text: text, calc: true), frame: self.label.frame).map({$0 + 4 + 4 + 4})
if widths.count > 0 {
let tooBig = widths.count > 3
let path = UIBezierPath.init()
path.move(to: CGPoint.zero)
path.addLine(to: CGPoint.init(x: min(widths[0], self.frame.width), y: 0))
path.addLine(to: CGPoint.init(x: min(widths[0], self.frame.width), y: 4))
for i in 1..<widths.prefix(3).count {
path.addLine(to: CGPoint.init(x: min(widths[i - 1], self.frame.width) , y: CGFloat(i*29) + 4))
path.addLine(to: CGPoint.init(x: min(widths[i], self.frame.width), y: CGFloat(i*29) + 4))
}
if tooBig {
path.addLine(to: CGPoint.init(x: self.frame.width, y: path.currentPoint.y))
path.addLine(to: CGPoint.init(x: self.frame.width, y: self.frame.height))
} else {
path.addLine(to: CGPoint.init(x: min(widths.last ?? 500.0, self.frame.width), y: self.frame.height))
}
path.addLine(to: CGPoint.init(x: 0, y: self.frame.height))
path.close()
self.shapeLayer.path = path.cgPath
} else {
self.shapeLayer.path = UIBezierPath.init(rect: CGRect.init(origin: CGPoint.zero, size: self.frame.size)).cgPath
}
}
func formatString(text: String, calc: Bool = false) -> NSAttributedString {
let para = NSMutableParagraphStyle()
para.alignment = .left
para.minimumLineHeight = 29
para.maximumLineHeight = 29
para.lineBreakMode = calc ? .byWordWrapping : .byTruncatingTail
return NSAttributedString.init(string: text,
attributes: [.font: UIFont.systemFont(ofSize: 24, weight: .regular),
.foregroundColor: UIColor.white,
.paragraphStyle: para])
// .kern:
}
func calcLinesWidths(text: NSAttributedString, frame: CGRect) -> [CGFloat] {
var newFrame = frame
newFrame.size.height = 200
var result: [CGFloat] = []
let fs = CTFramesetterCreateWithAttributedString(text)
let frame = CTFramesetterCreateFrame(fs, CFRangeMake(0, 0), CGPath.init(rect: newFrame, transform: nil), nil)
let lines = CTFrameGetLines(frame)
for line in lines as! Array<CTLine> {
let bounds = CTLineGetBoundsWithOptions(line, .useGlyphPathBounds)
let range = CTLineGetStringRange(line)
print("range = \(range.location) \(range.length)")
result.append(bounds.width - bounds.origin.x)
}
return result
}
required init?(coder aDecoder: NSCoder) {
return nil
}
}
| mit |
ysnrkdm/Graphene | Sources/Graphene/BoardBuilder.swift | 1 | 1642 | //
// BoardBuilder.swift
// FlatReversi
//
// Created by Kodama Yoshinori on 10/30/14.
// Copyright (c) 2014 Yoshinori Kodama. All rights reserved.
//
import Foundation
open class BoardBuilder {
public class func build(_ fromText: String) -> BoardRepresentation {
let board = SimpleBitBoard()
board.initialize(8, height: 8)
var i = 0
for c in fromText.characters {
switch(c) {
case "B", "O":
board.set(.black, x: i % 8, y: i / 8)
case "W", "X":
board.set(.white, x: i % 8, y: i / 8)
case ".", "-":
board.set(.empty, x: i % 8, y: i / 8)
default:
assertionFailure("")
}
i += 1
}
return build(board)
}
public class func build(_ fromBoard: Board) -> BoardRepresentation {
let bm = BoardMediator(board: fromBoard)
let ret = BoardRepresentation(boardMediator: bm)
return ret
}
public class func buildBitBoard(_ fromText: String) -> BoardRepresentation {
let board = SimpleBitBoard()
board.initialize(8, height: 8)
var i = 0
for c in fromText.characters {
switch(c) {
case "B":
board.set(.black, x: i % 8, y: i / 8)
case "W":
board.set(.white, x: i % 8, y: i / 8)
case ".":
board.set(.empty, x: i % 8, y: i / 8)
default:
assertionFailure("")
}
i += 1
}
return build(board)
}
}
| mit |
mruiz723/CourseiOSSwift3 | HelloWorld/HelloWorld/Controllers/ViewController.swift | 1 | 1357 | //
// ViewController.swift
// HelloWorld
//
// Created by Marlon David Ruiz Arroyave on 9/22/17.
// Copyright © 2017 Eafit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var welcomeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendName(_ sender: Any) {
if (nameTextField.text?.characters.count)! > 0 {
welcomeLabel.text = "Welcome \(nameTextField.text!)!!!"
welcomeLabel.isHidden = false
}else {
welcomeLabel.isHidden = true
let alertController = UIAlertController(title: "Error", message: "Debes digitar tu nombre", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
view.endEditing(true) //Hide the keyboard
}
}
| mit |
box/box-ios-sdk | Sources/Modules/TasksModule.swift | 1 | 10686 | //
// TasksModule.swift
// BoxSDK-iOS
//
// Created by Daniel Cech on 8/27/19.
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
/// Provides Tasks management
public class TasksModule {
/// Required for communicating with Box APIs.
weak var boxClient: BoxClient!
// swiftlint:disable:previous implicitly_unwrapped_optional
/// Initializer
///
/// - Parameter boxClient: Required for communicating with Box APIs.
init(boxClient: BoxClient) {
self.boxClient = boxClient
}
// MARK: - Tasks
/// Fetches a specific task.
///
/// - Parameters:
/// - taskId: The ID of the task.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full task object or an error.
public func get(
taskId: String,
fields: [String]? = nil,
completion: @escaping Callback<Task>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Used to create a single task for single user on a single file.
///
/// - Parameters:
/// - fileId: The ID of the file this task is associated with.
/// - action: The action the task assignee will be prompted to do.
/// Must be review for an approval task and complete for a general task
/// - message: An optional message to include with the task.
/// - dueAt: When this task is due.
/// - completionRule: The rule that determines whether a task is completed (default value set by API if not passed is all_assignees)
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full task object or an error.
public func create(
fileId: String,
action: TaskAction,
message: String? = nil,
dueAt: Date? = nil,
completionRule: TaskCompletionRule? = nil,
fields: [String]? = nil,
completion: @escaping Callback<Task>
) {
var json = [String: Any]()
json["item"] = ["type": "file", "id": fileId]
json["action"] = action.description
json["message"] = message
json["due_at"] = dueAt?.iso8601
json["completion_rule"] = completionRule?.description
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/tasks", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Updates a specific task.
///
/// - Parameters:
/// - taskId: The ID of the updated task.
/// - action: The action the task assignee will be prompted to do.
/// Must be review for an approval task and complete for a general task
/// - message: An optional message to include with the task.
/// - dueAt: When this task is due.
/// - completionRule: The rule that determines whether a task is completed (default value set by API if not passed is all_assignees)
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full task object or an error.
public func update(
taskId: String,
action: TaskAction,
message: String? = nil,
dueAt: Date? = nil,
completionRule: TaskCompletionRule? = nil,
fields: [String]? = nil,
completion: @escaping Callback<Task>
) {
var json = [String: Any]()
json["action"] = action.description
json["message"] = message
json["due_at"] = dueAt?.iso8601
json["completion_rule"] = completionRule?.description
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Permanently deletes a specific task.
///
/// - Parameters:
/// - taskId: The ID of the deleted task.
/// - completion: Returns a full task object or an error.
public func delete(
taskId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
// MARK: - Task Assignments
/// Fetches a specific task assignment.
///
/// - Parameters:
/// - taskAssignmentId: The ID of the task assignment.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full task assignment object or an error.
public func getAssignment(
taskAssignmentId: String,
fields: [String]? = nil,
completion: @escaping Callback<TaskAssignment>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/task_assignments/\(taskAssignmentId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Used to assign a task to a single user identified by userId.
/// There can be multiple assignments on a given task.
///
/// - Parameters:
/// - taskId: The ID of the task this assignment is for.
/// - userId: The ID of the user this assignment is for.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full task assignment object or an error.
public func assign(
taskId: String,
userId: String,
fields: [String]? = nil,
completion: @escaping Callback<TaskAssignment>
) {
var json = [String: Any]()
json["task"] = ["type": "task", "id": taskId]
json["assign_to"] = ["id": userId]
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/task_assignments", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Used to assign a task to a single user identified by login.
/// There can be multiple assignments on a given task.
///
/// - Parameters:
/// - taskId: The ID of the task this assignment is for.
/// - login: Optional. The login email address for the user this assignment is for.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full task assignment object or an error.
public func assignByEmail(
taskId: String,
email: String,
fields: [String]? = nil,
completion: @escaping Callback<TaskAssignment>
) {
var json = [String: Any]()
json["task"] = ["type": "task", "id": taskId]
json["assign_to"] = ["login": email]
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/task_assignments", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Used to update a task assignment.
///
/// - Parameters:
/// - taskAssignmentId: The ID of the task assignment.
/// - message: An optional message to include with the task.
/// - resolutionState: Optional. The resolution state of task.
/// When updating a task assignment, the resolution state depends on the action
/// type of the task. If you want to update a review task, the resolution_state
/// can be set to incomplete, approved, or rejected. A complete task
/// can have a resolutionState of incomplete or completed.
/// - completion: Returns a full task assignment object or an error.
public func updateAssignment(
taskAssignmentId: String,
message: String? = nil,
resolutionState: AssignmentState? = nil,
completion: @escaping Callback<TaskAssignment>
) {
var json = [String: Any]()
json["message"] = message
json["resolution_state"] = resolutionState?.description
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/task_assignments/\(taskAssignmentId)", configuration: boxClient.configuration),
json: json,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Permanently deletes a specific task.
///
/// - Parameters:
/// - taskId: The ID of the deleted task.
/// - completion: Returns a success or an error if task assignment can't be deleted.
public func deleteAssignment(
taskAssignmentId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/task_assignments/\(taskAssignmentId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Fetches a all task assignments for particular task.
///
/// - Parameters:
/// - taskAssignmentId: The ID of the task assignment.
/// - completion: Returns a list of task assignments for some task or an error.
public func listAssignments(
forTaskId taskId: String,
completion: @escaping Callback<[TaskAssignment]>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/tasks/\(taskId)/assignments", configuration: boxClient.configuration),
completion: { result in
let objectResult: Result<EntryContainer<TaskAssignment>, BoxSDKError> = result.flatMap { ObjectDeserializer.deserialize(data: $0.body) }
let mappedResult: Result<[TaskAssignment], BoxSDKError> = objectResult.map { $0.entries }
completion(mappedResult)
}
)
}
}
| apache-2.0 |
Eonil/Monolith.Swift | UIKitExtras/Sources/StaticTable/StaticTableViewController.swift | 3 | 16643 | //
// StaticTableViewController.swift
// CratesIOViewer
//
// Created by Hoon H. on 11/22/14.
//
//
import Foundation
import UIKit
//private let UILayoutPriorityRequired = 1000
//private let UILayoutPriorityDefaultHigh = 750
//private let UILayoutPriorityFittingSizeLevel = 50
private let REQUIRED = 1000 as Float
private let HIGH = 750 as Float
private let FITTING = 50 as Float
/// This class is designed for very small amount of cells.
/// Keeps all cells in memory.
public class StaticTableViewController: UITableViewController {
public typealias Table = StaticTable
public typealias Section = StaticTableSection
public typealias Row = StaticTableRow
private var _table = nil as Table?
deinit {
if let t = _table {
unownTable(t)
}
}
private func ownTable(targetTable:Table) {
precondition(table.hostTableViewController == nil, "Supplied table object alread bound to another table view controller.")
table.hostTableViewController = self
tableView?.tableHeaderView = table.header
tableView?.tableFooterView = table.footer
tableView?.reloadData()
}
private func unownTable(targetTable:Table) {
assert(table.hostTableViewController == self)
table.hostTableViewController = nil
tableView?.tableHeaderView = nil
tableView?.tableFooterView = nil
}
/// Table must be always non-nil value.
public final var table:Table {
get {
if _table == nil {
_table = Table()
ownTable(_table!)
}
return _table!
}
set(v) {
if _table != nil {
unownTable(_table!)
}
_table = v
ownTable(_table!)
}
// willSet {
// assert(table.hostTableViewController == self)
// table.hostTableViewController = nil
//
// tableView?.tableHeaderView = nil
// tableView?.tableFooterView = nil
// }
// didSet {
// precondition(table.hostTableViewController == nil, "Supplied table object alread bound to another table view controller.")
// table.hostTableViewController = self
// tableView?.tableHeaderView = table.header
// tableView?.tableFooterView = table.footer
// tableView?.reloadData()
// }
}
public override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return table.sections.count ||| 0
}
public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return table.sections[section].rows.count
}
public override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let sz = tableView.bounds.size
let sz1 = CGSize(width: sz.width, height: 0)
return table.sections[section].header?.heightAsCellInTableView(tableView) ||| 0
}
public override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let sz = tableView.bounds.size
let sz1 = CGSize(width: sz.width, height: 0)
return table.sections[section].footer?.heightAsCellInTableView(tableView) ||| 0
}
public override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return table.sections[section].header
}
public override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return table.sections[section].footer
}
public override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return table.rowAtIndexPath(indexPath).cell.heightAsCellInTableView(tableView)
}
public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return table.rowAtIndexPath(indexPath).cell
}
public override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return table.rowAtIndexPath(indexPath).willSelect()?.indexPath
}
public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
table.rowAtIndexPath(indexPath).didSelect()
}
public override func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return table.rowAtIndexPath(indexPath).willDeselect()?.indexPath
}
public override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
table.rowAtIndexPath(indexPath).didDeselect()
}
}
private extension UIView {
func heightForMaximumWidth(width:CGFloat) -> CGFloat {
assert(width >= 0)
let sz1 = systemLayoutSizeFittingSize(CGSize(width: width, height: 0), withHorizontalFittingPriority: HIGH, verticalFittingPriority: FITTING)
return sz1.height
// let sz2 = intrinsicContentSize()
// return max(sz1.height, sz2.height)
}
func heightAsCellInTableView(tableView:UITableView) -> CGFloat {
return heightForMaximumWidth(tableView.bounds.size.width)
}
}
/// If you need to modify multiple elements at once, then the best practice is
/// making a new table and replacing whole table with it instead replacing each elements.
public class StaticTable {
public typealias Section = StaticTableSection
public typealias Row = StaticTableRow
private var _sections = [] as [Section]
public init() {
}
deinit {
for s in _sections {
s.table = nil
}
}
/// There's no effective way to set the header's size automatically using auto-layout.
/// You must set its frame manually BEFORE passing it into this property.
public var header:UIView? {
didSet {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(header)
// if let v = header {
// v.frame = CGRect(origin: CGPointZero, size: v.systemLayoutSizeFittingSize(CGSizeZero))
// }
hostTableViewController?.tableView?.tableHeaderView = header
}
}
/// There's no effective way to set the footer's size automatically using auto-layout.
/// You must set its frame manually BEFORE passing it into this property.
public var footer:UIView? {
didSet {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(footer)
// if let v = header {
// v.frame = CGRect(origin: CGPointZero, size: v.systemLayoutSizeFittingSize(CGSizeZero))
// }
hostTableViewController?.tableView?.tableFooterView = footer
}
}
public var sections:[Section] {
get {
return _sections
}
set(v) {
for s in _sections {
assert(s.table === self, "Old sections must still be bound to this table.")
s.table = nil
}
_sections = v
for s in _sections {
assert(s.table === self, "New sections must not be bound to any section.")
s.table = nil
}
reloadSelf()
}
}
public func setSections(sections:[Section], animation:UITableViewRowAnimation) {
if let t = hostTableViewController?.tableView {
_sections = []
t.deleteSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: sections.count)), withRowAnimation: animation)
_sections = sections
t.insertSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: sections.count)), withRowAnimation: animation)
}
}
public func insertSection(s:Section, atIndex:Int, animation:UITableViewRowAnimation) {
precondition(s.table == nil, "Supplied section must not be bound to a table.")
assert(hostTableViewController?.tableView == nil || _sections.count == hostTableViewController?.tableView?.numberOfSections())
_sections.insert(s, atIndex: atIndex)
s.table = self
hostTableViewController?.tableView?.insertSections(NSIndexSet(intArray: [atIndex]), withRowAnimation: animation)
}
public func replaceSectionAtIndex(index:Int, withSection:Section, animation:UITableViewRowAnimation) {
precondition(withSection.table == nil, "Supplied section must not be bound to a table.")
assert(sections[index].table === self)
if sections[index] !== withSection {
let old = sections[index]
old.table = nil
_sections[index] = withSection
withSection.table = self
withSection.reloadSelfInTable(animation: animation)
}
}
public func deleteSectionAtIndex(index:Int, animation:UITableViewRowAnimation) {
assert(sections[index].table === self)
sections[index].table = nil
_sections.removeAtIndex(index)
hostTableViewController?.tableView?.deleteSections(NSIndexSet(intArray: [index]), withRowAnimation: animation)
}
private func reloadSelf() {
hostTableViewController?.tableView?.reloadData()
}
private func reloadSectionsAtIndexes(indexes:[Int], animation:UITableViewRowAnimation) {
hostTableViewController?.tableView?.reloadSections(NSIndexSet(intArray: indexes), withRowAnimation: animation)
}
private weak var hostTableViewController:UITableViewController? {
didSet {
}
}
}
public class StaticTableSection {
public typealias Table = StaticTable
public typealias Row = StaticTableRow
private var _rows = [] as [Row]
private var _header : UIView?
private var _footer : UIView?
public init() {
}
deinit {
for r in _rows {
r.section = nil
}
}
/// Height will be resolved using auto-layout. (`systemLayoutSizeFittingSize`)
public var header:UIView? {
get {
return _header
}
set(v) {
setHeaderWithAnimation(v, animation: UITableViewRowAnimation.None)
}
}
/// Height will be resolved using auto-layout. (`systemLayoutSizeFittingSize`)
public var footer:UIView? {
get {
return _footer
}
set(v) {
setFooterWithAnimation(v, animation: UITableViewRowAnimation.None)
}
}
public var rows:[StaticTableRow] {
get {
return _rows
}
set(v) {
setRows(v, animation: UITableViewRowAnimation.None)
}
}
public func setHeaderWithAnimation(v:UIView?, animation:UITableViewRowAnimation) {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(v)
_header = v
if table != nil {
reloadSelfInTable(animation: animation)
}
}
public func setFooterWithAnimation(v:UIView?, animation:UITableViewRowAnimation) {
assertView____SHOULD____SupportTranslationOfAutoresizingLayout(v)
_footer = v
if table != nil {
reloadSelfInTable(animation: animation)
}
}
public func setRows(rows:[Row], animation:UITableViewRowAnimation) {
for r in _rows {
assert(r.section === self, "Old rows must still be bound to this section.")
r.section = nil
}
_rows = rows
for r in _rows {
assert(r.section === nil, "New rows must not be bound to any section.")
r.section = self
}
reloadSelfInTable(animation: animation)
}
public func insertRow(r:Row, atIndex:Int, animation:UITableViewRowAnimation) {
precondition(r.section == nil, "Supplied row must not be bound to a section.")
r.section = self
_rows.insert(r, atIndex: atIndex)
table?.hostTableViewController?.tableView?.insertRowsAtIndexPaths([NSIndexPath(forRow: atIndex, inSection: indexInTable!)], withRowAnimation: animation)
}
public func replaceRowAtIndex(index:Int, withRow:Row, animation:UITableViewRowAnimation) {
precondition(withRow.section == nil, "Supplied row must not be bound to a section.")
assert(rows[index].section === self)
if rows[index] !== withRow {
let old = rows[index]
old.section = nil
withRow.section = self
_rows[index] = withRow
withRow.reloadSelfInSection(animation: animation)
}
}
public func deleteRowAtIndex(index:Int, animation:UITableViewRowAnimation) {
assert(rows[index].section === self)
rows[index].section = nil
_rows.removeAtIndex(index)
table?.hostTableViewController?.tableView?.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: indexInTable!)], withRowAnimation: animation)
}
public func deleteAllRowsWithAnimation(animation:UITableViewRowAnimation) {
for r in rows {
r.section = nil
}
_rows.removeAll(keepCapacity: false)
reloadSelfInTable(animation: animation)
}
public func reloadSelfWithAnimation(animation:UITableViewRowAnimation) {
reloadSelfInTable(animation: animation)
}
private weak var table:Table? {
didSet {
}
}
private var indexInTable:Int? {
get {
if let t = table {
for i in 0..<t.sections.count {
if t.sections[i] === self {
return i
}
}
}
return nil
}
}
private func reloadSelfInTable(#animation:UITableViewRowAnimation) {
table?.reloadSectionsAtIndexes([indexInTable!], animation: animation)
}
private func reloadRowsAtIndexes(indexes:[Int], animation:UITableViewRowAnimation) {
if let sidx = indexInTable {
var idxps = [] as [NSIndexPath]
for idx in indexes {
idxps.append(NSIndexPath(forRow: idx, inSection: indexInTable!))
}
table?.hostTableViewController?.tableView?.reloadRowsAtIndexPaths(idxps, withRowAnimation: animation)
}
}
}
public class StaticTableRow {
public typealias Table = StaticTable
public typealias Section = StaticTableSection
private var _cell : UITableViewCell
public init(cell:UITableViewCell) {
_cell = cell
}
public var cell:UITableViewCell {
get {
return _cell
}
}
/// Return another row object if you want to override.
public func willSelect() -> StaticTableRow? {
return self
}
public func didSelect() {
}
/// Return another row object if you want to override.
public func willDeselect() -> StaticTableRow? {
return self
}
public func didDeselect() {
}
public func setCell(cell:UITableViewCell, animation:UITableViewRowAnimation) {
_cell = cell
reloadSelfInSection(animation: UITableViewRowAnimation.None)
}
private weak var section:Section? {
didSet {
}
}
private var indexInSection:Int? {
get {
if let s = section {
for i in 0..<s.rows.count {
if s.rows[i] === self {
return i
}
}
}
return nil
}
}
private func reloadSelfInSection(#animation:UITableViewRowAnimation) {
section?.reloadRowsAtIndexes([indexInSection!], animation: animation)
}
}
public extension StaticTable {
public func rowAtIndexPath(indexPath:NSIndexPath) -> Row {
return sections[indexPath.section].rows[indexPath.row]
}
public func appendSection(section:Section, animation:UITableViewRowAnimation) {
insertSection(section, atIndex: sections.count, animation: animation)
}
public func appendSection(section:Section) {
insertSection(section, atIndex: sections.count, animation: UITableViewRowAnimation.None)
}
public func insertSectionAtIndex(index:Int, animation:UITableViewRowAnimation) {
insertSection(Section(), atIndex: index, animation: animation)
}
public func appendSectionWithAnimation(animation:UITableViewRowAnimation) -> Section {
insertSectionAtIndex(sections.count, animation: animation)
return sections.last!
}
public func appendSection() -> Section {
appendSectionWithAnimation(UITableViewRowAnimation.None)
return sections.last!
}
public func deleteSectionAtIndex(index:Int) {
deleteSectionAtIndex(index, animation: UITableViewRowAnimation.None)
}
public func deleteLastSection() {
deleteSectionAtIndex(sections.count-1)
}
}
public extension StaticTableSection {
public func appendRow(row:Row, animation:UITableViewRowAnimation) {
insertRow(row, atIndex: rows.count, animation: animation)
}
public func appendRow(row:Row) {
appendRow(row, animation: UITableViewRowAnimation.None)
}
public func insertRowAtIndex(index:Int, animation:UITableViewRowAnimation) {
insertRow(Row(cell: UITableViewCell()), atIndex: index, animation: animation)
}
public func appendRowWithAnimation(animation:UITableViewRowAnimation) -> Row {
insertRowAtIndex(rows.count, animation: animation)
return rows.last!
}
public func appendRow() -> Row {
appendRowWithAnimation(UITableViewRowAnimation.None)
return rows.last!
}
public func deleteRowAtIndex(index:Int) {
deleteRowAtIndex(index, animation: UITableViewRowAnimation.None)
}
public func deleteLastRow() {
deleteRowAtIndex(rows.count-1)
}
public func deleteAllRows() {
deleteAllRowsWithAnimation(UITableViewRowAnimation.None)
}
}
public extension StaticTableRow {
public var indexPath:NSIndexPath? {
get {
if section == nil { return nil }
return NSIndexPath(forRow: indexInSection!, inSection: section!.indexInTable!)
}
}
}
private extension NSIndexSet {
convenience init(intArray:[Int]) {
let s1 = NSMutableIndexSet()
for v in intArray {
s1.addIndex(v)
}
self.init(indexSet: s1)
}
var intArray:[Int] {
get {
var a1 = [] as [Int]
self.enumerateIndexesUsingBlock { (index:Int, _) -> Void in
a1.append(index)
}
return a1
}
}
}
private func assertView____SHOULD____SupportTranslationOfAutoresizingLayout(v:UIView?) {
assert(v == nil || v!.translatesAutoresizingMaskIntoConstraints() == true, "Layout of table/section header/footer view are controlled by `UITableView`, then it should support translation of autoresizing masks.")
}
| mit |
domenicosolazzo/practice-swift | Views/ScrollViews/ScrollViews/ScrollViews/PagedScrollViewController.swift | 1 | 4525 | //
// PagedScrollViewController.swift
// ScrollViews
//
// Created by Domenico on 06/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
class PagedScrollViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var pageControl: UIPageControl!
// It will hold all the images to display. 1 for page
var pageImages: [UIImage] = []
// It will hold instances of UIImageView to display each image on its respective page
var pageViews: [UIImageView?] = []
override func viewDidLoad() {
super.viewDidLoad()
// set up the page images
pageImages = [UIImage(named: "photo1.png")!,
UIImage(named: "photo2.png")!,
UIImage(named: "photo3.png")!,
UIImage(named: "photo4.png")!,
UIImage(named: "photo5.png")!]
let pageCount = pageImages.count
// set the page control to the first page and tell it how many pages there are.
pageControl.currentPage = 0
pageControl.numberOfPages = pageCount
// Set up the array that holds the UIImageView instances. At first, no pages have been lazily loaded and so you just fill it with nil objects as placeholders – one for each page
for _ in 0..<pageCount {
pageViews.append(nil)
}
// The scroll view, as before, needs to know its content size. Since you want a horizontal paging scroll view (it could just as easily be vertical if you want), you calculate the width to be the number of pages multiplied by the width of the scroll view. The height of the content is the same as the height of the scroll view.
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
height: pagesScrollViewSize.height)
// need some pages shown initially
loadVisiblePages()
}
func loadPage(_ page: Int) {
if page < 0 || page >= pageImages.count {
// If it's outside the range of what you have to display, then do nothing
return
}
// Using optional binding to check if you’ve already loaded the view
if let pageView = pageViews[page] {
// Do nothing. The view is already loaded.
} else {
// Need to create a page
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
// It creates a new UIImageView, sets it up and adds it to the scroll view
let newPageView = UIImageView(image: pageImages[page])
newPageView.contentMode = .scaleAspectFit
newPageView.frame = frame
scrollView.addSubview(newPageView)
// Replace the nil in the pageViews array with the view you’ve just created
pageViews[page] = newPageView
}
}
func purgePage(_ page: Int) {
if page < 0 || page >= pageImages.count {
// If it's outside the range of what you have to display, then do nothing
return
}
// Remove a page from the scroll view and reset the container array
if let pageView = pageViews[page] {
pageView.removeFromSuperview()
pageViews[page] = nil
}
}
func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
// Update the page control
pageControl.currentPage = page
// Work out which pages you want to load
let firstPage = page - 1
let lastPage = page + 1
// Purge anything before the first page
for index in 0 ..< firstPage += 1 {
purgePage(index)
}
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
// Purge anything after the last page
for index in lastPage+1 ..< pageImages.count += 1 {
purgePage(index)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Load the pages that are now on screen
loadVisiblePages()
}
}
| mit |
MateuszKarwat/Napi | Napi/Extensions/UserDefaults+RegisterDefaults.swift | 1 | 1031 | //
// Created by Mateusz Karwat on 08/03/2017.
// Copyright © 2017 Mateusz Karwat. All rights reserved.
//
import Foundation
extension UserDefaults {
/// Tries to add the contents of the `DefaultSettings.plist` to the registration domain.
///
/// - Note: To get rid of current settings, remove .plist file and run `killall -u $USER cfprefsd`.
func registerDefaultSettings() {
guard
let defaultSettingsURL = Bundle.main.url(forResource: "DefaultPreferences", withExtension: "plist"),
let plistContent = FileManager.default.contents(atPath: defaultSettingsURL.path) else {
return
}
do {
let plistData = try PropertyListSerialization.propertyList(from: plistContent, options: [], format: nil) as? [String : Any]
if let plistData = plistData {
self.register(defaults: plistData)
}
} catch let error {
log.error(error.localizedDescription)
return
}
}
}
| mit |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Service/OrderCreationService.swift | 1 | 2102 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import RxSwift
/// Used to create a pending order when the user confirms the transaction
public protocol OrderCreationServiceAPI: AnyObject {
func create(using candidateOrderDetails: CandidateOrderDetails) -> Single<CheckoutData>
}
final class OrderCreationService: OrderCreationServiceAPI {
// MARK: - Service Error
enum ServiceError: Error {
case mappingError
}
// MARK: - Properties
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let client: OrderCreationClientAPI
// MARK: - Setup
init(
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
client: OrderCreationClientAPI = resolve()
) {
self.analyticsRecorder = analyticsRecorder
self.client = client
}
// MARK: - API
func create(using candidateOrderDetails: CandidateOrderDetails) -> Single<CheckoutData> {
let data = OrderPayload.Request(
quoteId: candidateOrderDetails.quoteId,
action: candidateOrderDetails.action,
fiatValue: candidateOrderDetails.fiatValue,
fiatCurrency: candidateOrderDetails.fiatCurrency,
cryptoValue: candidateOrderDetails.cryptoValue,
paymentType: candidateOrderDetails.paymentMethod?.method,
paymentMethodId: candidateOrderDetails.paymentMethodId
)
let creation = client
.create(
order: data,
createPendingOrder: true
)
.asSingle()
.map(weak: self) { (self, response) in
OrderDetails(recorder: self.analyticsRecorder, response: response)
}
.map { details -> OrderDetails in
guard let details = details else {
throw ServiceError.mappingError
}
return details
}
.map { CheckoutData(order: $0) }
return creation
.asObservable()
.asSingle()
}
}
| lgpl-3.0 |
qoncept/TensorSwift | Tests/TensorSwiftTests/TensorSwiftTests.swift | 1 | 636 | //
// TensorSwiftTests.swift
// TensorSwift
//
// Created by Araki Takehiro on 2016/09/28.
//
//
import XCTest
class TensorSwiftTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
static var allTests : [(String, (TensorSwiftTests) -> () throws -> Void)] {
return [
]
}
}
| mit |
epv44/TwitchAPIWrapper | Sources/TwitchAPIWrapper/Models/DeleteVideoResponse.swift | 1 | 344 | //
// DeleteVideoResponse.swift
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 5/28/21.
//
import Foundation
/// Response object for the delete video request see: https://dev.twitch.tv/docs/api/reference/#delete-videos
public struct DeleteVideoResponse: Codable {
/// Date returned - list of id's
public let data: [String]
}
| mit |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/NotificationTextContentTests.swift | 1 | 3750 | import XCTest
@testable import WordPress
final class NotificationTextContentTests: XCTestCase {
private let contextManager = TestContextManager()
private let entityName = Notification.classNameWithoutNamespaces()
private var subject: NotificationTextContent?
private struct Expectations {
static let text = "xxxxxx xxxxxx and 658 others liked your post Bookmark Posts with Save For Later"
static let approveAction = ApproveCommentAction(on: true, command: ApproveComment(on: true))
static let trashAction = TrashCommentAction(on: true, command: TrashComment(on: true))
}
override func setUp() {
super.setUp()
subject = NotificationTextContent(dictionary: mockDictionary(), actions: mockedActions(), ranges: [], parent: loadLikeNotification())
}
override func tearDown() {
subject = nil
super.tearDown()
}
func testKindReturnsExpectation() {
let notificationKind = subject?.kind
XCTAssertEqual(notificationKind, .text)
}
func testStringReturnsExpectation() {
let value = subject?.text
XCTAssertEqual(value, Expectations.text)
}
func testRangesAreEmpty() {
let value = subject?.ranges
XCTAssertEqual(value?.count, 0)
}
func testActionsReturnMockedActions() {
let value = subject?.actions
let mockActionsCount = mockedActions().count
XCTAssertEqual(value?.count, mockActionsCount)
}
func testMetaReturnsExpectation() {
let value = subject?.meta
XCTAssertNil(value)
}
func testKindReturnsButtonForButtonContent() {
subject = NotificationTextContent(dictionary: mockButtonContentDictionary(), actions: mockedActions(), ranges: [], parent: loadLikeNotification())
let notificationKind = subject?.kind
XCTAssertEqual(notificationKind, .button)
}
func testParentReturnsValuePassedAsParameter() {
let injectedParent = loadLikeNotification()
let parent = subject?.parent
XCTAssertEqual(parent?.notificationIdentifier, injectedParent.notificationIdentifier)
}
func testApproveCommentActionIsOn() {
let approveCommentIdentifier = ApproveCommentAction.actionIdentifier()
let on = subject?.isActionOn(id: approveCommentIdentifier)
XCTAssertTrue(on!)
}
func testApproveCommentActionIsEnabled() {
let approveCommentIdentifier = ApproveCommentAction.actionIdentifier()
let on = subject?.isActionEnabled(id: approveCommentIdentifier)
XCTAssertTrue(on!)
}
func testActionWithIdentifierReturnsExpectedAction() {
let approveCommentIdentifier = ApproveCommentAction.actionIdentifier()
let action = subject?.action(id: approveCommentIdentifier)
XCTAssertEqual(action?.identifier, approveCommentIdentifier)
}
private func mockDictionary() -> [String: AnyObject] {
return getDictionaryFromFile(named: "notifications-text-content.json")
}
private func mockButtonContentDictionary() -> [String: AnyObject] {
return getDictionaryFromFile(named: "notifications-button-text-content.json")
}
private func getDictionaryFromFile(named fileName: String) -> [String: AnyObject] {
return contextManager.object(withContentOfFile: fileName) as! [String: AnyObject]
}
private func loadLikeNotification() -> WordPress.Notification {
return contextManager.loadEntityNamed(entityName, withContentsOfFile: "notifications-like.json") as! WordPress.Notification
}
private func mockedActions() -> [FormattableContentAction] {
return [Expectations.approveAction,
Expectations.trashAction]
}
}
| gpl-2.0 |
harryworld/MomentsVideoImport | Example/Tests/Tests.swift | 2 | 769 | import UIKit
import XCTest
import HNGVideoImport
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
uasys/swift | test/DebugInfo/generic_arg4.swift | 4 | 767 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
// REQUIRES: objc_interop
public struct Q<T> {
let x: T
}
// CHECK: define {{.*}}_T012generic_arg43fooySayAA1QVyxGGlF
// CHECK: call void @llvm.dbg.declare
// CHECK: call void @llvm.dbg.declare(metadata %[[TY:.*]]** %[[ALLOCA:[^,]+]],
// CHECK-SAME: metadata ![[ARG:.*]], metadata !DIExpression())
// CHECK: store %[[TY]]* %0, %[[TY]]** %[[ALLOCA]], align
// No deref here: the array argument is passed by value.
// CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
// CHECK-SAME: line: [[@LINE+2]], type: ![[TY:.*]])
// CHECK: ![[TY]] = !DICompositeType({{.*}}identifier: "_T0Say12generic_arg41QVyAA3fooySayACyxGGlFQq_GGD")
public func foo<T>(_ arg: [Q<T>]) {
}
| apache-2.0 |
breadwallet/breadwallet-ios | breadwalletTests/BRUserAgentHeaderGeneratorTests.swift | 1 | 1364 | //
// BRUserAgentHeaderGeneratorTests.swift
// breadwalletTests
//
// Created by Ray Vander Veen on 2019-01-16.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
import XCTest
class BRUserAgentHeaderGeneratorTests: XCTestCase {
func testAppVersions() {
XCTAssertTrue(BRUserAgentHeaderGenerator.appVersionString(with: ("3", "7", "1", "390")) == "3071390")
XCTAssertTrue(BRUserAgentHeaderGenerator.appVersionString(with: ("3", "7", "0", "1")) == "3070001")
XCTAssertTrue(BRUserAgentHeaderGenerator.appVersionString(with: ("3", "10", "0", "1")) == "3100001")
XCTAssertTrue(BRUserAgentHeaderGenerator.appVersionString(with: ("3", "7", "0", "13")) == "3070013")
XCTAssertTrue(BRUserAgentHeaderGenerator.appVersionString(with: ("3", "0", "0", "15")) == "3000015")
}
func testFullUserAgentHeader() {
let expected = "breadwallet/3071390 CFNetwork/1.2.0 Darwin/18.2.0"
XCTAssertTrue(BRUserAgentHeaderGenerator.userAgentHeaderString(appName: "breadwallet",
appVersion: "3071390",
darwinVersion: "Darwin/18.2.0",
cfNetworkVersion: "CFNetwork/1.2.0") == expected)
}
}
| mit |
phatblat/3DTouchDemo | 3DTouchDemo/TouchCanvas/TouchCanvas/AppDelegate.swift | 1 | 290 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The application delegate.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
} | mit |
jbrayton/Golden-Hill-HTTP-Library | GoldenHillHTTPLibrary/String+Capitalize.swift | 1 | 392 | //
// String+Capitalize.swift
// GoldenHillHTTPLibrary
//
// Created by John Brayton on 3/1/17.
// Copyright © 2017 John Brayton. All rights reserved.
//
import Foundation
extension String {
func ghs_capitalizingFirstLetter() -> String {
let first = String(self.prefix(1)).capitalized
let other = String(self.dropFirst())
return first + other
}
}
| mit |
epv44/TwitchAPIWrapper | Example/Tests/Response Tests/GetBannedUserResponseTests.swift | 1 | 977 | //
// GetBannedUserResponseTests.swift
// TwitchAPIWrapper_Tests
//
// Created by Eric Vennaro on 6/14/21.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import XCTest
@testable import TwitchAPIWrapper
class GetBannedUserResponseTests: XCTestCase {
func testBuildModel_shouldSucceed() throws {
let decoder = JSONDecoder.twitchAPIStandard()
let wrapper = try decoder.decode(BannedUsersResponse.self, from: Fixtures.dataFromFixtureFile("BannedUser"))
XCTAssertEqual(wrapper.pagination.cursor, "eyJiIjpudWxsLCJhIjp7IkN1cnNvciI6IjEwMDQ3MzA2NDo4NjQwNjU3MToxSVZCVDFKMnY5M1BTOXh3d1E0dUdXMkJOMFcifX0")
XCTAssertEqual(wrapper.bannedUsers[0].userId, "423374343")
XCTAssertEqual(wrapper.bannedUsers[0].userLogin, "glowillig")
XCTAssertEqual(wrapper.bannedUsers[0].userName, "glowillig")
XCTAssertEqual(wrapper.bannedUsers[0].expiresAt, ISO8601DateFormatter().date(from: "2019-03-15T02:00:28Z"))
}
}
| mit |
phimage/XcodeProjKit | Tests/Utils.swift | 1 | 2534 | //
// Utils.swift
//
//
// Created by phimage on 25/10/2020.
//
import Foundation
import XCTest
class Utils {
static let bundle = Bundle(for: Utils.self)
static let testURL: URL = {
#if compiler(>=5.3)
let thisFilePath = #filePath
#else
let thisFilePath = #file
#endif
return URL(fileURLWithPath: thisFilePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Tests")
}()
static func url(forResource resource: String, withExtension ext: String) -> URL? {
#if !os(Linux)
if let url = bundle.url(forResource: resource, withExtension: ext) {
return url
}
#endif
var url = URL(fileURLWithPath: "Tests/\(resource).\(ext)")
if FileManager.default.fileExists(atPath: url.path) {
return url
}
url = testURL.appendingPathComponent(resource).appendingPathExtension(ext)
if FileManager.default.fileExists(atPath: url.path) {
return url
}
return nil
}
}
extension XCTestCase {
func url(forResource resource: String, withExtension ext: String) -> URL? {
return Utils.url(forResource: resource, withExtension: ext)
}
func assertContentsEqual(_ url: URL, _ testURL: URL ) {
do {
let contents = try String(contentsOf: url)
let testContents = try String(contentsOf: testURL)
XCTAssertEqual(contents, testContents)
} catch {
XCTFail("\(error)")
}
}
func assertContentsNotEqual(_ url: URL, _ testURL: URL ) {
do {
let contents = try String(contentsOf: url)
let testContents = try String(contentsOf: testURL)
XCTAssertNotEqual(contents, testContents)
} catch {
XCTFail("\(error)")
}
}
}
extension String {
func replacingOccurrences(matchingPattern pattern: String, by replacement: String) -> String {
do {
let expression = try NSRegularExpression(pattern: pattern, options: [])
let matches = expression.matches(in: self, options: [], range: NSRange(startIndex..<endIndex, in: self))
return matches.reversed().reduce(into: self) { (current, result) in
let range = Range(result.range, in: current)!
current.replaceSubrange(range, with: replacement)
}
} catch {
return self
}
}
}
| mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CodeGuruProfiler/CodeGuruProfiler_API.swift | 1 | 20661 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/*
Client object for interacting with AWS CodeGuruProfiler service.
This section provides documentation for the Amazon CodeGuru Profiler API operations. <p>Amazon CodeGuru Profiler collects runtime performance data from your live applications, and provides recommendations that can help you fine-tune your application performance. Using machine learning algorithms, CodeGuru Profiler can help you find your most expensive lines of code and suggest ways you can improve efficiency and remove CPU bottlenecks. </p> <p>Amazon CodeGuru Profiler provides different visualizations of profiling data to help you identify what code is running on the CPU, see how much time is consumed, and suggest ways to reduce CPU utilization. </p> <note> <p>Amazon CodeGuru Profiler currently supports applications written in all Java virtual machine (JVM) languages. While CodeGuru Profiler supports both visualizations and recommendations for applications written in Java, it can also generate visualizations and a subset of recommendations for applications written in other JVM languages.</p> </note> <p> For more information, see <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html">What is Amazon CodeGuru Profiler</a> in the <i>Amazon CodeGuru Profiler User Guide</i>. </p>
*/
public struct CodeGuruProfiler: AWSService {
// MARK: Member variables
public let client: AWSClient
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the CodeGuruProfiler client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "codeguru-profiler",
serviceProtocol: .restjson,
apiVersion: "2019-07-18",
endpoint: endpoint,
errorType: CodeGuruProfilerErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Add up to 2 anomaly notifications channels for a profiling group.
public func addNotificationChannels(_ input: AddNotificationChannelsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AddNotificationChannelsResponse> {
return self.client.execute(operation: "AddNotificationChannels", path: "/profilingGroups/{profilingGroupName}/notificationConfiguration", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the time series of values for a requested list of frame metrics from a time period.
public func batchGetFrameMetricData(_ input: BatchGetFrameMetricDataRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchGetFrameMetricDataResponse> {
return self.client.execute(operation: "BatchGetFrameMetricData", path: "/profilingGroups/{profilingGroupName}/frames/-/metrics", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Used by profiler agents to report their current state and to receive remote configuration updates. For example, ConfigureAgent can be used to tell and agent whether to profile or not and for how long to return profiling data.
public func configureAgent(_ input: ConfigureAgentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ConfigureAgentResponse> {
return self.client.execute(operation: "ConfigureAgent", path: "/profilingGroups/{profilingGroupName}/configureAgent", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a profiling group.
public func createProfilingGroup(_ input: CreateProfilingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateProfilingGroupResponse> {
return self.client.execute(operation: "CreateProfilingGroup", path: "/profilingGroups", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a profiling group.
public func deleteProfilingGroup(_ input: DeleteProfilingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteProfilingGroupResponse> {
return self.client.execute(operation: "DeleteProfilingGroup", path: "/profilingGroups/{profilingGroupName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a ProfilingGroupDescription object that contains information about the requested profiling group.
public func describeProfilingGroup(_ input: DescribeProfilingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeProfilingGroupResponse> {
return self.client.execute(operation: "DescribeProfilingGroup", path: "/profilingGroups/{profilingGroupName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of FindingsReportSummary objects that contain analysis results for all profiling groups in your AWS account.
public func getFindingsReportAccountSummary(_ input: GetFindingsReportAccountSummaryRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetFindingsReportAccountSummaryResponse> {
return self.client.execute(operation: "GetFindingsReportAccountSummary", path: "/internal/findingsReports", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Get the current configuration for anomaly notifications for a profiling group.
public func getNotificationConfiguration(_ input: GetNotificationConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetNotificationConfigurationResponse> {
return self.client.execute(operation: "GetNotificationConfiguration", path: "/profilingGroups/{profilingGroupName}/notificationConfiguration", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the JSON-formatted resource-based policy on a profiling group.
public func getPolicy(_ input: GetPolicyRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetPolicyResponse> {
return self.client.execute(operation: "GetPolicy", path: "/profilingGroups/{profilingGroupName}/policy", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Gets the aggregated profile of a profiling group for a specified time range. Amazon CodeGuru Profiler collects posted agent profiles for a profiling group into aggregated profiles. <note> <p> Because aggregated profiles expire over time <code>GetProfile</code> is not idempotent. </p> </note> <p> Specify the time range for the requested aggregated profile using 1 or 2 of the following parameters: <code>startTime</code>, <code>endTime</code>, <code>period</code>. The maximum time range allowed is 7 days. If you specify all 3 parameters, an exception is thrown. If you specify only <code>period</code>, the latest aggregated profile is returned. </p> <p> Aggregated profiles are available with aggregation periods of 5 minutes, 1 hour, and 1 day, aligned to UTC. The aggregation period of an aggregated profile determines how long it is retained. For more information, see <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_AggregatedProfileTime.html"> <code>AggregatedProfileTime</code> </a>. The aggregated profile's aggregation period determines how long it is retained by CodeGuru Profiler. </p> <ul> <li> <p> If the aggregation period is 5 minutes, the aggregated profile is retained for 15 days. </p> </li> <li> <p> If the aggregation period is 1 hour, the aggregated profile is retained for 60 days. </p> </li> <li> <p> If the aggregation period is 1 day, the aggregated profile is retained for 3 years. </p> </li> </ul> <p>There are two use cases for calling <code>GetProfile</code>.</p> <ol> <li> <p> If you want to return an aggregated profile that already exists, use <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ListProfileTimes.html"> <code>ListProfileTimes</code> </a> to view the time ranges of existing aggregated profiles. Use them in a <code>GetProfile</code> request to return a specific, existing aggregated profile. </p> </li> <li> <p> If you want to return an aggregated profile for a time range that doesn't align with an existing aggregated profile, then CodeGuru Profiler makes a best effort to combine existing aggregated profiles from the requested time range and return them as one aggregated profile. </p> <p> If aggregated profiles do not exist for the full time range requested, then aggregated profiles for a smaller time range are returned. For example, if the requested time range is from 00:00 to 00:20, and the existing aggregated profiles are from 00:15 and 00:25, then the aggregated profiles from 00:15 to 00:20 are returned. </p> </li> </ol>
public func getProfile(_ input: GetProfileRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetProfileResponse> {
return self.client.execute(operation: "GetProfile", path: "/profilingGroups/{profilingGroupName}/profile", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of Recommendation objects that contain recommendations for a profiling group for a given time period. A list of Anomaly objects that contains details about anomalies detected in the profiling group for the same time period is also returned.
public func getRecommendations(_ input: GetRecommendationsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetRecommendationsResponse> {
return self.client.execute(operation: "GetRecommendations", path: "/internal/profilingGroups/{profilingGroupName}/recommendations", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// List the available reports for a given profiling group and time range.
public func listFindingsReports(_ input: ListFindingsReportsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListFindingsReportsResponse> {
return self.client.execute(operation: "ListFindingsReports", path: "/internal/profilingGroups/{profilingGroupName}/findingsReports", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists the start times of the available aggregated profiles of a profiling group for an aggregation period within the specified time range.
public func listProfileTimes(_ input: ListProfileTimesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListProfileTimesResponse> {
return self.client.execute(operation: "ListProfileTimes", path: "/profilingGroups/{profilingGroupName}/profileTimes", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of profiling groups. The profiling groups are returned as ProfilingGroupDescription objects.
public func listProfilingGroups(_ input: ListProfilingGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListProfilingGroupsResponse> {
return self.client.execute(operation: "ListProfilingGroups", path: "/profilingGroups", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of the tags that are assigned to a specified resource.
public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> {
return self.client.execute(operation: "ListTagsForResource", path: "/tags/{resourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Submits profiling data to an aggregated profile of a profiling group. To get an aggregated profile that is created with this profiling data, use GetProfile .
public func postAgentProfile(_ input: PostAgentProfileRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PostAgentProfileResponse> {
return self.client.execute(operation: "PostAgentProfile", path: "/profilingGroups/{profilingGroupName}/agentProfile", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds permissions to a profiling group's resource-based policy that are provided using an action group. If a profiling group doesn't have a resource-based policy, one is created for it using the permissions in the action group and the roles and users in the principals parameter. <p> The one supported action group that can be added is <code>agentPermission</code> which grants <code>ConfigureAgent</code> and <code>PostAgent</code> permissions. For more information, see <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-ug/resource-based-policies.html">Resource-based policies in CodeGuru Profiler</a> in the <i>Amazon CodeGuru Profiler User Guide</i>, <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_ConfigureAgent.html"> <code>ConfigureAgent</code> </a>, and <a href="https://docs.aws.amazon.com/codeguru/latest/profiler-api/API_PostAgentProfile.html"> <code>PostAgentProfile</code> </a>. </p> <p> The first time you call <code>PutPermission</code> on a profiling group, do not specify a <code>revisionId</code> because it doesn't have a resource-based policy. Subsequent calls must provide a <code>revisionId</code> to specify which revision of the resource-based policy to add the permissions to. </p> <p> The response contains the profiling group's JSON-formatted resource policy. </p>
public func putPermission(_ input: PutPermissionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutPermissionResponse> {
return self.client.execute(operation: "PutPermission", path: "/profilingGroups/{profilingGroupName}/policy/{actionGroup}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Remove one anomaly notifications channel for a profiling group.
public func removeNotificationChannel(_ input: RemoveNotificationChannelRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RemoveNotificationChannelResponse> {
return self.client.execute(operation: "RemoveNotificationChannel", path: "/profilingGroups/{profilingGroupName}/notificationConfiguration/{channelId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes permissions from a profiling group's resource-based policy that are provided using an action group. The one supported action group that can be removed is agentPermission which grants ConfigureAgent and PostAgent permissions. For more information, see Resource-based policies in CodeGuru Profiler in the Amazon CodeGuru Profiler User Guide, ConfigureAgent , and PostAgentProfile .
public func removePermission(_ input: RemovePermissionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RemovePermissionResponse> {
return self.client.execute(operation: "RemovePermission", path: "/profilingGroups/{profilingGroupName}/policy/{actionGroup}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Sends feedback to CodeGuru Profiler about whether the anomaly detected by the analysis is useful or not.
public func submitFeedback(_ input: SubmitFeedbackRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SubmitFeedbackResponse> {
return self.client.execute(operation: "SubmitFeedback", path: "/internal/profilingGroups/{profilingGroupName}/anomalies/{anomalyInstanceId}/feedback", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Use to assign one or more tags to a resource.
public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceResponse> {
return self.client.execute(operation: "TagResource", path: "/tags/{resourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Use to remove one or more tags from a resource.
public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceResponse> {
return self.client.execute(operation: "UntagResource", path: "/tags/{resourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates a profiling group.
public func updateProfilingGroup(_ input: UpdateProfilingGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateProfilingGroupResponse> {
return self.client.execute(operation: "UpdateProfilingGroup", path: "/profilingGroups/{profilingGroupName}", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension CodeGuruProfiler {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: CodeGuruProfiler, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| apache-2.0 |
TouchInstinct/LeadKit | Sources/Extensions/DataLoading/GeneralDataLoading/GeneralDataLoadingController+DefaultImplementation.swift | 1 | 2363 | //
// Copyright (c) 2018 Touch Instinct
//
// 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 RxSwift
import RxCocoa
public extension GeneralDataLoadingController {
// MARK: - DisposeBagHolder default implementation
var disposeBag: DisposeBag {
viewModel.disposeBag
}
// MARK: - StatefulViewController default implementation
func hasContent() -> Bool {
viewModel.hasContent
}
// MARK: - GeneralDataLoadingController default implementation
func initialLoadDataLoadingView() {
addViews()
configureLayout()
configureAppearance()
setupStateViews()
configureBarButtons()
localize()
bindViews()
bindLoadingState()
}
func setupStateViews() {
loadingView = TextPlaceholderView(title: .loading)
errorView = TextWithButtonPlaceholder(title: .error,
buttonTitle: .retryLoadMore,
tapHandler: reload)
emptyView = TextPlaceholderView(title: .empty)
}
func reload() {
viewModel.reload()
}
}
public extension GeneralDataLoadingController where Self: DisposeBagHolder {
func bindLoadingState() {
bindLoadingState(from: viewModel.loadingStateDriver)
}
}
| apache-2.0 |
KeisukeSoma/RSSreader | RSSReader/View6.swift | 1 | 3161 |
//
// View6.swift
// RSSReader
//
// Created by mikilab on 2015/06/19.
// Copyright (c) 2015年 susieyy. All rights reserved.
//
import UIKit
class View6: UITableViewController, MWFeedParserDelegate {
var items = [MWFeedItem]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
request()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func request() {
let URL = NSURL(string: "http://news.livedoor.com/topics/rss/eco.xml")
let feedParser = MWFeedParser(feedURL: URL);
feedParser.delegate = self
feedParser.parse()
}
func feedParserDidStart(parser: MWFeedParser) {
SVProgressHUD.show()
self.items = [MWFeedItem]()
}
func feedParserDidFinish(parser: MWFeedParser) {
SVProgressHUD.dismiss()
self.tableView.reloadData()
}
func feedParser(parser: MWFeedParser, didParseFeedInfo info: MWFeedInfo) {
print(info)
self.title = info.title
}
func feedParser(parser: MWFeedParser, didParseFeedItem item: MWFeedItem) {
print(item)
self.items.append(item)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "FeedCell")
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = self.items[indexPath.row] as MWFeedItem
let con = KINWebBrowserViewController()
let URL = NSURL(string: item.link)
con.loadURL(URL)
self.navigationController?.pushViewController(con, animated: true)
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let item = self.items[indexPath.row] as MWFeedItem
cell.textLabel?.text = item.title
cell.textLabel?.font = UIFont.systemFontOfSize(14.0)
cell.textLabel?.numberOfLines = 0
let projectURL = item.link.componentsSeparatedByString("?")[0]
let imgURL: NSURL? = NSURL(string: projectURL + "/cover_image?style=200x200#")
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
// cell.imageView?.setImageWithURL(imgURL, placeholderImage: UIImage(named: "logo.png"))
}
}
| mit |
xcbakery/xcbakery | Sources/CookingKit/Recipe/Model/Recipe.swift | 1 | 806 | //
// XCBRecipe.swift
// xcbakery
//
// Created by Nam Seok Hyeon on 5/19/17.
// Copyright © 2017 Nimbl3. All rights reserved.
//
import Foundation
import SwiftyJSON
public struct Recipe {
public let templateURL: URL
public let name: String
public let version: String
public let variableNames: [String]
public init?(json: JSON, templateURL: URL) {
guard let name = json[RecipeMappingKey.name].string else { return nil }
guard let version = json[RecipeMappingKey.version].string else { return nil }
guard let variableNames = json[RecipeMappingKey.variableNames].arrayObject as? [String] else { return nil }
self.templateURL = templateURL
self.name = name
self.version = version
self.variableNames = variableNames
}
}
| mit |
poolqf/FillableLoaders | Source/FillableLoader.swift | 1 | 12047 | //
// FillableLoader.swift
// PQFFillableLoaders
//
// Created by Pol Quintana on 25/7/15.
// Copyright (c) 2015 Pol Quintana. All rights reserved.
//
import UIKit
open class FillableLoader: UIView, CAAnimationDelegate {
internal var shapeLayer = CAShapeLayer()
internal var strokeLayer = CAShapeLayer()
internal var path: CGPath!
internal var loaderView = UIView()
internal var animate: Bool = false
internal var extraHeight: CGFloat = 0
internal var oldYPoint: CGFloat = 0
internal weak var loaderSuperview: UIView?
// MARK: Public Variables
/// Duration of the animation (Default: 10.0)
open var duration: TimeInterval = 10.0
/// Loader background height (Default: ScreenHeight/6 + 30)
open var rectSize: CGFloat = UIScreen.main.bounds.height/6 + 30
/// A Boolean value that determines whether the loader should have a swing effect while going up (Default: true)
open var swing: Bool = true
/// A Boolean value that determines whether the loader movement is progress based or not (Default: false)
open var progressBased: Bool = false
// MARK: Custom Getters and Setters
internal var _backgroundColor: UIColor?
internal var _loaderColor: UIColor?
internal var _loaderBackgroundColor: UIColor?
internal var _loaderStrokeColor: UIColor?
internal var _loaderStrokeWidth: CGFloat = 0.5
internal var _loaderAlpha: CGFloat = 1.0
internal var _cornerRadius: CGFloat = 0.0
internal var _progress: CGFloat = 0.0
internal var _mainBgColor: UIColor = UIColor(white: 0.2, alpha: 0.6)
/// Background color of the view holding the loader
open var mainBgColor: UIColor {
get { return _mainBgColor }
set {
_mainBgColor = newValue
super.backgroundColor = _mainBgColor
}
}
/// Loader view background color (Default: Clear)
override open var backgroundColor: UIColor? {
get { return _backgroundColor }
set {
super.backgroundColor = mainBgColor
_backgroundColor = newValue
loaderView.backgroundColor = newValue
loaderView.layer.backgroundColor = newValue?.cgColor
}
}
/// Filled loader color (Default: Blue)
open var loaderColor: UIColor? {
get { return _loaderColor }
set {
_loaderColor = newValue
shapeLayer.fillColor = newValue?.cgColor
}
}
/// Unfilled loader color (Default: White)
open var loaderBackgroundColor: UIColor? {
get { return _loaderBackgroundColor }
set {
_loaderBackgroundColor = newValue
strokeLayer.fillColor = newValue?.cgColor
}
}
/// Loader outline line color (Default: Black)
open var loaderStrokeColor: UIColor? {
get { return _loaderStrokeColor }
set {
_loaderStrokeColor = newValue
strokeLayer.strokeColor = newValue?.cgColor
}
}
/// Loader outline line width (Default: 0.5)
open var loaderStrokeWidth: CGFloat {
get { return _loaderStrokeWidth }
set {
_loaderStrokeWidth = newValue
strokeLayer.lineWidth = newValue
}
}
/// Loader view alpha (Default: 1.0)
open var loaderAlpha: CGFloat {
get { return _loaderAlpha }
set {
_loaderAlpha = newValue
loaderView.alpha = newValue
}
}
/// Loader view corner radius (Default: 0.0)
open var cornerRadius: CGFloat {
get { return _cornerRadius }
set {
_cornerRadius = newValue
loaderView.layer.cornerRadius = newValue
}
}
/// Loader fill progress from 0.0 to 1.0 . It will automatically fire an animation to update the loader fill progress (Default: 0.0)
open var progress: CGFloat {
get { return _progress }
set {
if (!progressBased || newValue > 1.0 || newValue < 0.0) { return }
_progress = newValue
applyProgress()
}
}
// MARK: Initializers Methods
/**
Creates and SHOWS a loader with the given path
:param: path Loader CGPath
:returns: The loader that's already being showed
*/
open static func showLoader(with path: CGPath, on view: UIView? = nil) -> Self {
let loader = createLoader(with: path, on: view)
loader.showLoader()
return loader
}
/**
Creates and SHOWS a progress based loader with the given path
:param: path Loader CGPath
:returns: The loader that's already being showed
*/
open static func showProgressBasedLoader(with path: CGPath, on view: UIView? = nil) -> Self {
let loader = createProgressBasedLoader(with: path, on: view)
loader.showLoader()
return loader
}
/**
Creates a loader with the given path
:param: path Loader CGPath
:returns: The created loader
*/
open static func createLoader(with path: CGPath, on view: UIView? = nil) -> Self {
let loader = self.init()
loader.initialSetup(on: view)
loader.add(path)
return loader
}
/**
Creates a progress based loader with the given path
:param: path Loader CGPath
:returns: The created loader
*/
open static func createProgressBasedLoader(with path: CGPath, on view: UIView? = nil) -> Self {
let loader = self.init()
loader.progressBased = true
loader.initialSetup(on: view)
loader.add(path)
return loader
}
internal func initialSetup(on view: UIView? = nil) {
//Setting up frame
var window = view
if view == nil, let mainWindow = UIApplication.shared.delegate?.window {
window = mainWindow
}
guard let w = window else { return }
self.frame = w.frame
self.center = CGPoint(x: w.bounds.midX, y: w.bounds.midY)
w.addSubview(self)
loaderSuperview = w
//Initial Values
defaultValues()
//Setting up loaderView
loaderView.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: rectSize)
loaderView.center = CGPoint(x: frame.width/2, y: frame.height/2)
loaderView.layer.cornerRadius = cornerRadius
//Add loader to its superview
self.addSubview(loaderView)
//Initially hidden
isHidden = true
}
internal func add(_ path: CGPath) {
let bounds = path.boundingBox
let center = bounds.origin
let height = bounds.height
let width = bounds.width
assert(height <= loaderView.frame.height, "The height(\(height)) of the path has to fit the dimensions (Height: \(loaderView.frame.height) Width: \(frame.width))")
assert(width <= loaderView.frame.width, "The width(\(width)) of the path has to fit the dimensions (Height: \(loaderView.frame.width) Width: \(frame.width))")
var transformation = CGAffineTransform(translationX: -center.x - width/2 + loaderView.frame.width/2, y: -center.y - height/2 + loaderView.frame.height/2)
self.path = path.copy(using: &transformation)!
}
// MARK: Prepare Loader
/**
Shows the loader.
Atention: do not use this method after creating a loader with `showLoaderWithPath(path:)`
*/
open func showLoader() {
alpha = 1.0
isHidden = false
animate = true
generateLoader()
startAnimating()
if superview == nil {
loaderSuperview?.addSubview(self)
}
}
/**
Stops loader animations and removes it from its superview
*/
open func removeLoader(_ animated: Bool = true) {
let completion: () -> () = {
self.isHidden = false
self.animate = false
self.removeFromSuperview()
self.layer.removeAllAnimations()
self.shapeLayer.removeAllAnimations()
}
guard animated else {
completion()
return
}
UIView.animateKeyframes(withDuration: 0.2,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.alpha = 0.0
}) { _ in
completion()
}
}
internal func layoutPath() {
let maskingLayer = CAShapeLayer()
maskingLayer.frame = loaderView.bounds
maskingLayer.path = path
strokeLayer = CAShapeLayer()
strokeLayer.frame = loaderView.bounds
strokeLayer.path = path
strokeLayer.strokeColor = loaderStrokeColor?.cgColor
strokeLayer.lineWidth = loaderStrokeWidth
strokeLayer.fillColor = loaderBackgroundColor?.cgColor
loaderView.layer.addSublayer(strokeLayer)
let baseLayer = CAShapeLayer()
baseLayer.frame = loaderView.bounds
baseLayer.mask = maskingLayer
shapeLayer.fillColor = loaderColor?.cgColor
shapeLayer.lineWidth = 0.2
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.frame = loaderView.bounds
oldYPoint = rectSize + extraHeight
shapeLayer.position = CGPoint(x: shapeLayer.position.x, y: oldYPoint)
loaderView.layer.addSublayer(baseLayer)
baseLayer.addSublayer(shapeLayer)
}
internal func defaultValues() {
duration = 10.0
backgroundColor = UIColor.clear
loaderColor = UIColor(red: 0.41, green: 0.728, blue: 0.892, alpha: 1.0)
loaderBackgroundColor = UIColor.white
loaderStrokeColor = UIColor.black
loaderStrokeWidth = 0.5
loaderAlpha = 1.0
cornerRadius = 0.0
}
//MARK: Animations
internal func startMoving(up: Bool) {
if (progressBased) { return }
let key = up ? "up" : "down"
let moveAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y")
moveAnimation.values = up ? [loaderView.frame.height/2 + rectSize/2, loaderView.frame.height/2 - rectSize/2 - extraHeight] : [loaderView.frame.height/2 - rectSize/2 - extraHeight, loaderView.frame.height/2 + rectSize/2]
moveAnimation.duration = duration
moveAnimation.isRemovedOnCompletion = false
moveAnimation.fillMode = kCAFillModeForwards
moveAnimation.delegate = self
moveAnimation.setValue(key, forKey: "animation")
shapeLayer.add(moveAnimation, forKey: key)
}
internal func applyProgress() {
let yPoint = (rectSize + extraHeight)*(1-progress)
let progressAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y")
progressAnimation.values = [oldYPoint, yPoint]
progressAnimation.duration = 0.2
progressAnimation.isRemovedOnCompletion = false
progressAnimation.fillMode = kCAFillModeForwards
shapeLayer.add(progressAnimation, forKey: "progress")
oldYPoint = yPoint
}
internal func startswinging() {
let swingAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
swingAnimation.values = [0, randomAngle(), -randomAngle(), randomAngle(), -randomAngle(), randomAngle(), 0]
swingAnimation.duration = 12.0
swingAnimation.isRemovedOnCompletion = false
swingAnimation.fillMode = kCAFillModeForwards
swingAnimation.delegate = self
swingAnimation.setValue("rotation", forKey: "animation")
shapeLayer.add(swingAnimation, forKey: "rotation")
}
internal func randomAngle() -> Double {
return M_PI_4/(Double(arc4random_uniform(16)) + 8)
}
//MARK: Abstract methods
internal func generateLoader() {
preconditionFailure("Call this method from the desired FillableLoader type class")
}
internal func startAnimating() {
preconditionFailure("Call this method from the desired FillableLoader type class")
}
}
| mit |
uasys/swift | test/SILGen/objc_bridged_using_protocol_extension_impl.swift | 1 | 1685 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
protocol Fooable {}
extension Fooable where Self: _ObjectiveCBridgeable {
func _bridgeToObjectiveC() -> _ObjectiveCType {
fatalError()
}
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) {
fatalError()
}
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool {
fatalError()
}
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
fatalError()
}
}
struct Foo: Fooable, _ObjectiveCBridgeable {
typealias _ObjectiveCType = NSObject
}
struct Gen<T, U>: Fooable, _ObjectiveCBridgeable {
typealias _ObjectiveCType = NSObject
}
class Bar: NSObject {
dynamic func bar(_: Any) {}
}
// CHECK-LABEL: sil hidden @_T042objc_bridged_using_protocol_extension_impl7callBaryAA0H0C3bar_AA3FooV3footF
func callBar(bar: Bar, foo: Foo) {
// CHECK: [[BRIDGE:%.*]] = function_ref @_T042objc_bridged_using_protocol_extension_impl7FooablePAAs21_ObjectiveCBridgeableRzAaBRzlE09_bridgeToH1C01_H5CTypesADPQzyF
// CHECK: apply [[BRIDGE]]<Foo>
bar.bar(foo)
}
// CHECK-LABEL:sil hidden @_T042objc_bridged_using_protocol_extension_impl7callBaryAA0H0C3bar_AA3GenVySiSSG3gentF
func callBar(bar: Bar, gen: Gen<Int, String>) {
// CHECK: [[BRIDGE:%.*]] = function_ref @_T042objc_bridged_using_protocol_extension_impl7FooablePAAs21_ObjectiveCBridgeableRzAaBRzlE09_bridgeToH1C01_H5CTypesADPQzyF
// CHECK: apply [[BRIDGE]]<Gen<Int, String>>
bar.bar(gen)
}
| apache-2.0 |
Navarjun/NA-iOS-Utils | NSDate-ext.swift | 1 | 579 | //
// NSDate-ext.swift
//
// Created by Navarjun on 5/27/15.
//
import Foundation
extension NSDate {
func isLaterThan(date: NSDate) -> Bool {
if compare(date) == .OrderedDescending {
return true
}
return false
}
func isEqualTo(date: NSDate) -> Bool {
if compare(date) == .OrderedSame {
return true
}
return false
}
func isEarlierThan(date: NSDate) -> Bool {
if compare(date) == .OrderedAscending {
return true
}
return false
}
} | gpl-3.0 |
zenonas/barmaid | Barmaid/Homebrew.swift | 1 | 1378 | //
// BrewServices.swift
// Barmaid
//
// Created by Zen Kyprianou on 14/07/2014.
// Copyright (c) 2014 Zen Kyprianou. All rights reserved.
//
import Cocoa
class Homebrew {
var task: NSTask!
var pipe: NSPipe!
var file: NSFileHandle!
var services: NSMutableArray!
init() {
self.findServices()
}
func findServices() {
self.services = NSMutableArray()
self.task = NSTask()
self.task.launchPath = "/bin/bash"
self.pipe = NSPipe()
self.file = NSFileHandle()
self.task.standardOutput = self.pipe
self.file = self.pipe.fileHandleForReading
self.task.arguments = ["-c", "/usr/bin/find -L /usr/local/opt -type f -name 'homebrew*.plist'"]
self.task.launch()
self.task.waitUntilExit()
var data = NSData()
data = self.file.readDataToEndOfFile()
var stringResult = NSString(data: data, encoding: NSUTF8StringEncoding) as String
var allPaths = stringResult.componentsSeparatedByString("\n")
for service in allPaths {
if (service != "") {
var key = service.componentsSeparatedByString("/")[4].capitalizedString
var newService = Service(name: key, path: service)
self.services.addObject(newService)
}
}
}
} | mit |
DroidsOnRoids/MazeSpriteKit | Maze/GameViewController.swift | 1 | 2043 | /*
* Copyright (c) 2015 Droids on Roids 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 SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFit
skView.presentScene(scene)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit |
shopgun/shopgun-ios-sdk | Sources/TjekEventsTracker/EventHandling/Event+TjekEventsTrackerContext.swift | 1 | 459 | ///
/// Copyright (c) 2018 Tjek. All rights reserved.
///
import Foundation
extension Event {
func addingContext(_ context: TjekEventsTracker.Context) -> Event {
var event = self
// add geohash & timestamp (if available)
if let location = context.location {
event = event.addingLocation(geohash: location.geohash, timestamp: location.timestamp)
}
return event
}
}
| mit |
iosprogrammingwithswift/iosprogrammingwithswift | 04_Swift2015_Final.playground/Pages/03_Strings And Characters.xcplaygroundpage/Contents.swift | 1 | 3434 | //: [Previous](@previous) | [Next](@next)
//: Fun Fact: Swift’s String type is bridged with Foundation’s NSString class. If you are working with the Foundation framework in Cocoa, the entire NSString API is available to call on any String value you create when type cast to NSString, as described in AnyObject. You can also use a String value with any API that requires an NSString instance.
//: String Literals
let someString = "Some string literal value"
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// these two strings are both empty, and are equivalent to each other
if emptyString.isEmpty {
print("Nothing to see here")
}
var variableString = "Horse"
variableString += " and carriage"
// variableString is now "Horse and carriage"
let constantString = "Highlander"
//constantString += " and another Highlander"
// this reports a compile-time error - a constant string cannot be modified
//: Strings Are Value Types
for character in "Dog!🐶".characters {
print(character)
}
//: String Interpolation
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
//: Counting Characters
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
// prints "unusualMenagerie has 40 characters"
//: Character access
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G
greeting[greeting.endIndex.predecessor()]
// !
greeting[greeting.startIndex.successor()]
// u
let index = greeting.startIndex.advancedBy(7)
greeting[index]
// a
//: Comparing Strings
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
print("These two strings are considered equal")
}
// prints "These two strings are considered equal"
//: Prefix and Suffix Equality
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
print("There are \(act1SceneCount) scenes in Act 1")
var mansionCount = 0
var cellCount = 0
for scene in romeoAndJuliet {
if scene.hasSuffix("Capulet's mansion") {
++mansionCount
} else if scene.hasSuffix("Friar Lawrence's cell") {
++cellCount
}
}
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
/*:
largely Based of [Apple's Swift Language Guide: Strings And Characters](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-ID285 ) & [Apple's A Swift Tour](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1 )
*/
//: [Previous](@previous) | [Next](@next)
| mit |
NGeenLibraries/NGeen | Example/App/Model/Story/Story.swift | 1 | 1216 | //
// Story.swift
// Copyright (c) 2014 NGeen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class Story: Base {
//MARK: Constructor
required init() {}
}
| mit |
asurinsaka/swift_examples_2.1 | LocateMe/LocateMe/TrackViewController.swift | 1 | 6293 | //
// TrackViewController.swift
// LocateMe
//
// Created by doudou on 8/17/14.
// Copyright (c) 2014 larryhou. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
class TrackViewController:UITableViewController, SetupSettingReceiver, CLLocationManagerDelegate
{
enum TrackStatus:String
{
case Tracking = "Tracking"
case Acquired = "Acquired Location"
case Error = "Error"
}
enum SectionType:Int
{
case TrackStatus
case Property
case Measurements
}
enum CellIdentifier:String
{
case Status = "StatusCell"
case Measurement = "MeasurementCell"
case Property = "PropertyCell"
}
private var measurements:[CLLocation]!
private var location:CLLocation!
private var status:TrackStatus!
private var dateFormatter:NSDateFormatter!
private var locationManager:CLLocationManager!
private var setting:LocateSettingInfo!
func setupSetting(setting: LocateSettingInfo)
{
self.setting = setting
}
override func viewDidLoad()
{
measurements = []
locationManager = CLLocationManager()
dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = localizeString("DateFormat")
}
override func viewWillDisappear(animated: Bool)
{
stopTrackLocation()
}
override func viewWillAppear(animated: Bool)
{
print(setting)
startTrackLocation()
}
@IBAction func refresh(sender: UIBarButtonItem)
{
startTrackLocation()
}
//MARK: 定位相关
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation)
{
measurements.insert(newLocation, atIndex: 0)
location = newLocation
if location.horizontalAccuracy <= setting.accuracy
{
status = .Acquired
navigationItem.rightBarButtonItem!.enabled = true
stopTrackLocation()
}
tableView.reloadData()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
status = .Error
navigationItem.rightBarButtonItem!.enabled = true
tableView.reloadData()
}
func startTrackLocation()
{
status = .Tracking
navigationItem.rightBarButtonItem!.enabled = false
tableView.reloadData()
locationManager.delegate = self
locationManager.desiredAccuracy = setting.accuracy
locationManager.distanceFilter = CLLocationDistance(setting.sliderValue)
if CLLocationManager.authorizationStatus() != .AuthorizedWhenInUse
{
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
}
func stopTrackLocation()
{
locationManager.stopUpdatingLocation()
locationManager.delegate = nil
}
//MARK: 列表相关
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 3
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
switch SectionType(rawValue: indexPath.section)!
{
case .TrackStatus:return 44.0
default:return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
switch SectionType(rawValue: section)!
{
case .TrackStatus:return 1
case .Property:return 4
case .Measurements:return measurements.count
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
switch SectionType(rawValue: section)!
{
case .TrackStatus:return localizeString("Status")
case .Property:return localizeString("RTStats")
case .Measurements:return localizeString("All Measurements")
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch SectionType(rawValue: indexPath.section)!
{
case .TrackStatus:
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Status.rawValue) as! TrackStatusTableViewCell
cell.label.text = localizeString(status.rawValue)
if status == .Tracking
{
if !cell.indicator.isAnimating()
{
cell.indicator.startAnimating()
}
}
else
{
if cell.indicator.isAnimating()
{
cell.indicator.stopAnimating()
}
}
return cell
case .Property:
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Property.rawValue)! as UITableViewCell
switch indexPath.row
{
case 0:
cell.textLabel!.text = localizeString("accuracy")
cell.detailTextLabel!.text = location != nil ? location.getHorizontalAccuracyString() : "-"
case 1:
cell.textLabel!.text = localizeString("course")
cell.detailTextLabel!.text = location != nil ? location.getCourseString() : "-"
case 2:
cell.textLabel!.text = localizeString("speed")
cell.detailTextLabel!.text = location != nil ? location.getSpeedString() : "-"
case 3: fallthrough default:
cell.textLabel!.text = localizeString("time")
cell.detailTextLabel!.text = location != nil ? dateFormatter.stringFromDate(location.timestamp) : "-"
}
return cell
case .Measurements:
let location:CLLocation = measurements[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.Measurement.rawValue)! as UITableViewCell
cell.textLabel!.text = location.getCoordinateString()
cell.detailTextLabel!.text = dateFormatter.stringFromDate(location.timestamp)
return cell
}
}
//MARK: 数据透传
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "LocationDetailSegue"
{
let indexPath = tableView.indexPathForCell(sender as! UITableViewCell)
let destinationCtrl = segue.destinationViewController as! LocationDetailViewController
destinationCtrl.location = measurements[indexPath!.row]
}
}
}
| mit |
Brightify/ReactantUI | Tests/ReactantUI/TestLiveUIConfiguration.swift | 1 | 611 | //
// TestLiveUIConfiguration.swift
// LiveUI-iOSTests
//
// Created by Matyáš Kříž on 06/08/2018.
//
import ReactantLiveUI
import UIKit
struct TestLiveUIConfiguration: ReactantLiveUIConfiguration {
var applicationDescriptionPath: String? = ProcessInfo.processInfo.environment["applicationDescriptionPath"]
var rootDir = ProcessInfo.processInfo.environment["rootDir"] ?? ""
var resourceBundle = Bundle()
var commonStylePaths: [String] = [
ProcessInfo.processInfo.environment["commonStylesPath"]
].compactMap { $0 }
var componentTypes: [String: UIView.Type] = [:]
}
| mit |
PauuloG/app-native-ios | film-quizz/Classes/ViewControllers/ViewController.swift | 1 | 2067 | //
// ViewController.swift
// film-quizz
//
// Created by Paul Gabriel on 06/06/16.
// Copyright © 2016 Paul Gabriel. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var PlayButton: UIButton!
@IBOutlet weak var SuccessButton: UIButton!
let launchedBefore = NSUserDefaults.standardUserDefaults().boolForKey("launchedBefore")
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
if self.launchedBefore {
UserManager.retrieveUser()
}
else {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "launchedBefore")
UserManager.createUser()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red:0.19, green:0.18, blue:0.22, alpha:1.0)
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
PlayButton.layer.cornerRadius = 20
PlayButton.layer.backgroundColor = UIColor(red:0.93, green:0.46, blue:0.40, alpha:1.0).CGColor
SuccessButton.layer.cornerRadius = 20
SuccessButton.layer.backgroundColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0).CGColor
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem // This will show in the next view controller being pushed
}
}
| mit |
joemcbride/outlander-osx | src/Outlander/CharacterStatusViewController.swift | 1 | 307 | //
// CharacterStatusViewController.swift
// Outlander
//
// Created by Joseph McBride on 6/9/15.
// Copyright (c) 2015 Joe McBride. All rights reserved.
//
import Cocoa
class CharacterStatusViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit |
GabrielAraujo/VaporMongo | Sources/App/Resp.swift | 1 | 1205 | //
// Resp.swift
// VaporMongo
//
// Created by Gabriel Araujo on 07/11/16.
//
//
import Foundation
import Vapor
import HTTP
struct Resp : ResponseRepresentable {
let success: Bool
let error: Int?
let message: String
let data: Node?
init(success:Bool, error:Int?, message:String, data:Node?) {
self.success = success
self.error = error
self.message = message
self.data = data
}
//Success
init(data:Node) {
self.success = true
self.error = nil
self.message = "Success!"
self.data = data
}
init(message:String) {
self.success = true
self.error = nil
self.message = message
self.data = nil
}
//Error
init(error:Errors) {
self.success = false
self.error = error.getId()
self.message = error.getMessage()
self.data = nil
}
func makeResponse() throws -> Response {
let json = try JSON(node:
[
"success": success,
"error": error,
"message": message,
"data": data
]
)
return try json.makeResponse()
}
}
| mit |
pikacode/EBBannerView | EBBannerView/SwiftClasses/EBBannerWindow.swift | 1 | 2838 | //
// EBBannerWindow.swift
// EBBannerViewSwift
//
// Created by pikacode on 2020/1/2.
//
import UIKit
class EBBannerWindow: UIWindow {
@available(iOS 13.0, *)
public override init(windowScene: UIWindowScene){
super.init(windowScene: windowScene)
}
static let shared: EBBannerWindow = {
var window: EBBannerWindow
if #available(iOS 13.0, *) {
window = EBBannerWindow(windowScene: UIApplication.shared.keyWindow!.windowScene!)
} else {
window = EBBannerWindow(frame: .zero)
}
window.windowLevel = .alert
window.layer.masksToBounds = false
let keyWindow = UIApplication.shared.keyWindow
window.makeKeyAndVisible()
/* fix bug:
EBBannerViewController setSupportedInterfaceOrientations -> Portrait
push to a VC with orientation Left
UITextFiled's pad will show a wrong orientation with Portrait
*/
EBEmptyWindow.shared.makeKeyAndVisible()
keyWindow?.makeKeyAndVisible()
EBBannerController.setSupportedInterfaceOrientations(value: [.portrait, .landscape])
EBBannerController.setStatusBarHidden(hidden: false)
let vc = EBBannerController()
vc.view.backgroundColor = .clear
let size = UIScreen.main.bounds.size
vc.view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
window.rootViewController = vc
return window
}()
override init(frame: CGRect) {
super.init(frame: frame)
addObserver(self, forKeyPath: "frame", options: [.new, .old], context: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
if #available(iOS 13.0, *) {
print("")
} else {
removeObserver(self, forKeyPath: "frame")
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "frame" && !frame.equalTo(.zero) {
frame = .zero
}
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
var view: UIView?
for v in rootViewController?.view.subviews ?? [UIView]() {
if v.frame.contains(point) {
view = v
break
}
}
if view == nil {
if #available(iOS 13.0, *) {
return UIApplication.shared.keyWindow?.hitTest(point, with: event)
} else {
return super.hitTest(point, with: event)
}
} else {
let p = convert(point, to: view)
return view?.hitTest(p, with: event)
}
}
}
| mit |
JBerkvens/SmartMobile-iOS-2016 | Practica/HellGlow World (appcoda)/HellGlow World (appcoda)/ViewController.swift | 1 | 944 | //
// ViewController.swift
// HellGlow World (appcoda)
//
// Created by Jeroen Berkvens on 10/03/16.
// Copyright © 2016 Fontys Universities. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showMessage(sender: AnyObject) {
let alertController = UIAlertController(title: "Welcome to My Second App", message: "HellGlow World", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| gpl-3.0 |
wavecos/curso_ios_3 | QuakeRadar/QuakeRadar/AppDelegate.swift | 1 | 2073 | //
// AppDelegate.swift
// QuakeRadar
//
// Created by onix on 11/22/14.
// Copyright (c) 2014 tekhne. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 |
HTWDD/HTWDresden-iOS | HTWDD/Core/Extensions/NSObject+Rx.swift | 1 | 1621 | // from https://github.com/RxSwiftCommunity/NSObject-Rx -> don't want to import in every file a module for this
import Foundation
import RxSwift
import ObjectiveC
import RealmSwift
extension Reactive where Base: NSObject {
}
public extension NSObject {
private struct AssociatedKeys {
static var DisposeBag = "rx_disposeBag"
}
private func doLocked(closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
var rx_disposeBag: DisposeBag {
get {
var disposeBag: DisposeBag!
doLocked {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag
if let lookup = lookup {
disposeBag = lookup
} else {
let newDisposeBag = DisposeBag()
self.rx_disposeBag = newDisposeBag
disposeBag = newDisposeBag
}
}
return disposeBag
}
set {
doLocked {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
protocol ScopeFunc {}
extension ScopeFunc {
@inline(__always) func apply(block: (Self) -> ()) {
block(self)
}
@inline(__always) func also(block: (Self) -> ()) -> Self {
block(self)
return self
}
@inline(__always) func with<R>(block: (Self) -> R) -> R {
return block(self)
}
}
extension NSObject: ScopeFunc {}
| gpl-2.0 |
cbot/Silk | Classes/Request.swift | 1 | 2001 | import Foundation
public class Request: Equatable {
public typealias SuccessClosure = ((_ body: String, _ data: Data, _ response: HTTPURLResponse, _ request: Request)->())?
public typealias ErrorClosure = ((_ error: NSError, _ body: String, _ data: Data, _ response: HTTPURLResponse?, _ request: Request)->())?
var manager: SilkManager
internal(set) var successClosure: SuccessClosure
internal(set) var errorClosure: ErrorClosure
private(set) var tag: String = UUID().uuidString
private(set) var group = "Requests"
public var compoundContext = [String: AnyObject]()
func context(_ context: [String: AnyObject]) -> Self {
compoundContext = context
return self
}
init(manager: SilkManager) {
self.manager = manager
}
@discardableResult
public func tag(_ requestTag: String) -> Self {
tag = requestTag
return self
}
@discardableResult
public func group(_ requestGroup: String) -> Self {
group = requestGroup
return self
}
@discardableResult
public func completion(_ success: SuccessClosure, error: ErrorClosure) -> Self {
successClosure = success
errorClosure = error
return self
}
@discardableResult
public func execute() -> Bool {
// empty implementation, for subclasses to override
return true
}
public func cancel() {
manager.unregisterRequest(self)
// empty implementation, for subclasses to override
}
func appendResponseData(_ data: Data, task: URLSessionTask) {
// empty implementation, for subclasses to override
}
func handleResponse(_ response: HTTPURLResponse, error: NSError?, task: URLSessionTask) {
// empty implementation, for subclasses to override
}
}
// MARK: - Equatable
public func ==(lhs: Request, rhs: Request) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
| mit |
cpoutfitters/cpoutfitters | CPOutfitters/Event.swift | 1 | 1279 | //
// Event.swift
// CPOutfitters
//
// Created by Aditya Purandare on 11/03/16.
// Copyright © 2016 SnazzyLLama. All rights reserved.
//
import UIKit
import Parse
class Event: PFObject {
var host: PFUser?
var details: String?
var date: NSDate?
var title: String?
var invited: [PFUser]?
var attending: [PFUser]?
var notAttending: [PFUser]?
var outfits: [PFUser: Outfit]?
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
static func parseClassName() -> String {
return "Event"
}
override init() {
super.init()
}
init(object: PFObject) {
super.init()
self.host = object["host"] as? PFUser
self.details = object["details"] as? String
self.date = object["date"] as? NSDate
self.title = object["title"] as? String
self.invited = object["invited"] as? [PFUser]
self.attending = object["attending"] as? [PFUser]
self.notAttending = object["not_attending"] as? [PFUser]
self.outfits = object["outfit"] as? [PFUser: Outfit]
}
}
| apache-2.0 |
steveholt55/metro | iOS/MetroTransit/Controller/Route/RoutesViewController.swift | 1 | 3953 | //
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import UIKit
import Alamofire
class RoutesViewController: UIViewController, RoutesViewModelListener {
@IBOutlet weak var tableview: UITableView!
var viewModel: RoutesViewModel!
//test
let httpClient = HTTPClient()
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel = RoutesViewModel(listener: self)
if !AppDelegate.isTesting() { // Needed to make mock server work for testing
self.viewModel.getRoutes()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let selectedIndexPath = tableview.indexPathForSelectedRow {
tableview.deselectRowAtIndexPath(selectedIndexPath, animated: true)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == DirectionsViewController.segue {
let viewController = segue.destinationViewController as! DirectionsViewController
viewController.viewModel = DirectionsViewModel(listener: viewController, route: self.viewModel.displayRoutes[tableview.indexPathForSelectedRow!.row])
} else if segue.identifier == VehiclesViewController.segue {
let viewController = segue.destinationViewController as! VehiclesViewController
let route = self.viewModel.displayRoutes[tableview.indexPathForSelectedRow!.row]
let vehicles = self.viewModel.vehicles
viewController.viewModel = VehiclesViewModel(listener: viewController, route: route, vehicles: vehicles)
}
}
static func getViewController() -> RoutesViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(String(RoutesViewController)) as! RoutesViewController
}
// MARK : - Screen
func showScreenPicker() {
let route = self.viewModel.displayRoutes[tableview.indexPathForSelectedRow!.row]
let controller = UIAlertController(title: route.name, message: nil, preferredStyle: .ActionSheet)
let directionsAction = UIAlertAction(title: "Directions", style: .Default, handler: { (action: UIAlertAction) -> Void in
self.performSegueWithIdentifier(DirectionsViewController.segue, sender: self)
})
let vehiclesAction = UIAlertAction(title: "Vehicles", style: .Default, handler: { (action: UIAlertAction) -> Void in
VehicleLocation.get(route, complete: { (vehicles) -> Void in
self.viewModel.vehicles = vehicles
if (vehicles.count > 0) {
self.performSegueWithIdentifier(VehiclesViewController.segue, sender: self)
} else {
self.alertNoVehicles(route)
}
})
})
controller.addAction(directionsAction)
controller.addAction(vehiclesAction)
controller.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction) -> Void in
if let selectedIndexPath = self.tableview.indexPathForSelectedRow {
self.tableview.deselectRowAtIndexPath(selectedIndexPath, animated: true)
}
}))
self.presentViewController(controller, animated: true, completion:nil)
}
func alertNoVehicles(route: Route) {
let title = route.name!
let message = "There are currently no active vehicles for this route."
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// MARK: - Routes view
func reload() {
self.tableview.reloadData()
}
} | mit |
yume190/JSONDecodeKit | Sources/JSONDecodeKit/JSON/JSON+Dictionary+ValueArray.swift | 1 | 1247 | //
// JSON+DictionaryArray.swift
// JSONDecodeKit
//
// Created by Yume on 2017/11/20.
// Copyright © 2017年 Yume. All rights reserved.
//
import Foundation
// MARK: Get [Key:[Value]]
extension JSON {
public func dictionaryValueArray<Key,Value:JSONDecodable>() -> [Key:[Value]] {
return toDictionaryValueArray(json: self) { (any:Any) -> [Value] in
(try? JSON(any: any).array()) ?? []
}
}
public func dictionaryValueArray<Key,Value:RawRepresentable>() -> [Key:[Value]] where Value.RawValue: PrimitiveType {
return toDictionaryValueArray(json: self) { (any:Any) -> [Value] in
JSON(any: any).array()
}
}
}
private func toDictionaryValueArray<Key,Value>(json: JSON, valueTransform:(Any) -> [Value]) -> [Key:[Value]] {
guard let dic = json.data as? NSDictionary else {
return [Key:[Value]]()
}
return dic.reduce([Key:[Value]]()) { (result:[Key:[Value]], set:(key: Any, value: Any)) -> [Key:[Value]] in
guard let key = set.key as? Key else {
return result
}
let values = valueTransform(set.value)
var result = result
result[key] = values
return result
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/01295-getselftypeforcontainer.swift | 11 | 479 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class A {
private let a = [B<(AnyObject, AnC) {
self.c = c
}
}
protocol c : b { func b
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/01084-getselftypeforcontainer.swift | 11 | 438 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
func a<i>() {
b b {
}
protocol f : b { func b
| apache-2.0 |
brentsimmons/Evergreen | Mac/Preferences/ExtensionPoints/ExtensionPointMarsEditWindowController.swift | 1 | 949 | //
// ExtensionPointMarsEditWindowController.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Cocoa
class ExtensionPointEnableMarsEditWindowController: NSWindowController {
private weak var hostWindow: NSWindow?
convenience init() {
self.init(windowNibName: NSNib.Name("ExtensionPointMarsEdit"))
}
override func windowDidLoad() {
super.windowDidLoad()
}
// MARK: API
func runSheetOnWindow(_ hostWindow: NSWindow) {
self.hostWindow = hostWindow
hostWindow.beginSheet(window!)
}
// MARK: Actions
@IBAction func cancel(_ sender: Any) {
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel)
}
@IBAction func enable(_ sender: Any) {
ExtensionPointManager.shared.activateExtensionPoint(ExtensionPointIdentifer.marsEdit)
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.OK)
}
}
| mit |
JakeLin/IBAnimatable | IBAnimatableApp/IBAnimatableApp/Playground/Utils/ParamType.swift | 2 | 3169 | //
// Created by jason akakpo on 27/07/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import Foundation
import UIKit
extension String {
/// Returns `NSAttributedString` with specified color.
func colorize(_ color: UIColor) -> NSAttributedString {
return NSAttributedString(string: self, attributes: [.foregroundColor: color])
}
}
extension Array {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript(safe index: Int) -> Element? {
return indices.contains(index) ? self[index] : nil /// Returns the element at the specified index iff it is within bounds, otherwise nil.
}
}
enum ParamType {
case number(min: Double, max: Double, interval: Double, ascending: Bool, unit: String)
case enumeration(values: [String])
#if swift(>=4.2)
init<T: RawRepresentable>(fromEnum: T.Type) where T: CaseIterable {
let iterator = iterateEnum(fromEnum)
let values = iterator.map { String(describing: $0.rawValue) }
self = .enumeration(values: values)
}
#else
init<T: RawRepresentable>(fromEnum: T.Type) where T: Hashable {
let iterator = iterateEnum(fromEnum)
let values = iterator.map { String(describing: $0.rawValue) }
self = .enumeration(values: values)
}
#endif
/// Number of different values to show in the picker
func count() -> Int {
switch self {
case let .number(min, max, interval, _, _):
return Int(ceil((max - min) / interval) + 1)
case .enumeration(let val):
return val.count
}
}
/// Number at Index, use just for number case.
func value(at index: Int) -> String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 3
switch self {
case let .number(min, _, interval, ascending, _) where ascending == true:
return formatter.string(from: NSNumber(value: min + Double(index) * interval))!
case let .number(_, max, interval, _, _):
return formatter.string(from: NSNumber(value: max - Double(index) * interval))!
case let .enumeration(values):
return values[safe: index] ?? ""
}
}
func title(at index: Int) -> String {
switch self {
case .enumeration:
return value(at: index)
case let .number(_, _, _, _, unit):
return ("\(value(at: index)) \(unit)").trimmingCharacters(in: CharacterSet.whitespaces)
}
}
var reversed: ParamType {
switch self {
case .number(let min, let max, let interval, let ascending, let unit):
return .number(min: min, max: max, interval: interval, ascending: !ascending, unit: unit)
case .enumeration(let values):
return .enumeration(values: values.reversed())
}
}
}
struct PickerEntry {
let params: [ParamType]
let name: String
}
extension PickerEntry {
/// Convert the entry to a `AnimationType` string
func toString(selectedIndexes indexes: Int?...) -> String {
let paramString = indexes.enumerated().compactMap({ (val: (Int, Int?)) -> String? in let (i, index) = val
return params[safe:i]?.value(at: index ?? 0)
}).joined(separator: ",")
return "\(name)(\(paramString))"
}
}
| mit |
AckeeCZ/ACKategories | ACKategoriesExample/Screens/VC composition/VCCompositionViewController.swift | 1 | 1226 | //
// VCCompositionViewController.swift
// ACKategories
//
// Created by Jakub Olejník on 12/09/2018.
// Copyright © 2018 Ackee, s.r.o. All rights reserved.
//
import UIKit
final class VCCompositionViewController: TitleViewController {
// MARK: Initializers
init() {
super.init(name: "Parent", color: .lightGray)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View life cycle
override func loadView() {
super.loadView()
let containerView = UIView()
view.addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
containerView.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 30),
containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
let childVC = TitleViewController(name: "Child", color: .blue)
display(childViewController: childVC, in: containerView)
}
}
| mit |
gerardogrisolini/Webretail | Sources/Webretail/Models/TagValue.swift | 1 | 2936 | //
// TagValue.swift
// Webretail
//
// Created by Gerardo Grisolini on 07/11/17.
//
import Foundation
import StORM
class TagValue: PostgresSqlORM, Codable {
public var tagValueId : Int = 0
public var tagGroupId : Int = 0
public var tagValueCode : String = ""
public var tagValueName : String = ""
public var tagValueTranslates: [Translation] = [Translation]()
public var tagValueCreated : Int = Int.now()
public var tagValueUpdated : Int = Int.now()
private enum CodingKeys: String, CodingKey {
case tagValueId
case tagGroupId
case tagValueCode
case tagValueName
case tagValueTranslates = "translations"
}
open override func table() -> String { return "tagvalues" }
open override func tableIndexes() -> [String] { return ["tagValueCode"] }
open override func to(_ this: StORMRow) {
tagValueId = this.data["tagvalueid"] as? Int ?? 0
tagGroupId = this.data["taggroupid"] as? Int ?? 0
tagValueCode = this.data["tagvaluecode"] as? String ?? ""
tagValueName = this.data["tagvaluename"] as? String ?? ""
if let translates = this.data["tagvaluetranslates"] as? [String:Any] {
let jsonData = try! JSONSerialization.data(withJSONObject: translates, options: [])
tagValueTranslates = try! JSONDecoder().decode([Translation].self, from: jsonData)
}
tagValueCreated = this.data["tagvaluecreated"] as? Int ?? 0
tagValueUpdated = this.data["tagvalueupdated"] as? Int ?? 0
}
func rows() -> [TagValue] {
var rows = [TagValue]()
for i in 0..<self.results.rows.count {
let row = TagValue()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
override init() {
super.init()
}
required init(from decoder: Decoder) throws {
super.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
tagValueId = try container.decode(Int.self, forKey: .tagValueId)
tagGroupId = try container.decode(Int.self, forKey: .tagGroupId)
tagValueCode = try container.decode(String.self, forKey: .tagValueCode)
tagValueName = try container.decode(String.self, forKey: .tagValueName)
tagValueTranslates = try container.decodeIfPresent([Translation].self, forKey: .tagValueTranslates) ?? [Translation]()
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(tagValueId, forKey: .tagValueId)
try container.encode(tagGroupId, forKey: .tagGroupId)
try container.encode(tagValueCode, forKey: .tagValueCode)
try container.encode(tagValueName, forKey: .tagValueName)
try container.encode(tagValueTranslates, forKey: .tagValueTranslates)
}
}
| apache-2.0 |
russbishop/swift | test/DebugInfo/patternmatching.swift | 1 | 3046 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o %t.ll
// RUN: FileCheck %s < %t.ll
// RUN: FileCheck --check-prefix=CHECK-SCOPES %s < %t.ll
// RUN: %target-swift-frontend -emit-sil -emit-verbose-sil -primary-file %s -o - | FileCheck %s --check-prefix=SIL-CHECK
func markUsed<T>(_ t: T) {}
func classifyPoint2(_ p: (Double, Double)) {
func return_same (_ input : Double) -> Double
{
return input; // return_same gets called in both where statements
}
switch p {
case (let x, let y) where
// CHECK: call double {{.*}}return_same{{.*}}, !dbg ![[LOC1:.*]]
// CHECK: br {{.*}}, label {{.*}}, label {{.*}}, !dbg ![[LOC2:.*]]
// CHECK: call{{.*}}markUsed{{.*}}, !dbg ![[LOC3:.*]]
// CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+2]],
// CHECK: ![[LOC2]] = !DILocation(line: [[@LINE+1]],
return_same(x) == return_same(y):
// CHECK: ![[LOC3]] = !DILocation(line: [[@LINE+1]],
markUsed(x)
// SIL-CHECK: dealloc_stack{{.*}}line:[[@LINE-1]]:17:cleanup
// Verify that the branch has a location >= the cleanup.
// SIL-CHECK-NEXT: br{{.*}}line:[[@LINE-3]]:17:cleanup
// CHECK-SCOPES: call {{.*}}markUsed
// CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X1:[0-9]+]],
// CHECK-SCOPES-SAME: !dbg ![[X1LOC:[0-9]+]]
// CHECK-SCOPES: call void @llvm.dbg
// CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X2:[0-9]+]],
// CHECK-SCOPES-SAME: !dbg ![[X2LOC:[0-9]+]]
// CHECK-SCOPES: call void @llvm.dbg
// CHECK-SCOPES: call void @llvm.dbg{{.*}}metadata ![[X3:[0-9]+]],
// CHECK-SCOPES-SAME: !dbg ![[X3LOC:[0-9]+]]
// CHECK-SCOPES: !DILocalVariable(name: "x",
case (let x, let y) where x == -y:
// Verify that all variables end up in separate appropriate scopes.
// CHECK-SCOPES: !DILocalVariable(name: "x", scope: ![[SCOPE1:[0-9]+]],
// CHECK-SCOPES-SAME: line: [[@LINE-3]]
// CHECK-SCOPES: ![[X1LOC]] = !DILocation(line: [[@LINE-4]], column: 15,
// CHECK-SCOPES-SAME: scope: ![[SCOPE1]])
// FIXME: ![[SCOPE1]] = distinct !DILexicalBlock({{.*}}line: [[@LINE-6]]
markUsed(x)
case (let x, let y) where x >= -10 && x < 10 && y >= -10 && y < 10:
// CHECK-SCOPES: !DILocalVariable(name: "x", scope: ![[SCOPE2:[0-9]+]],
// CHECK-SCOPES-SAME: line: [[@LINE-2]]
// CHECK-SCOPES: ![[X2LOC]] = !DILocation(line: [[@LINE-3]], column: 15,
// CHECK-SCOPES-SAME: scope: ![[SCOPE2]])
markUsed(x)
case (let x, let y):
// CHECK-SCOPES: !DILocalVariable(name: "x", scope: ![[SCOPE3:[0-9]+]],
// CHECK-SCOPES-SAME: line: [[@LINE-2]]
// CHECK-SCOPES: ![[X3LOC]] = !DILocation(line: [[@LINE-3]], column: 15,
// CHECK-SCOPES-SAME: scope: ![[SCOPE3]])
markUsed(x)
}
// CHECK: !DILocation(line: [[@LINE+1]],
}
| apache-2.0 |
dsaved/africhat-platform-0.1 | actor-apps/app-ios/ActorApp/Controllers/Compose/ComposeController.swift | 24 | 4980 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class ComposeController: ContactsBaseViewController, UISearchBarDelegate, UISearchDisplayDelegate {
var searchView: UISearchBar?
var searchDisplay: UISearchDisplayController?
var searchSource: ContactsSearchSource?
var tableView = UITableView()
init() {
super.init(contentSection: 1, nibName: nil, bundle: nil)
self.navigationItem.title = NSLocalizedString("ComposeTitle", comment: "Compose Title")
self.extendedLayoutIncludesOpaqueBars = true
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
view.backgroundColor = UIColor.whiteColor()
view.addSubview(tableView)
bindTable(tableView, fade: true)
searchView = UISearchBar()
searchView!.delegate = self
searchView!.frame = CGRectMake(0, 0, 0, 44)
searchView!.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
MainAppTheme.search.styleSearchBar(searchView!)
searchDisplay = UISearchDisplayController(searchBar: searchView, contentsController: self)
searchDisplay?.searchResultsDelegate = self
searchDisplay?.searchResultsTableView.rowHeight = 56
searchDisplay?.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
searchDisplay?.searchResultsTableView.backgroundColor = Resources.BackyardColor
searchDisplay?.searchResultsTableView.frame = tableView.frame
var header = TableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(searchView!)
var headerShadow = UIImageView(frame: CGRectMake(0, -4, 320, 4));
headerShadow.image = UIImage(named: "CardTop2");
headerShadow.contentMode = UIViewContentMode.ScaleToFill;
header.addSubview(headerShadow);
tableView.tableHeaderView = header
searchSource = ContactsSearchSource(searchDisplay: searchDisplay!)
super.viewDidLoad()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (section == 1) {
return super.tableView(tableView, numberOfRowsInSection: section)
} else {
return 1
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (indexPath.section == 1) {
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
} else {
if (indexPath.row == 0) {
let reuseId = "create_group";
var res = ContactActionCell(reuseIdentifier: reuseId)
res.bind("ic_add_user",
actionTitle: NSLocalizedString("CreateGroup", comment: "Create Group"),
isLast: false)
return res
} else {
let reuseId = "find_public";
var res = ContactActionCell(reuseIdentifier: reuseId)
res.bind("ic_add_user",
actionTitle: NSLocalizedString("Join public group", comment: "Create Group"),
isLast: false)
return res
}
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (tableView == self.tableView) {
if (indexPath.section == 0) {
if (indexPath.row == 0) {
navigateNext(GroupCreateViewController(), removeCurrent: true)
} else {
navigateNext(DiscoverViewController(), removeCurrent: true)
}
MainAppTheme.navigation.applyStatusBar()
} else {
var contact = objectAtIndexPath(indexPath) as! ACContact
navigateToMessagesWithPeerId(contact.getUid())
}
} else {
var contact = searchSource!.objectAtIndexPath(indexPath) as! ACContact
navigateToMessagesWithPeerId(contact.getUid())
}
}
// MARK: -
// MARK: Navigation
private func navigateToMessagesWithPeerId(peerId: jint) {
navigateNext(ConversationViewController(peer: ACPeer.userWithInt(peerId)), removeCurrent: true)
MainAppTheme.navigation.applyStatusBar()
}
func createGroup() {
navigateNext(GroupCreateViewController(), removeCurrent: true)
MainAppTheme.navigation.applyStatusBar()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = CGRectMake(0, 0, view.frame.width, view.frame.height)
}
} | mit |
xiaomudegithub/viossvc | viossvc/General/CustomView/CommTableViewBannerCell.swift | 1 | 2293 | //
// SkillShareBannerCell.swift
// viossvc
//
// Created by yaowang on 2016/10/29.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
class CommTableViewBannerCell: OEZTableViewPageCell {
let cellIdentifier = "BannerImageCell";
var bannerSrcs:[AnyObject]? = [];
override func awakeFromNib() {
super.awakeFromNib();
pageView.registerNib(UINib(nibName: "PageViewImageCell",bundle: nil), forCellReuseIdentifier: cellIdentifier);
// pageView.pageControl.currentPageIndicatorTintColor = AppConst.Color.CR;
pageView.pageControl.pageIndicatorTintColor = AppConst.Color.C4;
}
override func numberPageCountPageView(pageView: OEZPageView!) -> Int {
return bannerSrcs != nil ? bannerSrcs!.count : 0 ;
}
override func pageView(pageView: OEZPageView!, cellForPageAtIndex pageIndex: Int) -> OEZPageViewCell! {
let cell:OEZPageViewImageCell? = pageView.dequeueReusableCellWithIdentifier(cellIdentifier) as? OEZPageViewImageCell;
var urlString:String?
if bannerSrcs![pageIndex] is String {
urlString = bannerSrcs![pageIndex] as? String
}
else if bannerSrcs![pageIndex] is SkillBannerModel {
urlString = (bannerSrcs![pageIndex] as! SkillBannerModel).banner_pic
}
if urlString != nil {
cell?.contentImage.kf_setImageWithURL(NSURL(string:urlString!), placeholderImage: nil)
}
return cell;
}
override func update(data: AnyObject!) {
bannerSrcs = data != nil ? data as? Array<AnyObject> : []
pageView.pageControl.hidden = bannerSrcs?.count < 2
pageView.scrollView.scrollEnabled = bannerSrcs?.count > 1
pageView.reloadData()
}
func contentOffset(contentOffset:CGPoint) {
let yOffset:CGFloat = contentOffset.y ;
if yOffset <= 0.0 {
var rect:CGRect = frame;
rect.origin.y = yOffset ;
rect.size.height = fabs(yOffset) + CGRectGetHeight(frame);
rect.size.width = (rect.size.height * CGRectGetWidth(frame) / CGRectGetHeight(frame));
rect.origin.x = (CGRectGetWidth(frame) - rect.size.width)/2;
pageView.frame = rect;
}
}
}
| apache-2.0 |
MukeshKumarS/Swift | test/Generics/generic_types.swift | 1 | 8452 | // RUN: %target-parse-verify-swift
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(a: T) -> T {
return a
}
func f(a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case Element(T)
case None
init() { self = .None }
init(_ t: T) { self = .Element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.Element
var uniontest2 : Optional<Int> = OptionalInt.None
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .None
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(a: T) {
formattedTest(a)
}
}
struct GenericReq<
T : GeneratorType, U : GeneratorType where T.Element == U.Element
> {}
func getFirst<R : GeneratorType>(r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: Range<Int>) {
_ = getFirst(ir.generate()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<R : SequenceType
where R.Generator.Element : MyFormattedPrintable> {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : SequenceType, GeneratorType {
typealias Generator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func generate() -> Generator { return self }
}
func useRangeOfPrintables(roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'SequenceType'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
struct HasNested<T> {
init<U>(_ t: T, _ u: U) {}
func f<U>(t: T, u: U) -> (T, U) {}
struct InnerGeneric<U> { // expected-error{{generic type 'InnerGeneric' nested}}
init() {}
func g<V>(t: T, u: U, v: V) -> (T, U, V) {}
}
struct Inner { // expected-error{{nested in generic type}}
init (_ x: T) {}
func identity(x: T) -> T { return x }
}
}
func useNested(ii: Int, hni: HasNested<Int>,
xisi : HasNested<Int>.InnerGeneric<String>,
xfs: HasNested<Float>.InnerGeneric<String>) {
var i = ii, xis = xisi
typealias InnerI = HasNested<Int>.Inner
var innerI = InnerI(5)
typealias InnerF = HasNested<Float>.Inner
var innerF : InnerF = innerI // expected-error{{cannot convert value of type 'InnerI' (aka 'HasNested<Int>.Inner') to specified type 'InnerF' (aka 'HasNested<Float>.Inner')}}
innerI.identity(i)
i = innerI.identity(i)
// Generic function in a generic class
typealias HNI = HasNested<Int>
var id = hni.f(1, u: 3.14159)
id = (2, 3.14159)
hni.f(1.5, 3.14159) // expected-error{{missing argument label 'u:' in call}}
hni.f(1.5, u: 3.14159) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Int'}}
// Generic constructor of a generic struct
HNI(1, 2.71828) // expected-warning{{unused}}
// FIXME: Should report this error: {{cannot convert the expression's type 'HNI' to type 'Int'}}
HNI(1.5, 2.71828) // expected-error{{cannot invoke initializer for type 'HNI' with an argument list of type '(Double, Double)'}} expected-note{{expected an argument list of type '(T, U)'}}
// Generic function in a nested generic struct
var ids = xis.g(1, u: "Hello", v: 3.14159)
ids = (2, "world", 2.71828)
xis = xfs // expected-error{{cannot assign value of type 'HasNested<Float>.InnerGeneric<String>' to type 'HasNested<Int>.InnerGeneric<String>'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}
// Check unqualified lookup of inherited types.
class Foo<T> {
typealias Nested = T
}
class Bar : Foo<Int> {
func f(x: Int) -> Nested {
return x
}
struct Inner {
func g(x: Int) -> Nested {
return x
}
func withLocal() {
struct Local {
func h(x: Int) -> Nested {
return x
}
}
}
}
}
extension Bar {
func g(x: Int) -> Nested {
return x
}
/* This crashes for unrelated reasons: <rdar://problem/14376418>
struct Inner2 {
func f(x: Int) -> Nested {
return x
}
}
*/
}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ArrayLiteralConvertible {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> {
func foo(x: T) {
_ = x as T
}
static func bar(x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of 'XParam<Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
typealias AssocP
}
protocol Q {
typealias AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U where T: P, T: Q, T.AssocP == T.AssocQ> { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'AssocP' (aka 'Int') and 'AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {} // expected-error 2{{type may not reference itself as a requirement}}
// expected-error@-1{{Bottom' requires that 'Top' inherit from 'Bottom<Top>'}}
// expected-note@-2{{requirement specified as 'T' : 'Bottom<Top>' [with T = Top]}}
class X6<T> {
let d: D<T>
init(_ value: T) {
d = D(value) // expected-error{{cannot invoke initializer for type 'X6<T>.D<_, _>' with an argument list of type '(T)'}} expected-note{{expected an argument list of type '(T2)'}}
}
class D<T2> { // expected-error{{generic type 'D' nested in type 'X6' is not allowed}}
init(_ value: T2) {}
}
}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{inheritance from non-protocol, non-class type 'T.A'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{inheritance from non-protocol, non-class type 'U.A'}}
// expected-error@-2 {{inheritance from non-protocol, non-class type 'T.A'}}
| apache-2.0 |
zasia3/archivervapor | Sources/App/AuthenticationMiddleware.swift | 1 | 714 | //
// AuthenticationMiddleware.swift
// Archiver
//
// Created by Joanna Zatorska on 01/06/2017.
//
//
import HTTP
public final class AuthenticationMiddleware: Middleware {
public func respond(to request: Request, chainingTo next: Responder) throws -> Response {
guard let token = request.auth.header?.bearer else {
throw RequestError.notAuthorized
}
guard let userId = request.headers["X-User-Id"] else {
throw RequestError.invalidUser
}
if try AuthToken.isValid(token.string, for: Identifier(userId)) {
return try next.respond(to: request)
}
throw RequestError.tokenExpired
}
}
| mit |
AlbertXYZ/HDCP | HDCP/HDCP/HDCG03Service.swift | 1 | 1159 | //
// HDCG03Service.swift
// HDCP
//
// Created by 徐琰璋 on 16/1/22.
// Copyright © 2016年 batonsoft. All rights reserved.
//
import Foundation
import ObjectMapper
class HDCG03Service {
/**
菜谱搜索
*
* parameter successBlock: 成功
* parameter failBlock: 失败
*/
func doGetRequest_HDCG03_URL(_ keyword:String,limit:Int,offset:Int,successBlock:@escaping (_ hm04Response:HDHM04Response)->Void,failBlock:@escaping (_ error:NSError)->Void){
HDRequestManager.doPostRequest(["tagid":"" as AnyObject,"keyword":keyword as AnyObject,"limit":limit as AnyObject,"offset":offset as AnyObject], URL: Constants.HDCG03_URL) { (response) -> Void in
if response.result.error == nil {
/// JSON 转换成对象
let response = Mapper<HDHM04Response>().map(JSONObject: response.result.value)
/// 回调
successBlock(response!)
}else{
failBlock(response.result.error! as NSError)
}
}
}
}
| mit |
arietis/codility-swift | 7.3.swift | 1 | 581 | public func solution(inout S : String) -> Int {
// write your code in Swift 2.2
if S.characters.count == 0 {
return 1
}
if S.characters.count % 2 > 0 {
return 0
}
var a = S.characters.map {String($0)}
var b: [String] = []
for i in 0..<a.count {
if a[i] == "(" {
b.append(a[i])
} else {
if b.last == "(" {
b.removeLast()
} else {
return 0
}
}
}
if b.count > 0 {
return 0
} else {
return 1
}
}
| mit |
yoonhg84/ModalPresenter | RxModalityStack/Modality.swift | 1 | 1018 | //
// Created by Chope on 2018. 4. 4..
// Copyright (c) 2018 Chope Industry. All rights reserved.
//
import UIKit
public protocol ModalityType: Equatable {
var modalityPresentableType: (UIViewController & ModalityPresentable).Type { get }
}
public protocol ModalityData: Equatable {
static var none: Self { get }
}
public struct Modality<T: ModalityType, D: ModalityData>: Equatable, Hashable {
public let id: String
public let type: T
public let data: D
public let transition: ModalityTransition
public let viewController: UIViewController
public var hashValue: Int {
return viewController.hashValue
}
public static func ==(lhs: Modality<T, D>, rhs: Modality<T, D>) -> Bool {
guard lhs.type == rhs.type else { return false }
guard lhs.data == rhs.data else { return false }
guard lhs.transition == rhs.transition else { return false }
guard lhs.viewController == rhs.viewController else { return false }
return true
}
} | mit |
maxbritto/cours-ios11-swift4 | Maitriser/Objectif_interface_dynamique/SecretNumber/SecretNumberTests/GameControllerTests.swift | 1 | 2631 | //
// GameControllerTests.swift
// GameControllerTests
//
// Created by Maxime Britto on 08/12/2017.
// Copyright © 2017 Maxime Britto. All rights reserved.
//
import XCTest
@testable import SecretNumber
class GameControllerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testGameStatus() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let gameController = GameController()
XCTAssertFalse(gameController.isGameInProgress)
gameController.startNewGame(withSecretNumber: 40)
XCTAssertTrue(gameController.isGameInProgress)
gameController.checkGuessedValue(20)
XCTAssertTrue(gameController.isGameInProgress)
gameController.checkGuessedValue(60)
XCTAssertTrue(gameController.isGameInProgress)
gameController.checkGuessedValue(40)
XCTAssertFalse(gameController.isGameInProgress)
}
func testBoundaries() {
let gameController = GameController()
gameController.startNewGame(withSecretNumber: 60)
XCTAssertEqual(GameController.MIN_VALUE, gameController.lowBoundary)
XCTAssertEqual(GameController.MAX_VALUE, gameController.highBoundary)
gameController.checkGuessedValue(30)
XCTAssertEqual(30, gameController.lowBoundary)
XCTAssertEqual(GameController.MAX_VALUE, gameController.highBoundary)
gameController.checkGuessedValue(70)
XCTAssertEqual(30, gameController.lowBoundary)
XCTAssertEqual(70, gameController.highBoundary)
gameController.checkGuessedValue(55)
XCTAssertEqual(55, gameController.lowBoundary)
XCTAssertEqual(70, gameController.highBoundary)
gameController.checkGuessedValue(65)
XCTAssertEqual(55, gameController.lowBoundary)
XCTAssertEqual(65, gameController.highBoundary)
gameController.startNewGame()
XCTAssertEqual(GameController.MIN_VALUE, gameController.lowBoundary, "After a new game, boundaries should have been reinitialized")
XCTAssertEqual(GameController.MAX_VALUE, gameController.highBoundary, "After a new game, boundaries should have been reinitialized")
}
}
| apache-2.0 |
benlangmuir/swift | test/api-digester/compare-dump-abi.swift | 15 | 2097 | // REQUIRES: VENDOR=apple
// RUN: %empty-directory(%t.mod1)
// RUN: %empty-directory(%t.mod2)
// RUN: %empty-directory(%t.sdk)
// RUN: %empty-directory(%t.module-cache)
// RUN: %empty-directory(%t.baseline/ABI)
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-module -o %t.mod1/cake.swiftmodule %S/Inputs/cake_baseline/cake.swift -parse-as-library -enable-library-evolution -I %S/Inputs/APINotesLeft %clang-importer-sdk-nosource -emit-module-source-info -emit-module-source-info-path %t.mod1/cake.swiftsourceinfo 2> %t.compiler-diags
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -emit-module -o %t.mod2/cake.swiftmodule %S/Inputs/cake_current/cake.swift -parse-as-library -enable-library-evolution -I %S/Inputs/APINotesRight %clang-importer-sdk-nosource -emit-module-source-info -emit-module-source-info-path %t.mod2/cake.swiftsourceinfo
// RUN: %api-digester -dump-sdk -module cake -output-dir %t.baseline -module-cache-path %t.module-cache %clang-importer-sdk-nosource -I %t.mod1 -I %S/Inputs/APINotesLeft -abi
// RUN: %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module cake -I %t.mod2 -I %S/Inputs/APINotesLeft -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -o %t.result
// RUN: %clang -E -P -w -x c %S/Outputs/Cake-abi.txt -o - | sed '/^\s*$/d' > %t.abi.expected
// RUN: %clang -E -P -w -x c %t.result -o - | sed '/^\s*$/d' > %t.abi.result.tmp
// RUN: diff -u %t.abi.expected %t.abi.result.tmp
// A compiler-style diag to ensure we have source locations associated with breakages.
// RUN: not %api-digester -diagnose-sdk -print-module -baseline-dir %t.baseline -module cake -I %t.mod2 -I %S/Inputs/APINotesLeft -module-cache-path %t.module-cache %clang-importer-sdk-nosource -abi -o %t.result -compiler-style-diags 2> %t.abi.compiler.diags
// RUN: %FileCheck %s < %t.abi.compiler.diags
// CHECK: cake_current/cake.swift:39:15: error: ABI breakage: struct C6 is now with @frozen
// CHECK: cake_current/cake.swift:41:13: error: ABI breakage: enum IceKind is now without @frozen
| apache-2.0 |
mozilla-mobile/firefox-ios | Client/Protocols/ReusableCell.swift | 2 | 2097 | // 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
/// A protocol for any object to inherit the `cellIdentifier` string property.
///
/// Intended for use with views that must register/deque cells, this allows
/// a cleaner implementation of the cell identifier by bypassing it being
/// hardcoded which is prone to error.
///
/// As defined in the extensions, this will generally, where adhering to the
/// implemented conditions, return a string describing `self`.
protocol ReusableCell: AnyObject {
static var cellIdentifier: String { get }
}
extension ReusableCell where Self: UICollectionViewCell {
static var cellIdentifier: String { return String(describing: self) }
}
extension ReusableCell where Self: UITableViewCell {
static var cellIdentifier: String { return String(describing: self) }
}
extension ReusableCell where Self: UITableViewHeaderFooterView {
static var cellIdentifier: String { return String(describing: self) }
}
extension ReusableCell where Self: UICollectionReusableView {
static var cellIdentifier: String { return String(describing: self) }
}
extension UICollectionView: Loggable {
func dequeueReusableCell<T: ReusableCell>(cellType: T.Type, for indexPath: IndexPath) -> T? {
guard let cell = dequeueReusableCell(withReuseIdentifier: T.cellIdentifier, for: indexPath) as? T else {
browserLog.warning("Cannot dequeue cell at index path \(indexPath)")
return nil
}
return cell
}
func register<T: ReusableCell>(cellType: T.Type) {
register(T.self, forCellWithReuseIdentifier: T.cellIdentifier)
}
}
extension UITableView {
func register<T: ReusableCell>(cellType: T.Type) {
register(T.self, forCellReuseIdentifier: T.cellIdentifier)
}
func registerHeaderFooter<T: ReusableCell>(cellType: T.Type) {
register(T.self, forHeaderFooterViewReuseIdentifier: T.cellIdentifier)
}
}
| mpl-2.0 |
kcalderon3/Grocery-iOS | GroceryApp/GroceryApp/SecondViewController.swift | 1 | 531 | //
// SecondViewController.swift
// GroceryApp
//
// Created by Kharisma Calderon on 7/11/17.
// Copyright © 2017 Kharisma Calderon. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 |
clarkcb/xsearch | swift/swiftsearch/Sources/swiftsearch/SearchFile.swift | 1 | 659 | //
// SearchFile.swift
// swiftsearch
//
// Created by Cary Clark on 6/2/15.
// Copyright (c) 2015 Cary Clark. All rights reserved.
//
import Foundation
public struct SearchFile {
public let containerSeparator = "!"
public let containers: [String]
public let filePath: String
public let fileType: FileType
public init(filePath: String, fileType: FileType) {
self.filePath = filePath
self.fileType = fileType
containers = []
}
public var description: String {
"\(containers.isEmpty ? "" : containers.joined(separator: containerSeparator) + containerSeparator)" +
filePath
}
}
| mit |
hdinhof1/CheckSplit | CheckSplit/DemoRun.swift | 1 | 2850 | //
// DemoRun.swift
// CheckSplit
//
// Created by Henry Dinhofer on 1/1/17.
// Copyright © 2017 Henry Dinhofer. All rights reserved.
//
import Foundation
class DemoRun {
let store = MealDataStore.sharedInstance
func setup() {
makeMenu()
getOrder()
}
func getOrder() {
getPeople()
getDrinks()
assignDrinks()
}
func assignDrinks() {
let numPatronsDrinking = 10
for index in 0..<numPatronsDrinking
{
let person = store.patrons[index]
let drink = store.drinks[index]
store.add(item: drink, toPerson: person)
}
store.add(item: store.drinks[4], toPerson: Person(name: "Ben G"))
store.add(item: store.drinks[2], toPerson: Person(name: "Mikey C"))
}
func getPeople() {
let ben = Person(name: "Ben G")
let henry = Person(name: "Henry D")
let ari = Person(name: "Ari M")
let david = Person(name: "David Z")
let josh = Person(name: "Josh E")
let mikey = Person(name: "Mikey C")
let dani = Person(name: "Dani S")
let ryan = Person(name: "Ryan C")
let alex = Person(name: "Alex H")
let githui = Person(name: "Githui M")
let people : [Person] = [ben, henry, ari, david, josh, mikey, dani, ryan, alex, githui]
for person in people {
store.add(item: person)
}
}
func getDrinks() {
let drinksCount = menu["Drinks"]?.count ?? 0
var randomDrinkList = [Drink]()
while (randomDrinkList.count < store.patrons.count) {
let randomIndex = Int(arc4random_uniform(UInt32(drinksCount)))
let randomDrink = store.drinks[randomIndex]
if randomDrinkList.contains(randomDrink) { continue }
else { randomDrinkList.append(randomDrink) }
}
store.drinks = randomDrinkList
// store.drinks.append(contentsOf: randomDrinkList)
}
func makeMenu() {
store.clear()
for sectionName in menu.keys {
let section = menu[sectionName] ?? ["NOT VALID" : 0]
for dish in section {
if sectionName == "Drinks"
{
let drink = Drink(name: dish.key, cost: Double(dish.value))
store.drinks.append(drink)
}
else if sectionName == "Appetizers" {
}
else if sectionName == "Entrees"
{
let food = Food(name: dish.key, cost: Double(dish.value))
store.food.append(food)
}
}
}
}
}
| apache-2.0 |
rastogigaurav/mTV | mTV/mTV/ViewModels/MovieDetailsViewModel.swift | 1 | 1854 | //
// MovieDetailsViewModel.swift
// mTV
//
// Created by Gaurav Rastogi on 6/25/17.
// Copyright © 2017 Gaurav Rastogi. All rights reserved.
//
import UIKit
class MovieDetailsViewModel: NSObject {
var displayMovieDetails:DisplayMovieDetailsProtocol
var movie:Movie?
init(with displayDetail:DisplayMovieDetailsProtocol) {
self.displayMovieDetails = displayDetail
}
func fetchDetailAndPopulate(forMovieWith movieId:Int, reload:@escaping ()->())->Void{
self.displayMovieDetails.fetchDetails(forMovieWith: movieId) { (movie) in
self.movie = movie
reload()
}
}
func namesOfProductionCompanies()->String?{
if let movie = self.movie{
if movie.productionCompanies.count > 0{
var companyNames = ""
for company in (self.movie?.productionCompanies)!{
companyNames.append(" | " + company.name)
}
let index = companyNames.index(companyNames.startIndex, offsetBy: 3)
return companyNames.substring(from: index)
}
}
return nil
}
func spokenLanguagesString()->String?{
if let movie = self.movie{
if movie.spokenLanguages.count > 0{
var languages = ""
for language in (self.movie?.spokenLanguages)!{
languages.append(" | " + language.name)
}
let index = languages.index(languages.startIndex, offsetBy: 3)
return languages.substring(from: index)
}
return (self.movie?.originalLanguage)!
}
else{
return nil
}
}
func numberOfRowsInSection(section:Int)->Int{
return 1
}
}
| mit |
hanhailong/practice-swift | Views/Pickers/SimplePicker/SimplePickerTests/SimplePickerTests.swift | 2 | 910 | //
// SimplePickerTests.swift
// SimplePickerTests
//
// Created by Domenico on 04/05/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import UIKit
import XCTest
class SimplePickerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
chausson/CHRequest | CHRequest/Classes/CHRequest+Extension.swift | 1 | 6905 | //
// CHRequest+Extension.swift
// Pods
//
// Created by Chausson on 2017/3/9.
//
//
import Foundation
import Result
public typealias ResultType = Result<Response, Error>
public typealias ResponseHandler = (DefaultDataResponse) -> Void
public typealias RequestCompletion = (_ result:ResultType)->()
public typealias UploadCompletion = (UploadRequest) -> Void
public typealias DownloadCompletion = (Data,URL) -> Void
public typealias ProgressHandle = (Progress) -> Void
public extension CHRequestable where Self:CHRequestAdapter{
@discardableResult
func request(_ completion: @escaping RequestCompletion) -> DataRequest {
let baseInfo = obtainBaseInfo(target:self)
let dataRequest = requestNormal(baseInfo.url, method: self.method, parameters: baseInfo.parms, encoding: self.encoding, headers: baseInfo.headFields)
let defultResponseHandler:ResponseHandler = obtainDefultResponse(baseInfo.url, parms: baseInfo.parms, completion: completion)
dataRequest.response(completionHandler: defultResponseHandler)
return dataRequest
}
}
public extension CHDownloadRequestable where Self:CHRequestAdapter{
@discardableResult
func download(progressClosure:ProgressHandle? = nil,_ completion: @escaping DownloadCompletion) -> DownloadRequest {
let baseInfo = obtainBaseInfo(target:self)
let downloadRequest = downloadNormal(baseInfo.url, method: self.method, parameters: baseInfo.parms, encoding: self.encoding, headers: baseInfo.headFields, fileName: self.fileName).downloadProgress { (progress) in
if let closure = progressClosure{
closure(progress)
}
}.responseData { (response) in
if let data = response.result.value ,let url = response.destinationURL{
completion(data,url)
}
}
return downloadRequest
}
}
public extension CHUploadDataRequestable where Self:CHRequestAdapter{
@discardableResult
func upload(progressClosure:ProgressHandle? = nil,_ completion:@escaping RequestCompletion) {
let baseInfo = obtainBaseInfo(target:self)
uploadNormal({ (multipartFormData) in
multipartFormData.append(self.data, withName: self.fileName, mimeType:self.mimeType)
}, to: baseInfo.url, encodingMemoryThreshold: self.encodingMemoryThreshold, method: self.method, headers: baseInfo.headFields) { (upload) in
upload.uploadProgress(closure: { (progress) in
if let closure = progressClosure{
closure(progress)
}
}).responseJSON { defultResponse in
let result = serializeResponse(defultResponse.response, request: defultResponse.request, data: defultResponse.data, error: defultResponse.error,parm:baseInfo.parms)
completion(result)
}
}
}
}
public extension CHUploadFileRequest where Self:CHRequestAdapter{
@discardableResult
func upload(progressClosure:ProgressHandle? = nil,_ completion:@escaping RequestCompletion) -> UploadRequest {
let baseInfo = obtainBaseInfo(target:self)
let defultResponseHandler:ResponseHandler = obtainDefultResponse(baseInfo.url, parms: baseInfo.parms, completion: completion)
let uploadRequest = uploadNormal(self.fileURL, to: baseInfo.url, method: self.method, headers: baseInfo.headFields).uploadProgress { progress in
if let closure = progressClosure{
closure(progress)
}
}.response(completionHandler: defultResponseHandler)
return uploadRequest
}
}
public extension CHUploadStreamRequestable where Self:CHRequestAdapter{
@discardableResult
func upload(progressClosure:ProgressHandle? = nil,_ completion:@escaping RequestCompletion) -> UploadRequest {
let baseInfo = obtainBaseInfo(target:self)
let defultResponseHandler:ResponseHandler = obtainDefultResponse(baseInfo.url, parms: baseInfo.parms, completion: completion)
let uploadRequest = uploadNormal(self.stream, to: baseInfo.url, method: self.method, headers: baseInfo.headFields).uploadProgress { progress in
if let closure = progressClosure{
closure(progress)
}
}.response(completionHandler: defultResponseHandler)
return uploadRequest
}
}
private func obtainBaseInfo<T:CHRequestable&CHRequestAdapter>(target:T)
-> (url:String,parms:[String :Any],headFields:[String :String]){
var url = target.baseURL+target.path
if target.customURL.characters.count > 0{
url = target.customURL
}
if !url.hasPrefix("http://") {
debugPrint("[Warning Request of URL is not valid]")
}
// 拼接Config中的基础参数
let parms:[String :Any] = jointDic(target.parameters(),target.allParameters)
let headFields:[String :String] = jointDic(target.headers(),target.allHttpHeaderFields) as! [String : String]
return (url,parms,headFields)
}
private func obtainDefultResponse(_ url:String,parms:[String:Any],completion:@escaping RequestCompletion)->ResponseHandler{
return { defultResponse in
guard let completionClosure:RequestCompletion = completion else{
debugPrint("\n[\(url) Request Finished nothing to do]")
return
}
//返回Response 传入闭包
let result = serializeResponse(defultResponse.response, request: defultResponse.request, data: defultResponse.data, error: defultResponse.error,parm:parms)
completionClosure(result)
}
}
private func jointDic(_ dic:[String:Any], _ otherDic:[String:Any]) -> [String:Any] {
var newDic:[String :Any] = [String: String]()
dic.forEach { (key, value) in
newDic[key] = value
}
otherDic.forEach { (key, value) in
newDic[key] = value
}
return newDic
}
private func serializeResponse(_ response: HTTPURLResponse?, request: URLRequest?, data: Data?, error: Swift.Error?,parm: [String:Any]?) ->
ResultType{
switch (response, data, error) {
case let (.some(response), data, .none):
let response = Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response,requestParm:parm)
return .success(response)
case let (_, _, .some(error)):
let error = Error.underlying(error)
return .failure(error)
default:
let error = Error.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil))
return .failure(error)
}
}
| mit |
sidepelican/swift-toml | Sources/Evaluator.swift | 1 | 1718 | /*
* Copyright 2016 JD Fergason
*
* 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
/**
Class to evaluate input text with a regular expression and return tokens
*/
class Evaluator {
let regex: String
let generator: TokenGenerator
let push: [String]?
let pop: Bool
let multiline: Bool
init (regex: String, generator: @escaping TokenGenerator,
push: [String]? = nil, pop: Bool = false, multiline: Bool = false) {
self.regex = regex
self.generator = generator
self.push = push
self.pop = pop
self.multiline = multiline
}
func evaluate (_ content: String) throws ->
(token: Token?, index: String.CharacterView.Index)? {
var token: Token?
var index: String.CharacterView.Index
var options: NSRegularExpression.Options = []
if multiline {
options = [.dotMatchesLineSeparators]
}
if let m = content.match(self.regex, options: options) {
token = try self.generator(m)
index = content.index(content.startIndex, offsetBy: m.characters.count)
return (token, index)
}
return nil
}
}
| apache-2.0 |
nguyenantinhbk77/practice-swift | Autolayout/Layout/Layout/AppDelegate.swift | 2 | 2145 | //
// AppDelegate.swift
// Layout
//
// Created by Domenico on 19.04.15.
// Copyright (c) 2015 Domenico Solazzo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
amco/couchbase-lite-ios | Swift/Tests/SampleCodeTest.swift | 1 | 16195 | //
// SampleCodeTest.swift
// CouchbaseLite
//
// Copyright (c) 2018 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
import CouchbaseLiteSwift
class SampleCodeTest: CBLTestCase {
var database: Database!
var replicator: Replicator!
// MARK: Database
func dontTestNewDatabase() throws {
// <doc>
do {
self.database = try Database(name: "my-database")
} catch {
print(error)
}
// </doc>
}
func dontTestLogging() throws {
// <doc>
Database.setLogLevel(.verbose, domain: .replicator)
Database.setLogLevel(.verbose, domain: .query)
// </doc>
}
func dontTestLoadingPrebuilt() throws {
// <doc>
let path = Bundle.main.path(forResource: "travel-sample", ofType: "cblite2")!
if !Database.exists(withName: "travel-sample") {
do {
try Database.copy(fromPath: path, toDatabase: "travel-sample", withConfig: nil)
} catch {
fatalError("Could not load pre-built database")
}
}
// </doc>
}
// MARK: Document
func dontTestInitializer() throws {
database = self.db
// <doc>
let newTask = MutableDocument()
.setString("task", forKey: "type")
.setString("todo", forKey: "owner")
.setDate(Date(), forKey: "createdAt")
try database.saveDocument(newTask)
// </doc>
}
func dontTestMutability() throws {
database = self.db
// <doc>
guard let document = database.document(withID: "xyz") else { return }
let mutableDocument = document.toMutable()
mutableDocument.setString("apples", forKey: "name")
try database.saveDocument(mutableDocument)
// </doc>
}
func dontTestTypedAcessors() throws {
let newTask = MutableDocument()
// <doc>
newTask.setValue(Date(), forKey: "createdAt")
let date = newTask.date(forKey: "createdAt")
// </doc>
print("\(date!)")
}
func dontTestBatchOperations() throws {
// <doc>
do {
try database.inBatch {
for i in 0...10 {
let doc = MutableDocument()
doc.setValue("user", forKey: "type")
doc.setValue("user \(i)", forKey: "name")
doc.setBoolean(false, forKey: "admin")
try database.saveDocument(doc)
print("saved user document \(doc.string(forKey: "name")!)")
}
}
} catch let error {
print(error.localizedDescription)
}
// </doc>
}
func dontTestBlob() throws {
#if TARGET_OS_IPHONE
database = self.db
let newTask = MutableDocument()
var image: UIImage!
// <doc>
let appleImage = UIImage(named: "avatar.jpg")!
let imageData = UIImageJPEGRepresentation(appleImage, 1)!
let blob = Blob(contentType: "image/jpeg", data: imageData)
newTask.setBlob(blob, forKey: "avatar")
try database.saveDocument(newTask)
if let taskBlob = newTask.blob(forKey: "image") {
image = UIImage(data: taskBlob.content!)
}
// </doc>
print("\(image)")
#endif
}
// MARK: Query
func dontTestIndexing() throws {
database = self.db
// <doc>
let index = IndexBuilder.valueIndex(items:
ValueIndexItem.expression(Expression.property("type")),
ValueIndexItem.expression(Expression.property("name")))
try database.createIndex(index, withName: "TypeNameIndex")
// </doc>
}
func dontTestSelect() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("type"),
SelectResult.property("name")
)
.from(DataSource.database(database))
do {
for result in try query.execute() {
print("document id :: \(result.string(forKey: "id")!)")
print("document name :: \(result.string(forKey: "name")!)")
}
} catch {
print(error)
}
// </doc>
}
func dontTestSelectAll() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(SelectResult.all())
.from(DataSource.database(database))
// </doc>
print("\(query)")
}
func dontTestWhere() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(SelectResult.all())
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("hotel")))
.limit(Expression.int(10))
do {
for result in try query.execute() {
if let dict = result.dictionary(forKey: "travel-sample") {
print("document name :: \(dict.string(forKey: "name")!)")
}
}
} catch {
print(error)
}
// </doc>
}
func dontTestCollectionOperator() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("name"),
SelectResult.property("public_likes")
)
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("hotel"))
.and(ArrayFunction.contains(Expression.property("public_likes"), value: Expression.string("Armani Langworth")))
)
do {
for result in try query.execute() {
print("public_likes :: \(result.array(forKey: "public_likes")!.toArray())")
}
}
// </doc>
}
func dontTestLikeOperator() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("country"),
SelectResult.property("name")
)
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("landmark"))
.and( Expression.property("name").like(Expression.string("Royal engineers museum")))
)
.limit(Expression.int(10))
do {
for result in try query.execute() {
print("name property :: \(result.string(forKey: "name")!)")
}
}
// </doc>
}
func dontTestWildCardMatch() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("country"),
SelectResult.property("name")
)
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("landmark"))
.and(Expression.property("name").like(Expression.string("eng%e%")))
)
.limit(Expression.int(10))
// </doc>
do {
for result in try query.execute() {
print("name property :: \(result.string(forKey: "name")!)")
}
}
}
func dontTestWildCardCharacterMatch() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("country"),
SelectResult.property("name")
)
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("landmark"))
.and(Expression.property("name").like(Expression.string("eng____r")))
)
.limit(Expression.int(10))
// </doc>
do {
for result in try query.execute() {
print("name property :: \(result.string(forKey: "name")!)")
}
}
}
func dontTestRegexMatch() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("name")
)
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("landmark"))
.and(Expression.property("name").like(Expression.string("\\bEng.*e\\b")))
)
.limit(Expression.int(10))
// </doc>
do {
for result in try query.execute() {
print("name property :: \(result.string(forKey: "name")!)")
}
}
}
func dontTestJoin() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Expression.property("name").from("airline")),
SelectResult.expression(Expression.property("callsign").from("airline")),
SelectResult.expression(Expression.property("destinationairport").from("route")),
SelectResult.expression(Expression.property("stops").from("route")),
SelectResult.expression(Expression.property("airline").from("route"))
)
.from(
DataSource.database(database!).as("airline")
)
.join(
Join.join(DataSource.database(database!).as("route"))
.on(
Meta.id.from("airline")
.equalTo(Expression.property("airlineid").from("route"))
)
)
.where(
Expression.property("type").from("route").equalTo(Expression.string("route"))
.and(Expression.property("type").from("airline").equalTo(Expression.string("airline")))
.and(Expression.property("sourceairport").from("route").equalTo(Expression.string("RIX")))
)
// </doc>
do {
for result in try query.execute() {
print("name property :: \(result.string(forKey: "name")!)")
}
}
}
func dontTestGroupBy() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Function.count(Expression.all())),
SelectResult.property("country"),
SelectResult.property("tz"))
.from(DataSource.database(database))
.where(
Expression.property("type").equalTo(Expression.string("airport"))
.and(Expression.property("geo.alt").greaterThanOrEqualTo(Expression.int(300)))
).groupBy(
Expression.property("country"),
Expression.property("tz")
)
do {
for result in try query.execute() {
print("There are \(result.int(forKey: "$1")) airports on the \(result.string(forKey: "tz")!) timezone located in \(result.string(forKey: "country")!) and above 300 ft")
}
}
// </doc>
}
func dontTestOrderBy() throws {
database = self.db
// <doc>
let query = QueryBuilder
.select(
SelectResult.expression(Meta.id),
SelectResult.property("title"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string("hotel")))
.orderBy(Ordering.property("title").ascending())
.limit(Expression.int(10))
// </doc>
print("\(query)")
}
func dontTestCreateFullTextIndex() throws {
database = self.db
// <doc>
// Insert documents
let tasks = ["buy groceries", "play chess", "book travels", "buy museum tickets"]
for task in tasks {
let doc = MutableDocument()
doc.setString("task", forKey: "type")
doc.setString(task, forKey: "name")
try database.saveDocument(doc)
}
// Create index
do {
let index = IndexBuilder.fullTextIndex(items: FullTextIndexItem.property("name")).ignoreAccents(false)
try database.createIndex(index, withName: "nameFTSIndex")
} catch let error {
print(error.localizedDescription)
}
// </doc>
}
func dontTestFullTextSearch() throws {
database = self.db
// <doc>
let whereClause = FullTextExpression.index("nameFTSIndex").match("'buy'")
let query = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(database))
.where(whereClause)
do {
for result in try query.execute() {
print("document id \(result.string(at: 0)!)")
}
} catch let error {
print(error.localizedDescription)
}
// </doc>
}
// MARK: Replication
func dontTestStartReplication() throws {
database = self.db
// <doc>
let url = URL(string: "ws://localhost:4984/db")!
let target = URLEndpoint(url: url)
let config = ReplicatorConfiguration(database: database, target: target)
config.replicatorType = .pull
self.replicator = Replicator(config: config)
self.replicator.start()
// </doc>
}
func dontTestEnableReplicatorLogging() throws {
// <doc>
// Replicator
Database.setLogLevel(.verbose, domain: .replicator)
// Network
Database.setLogLevel(.verbose, domain: .network)
// </doc>
}
func dontTestReplicatorStatus() throws {
// <doc>
self.replicator.addChangeListener { (change) in
if change.status.activity == .stopped {
print("Replication stopped")
}
}
// </doc>
}
func dontTestHandlingReplicationError() throws {
// <doc>
self.replicator.addChangeListener { (change) in
if let error = change.status.error as NSError? {
print("Error code :: \(error.code)")
}
}
// </doc>
}
func dontTestCertificatePinning() throws {
let url = URL(string: "wss://localhost:4985/db")!
let target = URLEndpoint(url: url)
// <doc>
let data = try self.dataFromResource(name: "cert", ofType: "cer")
let certificate = SecCertificateCreateWithData(nil, data)
let config = ReplicatorConfiguration(database: database, target: target)
config.pinnedServerCertificate = certificate
// </doc>
print("\(config)")
}
}
| apache-2.0 |
natecook1000/swift-compiler-crashes | crashes-duplicates/12872-swift-sourcemanager-getmessage.swift | 11 | 231 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
deinit {
init( = [ {
{
}
let end = {
func d( ) {
class
case ,
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/16077-swift-sourcemanager-getmessage.swift | 11 | 240 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
{
protocol A {
deinit {
enum b {
var a {
class B
{
class
case ,
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/15951-swift-sourcemanager-getmessage.swift | 11 | 214 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return m( [ {
enum b { func a
{
class
case ,
| mit |
YuhuaBillChen/Spartify | Spartify/Spartify/JoinPartyViewController.swift | 1 | 10157 | //
// JoinPartyViewController.swift
// Spartify
//
// Created by Bill on 1/23/16.
// Copyright © 2016 pennapps. All rights reserved.
//
import UIKit
import Parse
import CoreMotion
import Foundation
import AudioToolbox
class JoinPartyViewController: UIViewController {
let manager = CMMotionManager()
let SEQ_LENGTH = 4
let GRAVITY_MARGIN = 0.25
let ACCELE_TRH = 0.2
let DELAY_TRH = 50
var delayCounter = 0
var parseCounter = 0
var sucessfullyChangStatus = false
var currentState = "Normal"
let userObj = PFUser.currentUser()!
var partyObj:PFObject!
var hostObj:PFUser!
var guestObj:PFObject!
var isFinishedSeq = false
var partySeqArray = [String]()
var seqArray = [String]()
var settingSeqNo = -1
@IBOutlet weak var XYZLabel: UILabel!
@IBOutlet weak var leavePartyButton: UIButton!
@IBOutlet weak var partySeqLabel: UILabel!
@IBOutlet weak var yourSeqLabel: UILabel!
func changeMotionStatus(gx:Double,ax:Double,gy:Double,ay:Double,gz:Double,az:Double){
if (delayCounter > DELAY_TRH){
if (gx < (-1+self.GRAVITY_MARGIN) && abs(ax) + abs(ay) + abs(az) > self.ACCELE_TRH*3 ){
self.currentState = "Left"
self.sucessfullyChangStatus = true
self.delayCounter = 0
}
else if (gx > (1-self.GRAVITY_MARGIN) && abs(ax) + abs(ay) + abs(az) > self.ACCELE_TRH*3){
self.currentState = "Right"
self.sucessfullyChangStatus = true
self.delayCounter = 0
}
else if (gz < (-1+self.GRAVITY_MARGIN) && abs(ax) + abs(ay) + abs(az) > self.ACCELE_TRH*3 ){
self.currentState = "Forward"
self.sucessfullyChangStatus = true
self.delayCounter = 0
}
else if (gz > (1-self.GRAVITY_MARGIN) && abs(ax) + abs(ay) + abs(az) > self.ACCELE_TRH*3){
self.currentState = "Backward"
self.sucessfullyChangStatus = true
self.delayCounter = 0
}
else if (abs(gx) < (self.GRAVITY_MARGIN) && abs(gz) < self.GRAVITY_MARGIN && gy < -(1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){
self.currentState = "Up"
self.sucessfullyChangStatus = true
self.delayCounter = 0
}
else if (abs(gx) < (self.GRAVITY_MARGIN) && abs(gz) < self.GRAVITY_MARGIN && gy > (1-self.GRAVITY_MARGIN) && (abs(ax) + abs(ay) + abs(az)) > self.ACCELE_TRH*3){
self.currentState = "Down"
self.sucessfullyChangStatus = true
self.delayCounter = 0
}
else{
if (self.currentState != "Normal"){
self.currentState = "Normal"
self.sucessfullyChangStatus = true
}
}
}
}
func changeBackground(){
if (self.currentState == "Normal"){
self.view.backgroundColor = UIColor.whiteColor()
}
else if (self.currentState == "Left"){
self.view.backgroundColor = UIColor.redColor()
}
else if (self.currentState == "Right"){
self.view.backgroundColor = UIColor.greenColor()
}
else if (self.currentState == "Up"){
self.view.backgroundColor = UIColor.orangeColor()
}
else if (self.currentState == "Down"){
self.view.backgroundColor = UIColor.purpleColor()
}
else if (self.currentState == "Forward"){
self.view.backgroundColor = UIColor.blueColor()
}
else if (self.currentState == "Backward"){
self.view.backgroundColor = UIColor.yellowColor()
}
else{
self.view.backgroundColor = UIColor.grayColor()
}
}
func vibrate(){
AudioToolbox.AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
func beep(){
AudioToolbox.AudioServicesPlaySystemSound(1109)
}
func addSeqUpdater(){
if (!isFinishedSeq){
if (self.settingSeqNo < self.SEQ_LENGTH ){
self.addOneSeq(self.currentState)
self.delayCounter = -DELAY_TRH
vibrate()
if ( self.settingSeqNo == self.SEQ_LENGTH ){
if (self.seqArray == self.partySeqArray){
self.setSeqEnd();
}
else{
setSeqStart()
}
}
}
}
}
func partyObjUpdate(){
partyObj.fetchInBackgroundWithBlock(){
(obj: PFObject?, error: NSError?) -> Void in
if (error == nil && obj != nil){
self.partyObj = obj
if (self.isFinishedSeq || self.seqArray.count == 0 || self.partySeqArray.count == 0 ){
if (obj!["sequence"] != nil && obj!["sequence"].count > 0){
if (obj!["sequence"] as! Array<NSString> != self.partySeqArray){
self.partySeqArray = obj!["sequence"] as! [String]
self.partySeqLabel.hidden = false
self.partySeqLabel.text = self.partySeqArray.joinWithSeparator("--->")
self.setSeqStart()
}
}
}
}
}
}
func updateCheck(){
if (self.sucessfullyChangStatus){
self.XYZLabel!.text = self.currentState
changeBackground()
beep()
if (self.currentState != "Normal"){
addSeqUpdater()
}
self.sucessfullyChangStatus = false;
}
else{
self.delayCounter += 1
}
}
func parseCheck(){
if (parseCounter < 100){
parseCounter += 1
}
else{
self.partyObjUpdate()
parseCounter = 0
}
}
func motionInit(){
if manager.deviceMotionAvailable {
let _:CMAccelerometerData!
let _:NSError!
manager.deviceMotionUpdateInterval = 0.01
manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler:{
accelerometerData, error in
let x = accelerometerData!.gravity.x
let y = accelerometerData!.gravity.y
let z = accelerometerData!.gravity.z
let x2 = accelerometerData!.userAcceleration.x;
let y2 = accelerometerData!.userAcceleration.y;
let z2 = accelerometerData!.userAcceleration.z;
self.changeMotionStatus(x,ax:x2,gy:y,ay:y2,gz:z,az:z2);
if (self.currentState != "Normal"){
}
self.updateCheck()
self.parseCheck()
let dispStr = String(format:"%s g x: %1.2f, y: %1.2f, z: %1.2f a x: %1.2f y:%1.2f z:%1.2f",self.currentState, x,y,z,x2,y2,z2)
print(dispStr)
})
}
}
@IBAction func leavePartyPressed(sender: UIButton) {
sender.enabled = false;
guestObj.deleteInBackgroundWithBlock{
(success: Bool, error: NSError?) -> Void in
if (success) {
// The object has been saved.
self.jumpToMainMenu()
} else {
// There was a problem, check error.description
print("failed to create a new party room")
self.leavePartyButton.enabled = true;
}
}
}
func parseInit(){
let guestQuery = PFQuery(className: "Guest");
guestQuery.whereKey("userId", equalTo:userObj);
guestQuery.getFirstObjectInBackgroundWithBlock{
(obj: PFObject?, error: NSError?) -> Void in
if (error != nil){
print ("Fetching party query failed")
}
else{
self.guestObj = obj!
self.partyObj = (self.guestObj["partyId"])! as! PFObject
self.hostObj = (self.partyObj["userId"])! as! PFUser
}
}
}
func setSeqStart(){
clearSeq()
self.isFinishedSeq = false
settingSeqNo = 0
self.yourSeqLabel.hidden = false
self.yourSeqLabel.text=""
}
func addOneSeq(motion:String){
self.seqArray.append(motion)
settingSeqNo = seqArray.count
self.yourSeqLabel.hidden = false
self.yourSeqLabel.text = seqArray.joinWithSeparator("--->")
}
func clearSeq(){
self.yourSeqLabel.hidden = true
self.seqArray.removeAll()
self.settingSeqNo = -1
}
func setSeqEnd(){
self.isFinishedSeq = true
self.yourSeqLabel.hidden = false
self.yourSeqLabel.text = "You've finished this party sequence"
settingSeqNo = 0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
motionInit()
parseInit()
}
func jumpToMainMenu(){
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("MainMenuVC") as! ViewController
manager.stopDeviceMotionUpdates();
self.presentViewController(vc, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 |
colourful987/JustMakeGame-FlappyBird | Code/L08/FlappyBird-End/FlappyBird/GameScene.swift | 1 | 18818 | //
// GameScene.swift
// FlappyBird
//
// Created by pmst on 15/10/4.
// Copyright (c) 2015年 pmst. All rights reserved.
//
import SpriteKit
enum Layer: CGFloat {
case Background
case Obstacle
case Foreground
case Player
case UI
}
enum GameState{
case MainMenu
case Tutorial
case Play
case Falling
case ShowingScore
case GameOver
}
struct PhysicsCategory {
static let None: UInt32 = 0
static let Player: UInt32 = 0b1 // 1
static let Obstacle: UInt32 = 0b10 // 2
static let Ground: UInt32 = 0b100 // 4
}
class GameScene: SKScene,SKPhysicsContactDelegate{
// MARK: - 常量
let kGravity:CGFloat = -1500.0
let kImpulse:CGFloat = 400
let kGroundSpeed:CGFloat = 150.0
let kBottomObstacleMinFraction: CGFloat = 0.1
let kBottomObstacleMaxFraction: CGFloat = 0.6
let kGapMultiplier: CGFloat = 3.5
let kFontName = "AmericanTypewriter-Bold"
let kMargin: CGFloat = 20.0
let kAnimDelay = 0.3
let worldNode = SKNode()
var playableStart:CGFloat = 0
var playableHeight:CGFloat = 0
let player = SKSpriteNode(imageNamed: "Bird0")
var lastUpdateTime :NSTimeInterval = 0
var dt:NSTimeInterval = 0
var playerVelocity = CGPoint.zero
let sombrero = SKSpriteNode(imageNamed: "Sombrero")
var hitGround = false
var hitObstacle = false
var gameState: GameState = .Play
var scoreLabel:SKLabelNode!
var score = 0
// MARK: - 变量
// MARK: - 音乐
let dingAction = SKAction.playSoundFileNamed("ding.wav", waitForCompletion: false)
let flapAction = SKAction.playSoundFileNamed("flapping.wav", waitForCompletion: false)
let whackAction = SKAction.playSoundFileNamed("whack.wav", waitForCompletion: false)
let fallingAction = SKAction.playSoundFileNamed("falling.wav", waitForCompletion: false)
let hitGroundAction = SKAction.playSoundFileNamed("hitGround.wav", waitForCompletion: false)
let popAction = SKAction.playSoundFileNamed("pop.wav", waitForCompletion: false)
let coinAction = SKAction.playSoundFileNamed("coin.wav", waitForCompletion: false)
override func didMoveToView(view: SKView) {
physicsWorld.gravity = CGVector(dx: 0, dy: 0)
physicsWorld.contactDelegate = self
addChild(worldNode)
setupBackground()
setupForeground()
setupPlayer()
setupSomebrero()
startSpawning()
setupLabel()
flapPlayer()
}
// MARK: Setup Method
func setupBackground(){
// 1
let background = SKSpriteNode(imageNamed: "Background")
background.anchorPoint = CGPointMake(0.5, 1)
background.position = CGPointMake(size.width/2.0, size.height)
background.zPosition = Layer.Background.rawValue
worldNode.addChild(background)
// 2
playableStart = size.height - background.size.height
playableHeight = background.size.height
// 新增
let lowerLeft = CGPoint(x: 0, y: playableStart)
let lowerRight = CGPoint(x: size.width, y: playableStart)
// 1
self.physicsBody = SKPhysicsBody(edgeFromPoint: lowerLeft, toPoint: lowerRight)
self.physicsBody?.categoryBitMask = PhysicsCategory.Ground
self.physicsBody?.collisionBitMask = 0
self.physicsBody?.contactTestBitMask = PhysicsCategory.Player
}
func setupForeground() {
for i in 0..<2{
let foreground = SKSpriteNode(imageNamed: "Ground")
foreground.anchorPoint = CGPoint(x: 0, y: 1)
// 改动1
foreground.position = CGPoint(x: CGFloat(i) * size.width, y: playableStart)
foreground.zPosition = Layer.Foreground.rawValue
// 改动2
foreground.name = "foreground"
worldNode.addChild(foreground)
}
}
func setupPlayer(){
player.position = CGPointMake(size.width * 0.2, playableHeight * 0.4 + playableStart)
player.zPosition = Layer.Player.rawValue
let offsetX = player.size.width * player.anchorPoint.x
let offsetY = player.size.height * player.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 17 - offsetX, 23 - offsetY)
CGPathAddLineToPoint(path, nil, 39 - offsetX, 22 - offsetY)
CGPathAddLineToPoint(path, nil, 38 - offsetX, 10 - offsetY)
CGPathAddLineToPoint(path, nil, 21 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 4 - offsetX, 1 - offsetY)
CGPathAddLineToPoint(path, nil, 3 - offsetX, 15 - offsetY)
CGPathCloseSubpath(path)
player.physicsBody = SKPhysicsBody(polygonFromPath: path)
player.physicsBody?.categoryBitMask = PhysicsCategory.Player
player.physicsBody?.collisionBitMask = 0
player.physicsBody?.contactTestBitMask = PhysicsCategory.Obstacle | PhysicsCategory.Ground
worldNode.addChild(player)
}
func setupSomebrero(){
sombrero.position = CGPointMake(31 - sombrero.size.width/2, 29 - sombrero.size.height/2)
player.addChild(sombrero)
}
func setupLabel() {
scoreLabel = SKLabelNode(fontNamed: "AmericanTypewriter-Bold")
scoreLabel.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
scoreLabel.position = CGPoint(x: size.width/2, y: size.height - 20)
scoreLabel.text = "0"
scoreLabel.verticalAlignmentMode = .Top
scoreLabel.zPosition = Layer.UI.rawValue
worldNode.addChild(scoreLabel)
}
func setupScorecard() {
if score > bestScore() {
setBestScore(score)
}
let scorecard = SKSpriteNode(imageNamed: "ScoreCard")
scorecard.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
scorecard.name = "Tutorial"
scorecard.zPosition = Layer.UI.rawValue
worldNode.addChild(scorecard)
let lastScore = SKLabelNode(fontNamed: kFontName)
lastScore.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
lastScore.position = CGPoint(x: -scorecard.size.width * 0.25, y: -scorecard.size.height * 0.2)
lastScore.text = "\(score)"
scorecard.addChild(lastScore)
let bestScoreLabel = SKLabelNode(fontNamed: kFontName)
bestScoreLabel.fontColor = SKColor(red: 101.0/255.0, green: 71.0/255.0, blue: 73.0/255.0, alpha: 1.0)
bestScoreLabel.position = CGPoint(x: scorecard.size.width * 0.25, y: -scorecard.size.height * 0.2)
bestScoreLabel.text = "\(self.bestScore())"
scorecard.addChild(bestScoreLabel)
let gameOver = SKSpriteNode(imageNamed: "GameOver")
gameOver.position = CGPoint(x: size.width/2, y: size.height/2 + scorecard.size.height/2 + kMargin + gameOver.size.height/2)
gameOver.zPosition = Layer.UI.rawValue
worldNode.addChild(gameOver)
let okButton = SKSpriteNode(imageNamed: "Button")
okButton.position = CGPoint(x: size.width * 0.25, y: size.height/2 - scorecard.size.height/2 - kMargin - okButton.size.height/2)
okButton.zPosition = Layer.UI.rawValue
worldNode.addChild(okButton)
let ok = SKSpriteNode(imageNamed: "OK")
ok.position = CGPoint.zero
ok.zPosition = Layer.UI.rawValue
okButton.addChild(ok)
//MARK - BUG 如果死的很快 这里的sharebutton.size = (0,0)
let shareButton = SKSpriteNode(imageNamed: "Button")
shareButton.position = CGPoint(x: size.width * 0.75, y: size.height/2 - scorecard.size.height/2 - kMargin - shareButton.size.height/2)
shareButton.zPosition = Layer.UI.rawValue
worldNode.addChild(shareButton)
let share = SKSpriteNode(imageNamed: "Share")
share.position = CGPoint.zero
share.zPosition = Layer.UI.rawValue
shareButton.addChild(share)
gameOver.setScale(0)
gameOver.alpha = 0
let group = SKAction.group([
SKAction.fadeInWithDuration(kAnimDelay),
SKAction.scaleTo(1.0, duration: kAnimDelay)
])
group.timingMode = .EaseInEaseOut
gameOver.runAction(SKAction.sequence([
SKAction.waitForDuration(kAnimDelay),
group
]))
scorecard.position = CGPoint(x: size.width * 0.5, y: -scorecard.size.height/2)
let moveTo = SKAction.moveTo(CGPoint(x: size.width/2, y: size.height/2), duration: kAnimDelay)
moveTo.timingMode = .EaseInEaseOut
scorecard.runAction(SKAction.sequence([
SKAction.waitForDuration(kAnimDelay * 2),
moveTo
]))
okButton.alpha = 0
shareButton.alpha = 0
let fadeIn = SKAction.sequence([
SKAction.waitForDuration(kAnimDelay * 3),
SKAction.fadeInWithDuration(kAnimDelay)
])
okButton.runAction(fadeIn)
shareButton.runAction(fadeIn)
let pops = SKAction.sequence([
SKAction.waitForDuration(kAnimDelay),
popAction,
SKAction.waitForDuration(kAnimDelay),
popAction,
SKAction.waitForDuration(kAnimDelay),
popAction,
SKAction.runBlock(switchToGameOver)
])
runAction(pops)
}
// MARK: - GamePlay
func createObstacle()->SKSpriteNode{
let sprite = SKSpriteNode(imageNamed: "Cactus")
sprite.zPosition = Layer.Obstacle.rawValue
sprite.userData = NSMutableDictionary()
//========以下为新增内容=========
let offsetX = sprite.size.width * sprite.anchorPoint.x
let offsetY = sprite.size.height * sprite.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 3 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 5 - offsetX, 309 - offsetY)
CGPathAddLineToPoint(path, nil, 16 - offsetX, 315 - offsetY)
CGPathAddLineToPoint(path, nil, 39 - offsetX, 315 - offsetY)
CGPathAddLineToPoint(path, nil, 51 - offsetX, 306 - offsetY)
CGPathAddLineToPoint(path, nil, 49 - offsetX, 1 - offsetY)
CGPathCloseSubpath(path)
sprite.physicsBody = SKPhysicsBody(polygonFromPath: path)
sprite.physicsBody?.categoryBitMask = PhysicsCategory.Obstacle
sprite.physicsBody?.collisionBitMask = 0
sprite.physicsBody?.contactTestBitMask = PhysicsCategory.Player
return sprite
}
func spawnObstacle(){
//1
let bottomObstacle = createObstacle()
let startX = size.width + bottomObstacle.size.width/2
let bottomObstacleMin = (playableStart - bottomObstacle.size.height/2) + playableHeight * kBottomObstacleMinFraction
let bottomObstacleMax = (playableStart - bottomObstacle.size.height/2) + playableHeight * kBottomObstacleMaxFraction
bottomObstacle.position = CGPointMake(startX, CGFloat.random(min: bottomObstacleMin, max: bottomObstacleMax))
bottomObstacle.name = "BottomObstacle"
worldNode.addChild(bottomObstacle)
let topObstacle = createObstacle()
topObstacle.zRotation = CGFloat(180).degreesToRadians()
topObstacle.position = CGPoint(x: startX, y: bottomObstacle.position.y + bottomObstacle.size.height/2 + topObstacle.size.height/2 + player.size.height * kGapMultiplier)
topObstacle.name = "TopObstacle"
worldNode.addChild(topObstacle)
let moveX = size.width + topObstacle.size.width
let moveDuration = moveX / kGroundSpeed
let sequence = SKAction.sequence([
SKAction.moveByX(-moveX, y: 0, duration: NSTimeInterval(moveDuration)),
SKAction.removeFromParent()
])
topObstacle.runAction(sequence)
bottomObstacle.runAction(sequence)
}
func startSpawning(){
let firstDelay = SKAction.waitForDuration(1.75)
let spawn = SKAction.runBlock(spawnObstacle)
let everyDelay = SKAction.waitForDuration(1.5)
let spawnSequence = SKAction.sequence([
spawn,everyDelay
])
let foreverSpawn = SKAction.repeatActionForever(spawnSequence)
let overallSequence = SKAction.sequence([firstDelay,foreverSpawn])
runAction(overallSequence, withKey: "spawn")
}
func stopSpawning() {
removeActionForKey("spawn")
worldNode.enumerateChildNodesWithName("TopObstacle", usingBlock: { node, stop in
node.removeAllActions()
})
worldNode.enumerateChildNodesWithName("BottomObstacle", usingBlock: { node, stop in
node.removeAllActions()
})
}
func flapPlayer(){
// 发出一次煽动翅膀的声音
runAction(flapAction)
// 重新设定player的速度!!
playerVelocity = CGPointMake(0, kImpulse)
// 使得帽子下上跳动
let moveUp = SKAction.moveByX(0, y: 12, duration: 0.15)
moveUp.timingMode = .EaseInEaseOut
let moveDown = moveUp.reversedAction()
sombrero.runAction(SKAction.sequence([moveUp,moveDown]))
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
switch gameState {
case .MainMenu:
break
case .Tutorial:
break
case .Play:
flapPlayer()
break
case .Falling:
break
case .ShowingScore:
switchToNewGame()
break
case .GameOver:
break
}
}
// MARK: - Updates
override func update(currentTime: CFTimeInterval) {
if lastUpdateTime > 0 {
dt = currentTime - lastUpdateTime
} else {
dt = 0
}
lastUpdateTime = currentTime
switch gameState {
case .MainMenu:
break
case .Tutorial:
break
case .Play:
updateForeground()
updatePlayer()
checkHitObstacle()
checkHitGround()
updateScore()
break
case .Falling:
updatePlayer()
checkHitGround()
break
case .ShowingScore:
break
case .GameOver:
break
}
}
func updatePlayer(){
// 只有Y轴上的重力加速度为-1500
let gravity = CGPoint(x: 0, y: kGravity)
let gravityStep = gravity * CGFloat(dt) //计算dt时间下速度的增量
playerVelocity += gravityStep //计算当前速度
// 位置计算
let velocityStep = playerVelocity * CGFloat(dt) //计算dt时间中下落或上升距离
player.position += velocityStep //计算player的位置
// 倘若Player的Y坐标位置在地面上了就不能再下落了 直接设置其位置的y值为地面的表层坐标
if player.position.y - player.size.height/2 < playableStart {
player.position = CGPoint(x: player.position.x, y: playableStart + player.size.height/2)
}
}
func updateForeground(){
worldNode.enumerateChildNodesWithName("foreground") { (node, stop) -> Void in
if let foreground = node as? SKSpriteNode{
let moveAmt = CGPointMake(-self.kGroundSpeed * CGFloat(self.dt), 0)
foreground.position += moveAmt
if foreground.position.x < -foreground.size.width{
foreground.position += CGPoint(x: foreground.size.width * CGFloat(2), y: 0)
}
}
}
}
func checkHitObstacle() {
if hitObstacle {
hitObstacle = false
switchToFalling()
}
}
func checkHitGround() {
if hitGround {
hitGround = false
playerVelocity = CGPoint.zero
player.zRotation = CGFloat(-90).degreesToRadians()
player.position = CGPoint(x: player.position.x, y: playableStart + player.size.width/2)
runAction(hitGroundAction)
switchToShowScore()
}
}
func updateScore() {
worldNode.enumerateChildNodesWithName("BottomObstacle", usingBlock: { node, stop in
if let obstacle = node as? SKSpriteNode {
if let passed = obstacle.userData?["Passed"] as? NSNumber {
if passed.boolValue {
return
}
}
if self.player.position.x > obstacle.position.x + obstacle.size.width/2 {
self.score++
self.scoreLabel.text = "\(self.score)"
self.runAction(self.coinAction)
obstacle.userData?["Passed"] = NSNumber(bool: true)
}
}
})
}
// MARK: - Game States
func switchToFalling() {
gameState = .Falling
runAction(SKAction.sequence([
whackAction,
SKAction.waitForDuration(0.1),
fallingAction
]))
player.removeAllActions()
stopSpawning()
}
func switchToShowScore() {
gameState = .ShowingScore
player.removeAllActions()
stopSpawning()
setupScorecard()
}
func switchToNewGame() {
runAction(popAction)
let newScene = GameScene(size: size)
let transition = SKTransition.fadeWithColor(SKColor.blackColor(), duration: 0.5)
view?.presentScene(newScene, transition: transition)
}
func switchToGameOver() {
gameState = .GameOver
}
// MARK: - SCORE
func bestScore()->Int{
return NSUserDefaults.standardUserDefaults().integerForKey("BestScore")
}
func setBestScore(bestScore:Int){
NSUserDefaults.standardUserDefaults().setInteger(bestScore, forKey: "BestScore")
NSUserDefaults.standardUserDefaults().synchronize()
}
// MARK: - Physics
func didBeginContact(contact: SKPhysicsContact) {
let other = contact.bodyA.categoryBitMask == PhysicsCategory.Player ? contact.bodyB : contact.bodyA
if other.categoryBitMask == PhysicsCategory.Ground {
hitGround = true
}
if other.categoryBitMask == PhysicsCategory.Obstacle {
hitObstacle = true
}
}
}
| mit |
Jerrrr/SwiftyStarRatingView | Example/Example/AppDelegate.swift | 1 | 2161 | //
// AppDelegate.swift
// Example
//
// Created by jerry on 16/12/7.
// Copyright © 2016年 jerry. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-3.0 |
richardxyx/BoardBank | MonoBank/AppDelegate.swift | 1 | 670 | //
// AppDelegate.swift
// MonoBank
//
// Created by Richard Neitzke on 31/12/2016.
// Copyright © 2016 Richard Neitzke. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .pad {
return .all
} else {
return .portrait
}
}
}
| mit |
Fenrikur/ef-app_ios | Eurofurence/Views/Routers/Storyboard/WindowAlertRouter.swift | 1 | 1466 | import UIKit
struct WindowAlertRouter: AlertRouter {
static var shared: WindowAlertRouter = {
guard let window = UIApplication.shared.delegate?.window, let unwrappedWindow = window else { fatalError("No application window available") }
return WindowAlertRouter(window: unwrappedWindow)
}()
var window: UIWindow
func show(_ alert: Alert) {
let alertController = UIAlertController(title: alert.title, message: alert.message, preferredStyle: .alert)
for action in alert.actions {
alertController.addAction(UIAlertAction(title: action.title, style: .default, handler: { (_) in
// TODO: Figure out a nice way of testing this as UIAlertAction does not expose the handler
action.invoke()
alertController.dismiss(animated: true)
}))
}
var presenting: UIViewController? = window.rootViewController
if let presented = presenting?.presentedViewController {
presenting = presented
}
presenting?.present(alertController, animated: true) {
alert.onCompletedPresentation?(Dismissable(viewController: presenting))
}
}
private struct Dismissable: AlertDismissable {
var viewController: UIViewController?
func dismiss(_ completionHandler: (() -> Void)?) {
viewController?.dismiss(animated: true, completion: completionHandler)
}
}
}
| mit |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/LaytoutExtension/AnchorType.swift | 1 | 168 | import Foundation
enum AnchorType {
case top
case bottom
case trailing
case leading
case centerX
case centerY
case width
case height
}
| mit |
buyiyang/iosstar | iOSStar/Scenes/Discover/CustomView/SellingIntroCell.swift | 3 | 1316 | //
// SellingIntroCell.swift
// iOSStar
//
// Created by J-bb on 17/7/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class SellingIntroCell: SellingBaseCell {
@IBOutlet weak var jobLabel: UILabel!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var doDetail: UIButton!
@IBOutlet weak var backImageView: UIImageView!
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
backImageView.contentMode = .scaleAspectFill
backImageView.clipsToBounds = true
}
override func setPanicModel(model: PanicBuyInfoModel?) {
guard model != nil else {
return
}
nickNameLabel.text = model?.star_name
backImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model!.back_pic_url_tail), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model!.head_url_tail), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
jobLabel.text = model?.work
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| gpl-3.0 |
CosmicMind/Samples | Projects/Programmatic/Search/Search/RootViewController.swift | 1 | 4804 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
import Graph
class RootViewController: UIViewController {
// Model.
internal var graph: Graph!
internal var search: Search<Entity>!
// View.
internal var tableView: UserTableView!
open override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Color.grey.lighten5
// Prepare view.
prepareSearchBar()
prepareTableView()
// Prepare model.
prepareGraph()
prepareSearch()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
tableView?.reloadData()
}
}
/// Model.
extension RootViewController {
internal func prepareGraph() {
graph = Graph()
// Uncomment to clear the Graph data.
// graph.clear()
}
internal func prepareSearch() {
search = Search<Entity>(graph: graph).for(types: "User").where(properties: "name")
search.async { [weak self] (data) in
if 0 == data.count {
SampleData.createSampleData()
}
self?.reloadData()
}
}
internal func prepareTableView() {
tableView = UserTableView()
view.layout(tableView).edges()
}
internal func reloadData() {
var dataSourceItems = [DataSourceItem]()
let users = search.sync().sorted(by: { (a, b) -> Bool in
guard let n = a["name"] as? String, let m = b["name"] as? String else {
return false
}
return n < m
})
users.forEach {
dataSourceItems.append(DataSourceItem(data: $0))
}
tableView.dataSourceItems = dataSourceItems
}
}
extension RootViewController: SearchBarDelegate {
internal func prepareSearchBar() {
// Access the searchBar.
guard let searchBar = searchBarController?.searchBar else {
return
}
searchBar.delegate = self
}
func searchBar(searchBar: SearchBar, didClear textField: UITextField, with text: String?) {
reloadData()
}
func searchBar(searchBar: SearchBar, didChange textField: UITextField, with text: String?) {
guard let pattern = text?.trimmed, 0 < pattern.utf16.count else {
reloadData()
return
}
search.async { [weak self, pattern = pattern] (users) in
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return
}
var dataSourceItems = [DataSourceItem]()
for user in users {
if let name = user["name"] as? String {
let matches = regex.matches(in: name, range: NSRange(location: 0, length: name.utf16.count))
if 0 < matches.count {
dataSourceItems.append(DataSourceItem(data: user))
}
}
}
self?.tableView.dataSourceItems = dataSourceItems
}
}
}
| bsd-3-clause |
Ifinity/ifinity-swift-example | IfinitySDK-swift/VenuesMapViewController.swift | 1 | 4798 | //
// VenuesMapViewController.swift
// IfinitySDK-swift
//
// Created by Ifinity on 15.12.2015.
// Copyright © 2015 getifinity.com. All rights reserved.
//
import UIKit
import ifinitySDK
import MapKit
import SVProgressHUD
class VenuesMapViewController: UIViewController, MKMapViewDelegate, IFBluetoothManagerDelegate {
@IBOutlet var mapView: MKMapView?
var currentVenue: IFMVenue?
var currentFloor: IFMFloorplan?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Navigation"
}
override func viewWillAppear(animated: Bool) {
// Start looking for beacons around me
IFBluetoothManager.sharedManager().delegate = self
IFBluetoothManager.sharedManager().startManager()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "addPush:", name: IFPushManagerNotificationPushAdd, object: nil)
super.viewWillAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
IFBluetoothManager.sharedManager().delegate = nil
NSNotificationCenter.defaultCenter().removeObserver(self, name: IFPushManagerNotificationPushAdd, object: nil)
}
//MARK: - Pushes
func addPush(sender: AnyObject) {
var dict: [NSObject : AnyObject] = sender.userInfo
let push: IFMPush = dict["push"] as! IFMPush
NSLog("Venue Map New Push: %@", push.name)
}
@IBAction func clearCaches(sender: AnyObject) {
IFBluetoothManager.sharedManager().delegate = nil
SVProgressHUD.showWithMaskType(.Black)
IFDataManager.sharedManager().clearCaches()
IFDataManager.sharedManager().loadDataForLocation(CLLocation(latitude: 52, longitude: 21), distance: 1000, withPublicVenues: true, successBlock: { (venues) -> Void in
SVProgressHUD.dismiss()
IFBluetoothManager.sharedManager().delegate = self
}) { (error) -> Void in
NSLog("LoadDataForLocation error %@", error)
}
}
//MARK: - IFBluetoothManagerDelegates
func manager(manager: IFBluetoothManager, didDiscoverActiveBeaconsForVenue venue: IFMVenue?, floorplan: IFMFloorplan) {
guard venue != nil else {
return
}
if Int(venue!.type) == IFMVenueTypeMap {
NSLog("IFMVenueTypeMap %s", __FUNCTION__)
self.currentVenue = venue
self.currentFloor = floorplan
IFBluetoothManager.sharedManager().delegate = nil
self.performSegueWithIdentifier("IndoorLocation", sender: self)
} else if Int(venue!.type) == IFMVenueTypeBeacon {
NSLog("IFMVenueTypeBeacon %s", __FUNCTION__)
if self.currentVenue?.remote_id == venue?.remote_id {
return
}
// Center map to venue center coordinate
let center = CLLocationCoordinate2DMake(Double(venue!.center_lat), Double(venue!.center_lng))
let venueAnnotation = VenueAnnotation(coordinate: center, title: venue!.name, subtitle: "")
let distance: CLLocationDistance = 800.0
let camera = MKMapCamera(lookingAtCenterCoordinate: center, fromEyeCoordinate: center, eyeAltitude: distance)
self.mapView?.addAnnotation(venueAnnotation)
self.mapView?.setCamera(camera, animated: false)
}
self.currentVenue = venue
}
func manager(manager: IFBluetoothManager, didLostAllBeaconsForVenue venue: IFMVenue) {
self.currentVenue = nil
self.mapView?.removeAnnotations(self.mapView!.annotations)
}
func manager(manager: IFBluetoothManager, didLostAllBeaconsForFloorplan floorplan: IFMFloorplan) {
self.currentFloor = nil
self.mapView?.removeAnnotations(self.mapView!.annotations)
}
//MARK: - MKMapViewDelegate
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
// VenueAnnotation with some nice icon
if annotation is VenueAnnotation {
let annotationIdentifier: String = "venueIdentifier"
let pinView: MKPinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
pinView.pinTintColor = UIColor.greenColor()
pinView.canShowCallout = true
return pinView
}
return nil
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.destinationViewController is IndoorLocationViewController {
(segue.destinationViewController as! IndoorLocationViewController).currentFloor = self.currentFloor
}
}
}
| mit |
grandiere/box | box/Model/GridVisor/Render/Textures/MGridVisorRenderTexturesVirusFoe.swift | 1 | 732 | import UIKit
import MetalKit
class MGridVisorRenderTexturesVirusFoe:MetalTextureRandom
{
private let kTicksPerFrame:Int = 60
init(textureLoader:MTKTextureLoader)
{
let images:[UIImage] = [
#imageLiteral(resourceName: "assetTextureVirusFoeTargeted0"),
#imageLiteral(resourceName: "assetTextureVirusFoeTargeted1"),
#imageLiteral(resourceName: "assetTextureVirusFoeTargeted2"),
#imageLiteral(resourceName: "assetTextureVirusFoeTargeted3"),
#imageLiteral(resourceName: "assetTextureVirusFoeTargeted4")]
super.init(
ticksPerFrame:kTicksPerFrame,
images:images,
textureLoader:textureLoader)
}
}
| mit |
CosmicMind/Samples | Projects/Programmatic/FABMenuController/FABMenuController/AppDelegate.swift | 1 | 1991 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
window = UIWindow(frame: Screen.bounds)
window!.rootViewController = AppFABMenuController(rootViewController: ViewController())
window!.makeKeyAndVisible()
}
}
| bsd-3-clause |
Drusy/auvergne-webcams-ios | Carthage/Checkouts/realm-cocoa/examples/installation/osx/swift/DynamicExample/DynamicExample/AppDelegate.swift | 1 | 1155 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Cocoa
import RealmSwift
open class MyModel: Object {}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| apache-2.0 |
THREDOpenSource/SYNUtils | SYNUtils/SYNUtils/Extensions/Array+Utils.swift | 2 | 6200 | //
// Array+Utils.swift
// SYNUtils
//
// Created by John Hurliman on 6/23/15.
// Copyright (c) 2015 Syntertainment. All rights reserved.
//
import Foundation
extension Array {
typealias ElementCallback = Element -> Void
typealias IndexedElementCallback = (Int, Element) -> Void
typealias TestCallback = Element -> Bool
/// Convert an array of optional types to non-optional types by removing any
/// nil entries.
///
/// let compacted: [Int] = [1, 2, nil, 3].compact()
///
/// :param: array Array of optional types
/// :returns: A copy of the given array, typecasted with nil entries removed
static func compact(array: [T?]) -> [T] {
return array.filter { $0 != nil }.map { $0! }
}
/// Return the index of the first array element equal to `item`.
///
/// if let index = [1, 2, 3].indexOf(2) { ... }
///
/// :param: item The item to search for
/// :returns: A zero-based index for the first matching element in the
/// array, otherwise nil
func indexOf<U: Equatable>(item: U) -> Int? {
if item is Element {
return find(unsafeBitCast(self, [U].self), item)
}
return nil
}
/// Return the index of the first array element where the supplied function
/// returns true.
///
/// if let index = [1, 2, 3].indexOf({ $0 == 2 }) { ... }
///
/// :param: condition Function that takes an array element and returns true
/// for a match, otherwise false
/// :returns: A zero-based index for the first matching element in the
/// array, otherwise nil
func indexOf(condition: TestCallback) -> Int? {
for (index, element) in enumerate(self) {
if condition(element) { return index }
}
return nil
}
/// Execute a function for each element in the array.
///
/// [1, 2, 3].each { println($0) }
///
/// :param: function Function to run for each element
func each(function: ElementCallback) {
for item in self {
function(item)
}
}
/// Execute a function for each index and element tuple in the array.
///
/// [1, 2, 3].each { println("Index \($0) = \($1)") }
///
/// :param: function Function to run for each index and element tuple
func each(function: IndexedElementCallback) {
for (index, item) in enumerate(self) {
function(index, item)
}
}
/// Test if the array contains one or more elements.
///
/// if [1, 2, 3].contains(2, 3) { ... }
///
/// :param: items One or more elements to search for in the array. The array
/// must contain all of the given elements for this method to return true
/// :returns: True if all of the given elements were found in the array,
/// otherwise false
func contains<T: Equatable>(items: T...) -> Bool {
return items.every { self.indexOf($0) >= 0 }
}
/// Test if any of the array elements pass a given condition.
///
/// if [1, 2, 3].some({ $0 == 2 }) { ... }
///
/// :param: test Function that takes an array element and returns true or
/// false
/// :returns: True the first time an array element passes the test function,
/// otherwise false
func some(test: TestCallback) -> Bool {
for item in self {
if test(item) { return true }
}
return false
}
/// Test if all of the array elements pass a given condition.
///
/// if [1, 2, 3].every({ $0 is Int }) { ... }
///
/// :param: test Function that takes an array element and returns true or
/// false
/// :returns: True if every array element passes the test function,
/// otherwise false the first time an element fails the test
func every(test: TestCallback) -> Bool {
for item in self {
if !test(item) { return false }
}
return true
}
/// Flatten the elements of this array into a string, with the `separator`
/// string between each element in the output string.
///
/// [1, 2, 3].joinWithString("-") // "1-2-3"
///
/// :param: separator String to place between each element
/// :returns: A string representation of the array
func joinWithString(separator: String) -> String {
return separator.join(self.map { "\($0)" })
}
/// Return a randomly chosen element from the array.
///
/// if let num = [1, 2, 3].chooseRandom() { println("Chose \(num)") }
///
/// :returns: A randomly chosen element, or nil if the array is empty
func chooseRandom() -> T? {
if self.count == 0 { return nil }
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
// MARK: - Mutating Methods
/// Remove the last element from the array and return it.
///
/// [1, 2, 3].pop() // Array becomes [1, 2]
///
/// :returns: The last element in the array, or nil if the array is empty
mutating func pop() -> Element? {
return count > 0 ? removeAtIndex(count - 1) : nil
}
/// Remove the first element from the array and return it.
///
/// [1, 2, 3].shift() // Array becomes [2, 3]
///
/// :returns: The first element in the array, or nil if the array is empty
mutating func shift() -> Element? {
return count > 0 ? removeAtIndex(0) : nil
}
/// Add an element to the beginning of the array.
///
/// [1, 2, 3].unshift(0) // Array becomes [0, 1, 2, 3]
///
/// :param: item New item to prepend to the array
mutating func unshift(item: T) {
insert(item, atIndex: 0)
}
/// Add an element to the array a given number of times.
///
/// [].fill("a", 3) // Array becomes ["a", "a", "a"]
///
/// :param: value New element to append to the array
/// :param: count Number of times to append the new element
mutating func fill(value: Element, count: Int) {
for _ in 0..<count {
append(value)
}
}
}
| mit |
michalziman/mz-location-picker | MZLocationPicker/Classes/MZLocationPickerControllerExtensions.swift | 1 | 3466 | //
// MZLocationPickerControllerExtensions.swift
// Pods
//
// Created by Michal Ziman on 03/09/2017.
//
//
import UIKit
import CoreLocation
import MapKit
extension MZLocationPickerController: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension MZLocationPickerController: MKMapViewDelegate {
public func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if mapView.userTrackingMode == .follow || mapView.userTrackingMode == .followWithHeading {
selectOnCoordinates(mapView.userLocation.coordinate)
}
}
public func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
hideKeyboard()
}
public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard !(annotation is MKUserLocation) else {
return nil
}
var annotationView: MKAnnotationView
if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequeuedAnnotationView
annotationView.annotation = annotation
}
else {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
if let image = self.annotation.image {
annotationView.image = image
} else {
let tc = tintColor ?? locationPickerView.tintColor ?? annotationView.tintColor ?? .blue
annotationView.image = UIImage(named: "pin", in: Bundle(for: type(of:self)), compatibleWith: nil)?.tint(with: tc)
}
if let annotationImageOffset = self.annotation.centerOffset {
annotationView.centerOffset = annotationImageOffset
} else if let imageSize = annotationView.image?.size {
annotationView.centerOffset = CGPoint(x: 0, y: -imageSize.height/2 + 2)
}
}
return annotationView
}
}
extension MZLocationPickerController: UISearchBarDelegate {
public func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
locationPickerView.isShowingSearch = true
}
public func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
locationPickerView.isShowingSearch = false
}
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
locationPickerView.isShowingSearchResults = !searchText.isEmpty
searchTableController.searchQuery = searchText
}
}
extension MZLocationPickerController: MZLocationsTableDelegate {
func tableController(_ tableController: MZLocationsTableController, didPickLocation location: MZLocation) {
self.location = location
let cl = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
locationPickerView.chosenLocation = cl
if let a = location.address, !a.isEmpty {
locationPickerView.chosenLocationName = a
} else {
locationPickerView.chosenLocationName = location.coordinate.formattedCoordinates
}
locationPickerView.mapView.setCenter(location.coordinate, animated: true)
hideKeyboard()
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.